WaybillController.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\CarType;
  4. use App\Components\AsyncResponse;
  5. use App\Region;
  6. use App\Services\CarTypeService;
  7. use App\Services\LogisticService;
  8. use App\Services\OwnerService;
  9. use App\Services\UnitService;
  10. use App\Services\WaybillPayoffService;
  11. use App\Services\WaybillPriceModelService;
  12. use App\Services\WaybillService;
  13. use App\UploadFile;
  14. use App\WaybillAuditLog;
  15. use App\WaybillOnTop;
  16. use App\WaybillPriceModel;
  17. use App\Unit;
  18. use App\Waybill;
  19. use App\WaybillPayoff;
  20. use App\WaybillFinancialExcepted;
  21. use App\WaybillFinancialSnapshot;
  22. use Carbon\Carbon;
  23. use Illuminate\Database\Eloquent\Builder;
  24. use Illuminate\Database\Eloquent\Collection;
  25. use Illuminate\Database\Eloquent\Model;
  26. use Illuminate\Http\Request;
  27. use Illuminate\Support\Facades\Auth;
  28. use Illuminate\Support\Facades\DB;
  29. use Illuminate\Support\Facades\Gate;
  30. use Illuminate\Support\Facades\Storage;
  31. use Illuminate\Support\Facades\Validator;
  32. use Intervention\Image\Facades\Image;
  33. use Oursdreams\Export\Export;
  34. use Ramsey\Uuid\Uuid;
  35. class WaybillController extends Controller
  36. {
  37. use AsyncResponse;
  38. public function __construct()
  39. {
  40. app()->singleton('waybillService',WaybillService::class);
  41. }
  42. /**
  43. * @param Request $request
  44. * @param OwnerService $ownerService
  45. * @param LogisticService $logisticService
  46. * @return void
  47. */
  48. public function index(Request $request,OwnerService $ownerService,LogisticService $logisticService)
  49. {
  50. if(!Gate::allows('运输管理-运单-查询')){ return view("exception.authority"); }
  51. $paginateParams = $request->input();
  52. $waybills=app('waybillService')->paginate($request->input());
  53. return view('transport.waybill.index', [
  54. 'waybills' => $waybills,
  55. 'logistics' => $logisticService->getSelection(["id","name"],"物流"),
  56. 'owners' => $ownerService->getIntersectPermitting(),
  57. "carTypes" => CarType::query()->get(),
  58. 'paginateParams'=>$paginateParams,
  59. 'uriType'=>$request->uriType??'']);
  60. }
  61. public function create(Request $request,OwnerService $ownerService)
  62. {
  63. if(!Gate::allows('运输管理-运单-录入')){ return redirect(url('denied')); }
  64. $type=$request->type ?? "";
  65. if ($type==='ZF')$type='直发车';
  66. if ($type==='ZX')$type='专线';
  67. return view('transport.waybill.create',['owners'=>$ownerService->getIntersectPermitting(),'type'=>$type]);
  68. }
  69. public function store(Request $request)
  70. {
  71. if(!Gate::allows('运输管理-运单-录入')){ return redirect(url('denied')); }
  72. $this->validatorWaybill($request,false)->validate();
  73. /** @var WaybillService */
  74. $waybill=app('waybillService')->store($request);
  75. return redirect('transport/waybill/index')->with('successTip','新运单“'.$waybill->waybill_number.'”录入成功');
  76. }
  77. public function edit($id,LogisticService $logisticService,CarTypeService $carTypeService,UnitService $unitService)
  78. {
  79. //if(!Gate::allows('运输管理-编辑')){ return redirect(url('denied')); }
  80. $waybill = app('waybillService')->find($id);
  81. if ($waybill->order_id){
  82. /** @var Waybill $waybill */
  83. $waybill->load("order.owner");
  84. $waybill->destination_city_id = app("RegionService")->getCity($waybill->order->city ?? '',$waybill->order->province ?? '');
  85. }else{
  86. /** @var Waybill $waybill */
  87. $waybill->load("owner");
  88. }
  89. /** @var \stdClass $waybill */
  90. if (!$waybill)return view("exception.default",["code"=>"500","message"=>"数据已被删除或丢失"]);
  91. if ($waybill->deliver_at){
  92. $waybill->deliver_at_date=Carbon::parse($waybill->deliver_at)->format('Y-m-d');
  93. $waybill->deliver_at_time=Carbon::parse($waybill->deliver_at)->format('H:i:s');
  94. }
  95. $cities=app("RegionService")->getSelection(2);
  96. $units=$unitService->getSelection();
  97. $carTypes=$carTypeService->getSelection();
  98. return view('transport.waybill.edit',['waybill'=>$waybill,'logistics'=>$logisticService->getSelection(["id","name"],"物流"),'cities'=>$cities,'units'=>$units,'carTypes'=>$carTypes]);
  99. }
  100. public function update(Request $request, $id,WaybillPriceModelService $waybillPriceModelService,
  101. LogisticService $logisticService,WaybillPayoffService $waybillPayoffService)
  102. {
  103. if(!Gate::allows('运输管理-运单-调度')){ return redirect(url('/')); }
  104. if (!$request->warehouse_weight && $request->warehouse_weight_unit_id){
  105. $request->offsetUnset('warehouse_weight_unit_id');
  106. }
  107. if (!$request->warehouse_weight_other && $request->warehouse_weight_unit_id_other){
  108. $request->offsetUnset('warehouse_weight_unit_id_other');
  109. }
  110. if (!$request->carrier_weight && $request->carrier_weight_unit_id){
  111. $request->offsetUnset('carrier_weight_unit_id');
  112. }
  113. if (!$request->carrier_weight_other && $request->carrier_weight_unit_id_other){
  114. $request->offsetUnset('carrier_weight_unit_id_other');
  115. }
  116. $this->validatorWaybillDispatch($request,$id)->validate();
  117. $waybillPayoffParam = [];
  118. $waybillPayoffParam['total_receivable']=0;
  119. /** @var WaybillService */
  120. $waybill = app('waybillService')->update($request,$id);
  121. if ($waybill->type=="直发车"){
  122. if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
  123. elseif ($waybill->collect_fee)$waybillPayoffParam['total_receivable'] = ($waybill->collect_fee);
  124. $waybillPayoffParam['total_expense'] = ($waybill->fee)+($waybill->other_fee)-($waybill->collect_fee);
  125. }else {
  126. $waybillPriceModel_id=$request->input('waybillPriceModel');
  127. if ($waybillPriceModel_id){
  128. $carrier_weight=$request->input('carrier_weight');
  129. $waybillPriceModel=$waybillPriceModelService->find($waybillPriceModel_id);
  130. $logistic=$logisticService->find($waybill->logistic_id);
  131. if ($carrier_weight<$waybillPriceModel->initial_weight){
  132. $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$logistic->delivery_fee;
  133. }else{
  134. $fee=(($waybillPriceModel->unit_price)*$carrier_weight)+$logistic->delivery_fee;
  135. }
  136. if ($waybillPriceModel->base_fee&&$fee<$waybillPriceModel->base_fee){
  137. $fee=$waybillPriceModel->base_fee;
  138. }
  139. $waybill->fee=$fee;
  140. $waybill->waybill_price_model_id=$waybillPriceModel_id;
  141. }
  142. $waybill->save();
  143. if ($waybill->charge)$waybillPayoffParam['total_receivable'] = ($waybill->charge);
  144. elseif($waybill->collect_fee) {
  145. $waybillPayoffParam['total_receivable'] = $waybill->collect_fee;
  146. }
  147. $waybillPayoffParam['total_expense'] = ($waybill->pick_up_fee)+($waybill->other_fee)+($waybill->fee);
  148. }
  149. if ($waybillPayoffParam['total_receivable'] > 0){
  150. $waybillPayoffParam['waybill_id'] = $id;
  151. $waybillPayoffParam['gross_margin'] = $waybillPayoffParam['total_receivable'] - $waybillPayoffParam['total_expense'];
  152. $waybillPayoffParam['gross_profit_rate'] = $waybillPayoffParam['gross_margin']/$waybillPayoffParam['total_receivable'];
  153. $waybillPayoffService->updateOrCreate($waybillPayoffParam);
  154. }
  155. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  156. WaybillAuditLog::query()->create([
  157. 'waybill_id'=>$id,
  158. 'audit_stage'=>'发起调度',
  159. 'user_id'=>Auth::id(),
  160. ]);
  161. return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”调度成功');
  162. }
  163. public function checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id){
  164. //确保承运商计数与计数单位为一个数组且长度2
  165. if(!$logistic_id)return false;
  166. if(!$destination_city_id)return false;
  167. if(!$carrier_weight)return false;
  168. if(!$carrier_weight_unit_id)return false;
  169. //多个计数标准,计算价格,取最贵
  170. if ($carrier_weight[0]&&$carrier_weight[1]&&$carrier_weight_unit_id[0]&&$carrier_weight_unit_id[1]){
  171. //城市价格区间不为空
  172. $waybillPriceModelOne=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  173. ->where('range_min','<',$carrier_weight[0])->where('range_max','>=',$carrier_weight[0])
  174. ->where('unit_id',$carrier_weight_unit_id[0])->first();
  175. $waybillPriceModelTwo=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  176. ->where('range_min','<',$carrier_weight[1])->where('range_max','>=',$carrier_weight[1])
  177. ->where('unit_id',$carrier_weight_unit_id[1])->first();
  178. if ($waybillPriceModelOne&&$waybillPriceModelTwo){
  179. if ($waybillPriceModelOne->unit_price*$carrier_weight[0]>=$waybillPriceModelTwo->unit_price*$carrier_weight[1]){
  180. return $waybillPriceModelOne->id;
  181. }else{
  182. return $waybillPriceModelTwo->id;
  183. }
  184. }
  185. if ($waybillPriceModelOne)return $waybillPriceModelOne->id;
  186. if ($waybillPriceModelTwo)return $waybillPriceModelTwo->id;
  187. //价格区间为空
  188. $waybillPriceModelRangeOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[0]])->first();
  189. $waybillPriceModelRangeTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[1]])->first();
  190. if ($waybillPriceModelRangeOne&&$waybillPriceModelRangeTwo){
  191. if ($waybillPriceModelRangeOne->unit_price*$carrier_weight[0]>=$waybillPriceModelRangeTwo->unit_price*$carrier_weight[1]){
  192. return $waybillPriceModelRangeOne->id;
  193. }else{
  194. return $waybillPriceModelRangeTwo->id;
  195. }
  196. }
  197. if ($waybillPriceModelRangeOne)return $waybillPriceModelRangeOne->id;
  198. if ($waybillPriceModelRangeTwo)return $waybillPriceModelRangeTwo->id;
  199. //城市为空
  200. $city=Region::query()->where('id',$destination_city_id)->select('parent_id')->first();
  201. $waybillPriceModelProvinceOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  202. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[0],$carrier_weight[0],$carrier_weight[0]])->first();
  203. $waybillPriceModelProvinceTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  204. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[1],$carrier_weight[1],$carrier_weight[1]])->first();
  205. if ($waybillPriceModelProvinceOne&&$waybillPriceModelProvinceTwo){
  206. if ($waybillPriceModelProvinceOne->unit_price*$carrier_weight[0]>=$waybillPriceModelProvinceTwo->unit_price*$carrier_weight[1]){
  207. return $waybillPriceModelProvinceOne->id;
  208. }else{
  209. return $waybillPriceModelProvinceTwo->id;
  210. }
  211. }
  212. if ($waybillPriceModelProvinceOne)return $waybillPriceModelProvinceOne->id;
  213. if ($waybillPriceModelProvinceTwo)return $waybillPriceModelProvinceTwo->id;
  214. //城市价格区间都为空
  215. $waybillPriceModelProvinceRangeOne=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  216. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[0]])->first();
  217. $waybillPriceModelProvinceRangeTwo=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  218. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[1]])->first();
  219. if ($waybillPriceModelProvinceRangeOne&&$waybillPriceModelProvinceRangeTwo){
  220. if ($waybillPriceModelProvinceRangeOne->unit_price*$carrier_weight[0]>=$waybillPriceModelProvinceRangeTwo->unit_price*$carrier_weight[1]){
  221. return $waybillPriceModelProvinceRangeOne->id;
  222. }else{
  223. return $waybillPriceModelProvinceRangeOne->id;
  224. }
  225. }
  226. if ($waybillPriceModelProvinceRangeOne)return $waybillPriceModelProvinceRangeOne->id;
  227. if ($waybillPriceModelProvinceRangeTwo)return $waybillPriceModelProvinceRangeTwo->id;
  228. };
  229. for ($i=0;$i<count($carrier_weight);$i++){
  230. if ($carrier_weight[$i]&&$carrier_weight_unit_id[$i]){
  231. //城市价格区间不为空
  232. $waybillPriceModel=WaybillPriceModel::query()->where('logistic_id',$logistic_id)->where('city_id',$destination_city_id)
  233. ->where('range_min','<',$carrier_weight[$i])->where('range_max','>=',$carrier_weight[$i])
  234. ->where('unit_id',$carrier_weight_unit_id[$i])->first();
  235. if($waybillPriceModel)return $waybillPriceModel->id;
  236. //价格区间为空
  237. $waybillPriceModelRange=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND city_id = ? AND unit_id = ? AND range_max IS NULL',[$logistic_id,$destination_city_id,$carrier_weight_unit_id[$i]])->first();
  238. if ($waybillPriceModelRange){ return $waybillPriceModelRange->id;}
  239. //城市为空
  240. $city=Region::query()->where('id',$destination_city_id)->select('parent_id')->first();
  241. $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max >= ? AND range_min < ? AND city_id IS NULL',
  242. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[$i],$carrier_weight[$i],$carrier_weight[$i]])->first();
  243. if ($waybillPriceModelProvince){return $waybillPriceModelProvince->id;}
  244. //城市价格区间都为空
  245. $waybillPriceModelProvinceRange=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND unit_id = ? AND range_max IS NULL AND city_id IS NULL',
  246. [$logistic_id,$city->parent_id ?? 0,$carrier_weight_unit_id[$i]])->first();
  247. if ($waybillPriceModelProvinceRange){return $waybillPriceModelProvinceRange->id;}
  248. }
  249. }
  250. return false;
  251. }
  252. /*三层条件:无优先级,找到第一个直接返回
  253. * 无论是否为KG||T,计数单位一为KG,计数单位一为T,计数单位二为KG,计数单位二为T
  254. * 计数一与计数二同时存在取最贵价格:
  255. * 计数一存在,二不存在:
  256. * 计数二存在,一不存在:
  257. * 城市价格区间不为空,城市价格区间都为空,城市为空,价格区间为空
  258. * */
  259. public function isWaybillPriceModel(Request $request){
  260. $logistic_id=$request->input('logistic_id');
  261. $destination_city_id=$request->input('destination_city_id');
  262. $carrier_weight=$request->input('carrier_weight');
  263. $carrier_weight_unit_id=$request->input('carrier_weight_unit_id');
  264. $validatorData=["logistic_id"=>$logistic_id,"destination_city_id"=>$destination_city_id,
  265. 'carrier_weight'=>$carrier_weight[0],"carrier_weight_unit_id"=>$carrier_weight_unit_id[0],
  266. "carrier_weight_other"=>$carrier_weight[1],"carrier_weight_unit_id_other"=>$carrier_weight_unit_id[1]];
  267. $errors=Validator::make($validatorData,[
  268. 'logistic_id'=>'required|integer',
  269. 'destination_city_id'=>'required|integer',
  270. 'carrier_weight'=>'nullable|min:0|numeric|max:999999',
  271. 'carrier_weight_unit_id'=>'required_with:carrier_weight',
  272. 'carrier_weight_other'=>'nullable|min:0|numeric|max:999999',
  273. 'carrier_weight_unit_id_other'=>'required_with:carrier_weight_other',
  274. ],[
  275. 'required'=>':attribute 为必填项',
  276. 'max'=>':attribute 字符过多或输入值过大',
  277. 'min'=>':attribute 不得为负',
  278. 'numeric'=>':attribute 应为数字',
  279. 'unique'=>':attribute 已存在',
  280. 'required_with'=>':attribute 未填',
  281. 'integer'=>':attribute 必须为数字',
  282. ],[
  283. 'carrier_weight'=>'承运商计数(抛)',
  284. 'logistic_id'=>'承运商',
  285. 'destination_city_id'=>'目的市',
  286. 'carrier_weight_unit_id'=>'承运商计数单位',
  287. 'carrier_weight_other'=>'承运商计数二',
  288. 'carrier_weight_unit_id_other'=>'承运商计数单位二',
  289. ])->errors();
  290. if (count($errors)>0)return ['error'=>$errors];
  291. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  292. if (!$result){
  293. //单位为kg,T时
  294. $unitKG=Unit::query()->where('name','kg')->first();
  295. $unitT=Unit::query()->where('name','T')->first();
  296. if ($carrier_weight_unit_id[0]==$unitKG->id){
  297. $carrier_weight_unit_id[0]=$unitT->id;
  298. $carrier_weight[0]=$carrier_weight[0]/1000;
  299. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  300. if ($result)return ['success'=>$result];
  301. }
  302. if ($carrier_weight_unit_id[1]==$unitKG->id){
  303. $carrier_weight_unit_id[1]=$unitT->id;
  304. $carrier_weight[1]=$carrier_weight[1]/1000;
  305. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  306. if ($result)return ['success'=>$result];
  307. }
  308. if ($carrier_weight_unit_id[0]==$unitT->id){
  309. $carrier_weight_unit_id[0]=$unitKG->id;
  310. $carrier_weight[0]=$carrier_weight[0]*1000;
  311. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  312. if ($result)return ['success'=>$result];
  313. }
  314. if ($carrier_weight_unit_id[1]==$unitT->id){
  315. $carrier_weight_unit_id[1]=$unitKG->id;
  316. $carrier_weight[1]=$carrier_weight[1]*1000;
  317. $result=$this->checkWaybillPriceModel($logistic_id,$destination_city_id,$carrier_weight,$carrier_weight_unit_id);
  318. if ($result)return ['success'=>$result];
  319. }
  320. }
  321. return ['success'=>$result];
  322. }
  323. public function waybillUpdate(Request $request, $id){
  324. if(!Gate::allows('运输管理-编辑')){ return redirect(url('/')); }
  325. $this->validatorWaybill($request,$id)->validate();
  326. $data=$request->input();
  327. $waybill=app('waybillService')->find($id);
  328. $waybill->fill($data);
  329. if ($waybill->save()){
  330. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybill),Auth::user()['id']);
  331. return redirect('transport/waybill/index')->with('successTip','运单“'.$waybill->waybill_number.'”修改成功');
  332. }
  333. }
  334. public function waybillAudit(Request $request){
  335. if(!Gate::allows('运输管理-运单-运单审核')){ return redirect(url('/')); }
  336. $id=$request->input('id');
  337. $waybill=app('waybillService')->find($id);
  338. $isAudit=WaybillAuditLog::whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->first();
  339. if (empty($isAudit)){
  340. $waybillAuditLog=new WaybillAuditLog([
  341. 'waybill_id'=>$id,
  342. 'audit_stage'=>'运单阶段',
  343. 'user_id'=>Auth::id(),
  344. ]);
  345. $waybillAuditLog->save();
  346. $waybillAuditLog['user']=Auth::user();
  347. $waybill->status='已审核';
  348. $result=$waybill->save();
  349. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybill),Auth::user()['id']);
  350. return ['success'=>$result,'status'=>$waybill->status,'waybillAuditLog'=>$waybillAuditLog];
  351. }
  352. return ['exception'=>'请勿重复审核!'];
  353. }
  354. public function waybillEdit($id){
  355. if(!Gate::allows('运输管理-编辑')){ return redirect(url('/')); }
  356. $waybill=app('waybillService')->find($id);
  357. $owners=app("OwnerService")->getIntersectPermitting();
  358. return view('transport.waybill.waybillEdit',['waybill'=>$waybill,'owners'=>$owners]);
  359. }
  360. public function waybillRetreatAudit(Request $request){
  361. if(!Gate::allows('运输管理-运单-调度')){ return redirect(url('/')); }
  362. $id=$request->input('id');
  363. /** @var Model|\stdClass $waybill */
  364. $waybill=app('waybillService')->find($id);
  365. $waybillLog = WaybillAuditLog::query()->whereRaw('waybill_id = ? and audit_stage = ?',[$id,"运单阶段"])->delete();
  366. $waybill->status='待重审';
  367. return ['success'=>$waybill->save(),'status'=>$waybill->status,"log"=>$waybillLog];
  368. }
  369. public function waybillEndAudit(Request $request){
  370. if(!Gate::allows('运输管理-运单-调度审核')){ return redirect(url('/')); }
  371. $id=$request->input('id');
  372. $waybill=Waybill::query()->with(["owner","logistic","originationCity","destinationCity","carType",'priceModel',"amountUnit",
  373. "warehouseWeightUnit","carrierWeightUnit","warehouseWeightUnitOther","carrierWeightUnitOther"])->find($id);
  374. if (!$waybill->charge&&!$waybill->collect_fee)return ['exception'=>'收费或到付费用未填!'];
  375. if ($waybill->charge==0&&$waybill->collect_fee==0)return ['exception'=>'收费与到付费用都为0!'];
  376. if ($waybill->type=='专线'){
  377. if (!$waybill->carrier_weight_other||$waybill->carrier_weight_other==0)return ['exception'=>'承运商计重未填或为0!'];
  378. if (!$waybill->carrier_weight_unit_id_other)return ['exception'=>'承运商计重单位未选!'];
  379. }
  380. $isAudit=WaybillAuditLog::query()->whereRaw('waybill_id = ? and audit_stage = ?',[$id,"调度阶段"])->first();
  381. if (empty($isAudit)){
  382. $waybillAuditLog=new WaybillAuditLog([
  383. 'waybill_id'=>$id,
  384. 'audit_stage'=>'调度阶段',
  385. 'user_id'=>Auth::id(),
  386. ]);
  387. $waybillAuditLog->save();
  388. $waybillAuditLog['user']=Auth::user();
  389. if ($waybill->waybill_price_model_id||$waybill->type=='直发车'){
  390. $waybill->status='已完结';
  391. $result=$waybill->save();
  392. $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$id)->first();
  393. $waybillPayoffJson=json_encode($this->createReportData($waybill,$waybillPayoff),JSON_UNESCAPED_UNICODE);
  394. WaybillFinancialSnapshot::query()->create([
  395. 'waybill_id'=>$id,
  396. 'json_content'=>$waybillPayoffJson,
  397. ]);
  398. }else{
  399. $waybill->status='无模型';
  400. $result=$waybill->save();
  401. $waybillPayoff=WaybillPayoff::query()->where('waybill_id','=',$id)->first();
  402. if ($waybillPayoff){
  403. $waybillPayoffJson=json_encode($this->createReportData($waybill,$waybillPayoff),JSON_UNESCAPED_UNICODE);
  404. WaybillFinancialExcepted::query()->create([
  405. 'waybill_id'=>$id,
  406. 'json_content'=>$waybillPayoffJson,
  407. ]);
  408. }
  409. }
  410. app("waybillService")->createInstantBill($waybill);
  411. app('LogService')->log(__METHOD__,__FUNCTION__,$waybillPayoffJson,Auth::id());
  412. return ['success'=>$result,'status'=>$waybill->status,'waybillAuditLog'=>$waybillAuditLog];
  413. }
  414. return ['exception'=>'请勿重复审核!'];
  415. }
  416. //生成报表数据
  417. private function createReportData($waybill,$waybillPayoff){
  418. /** @var Waybill $waybill */
  419. $waybill->loadMissing(["order.owner"]);
  420. return [
  421. "type"=>$waybill->type,
  422. "waybill_number"=>$waybill->waybill_number,
  423. "owner_name"=>$waybill->order->owner->name ?? ($waybill->owner->name ?? null),
  424. "wms_bill_number"=>$waybill->wms_bill_number,
  425. "source_bill"=>$waybill->source_bill,
  426. "origination"=>$waybill->origination,
  427. "destination"=>$waybill->order->address ?? $waybill->destination,
  428. "recipient"=>$waybill->order->consignee_name ?? $waybill->recipient,
  429. "recipient_mobile"=>$waybill->order->consignee_phone ?? $waybill->recipient_mobile,
  430. "charge"=>$waybill->charge,
  431. "collect_fee"=>$waybill->collect_fee,
  432. "ordering_remark"=>$waybill->ordering_remark,
  433. "carrier_name"=>$waybill->logistic->name ?? null,
  434. "carrier_bill"=>$waybill->carrier_bill,
  435. "origination_city_name"=>$waybill->originationCity ? $waybill->originationCity->name : null,
  436. "destination_city_name"=>$waybill->order->city ?? ($waybill->destinationCity->name ?? null),
  437. "warehouse_weight"=>$waybill->warehouse_weight.($waybill->warehouseWeightUnit ? $waybill->warehouseWeightUnit->name : ''),
  438. "carrier_weight"=>$waybill->carrier_weight.($waybill->carrierWeightUnit ? $waybill->carrierWeightUnit->name : ''),
  439. "warehouse_weight_other"=>$waybill->warehouse_weight_other.($waybill->warehouseWeightUnitOther ? $waybill->warehouseWeightUnitOther->name : ''),
  440. "carrier_weight_other"=>$waybill->carrier_weight_other.($waybill->carrierWeightUnitOther ? $waybill->carrierWeightUnitOther->name : ''),
  441. "car_type_name"=>$waybill->carType ? $waybill->carType->name : null,
  442. "fee"=>$waybill->fee,
  443. "pick_up_fee"=>$waybill->pick_up_fee,
  444. "other_fee"=>$waybill->other_fee,
  445. "dispatch_remark"=>$waybill->dispatch_remark,
  446. "price_model_range_min"=>$waybill->priceModel ? $waybill->priceModel->range_min : null,
  447. "price_model_range_max"=>$waybill->priceModel ? $waybill->priceModel->range_max : null,
  448. "price_model_unit_price"=>$waybill->priceModel ? $waybill->priceModel->unit_price : null,
  449. "price_model_base_fee"=>$waybill->priceModel ? $waybill->priceModel->base_fee : null,
  450. "price_model_initial_weight"=>$waybill->priceModel ? $waybill->priceModel->initial_weight : null,
  451. "car_owner_info"=>$waybill->car_owner_info,
  452. "status"=>$waybill->status,
  453. "mileage"=>$waybill->mileage,
  454. 'amount'=>$waybill->amount.($waybill->amountUnit ? $waybill->amountUnit->name : ''),
  455. "inquire_tel"=>$waybill->inquire_tel,
  456. "other_charge"=>$waybill->other_charge,
  457. "other_charge_remark"=>$waybill->other_charge_remark,
  458. "deliver_at"=>$waybill->deliver_at,
  459. "created_at"=>$waybill->created_at,
  460. "auditLog_user_name"=>Auth::user()['name'],
  461. "total_expense"=>$waybillPayoff->total_expense,
  462. "total_receivable"=>$waybillPayoff->total_receivable,
  463. "gross_margin"=>$waybillPayoff->gross_margin,
  464. "gross_profit_rate"=>$waybillPayoff->gross_profit_rate,
  465. ];
  466. }
  467. public function upload(Request $request){
  468. $this->gate("运输管理-运单-图片上传");
  469. $files=$request->file("files");
  470. if (!$files)$this->error("未传递照片");
  471. $id=$request->input('id');
  472. $waybill=Waybill::query()->find($id);
  473. if (!$waybill)$this->error("未找到该运单!");
  474. $res = [];
  475. foreach ($files as $file){
  476. if (!$file->isValid()){
  477. return ['success'=>false,'error'=>"找不到照片!"];
  478. }
  479. $tmpFile = $file->getRealPath();
  480. if (! is_uploaded_file($tmpFile)) {
  481. return ['success'=>false,'error'=>"文件错误!"];
  482. }
  483. $fileExtension=$file->getClientOriginalExtension();
  484. // 5.存储, 生成一个随机文件名
  485. $fileName = date('ymd').'-'.Uuid::uuid1();//thumbnail common bulky
  486. $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$fileExtension);
  487. $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$fileExtension);
  488. $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$fileExtension);
  489. $result=move_uploaded_file ($tmpFile ,$bulkyName);
  490. if ($result){
  491. $img=Image::make($bulkyName);
  492. if ($img->height() > $img->width())
  493. $img->heighten(250)->save($commonName);
  494. else $img->widen(250)->save($commonName);
  495. $img->heighten(28)->save($thumbnailName);
  496. /** @var UploadFile|\stdClass $uploadFile */
  497. $uploadFile=new UploadFile([
  498. "table_name"=>"waybills",
  499. "table_id"=>$waybill->id,
  500. "url"=>'/files/'.$fileName,
  501. "type"=>$fileExtension,
  502. ]);
  503. if ($uploadFile->save())
  504. app('LogService')->log(__CLASS__,'运输图片上传',json_encode($request),Auth::user()['id']);
  505. $res[] = $uploadFile;
  506. }else $this->error("图片存储失败,检查服务器状态");
  507. }
  508. $this->success($res);
  509. }
  510. //批量上传图片
  511. public function batchUploadImages()
  512. {
  513. $this->gate("运输管理-运单-图片上传");
  514. ini_set('max_execution_time',1000);
  515. ini_set('memory_limit','100M');
  516. $images = request("images");
  517. $errors = [];
  518. $number = [];
  519. $mapping = [];
  520. $type = ["jpg","png","gif","jfif","pjpeg","jpeg","webp"];
  521. foreach ($images as $index => $image){
  522. $arr = explode(".",$image["name"]);
  523. $suffix = $arr[count($arr)-1];
  524. unset($arr[count($arr)-1]);
  525. $name = implode(".",$arr);
  526. if (array_search(strtolower($suffix),$type) === false){
  527. $errors[] = "“".$name."”格式错误";
  528. unset($images[$index]);
  529. continue;
  530. }
  531. $images[$index]["suffix"] = $suffix;
  532. $num = trim(rtrim($name,".".$suffix));
  533. $number[] = $num;
  534. $mapping[$num] = $index;
  535. }
  536. $waybills = Waybill::query()->select("id","source_bill")->whereIn('source_bill',$number)->get();
  537. foreach (array_diff($number,array_column($waybills->toArray(),"source_bill")) as $diff){
  538. $errors[] = "“".$diff."”不存在运单";
  539. unset($images[$mapping[$diff]]);
  540. }
  541. $insert = [];
  542. foreach ($waybills as $waybill){
  543. $image = $images[$mapping[$waybill->source_bill]];
  544. $fileName = date('ymd').'-'.Uuid::uuid1();
  545. $suffix = $image["suffix"];
  546. $thumbnailName=storage_path('app/public/files/'.$fileName.'-thumbnail.'.$suffix);
  547. $commonName=storage_path('app/public/files/'.$fileName.'-common.'.$suffix);
  548. $bulkyName=storage_path('app/public/files/'.$fileName.'-bulky.'.$suffix);
  549. preg_match('/^(data:\s*image\/(\w+);base64,)/',$image["src"],$res);
  550. $base64_img=base64_decode(str_replace($res[1],'', $image["src"]));
  551. Storage::put('public/files/'.$fileName.'-bulky.'.$suffix,$base64_img);
  552. $img=Image::make($bulkyName);
  553. if ($img->height() > $img->width())
  554. $img->heighten(250)->save($commonName);
  555. else $img->widen(250)->save($commonName);
  556. $img->heighten(28)->save($thumbnailName);
  557. $insert[] = [
  558. "table_name"=>"waybills",
  559. "table_id"=>$waybill->id,
  560. "url"=>'/files/'.$fileName,
  561. "type"=>strtolower($suffix),
  562. ];
  563. }
  564. if ($insert)UploadFile::query()->insert($insert);
  565. $waybills->load("uploadFiles");
  566. $this->success(["errors"=>$errors,"data"=>$waybills]);
  567. }
  568. //删除照片
  569. public function deleteImg(Request $request){
  570. $this->gate("运输管理-运单-图片删除");
  571. $query=UploadFile::query()->where('table_name','waybills');
  572. if ($request->input("url"))$query = $query->where('table_id',$request->input("id"))->where("url",$request->input("url"));
  573. else $query = $query->whereIn('table_id',$request->input("id"));
  574. foreach ($query->get() as $uploadFile){
  575. $bulky=storage_path('app/public/'.$uploadFile->url.'-bulky.'.$uploadFile->type);
  576. $common=storage_path('app/public/'.$uploadFile->url.'-common.'.$uploadFile->type);
  577. $thumbnail=storage_path('app/public/'.$uploadFile->url.'-thumbnail.'.$uploadFile->type);
  578. if (file_exists($bulky) && file_exists($common) && file_exists($thumbnail)){
  579. unlink($bulky);unlink($common);unlink($thumbnail);
  580. }
  581. }
  582. $query->delete();
  583. app('LogService')->log(__METHOD__,'图片删除',json_encode($request),Auth::user()['id']);
  584. $this->success();
  585. }
  586. public function export(){
  587. $this->gate('运输管理-运单-查询');
  588. if (request("checkAllSign")){
  589. request()->offsetUnset("checkAllSign");
  590. $waybills = app('waybillService')->get(request()->input());
  591. }else $waybills = app('waybillService')->get(["id"=>request("data")]);
  592. /** @var Collection $waybills */
  593. $row = [
  594. "运单类型", "货主", "上游单号", "wms订单号", "运单号", "运输收费",
  595. "其他收费", "其他收费备注", "始发地", "目的地","下单备注", "承运商", "承运商单号",
  596. "仓库计抛", "承运商计抛", "仓库计重", "承运商计重", "车型", "车辆信息",
  597. "计件", "里程数", "运费(元)", "提货费(元)", "其他费用(元)", "发货时间",
  598. "调度备注", "创建时间"
  599. ];
  600. $list = [];
  601. $waybills->each(function ($waybill)use(&$list){
  602. $list[] = [
  603. $waybill->type,
  604. $waybill->order->owner->name ?? ($waybill->owner->name ?? ""),
  605. $waybill->source_bill,
  606. $waybill->wms_bill_number,
  607. $waybill->waybill_number,
  608. $waybill->charge,
  609. $waybill->other_charge,
  610. $waybill->other_charge_remark,
  611. $waybill->origination,
  612. $waybill->order->address ?? $waybill->destination,
  613. $waybill->ordering_remark,
  614. $waybill->logistic->name ?? "",
  615. $waybill->carrier_bill,
  616. $waybill->warehouse_weight,
  617. $waybill->carrier_weight,
  618. $waybill->warehouse_weight_other,
  619. $waybill->carrier_weight_other,
  620. $waybill->car_type_name,
  621. $waybill->car_owner_info,
  622. $waybill->amount,
  623. $waybill->mileage,
  624. $waybill->fee,
  625. $waybill->pick_up_fee,
  626. $waybill->other_fee,
  627. $waybill->deliver_at,
  628. $waybill->dispatch_remark,
  629. $waybill->created_at,
  630. ];
  631. });
  632. return Export::make($row,$list,"运输记录单");
  633. }
  634. public function deliveringExport(Request $request){
  635. if ($request->checkAllSign){
  636. $param = $request->input();
  637. unset($param['checkAllSign']);
  638. $sql = app('waybillService')->getDeliveringSql($param);
  639. }else{
  640. $sql = app('waybillService')->getDeliveringSql(['id'=>$request->data]);
  641. }
  642. $e = new Export();
  643. $e->setMysqlConnection(config('database.connections.mysql.host'),
  644. config('database.connections.mysql.port'),config('database.connections.mysql.database')
  645. ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
  646. $e->setFileName("发运报表");
  647. return $e->sql($sql,[
  648. "created_at"=>"日期","carrier_name"=>"承运商",
  649. "waybill_number"=>"宝时运单号","origination"=>"提货仓",
  650. "owner_name"=>"货主","warehouse_weight_other"=>"预估重量",
  651. "warehouse_weight"=>"预估体积","status"=>"状态",
  652. "carrier_bill"=>"专线运单号","inquire_tel"=>"查件电话",
  653. "amount"=>"件数","carrier_weight_other"=>"重量",
  654. "carrier_weight"=>"体积"
  655. ])->direct();
  656. }
  657. //发运
  658. public function delivering(Request $request){
  659. if (!Auth::user())return view('exception.login');
  660. $waybills= app('waybillService')->paginate($request->input());
  661. if (!Auth::user()->isSuperAdmin()){
  662. $carriersUsers=DB::table('carrier_user')->where('user_id',Auth::id())->get();
  663. $carrierIds=array_column($carriersUsers->toArray(),'logistic_id');
  664. $waybills=$waybills->whereIn("logistic_id",$carrierIds);
  665. }
  666. return view('transport.waybill.delivering',compact('waybills'));
  667. }
  668. //承运商提交
  669. public function storeCarrierBill(Request $request){
  670. $errors=Validator::make($request->input(),[
  671. 'id'=>'required|integer',
  672. 'carrier_bill'=>'required',
  673. 'inquire_tel'=>'nullable',
  674. 'amount'=>'nullable|integer',
  675. 'carrier_weight'=>'required_without:carrier_weight_other|nullable|numeric',
  676. 'carrier_weight_other'=>'required_without:carrier_weight|nullable|numeric',
  677. ],[
  678. 'required'=>':attribute 为必填项',
  679. 'integer'=>':attribute 应为整数',
  680. 'numeric'=>':attribute 应为数字',
  681. 'required_with'=>':attribute 重量与体积至少存在一项',
  682. ],[
  683. 'carrier_bill'=>'专线运单号',
  684. 'inquire_tel'=>'查件电话',
  685. 'amount'=>'件数',
  686. 'carrier_weight'=>'体积',
  687. 'carrier_weight_other'=>'重量',
  688. ])->errors();
  689. if (count($errors)>0)return ["errors"=>$errors];
  690. $waybill=Waybill::query()->find($request->input('id'));
  691. if (!$waybill)return ["error"=>"未找到该运单!"];
  692. $waybill->fill($request->input());
  693. $waybill->update();
  694. return $waybill;
  695. }
  696. protected function validatorWaybill(Request $request,$id){
  697. if ($id){$wms_bill_number=$id;};
  698. $validator=Validator::make($request->input(),[
  699. 'owner_id'=>'required_without:order_id',
  700. 'wms_bill_number'=>['nullable','max:50',isset($wms_bill_number)?"unique:waybills,wms_bill_number,$wms_bill_number":'unique:waybills,wms_bill_number'],
  701. 'origination'=>'required|max:255',
  702. 'destination'=>'required_without:order_id|max:255',
  703. 'recipient'=>'required_without:order_id|max:50',
  704. 'recipient_mobile'=>['required_without:order_id','regex:/^(\d{7,11})|(1[3|4|5|7|8][0-9]\d{4,8})$/'],
  705. 'charge'=>'nullable|min:0|max:999999|numeric',
  706. 'collect_fee'=>'nullable|min:0|numeric',
  707. ],[
  708. 'required'=>':attribute 为必填项',
  709. 'required_without'=>':attribute 为必填项',
  710. 'alpha_num'=>':attribute 应为字母或数字',
  711. 'max'=>':attribute 字符过多或输入值过大',
  712. 'regex'=>':attribute 输入有误',
  713. 'integer'=>':attribute 应为整数',
  714. 'min'=>':attribute 不得为负',
  715. 'numeric'=>':attribute 应为数字',
  716. 'unique'=>':attribute 已存在',
  717. ],[
  718. 'owner_id'=>'货主',
  719. 'wms_bill_number'=>'WMS单号',
  720. 'origination'=>'始发地',
  721. 'destination'=>'目的地',
  722. 'recipient'=>'收件人',
  723. 'recipient_mobile'=>'收件人电话',
  724. 'charge'=>'收费',
  725. 'collect_fee'=>'到付金额',
  726. ]);
  727. return $validator;
  728. }
  729. protected function validatorWaybillDispatch(Request $request,$id){
  730. $rule=[
  731. 'logistic_id'=>'required_without:order_id|integer',
  732. 'carrier_bill'=>"sometimes|nullable|max:50|unique:waybills,carrier_bill,$id",
  733. 'fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  734. 'other_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  735. 'charge'=>'sometimes|nullable|min:0|numeric|max:999999',
  736. 'mileage'=>'nullable|numeric|min:0',
  737. 'amount'=>'numeric|min:0',
  738. 'amount_unit_id'=>'required',
  739. 'origination_city_id'=>'sometimes|required|integer',
  740. 'destination_city_id'=>'sometimes|required_without:order_id|integer',
  741. 'warehouse_weight_other'=>'sometimes|nullable|min:0|numeric|max:999999',
  742. 'warehouse_weight_unit_id_other'=>'sometimes|required_with:warehouse_weight_other|nullable|integer',
  743. 'pick_up_fee'=>'sometimes|nullable|min:0|numeric|max:999999',
  744. 'warehouse_weight'=>'sometimes|nullable|min:0|numeric|max:999999',
  745. 'warehouse_weight_unit_id'=>'sometimes|required_with:warehouse_weight|nullable|integer',
  746. 'carrier_weight'=>'sometimes|nullable|min:0|numeric|max:999999',
  747. 'carrier_weight_unit_id'=>'sometimes|required_with:carrier_weight',
  748. 'carrier_weight_other'=>'sometimes|nullable|min:0|numeric|max:999999',
  749. 'carrier_weight_unit_id_other'=>'sometimes|required_with:carrier_weight_other',
  750. ];
  751. if ($request->type == '专线'){
  752. $rule['origination_city_id']='required|integer';
  753. $rule['destination_city_id']='required_without:order_id|integer';
  754. }
  755. $validator=Validator::make($request->input(),$rule,[
  756. 'required'=>':attribute 为必填项',
  757. 'required_without'=>':attribute 为必填项',
  758. 'alpha_num'=>':attribute 应为字母或数字',
  759. 'max'=>':attribute 字符过多或输入值过大',
  760. 'min'=>':attribute 不得为负',
  761. 'numeric'=>':attribute 应为数字',
  762. 'unique'=>':attribute 已存在',
  763. 'required_with'=>':attribute 未填',
  764. 'integer'=>':attribute 必须为数字',
  765. ],[
  766. 'logistic_id'=>'承运商',
  767. 'carrier_bill'=>'承运商单号',
  768. 'fee'=>'运费',
  769. 'other_fee'=>'其他费用',
  770. 'charge'=>'收费',
  771. 'mileage'=>'里程数',
  772. 'amount'=>'计数',
  773. 'amount_unit_id'=>'计数单位',
  774. 'warehouse_weight'=>'仓库计数(抛)',
  775. 'carrier_weight'=>'承运商计数(抛)',
  776. 'pick_up_fee'=>'提货费',
  777. 'destination_city_id'=>'目的市',
  778. 'carrier_weight_unit_id'=>'承运商计数单位',
  779. 'warehouse_weight_unit_id'=>'仓库计数单位',
  780. 'warehouse_weight_other'=>'仓库计数二',
  781. 'carrier_weight_other'=>'承运商计数二',
  782. 'warehouse_weight_unit_id_other'=>'仓库技数单位二',
  783. 'carrier_weight_unit_id_other'=>'承运商计数单位二',
  784. ]);
  785. return $validator;
  786. }
  787. public function addCounty(){
  788. $name = app("RegionService")->formatName(request("name"),2);
  789. if (!$name)$this->error("非法参数");
  790. $region = Region::query()->firstOrCreate(["name"=>$name,"type"=>2,"parent_id"=>request("province")]);
  791. $this->success($region);
  792. }
  793. // 运单删除 软删除
  794. public function destroy(int $id){
  795. if(!GAte::allows('运输管理-运单-删除')){return['success'=>0,'status'=>'没有权限'];}
  796. if(is_null($id)){return ['success'=>'0','status'=>'传入id为空'];}
  797. $result = Waybill::where('id',$id)->delete();
  798. WaybillAuditLog::query()->create([
  799. 'waybill_id'=>$id,
  800. 'audit_stage'=>'删除运单',
  801. 'user_id'=>Auth::id(),
  802. ]);
  803. return ['success'=>$result,'status'=>$result];
  804. }
  805. // 回收站
  806. public function recycle(Request $request){
  807. if(!Gate::allows('运输管理-运单-删除')){return redirect('/');}
  808. $paginate = $request->input('paginate')??50;
  809. /** @var Collection $waybills */
  810. $waybills = Waybill::query()->with(['owner','order.owner','logistic','amountUnit','warehouseWeightUnit','carrierWeightUnit',
  811. 'warehouseWeightUnitOther','carrierWeightUnitOther','carType','waybillAuditLogs' => function ($query) {
  812. /** @var Builder $query */
  813. $query->with('user');
  814. }])->orderBy('deleted_at', 'DESC')->withTrashed()->whereNotNull('deleted_at')->paginate(50);
  815. $total = $waybills->count();
  816. $paginateParams = [];
  817. $paginateParams['paginate'] = $paginate;
  818. return view('transport.waybill.recycle',compact('waybills','total','paginateParams'));
  819. }
  820. // 软删除恢复
  821. public function apiRestoreSelected(Request $request){
  822. if(!Gate::allows('运输管理-运单-删除')){return ['success'=>'false','fail_info'=>'没有权限'];}
  823. $ids = $request->input('ids')??'';
  824. if($ids == ''){return ['success'=>'false','fail_info'=>'没有可恢复对象'];}
  825. $waybills = Waybill::withTrashed()->whereIn('id',$ids)->get();
  826. $waybills->each(function (Waybill $waybill){
  827. $waybill->restore();
  828. });
  829. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  830. foreach ($ids as $id) WaybillAuditLog::query()->create([
  831. 'waybill_id'=>$id,
  832. 'audit_stage'=>'恢复运单',
  833. 'user_id'=>Auth::id(),
  834. ]);
  835. return ['success'=>'true','waybills'=>$waybills];
  836. }
  837. // 修改运费
  838. public function changeFee(Request $request){
  839. if(!Gate::allows('运输管理-运单-运费')){return ['success'=>'false','fail_info'=>'没有权限'];}
  840. $wayBillId = $request->input('id');
  841. $waybillFee = $request->input('fee');
  842. if(is_null($wayBillId) or is_null($waybillFee)){
  843. return ['success'=>'false','fail_info'=>'参数异常'];
  844. }
  845. $result = Waybill::where('id',$wayBillId)->update(['fee'=>$waybillFee]);
  846. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  847. return ['success'=>$result,'status'=>$result];
  848. }
  849. // 修改运输收费
  850. public function changeCharge(Request $request){
  851. if(!Gate::allows('运输管理-运单-运单编辑')){return ['success'=>'false','fail_info'=>'没有权限'];}
  852. $wayBillId = $request->id;
  853. $waybillCharge = $request->input('charge');
  854. if(is_null($wayBillId) or is_null($waybillCharge)){
  855. return ['success'=>'false','fail_info'=>'参数异常'];
  856. }
  857. $result = Waybill::where('id',$wayBillId)->update(['charge'=>$waybillCharge]);
  858. app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  859. return ['success'=>$result,'status'=>$result];
  860. }
  861. // 置顶
  862. public function waybillOnTop(Request $request){
  863. $id = $request->input('id');
  864. $detail = $request->input('detail');
  865. if(!Gate::allows('运输管理-运单-置顶')){return ['success'=>'false','fail_info'=>'没有权限'];}
  866. if(is_null($id)){
  867. return ['success'=>'false','fail_info'=>'传参错误'];
  868. }
  869. $wayontop = WaybillOnTop::withTrashed()->where('waybill_id',$id);
  870. if(count($wayontop->get()) == 0){
  871. $wayontop = WaybillOnTop::create(['waybill_id'=>$id,'remark'=>$detail]);
  872. $result = $wayontop->save();
  873. }else{
  874. $result = WaybillOnTop::withTrashed()->where('waybill_id',$id)->restore();
  875. }
  876. return ['success'=>$result,'status'=>$result];
  877. }
  878. // 取消置顶
  879. public function cancelOnTop(Request $request){
  880. $id = $request->input('id');
  881. if(!Gate::allows('运输管理-运单-置顶')){return ['success'=>'false','fail_info'=>'没有权限'];}
  882. if(is_null($id)){
  883. return ['success'=>'false','fail_info'=>'传参错误'];
  884. }
  885. $result = WaybillOnTop::where('waybill_id',$id)->forceDelete();
  886. return ['success'=>$result,'status'=>$result];
  887. }
  888. //同步刷新仓库计重
  889. public function refreshWaveHouseWeight(Request $request){
  890. $wms_bill_number=$request->input('wms_bill_number');
  891. if(is_null($wms_bill_number)) return ['success'=>false,'fail_info'=>'传参错误'];
  892. $waybills=DB::connection('oracle')->table('DOC_ORDER_DETAILS')->where('orderno',$wms_bill_number)->get();
  893. if($waybills->isEmpty()) return ['success'=>false,'fail_info'=>'传参错误'];
  894. $warehouseWeight=0;
  895. foreach ($waybills as $waybill){
  896. if ($waybill->grossweight) $warehouseWeight += $waybill->grossweight;
  897. if (!$waybill->grossweight&& $waybill->netweight) $warehouseWeight +=$waybill->netweight;
  898. }
  899. $warehouseWeight=round($warehouseWeight,2);
  900. $waybill=Waybill::where('wms_bill_number',$wms_bill_number)->first();
  901. if ($warehouseWeight!=0){
  902. if ($waybill['warehouse_weight_other']!=$warehouseWeight){
  903. $waybill['warehouse_weight_other']=$warehouseWeight;
  904. $waybill->update();
  905. app('LogService')->log(__METHOD__,'刷新仓库计重'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  906. }
  907. }else{
  908. $warehouseWeight=$waybill['warehouse_weight_other'];
  909. }
  910. return ['success'=>true,'warehouseWeight'=>$warehouseWeight];
  911. }
  912. //寻找订单
  913. public function seekOrder()
  914. {
  915. $this->gate("运输管理");
  916. $code = request("code");
  917. if (!$code)$this->error("暂无绑定订单");
  918. $order = app("OrderService")->first(["code"=>$code]);
  919. if (!$order)$this->error("暂无绑定订单");
  920. $this->success($order);
  921. }
  922. //按日输入专线费
  923. public function dailyBilling(Request $request): array
  924. {
  925. if(!Gate::allows('运输管理-运单-按日计算专线费')){return ['success'=>false,'message'=>'没有权限'];}
  926. $dailyBilling=$request->input('param');
  927. $waybills=app('waybillService')->dailyBilling($dailyBilling);
  928. if ($waybills=='无数据')return ['success'=>false,'message'=>'当前选定发货日期没有任何记录'];
  929. if (!isset($waybills))return ['success'=>false,'message'=>'该日有记录未填写重量'];
  930. return ['success'=>true,'data'=>$waybills];
  931. }
  932. public function countPickUpFee(Request $request): array
  933. {
  934. if(!Gate::allows('运输管理-运单-查询')){ return ['success'=>false,'message'=>'没有权限']; }
  935. $param=$request->input('param');
  936. $waybills=app('waybillService')->get($param);
  937. $total_pick_up_fee=$waybills->sum('pick_up_fee');
  938. if ($total_pick_up_fee)$total_pick_up_fee=round($total_pick_up_fee);
  939. return ['success'=>true,'data'=>$total_pick_up_fee];
  940. }
  941. }