WaybillController.php 51 KB

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