CommodityController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commodity;
  4. use App\Imports\CommodityImport;
  5. use App\Owner;
  6. use App\Services\CommodityBarcodeService;
  7. use App\Services\CommodityService;
  8. use App\Services\OracleBasSkuService;
  9. use App\Services\OwnerService;
  10. use Exception;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Http\Response;
  14. use Illuminate\Support\Facades\Auth;
  15. use Illuminate\Support\Facades\Gate;
  16. use Illuminate\Support\Facades\Validator;
  17. use Maatwebsite\Excel\Facades\Excel;
  18. class CommodityController extends Controller
  19. {
  20. /**
  21. * Display a listing of the resource.
  22. *
  23. * @return Response
  24. */
  25. public function index()
  26. {
  27. if(!Gate::allows('商品信息-查询')){ return redirect(url('denied')); }
  28. $commodities=Commodity::query()->orderBy('id','desc')->paginate(50);
  29. return view('maintenance.commodity.index',['commodities'=>$commodities]);
  30. }
  31. /**
  32. * Show the form for creating a new resource.
  33. *
  34. * @return Response
  35. */
  36. public function create()
  37. {
  38. if(!Gate::allows('商品信息-录入')){ return redirect(url('denied')); }
  39. $ownerService=app(OwnerService::class);
  40. $owners = $ownerService->getIntersectPermitting();
  41. return view('maintenance.commodity.create',compact('owners'));
  42. }
  43. /**
  44. * Store a newly created resource in storage.
  45. *
  46. * @param Request $request
  47. * @return Response
  48. */
  49. public function store(Request $request)
  50. {
  51. if(!Gate::allows('商品信息-录入')){ return redirect(url('denied')); }
  52. $this->validatorCreate($request->all())->validate();
  53. $commodity=new Commodity($request->all());
  54. $commodity->save();
  55. $commodity->newBarcode($request->input('barcode'));
  56. app('LogService')->log(__METHOD__,'录入商品'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  57. return redirect('maintenance/commodity/create')->with('successTip',"成功录入商品信息:“{$request->input('name')}”");
  58. }
  59. protected function validatorCreate(array $data)
  60. {
  61. return Validator::make($data, [
  62. 'sku'=>['required', 'string', 'max:50'],
  63. 'name' => ['required', 'string', 'max:50'],
  64. 'barcode' => ['required', 'string', 'max:50'],
  65. 'owner_id' => ['required', 'string', 'max:50'],
  66. ]);
  67. }
  68. protected function validatorUpdate(array $data)
  69. {
  70. return Validator::make($data, [
  71. 'sku'=>['required', 'string', 'max:50'],
  72. 'name' => ['required', 'string', 'max:50'],
  73. 'barcode' => ['required', 'string', 'max:50'],
  74. 'owner_id' => ['required', 'string', 'max:50'],
  75. ]);
  76. }
  77. /**
  78. * Display the specified resource.
  79. *
  80. * @param Commodity $commodity
  81. * @return Response
  82. */
  83. public function show(Commodity $commodity)
  84. {
  85. //
  86. }
  87. /**
  88. * Show the form for editing the specified resource.
  89. *
  90. * @param Commodity $commodity
  91. * @return Response
  92. */
  93. public function edit(Commodity $commodity)
  94. {
  95. if(!Gate::allows('商品信息-编辑')){ return redirect(url('denied')); }
  96. $ownerService=app(OwnerService::class);
  97. $owners = $ownerService->getIntersectPermitting();
  98. return view('maintenance.commodity.edit',['commodity'=>$commodity,'owners'=>$owners]);
  99. }
  100. /**
  101. * Update the specified resource in storage.
  102. *
  103. * @param Request $request
  104. * @param Commodity $commodity
  105. * @return Response
  106. */
  107. public function update(Request $request, Commodity $commodity)
  108. {
  109. if(!Gate::allows('商品信息-编辑')){ return redirect(url('/')); }
  110. $this->validatorUpdate($request->all())->validate();
  111. $commodity->fill($request->all());
  112. $commodity->update();
  113. app('LogService')->log(__METHOD__,'修改商品信息'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
  114. return redirect('maintenance/commodity/')->with('successTip',"成功修改商品信息:“{$commodity['name']}”!");
  115. }
  116. /**
  117. * Remove the specified resource from storage.
  118. *
  119. * @param Commodity $commodity
  120. * @return array|Response
  121. * @throws Exception
  122. */
  123. public function destroy(Commodity $commodity)
  124. {
  125. if(!Gate::allows('商品信息-删除')){ return redirect(url('/')); }
  126. app('LogService')->log(__METHOD__,__FUNCTION__,$commodity->toJson(),Auth::user()['id']);
  127. $re=$commodity->delete();
  128. return ['success'=>$re];
  129. }
  130. public function import()
  131. {
  132. return view('maintenance.commodity.import');
  133. }
  134. public function isExist(Request $request)
  135. {
  136. if (app('CommodityService')->isExist($request->input()))
  137. return ["success"=>true];
  138. else return ["success"=>false];
  139. }
  140. public function importExcel(Request $request)
  141. {
  142. $isOverride = $request->input('isOverride');
  143. try{
  144. ini_set('max_execution_time',2500);
  145. ini_set('memory_limit','1526M');
  146. $extension=$request->file()['file']->getClientOriginalExtension();
  147. $extension[0] = strtoupper($extension[0]);
  148. Excel::import(new CommodityImport($isOverride), $request->file()['file']->path(),null,$extension);
  149. return '<h1 class="text-success">导入成功</h1>';
  150. }catch (Exception $e){
  151. if(strstr($e->getMessage(),'No ReaderType')){return '<h1 class="text-danger">没有上传写权限,请修改php.ini 对应的upload_tmp_dir 目录或其权限</h1>'.$e->getMessage();}
  152. if(strstr($e->getMessage(),'SQLSTATE')){return '<h1 class="text-danger">数据库插入错误,数据不支持,可能有重复或异常字符</h1>'.$e->getMessage();}
  153. if(strstr(strtolower($e->getMessage()),'sku')){return '<h1 class="text-danger">请在第一行将 商品编码 字段名改成“SKU”,不支持中文字段名,并且必须有该列</h1>'.$e->getMessage();}
  154. if(strstr(strtolower($e->getMessage()),'name')){return '<h1 class="text-danger">请在第一行将 商品名称 字段名改成“name”,不支持中文字段名,并且必须有该列</h1>'.$e->getMessage();}
  155. if(strstr(strtolower($e->getMessage()),'barcode')){return '<h1 class="text-danger">请在第一行将 商品条码 字段名改成“barcode”,不支持中文字段名,并且必须有该列</h1>'.$e->getMessage();}
  156. if(strstr(strtolower($e->getMessage()),'owner')){return '<h1 class="text-danger">请在第一行将 货主 字段名改成“owner”,不支持中文字段名,并且必须有该列</h1>'.$e->getMessage();}
  157. return '<h1 class="text-danger">失败</h1>'.$e->getMessage();
  158. }
  159. }
  160. public function apiGetCommodityByBarcode(Request $request)
  161. {
  162. $barcode=$request->input('barcode');
  163. $owner_id=$request->input('owner_id');
  164. // $name = '';
  165. $commodity=[];
  166. if($barcode){
  167. $commodity=Commodity::query()->where('owner_id',$owner_id)->whereHas('barcodes', function (Builder $query)use($barcode){
  168. $query->where('code',$barcode);
  169. })->first();
  170. if (!$commodity)$commodity=Commodity::query()->whereNotNull('owner_id')->whereHas('barcodes', function (Builder $query)use($barcode){
  171. $query->where('code',$barcode);
  172. })->first();
  173. // if($commodity&&$commodity['name']) $name=$commodity['name'];
  174. }
  175. return ['success'=>'true','commodity'=>$commodity];
  176. }
  177. public function syncWMS(Request $request){
  178. if(!Gate::allows('商品信息-编辑')){ return redirect(url('/')); }
  179. $owner_code = $request->owner_code ?? false;
  180. $owner_id = $request->owner_id ?? false;
  181. if (!$owner_code || !$owner_id)return ['success'=>false, 'data'=>"未指定货主"];
  182. $this->syncOwnerCommodities($owner_id,$owner_code);
  183. return ['success'=>true];
  184. }
  185. //通过货主与SKU同步 WMS商品至本地 有则比对修正,无则录入
  186. public function syncOwnerCommodities($owner_id,$owner_code,$sku = null, $barcode = null){
  187. ini_set('max_execution_time', '0');
  188. $params = ['customerid' => $owner_code];
  189. if ($sku) $params['sku'] = $sku;
  190. if ($barcode) $params['alternate_sku1'] = $barcode;
  191. /** @var OracleBasSkuService $oracleBasSkuService */
  192. $oracleBasSkuService = app('OracleBasSkuService');
  193. $amount = 1000;
  194. $sum = $oracleBasSkuService->count($params);
  195. $number = ceil($sum/$amount);
  196. for ($i = 0;$i<$number; $i++){
  197. $wmsCommodities = $oracleBasSkuService->getPiece($params,($i*$amount),$amount);
  198. if (!$wmsCommodities)continue;
  199. $this->execute($owner_id,$wmsCommodities);
  200. }
  201. }
  202. private function execute($owner_id,array $wmsCommodities){
  203. if (count($wmsCommodities) < 1)return;
  204. $today = date('Y-m-d H:i:s');
  205. $map = [];
  206. $skus = [];
  207. foreach ($wmsCommodities as $index => $wmsCommodity){
  208. $map[$wmsCommodity->sku] = $index;
  209. $skus[] = $wmsCommodity->sku;
  210. $trimSku = rtrim($wmsCommodity->sku,"*");
  211. if ($trimSku != $wmsCommodity->sku){
  212. $skus[] = $trimSku;
  213. $map[$trimSku] = $index;
  214. }
  215. }
  216. /** @var CommodityService $commodityService */
  217. $commodityService = app('CommodityService');
  218. /** @var CommodityBarcodeService $commodityBarcodeService */
  219. $commodityBarcodeService = app('CommodityBarcodeService');
  220. $commodities = $commodityService->getOwnerCommodities(['owner_id' => $owner_id, 'sku'=>$skus]);
  221. $updateCommodities = [];
  222. $updateCommodities[] = [
  223. 'id', 'sku', 'name', 'length', 'width', 'height', 'volumn',"pack_spec","remark"
  224. ];
  225. $barcodeMap = [];
  226. $commoditiesId = [];
  227. $barcodes = [];
  228. foreach ($commodities as $commodity){
  229. if (!isset($map[$commodity->sku]))continue;
  230. $wms = $wmsCommodities[$map[$commodity->sku]];
  231. $trimSku = rtrim($wms->sku,"*");
  232. if (($commodity->sku != $trimSku) || ($commodity->length != $wms->skulength)
  233. || ($commodity->width != $wms->skuwidth) || ($commodity->name != $wms->descr_c)
  234. || ($commodity->height != $wms->skuhigh) || ($commodity->volumn != $wms->cube)
  235. || ($commodity->pack_spec === null)){
  236. $updateCommodities[] = [
  237. 'id'=>$commodity->id,
  238. 'sku'=>$trimSku,
  239. 'name' => $wms->descr_c,
  240. 'length' => $wms->skulength,
  241. 'width' => $wms->skuwidth,
  242. 'height' => $wms->skuhigh,
  243. 'volumn' => $wms->cube,
  244. "pack_spec" => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
  245. 'remark' => $wms->notes,
  246. ];
  247. }
  248. if ($wms->alternate_sku1){
  249. $wmsCode = rtrim($wms->alternate_sku1,"*");
  250. $barcodeMap[$wmsCode] = $commodity->id;
  251. $barcodes[] = $wmsCode;
  252. }
  253. if ($wms->alternate_sku2){
  254. $wmsCode = rtrim($wms->alternate_sku2,"*");
  255. $barcodeMap[$wmsCode] = $commodity->id;
  256. $barcodes[] = $wmsCode;
  257. }
  258. $commoditiesId[] = $commodity->id;
  259. unset($wmsCommodities[$map[$commodity->sku]]);
  260. if (isset($map[$wms->sku]))unset($map[$commodity->sku]);
  261. if (isset($map[$trimSku]))unset($map[$trimSku]);
  262. }
  263. unset($commodities,$skus);
  264. if (count($updateCommodities) > 1){
  265. $commodityService->batchUpdate($updateCommodities);
  266. app('LogService')->log(__METHOD__,"同步商品-批量更新",json_encode($updateCommodities));
  267. $commodityBarcodes = $commodityBarcodeService->get(['commodity_id'=>$commoditiesId, 'code'=>$barcodes]);
  268. unset($commoditiesId,$barcodes);
  269. foreach ($commodityBarcodes as $barcode){
  270. if (($barcodeMap[$barcode->code] ?? false) && $barcodeMap[$barcode->code] == $barcode->commodity_id){
  271. unset($barcodeMap[$barcode->code]);
  272. }
  273. }
  274. if (count($barcodeMap) > 0){
  275. $barcodeInsert = [];
  276. foreach ($barcodeMap as $key => $value){
  277. $barcodeInsert[] = [
  278. 'commodity_id'=>$value,
  279. 'code' => $key,
  280. 'created_at' => $today
  281. ];
  282. }
  283. $commodityBarcodeService->insert($barcodeInsert);
  284. app('LogService')->log(__METHOD__,"同步商品-录入条码",json_encode($barcodeInsert));
  285. }
  286. }
  287. $createCommodities = [];
  288. $barcodeMap = [];
  289. $skus = [];
  290. $barcodes = [];
  291. $barcodeIndex = [];
  292. foreach ($map as $sku => $index){
  293. if (substr($sku,-1) == "*")continue;
  294. $wms = $wmsCommodities[$index];
  295. $createCommodities[] = [
  296. 'owner_id' => $owner_id,
  297. 'sku' => $wms->sku,
  298. 'name' => $wms->descr_c,
  299. 'length' => $wms->skulength,
  300. 'width' => $wms->skuwidth,
  301. 'height' => $wms->skuhigh,
  302. 'volumn' => $wms->cube,
  303. "pack_spec" => $wms->packid == 'STANDARD' ? 0 : explode("/",$wms->packid)[1],
  304. 'remark' => $wms->notes,
  305. "created_at" => $today,
  306. ];
  307. $barcodeMap[$wms->sku] = [];
  308. if ($wms->alternate_sku1){
  309. $code = rtrim($wms->alternate_sku1,"*");
  310. $barcodeMap[$wms->sku][] = $code;
  311. $barcodes[] = $code;
  312. $barcodeIndex[$code] = count($createCommodities) - 1;
  313. }
  314. if ($wms->alternate_sku2){
  315. $code = rtrim($wms->alternate_sku2,"*");
  316. $barcodeMap[$wms->sku][] = $code;
  317. $barcodes[] = $code;
  318. $barcodeIndex[$code] = count($createCommodities) - 1;
  319. }
  320. $skus[] = $wms->sku;
  321. unset($wmsCommodities[$index]);
  322. }
  323. if (count($barcodes) > 0){
  324. // ownerBarcodeSeekCommodityGet可指定第三个参数为true 默认无差别覆盖 如若指定该布尔值true代表仅覆盖SKU空值项
  325. $commodities = $commodityService->ownerBarcodeSeekCommodityGet(['id'=>$owner_id], $barcodes);
  326. $updateCommodities = [];
  327. $updateCommodities[] = [
  328. 'id', 'sku', 'name', 'length', 'width', 'height', 'volumn','pack_spec','remark'
  329. ];
  330. foreach ($commodities as $commodity){
  331. foreach ($commodity->barcodes as $code){
  332. if (isset($barcodeIndex[$code->code])){
  333. $goods = $createCommodities[$barcodeIndex[$code->code]] ?? false;
  334. if (!$goods)continue;
  335. $updateCommodities[] = [
  336. "id" => $commodity->id,
  337. 'sku'=>$goods['sku'],
  338. 'name' => $goods['name'],
  339. 'length' => $goods['length'],
  340. 'width' => $goods['width'],
  341. 'height' => $goods['height'],
  342. 'volumn' => $goods['volumn'],
  343. "pack_spec" => $goods["pack_spec"],
  344. 'remark' => $goods["notes"],
  345. ];
  346. unset($createCommodities[$barcodeIndex[$code->code]]);
  347. break;
  348. }
  349. }
  350. }
  351. if (count($updateCommodities) > 0){
  352. $commodityService->batchUpdate($updateCommodities);
  353. app('LogService')->log(__METHOD__,"同步商品-批量更新",json_encode($updateCommodities));
  354. }
  355. }
  356. if (count($createCommodities) > 0){
  357. $commodityService->insert($createCommodities);
  358. app('LogService')->log(__METHOD__,"同步商品-录入商品",json_encode($createCommodities));
  359. $commodities = $commodityService->get(['owner_id'=>$owner_id , 'sku'=>$skus]);
  360. $barcodeInsert = [];
  361. foreach ($commodities as $commodity){
  362. foreach ($barcodeMap[$commodity->sku] as $code){
  363. $barcodeInsert[] = [
  364. 'commodity_id'=>$commodity->id,
  365. 'code' => $code,
  366. 'created_at' => $today
  367. ];
  368. }
  369. }
  370. $commodityBarcodeService->insert($barcodeInsert);
  371. app('LogService')->log(__METHOD__,"同步商品-录入条码",json_encode($barcodeInsert));
  372. }
  373. }
  374. public function getCommodityApi(Request $request,CommodityService $service): array
  375. {
  376. $ownerService = new OwnerService();
  377. $owner = null;
  378. if($request->has("owner_id")){
  379. $owner = Owner::query()->where('id',$request->input("owner_id"))->first();
  380. } else {
  381. $ownerService->createByWmsCustomerIds([$request->input('owner_code')]);
  382. $owner = Owner::query()->where('code',$request['owner_code'])->first();
  383. }
  384. $service->syncWMSOrderCode($owner,[$request->input('sku')]);
  385. if (!$owner){
  386. return ['success' => false ,'message' => '货主未找到'];
  387. }
  388. $commodity = $service->getCommodityBy($owner,$request->input('sku'));
  389. if ($commodity){
  390. return ['success' => true,'data' => $commodity];
  391. }
  392. return ['success' => false,'message' => '请校验sku是否正确'];
  393. }
  394. }