WaybillController.php 50 KB

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