WaybillController.php 55 KB

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