Deliver.php 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  1. <?php
  2. namespace app\admin\controller;
  3. use app\admin\model\QcodeLarge;
  4. use app\admin\model\QcodeSmall;
  5. use app\common\controller\Backend;
  6. use app\admin\model\QcodeProduct;
  7. use app\admin\model\QcodeCompany;
  8. use app\admin\model\QcodeBach;
  9. use app\admin\model\QcodeExport;
  10. use fast\Arr;
  11. use PhpOffice\PhpSpreadsheet\IOFactory;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Exception;
  15. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  16. use app\admin\model\QcodeGoods;
  17. use think\Config;
  18. use think\Db;
  19. use think\Session;
  20. class Deliver extends Backend
  21. {
  22. /**
  23. * 首页
  24. */
  25. public function index()
  26. {
  27. return $this->view->fetch();
  28. }
  29. /**
  30. * 大件发货
  31. */
  32. public function lager()
  33. {
  34. $company = new QcodeCompany();
  35. $product = new QcodeProduct();
  36. $large = new QcodeLarge();
  37. $bach = new QcodeBach();
  38. $small = new QcodeSmall();
  39. $this->request->filter(['strip_tags', 'trim']);
  40. if (false === $this->request->isAjax()) {
  41. return $this->view->fetch();
  42. }
  43. if ($this->request->request('keyField')) {
  44. return $this->selectpage();
  45. }
  46. $userInfo = Session::get('admin');
  47. $where = ['delete_time' => ''];
  48. $filter = input('filter');
  49. $filter = json_decode($filter, true);
  50. $whereList = ['delete_time' => ''];
  51. if (isset($filter['matter_name'])) {
  52. $whereList['matter_no'] = $filter['matter_name'];
  53. }
  54. if (isset($filter['bach'])) {
  55. $whereList['bach_num'] = $filter['bach'];
  56. }
  57. if (isset($filter['manufacture_date'])) {
  58. $begin = substr($filter['manufacture_date'], 0, 19);
  59. $end = substr($filter['manufacture_date'], 22);
  60. $begin = (int)date('ymd', strtotime($begin));
  61. $end = (int)date('ymd', strtotime($end));
  62. $whereList['manufacture_date'] = ['between', [$begin, $end]];
  63. }
  64. // 查出相关 bach_id
  65. $bach_list = $bach->name($userInfo['company'].'_qcode_bach')->where($whereList)->column('_id');
  66. $bach_id = [];
  67. foreach ($bach_list as $v) {
  68. $id = substr(json_encode($v), 9, -2);
  69. $bach_id[] = $id;
  70. }
  71. // 获取分页参数
  72. $offset = input('offset', 0);
  73. $limit = input('limit', 10);
  74. // 获取所有大件记录用于总量判断
  75. $all_large_list = $large->name($userInfo['company'].'_qcode_large')
  76. ->where($where)
  77. ->where('l_status', 0)
  78. ->whereIn('bach_id', $bach_id)
  79. ->select();
  80. // 统计总数量
  81. $total = count($all_large_list);
  82. // 分页
  83. $large_list = array_slice($all_large_list, $offset, $limit);
  84. $list = [];
  85. foreach ($large_list as $k => $v) {
  86. $bach_detail = $bach->name($userInfo['company'].'_qcode_bach')->where('_id', $v['bach_id'])->find();
  87. // $num = (int)$bach_detail['num']; // 总张数
  88. // $small_num = (int)$bach_detail['small_num']; // 每箱张数
  89. // $boxes_per_pallet = (int)$bach_detail['total_boxes']; // 每托箱数
  90. // // 重新计算总箱数
  91. // $larger_num = $num / $small_num;
  92. // $full_pallets = floor($larger_num / $boxes_per_pallet);
  93. // $last_pallet_boxes = $larger_num % $boxes_per_pallet;
  94. $num = (float)$bach_detail['num'];
  95. $small_num = (float)$bach_detail['small_num'];
  96. $boxes_per_pallet = (float)$bach_detail['total_boxes'];
  97. $larger_num = $num / $small_num;
  98. $full_pallets = floor($larger_num / $boxes_per_pallet);
  99. $last_pallet_boxes = fmod($larger_num, $boxes_per_pallet); // 真正浮点取余
  100. $total_pallets = $full_pallets + ($last_pallet_boxes > 0 ? 1 : 0);
  101. // 当前是第几托(code中解析)
  102. $current_flow_str = substr($v['code'], 53, 6);
  103. $current_flow = (int) ltrim($current_flow_str, '0');
  104. $total_pallets = (int) $total_pallets;
  105. // 是否是最后一托
  106. $is_last = ($current_flow === $total_pallets) ? 1 : 0;
  107. // 修正箱数
  108. $total_boxes = $boxes_per_pallet;
  109. if ($is_last && $last_pallet_boxes > 0) {
  110. // 精准保留1位小数,不做四舍五入
  111. $total_boxes = number_format($last_pallet_boxes, 1, '.', '');
  112. // $total_boxes = $last_pallet_boxes;
  113. }
  114. $list[$k] = [
  115. 'id' => substr(json_encode($v['_id']), 9, -2),
  116. 'l_flow' => $current_flow,
  117. 'bach' => $bach_detail['bach_num'],
  118. 'num' => $num,
  119. 'small_num' => $small_num,
  120. 'order_ddbh' => $bach_detail['order_ddbh'],
  121. 'danwei' => $bach_detail['danwei'],
  122. 'cpbm' => $bach_detail['cpbm'],
  123. 'matter_name' => $bach_detail['matter_name'],
  124. 'total_boxes' => $total_boxes,
  125. 'tray_num' => $bach_detail['tray_num'],
  126. 'box_num' => $bach_detail['box_num'],
  127. 'pallet_height' => $bach_detail['pallet_height'],
  128. 'pallet_length' => $bach_detail['pallet_length'],
  129. 'pallet_width' => $bach_detail['pallet_width'],
  130. 'larger_num' => $larger_num,
  131. 'manufacture_date' => date('Y-m-d', strtotime('20' . $bach_detail['manufacture_date'])),
  132. 'code' => $v['code'],
  133. 'is_last' => $is_last,
  134. ];
  135. }
  136. return json(['total' => $total, 'rows' => $list]);
  137. }
  138. /**
  139. * 小件列表
  140. * @return \think\response\Json
  141. * @throws \think\Exception
  142. * @throws \think\db\exception\DataNotFoundException
  143. * @throws \think\db\exception\ModelNotFoundException
  144. * @throws \think\exception\DbException
  145. */
  146. public function smallList()
  147. {
  148. $userinfo = Session::get('admin');
  149. $lager = new QcodeLarge();
  150. $small = new QcodeSmall();
  151. if ($this->request->isAjax() === false){
  152. $this->error('请求错误');
  153. }
  154. $filter = input('filter');
  155. $filter = json_decode($filter,true);
  156. $order = input('order');
  157. $offset = input('offset');
  158. $limit = input('limit');
  159. $where = [
  160. 'delete_time' => '',
  161. ];
  162. if (isset($filter['large_id'])){
  163. $where['large_id'] =$filter['large_id'];
  164. }
  165. $smallList = $small->name($userinfo['company'].'_'.'qcode_small')
  166. ->where($where)
  167. ->skip($offset)
  168. ->limit($limit)
  169. ->select();
  170. $total = $small->name($userinfo['company'].'_'.'qcode_small')->where($where)->count();
  171. $list = [];
  172. foreach ($smallList as $k=>$v){
  173. $list[$k] = [
  174. 'code' => $v['code'],
  175. 'l_flow' => $v['l_flow'],
  176. 'print_num' => $v['p_nums'],
  177. 'status' => $v['status'],
  178. ];
  179. }
  180. return json(['total'=>$total,'rows'=>$list]);
  181. }
  182. /**
  183. * 导出发货
  184. * @return void
  185. * @throws \think\Exception
  186. * @throws \think\db\exception\DataNotFoundException
  187. * @throws \think\db\exception\ModelNotFoundException
  188. * @throws \think\exception\DbException
  189. */
  190. public function print()
  191. {
  192. $userinfo = Session::get('admin');
  193. $lager = new QcodeLarge();
  194. $bach = new QcodeBach();
  195. $small = new QcodeSmall();
  196. $export = new QcodeExport();
  197. if ($this->request->isAjax() === false){
  198. $this->error('请求错误');
  199. }
  200. $lager_id = input('lager_id');
  201. if ($lager_id === ''){
  202. $this->error('请至少选择一个大件');
  203. }
  204. $lagerId = [];
  205. if (strpos($lager_id,',') === false){
  206. $lagerId[0] = $lager_id;
  207. }else{
  208. $lagerId = explode(',',$lager_id);
  209. }
  210. $lager_num = count($lagerId);
  211. $bach_id = [];
  212. foreach ($lagerId as $k=>$v){
  213. $lagerList = $lager->name($userinfo['company'].'_'.'qcode_large')->where('_id',$v)->find();
  214. $bachList = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$lagerList['bach_id'])->find();
  215. $bach_id[$k] = substr(json_encode($bachList['_id']),9,-2);
  216. }
  217. $bach_id = array_unique($bach_id);
  218. $data = [];
  219. foreach ($bach_id as $k=>$v){
  220. $data[$k] = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$v)->field('matter_no')->find()['matter_no'];
  221. }
  222. $data = array_unique($data);
  223. if (count($data)>1){
  224. $this->error('请选择同一产品');
  225. }
  226. $n =0;
  227. foreach (explode(',',$lager_id) as $kk=>$vv){
  228. $n = $n + $small->name($userinfo['company'].'_'.'qcode_small')->where('large_id',$vv)->count();
  229. }
  230. // $bachDetail = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$bach_id[0])->find();
  231. $bachArray = $bach->name($userinfo['company'].'_'.'qcode_bach')
  232. ->where('_id', $bach_id[0])
  233. ->find();
  234. $bachDetail = $bachArray ? $bachArray->toArray() : [];
  235. if ($bachDetail['box_num'] === 1){
  236. $mater_type = 2;
  237. }else{
  238. $mater_type = 1;
  239. }
  240. $exportData = $this->exportdata($bach_id,$lager_id,$userinfo['company'],$lager_num,$n);
  241. $file_dir = $this->exportExcel($exportData);
  242. $row = [
  243. 'username' => $bachDetail['supplier_name'],//公司
  244. 'matter_no' => $bachDetail['matter_no'],
  245. 'order_ddbh' => $bachDetail['order_ddbh'],
  246. 'large_str' => $lager_id,
  247. 'status' => 0,
  248. 'bach_num' => $bachDetail['bach_num'],
  249. 'note' => '',
  250. 'user_id' => $userinfo['id'],
  251. 'create_time' => time(),
  252. 'file_dir' => $file_dir,
  253. 'company_id' => $userinfo['company'],
  254. 'large_num' => $lager_num,//你已选中 N 个大件【托盘数】
  255. 'small_num' => $n,//共包含了 N 个小件
  256. 'matter_name' => $bachDetail['matter_name'],//产品名称
  257. 'total_boxes' => $bachDetail['total_boxes'],//每托箱数
  258. 'tray_num' => $bachDetail['tray_num'],//每层箱数
  259. 'box_num' => $bachDetail['box_num'],//每托层数
  260. 'pallet_height' => $bachDetail['pallet_height'],//每托高度
  261. 'pallet_length' => $bachDetail['pallet_length'],//托盘规格
  262. 'pallet_width' => $bachDetail['pallet_width'],//托盘规格
  263. 'larger_num' => $bachDetail['larger_num'],//总箱数
  264. ];
  265. if ($bachDetail['box_num'] != 1){
  266. $row['num'] = $bachDetail['box_num'];
  267. $row['mater_type'] = 1;
  268. }else{
  269. $row['num'] = $bachDetail['s_weight'];
  270. $row['mater_type'] = 2;
  271. }
  272. $res = $export->save($row);
  273. if ($res === false){
  274. $this->error('发货失败');
  275. }
  276. $lager = new QcodeLarge();
  277. $lager->name($userinfo['company'].'_'.'qcode_large')->whereIn('_id',$lagerId)->update(['l_status'=>1]);
  278. $this->success('成功','',$file_dir);
  279. }
  280. /**
  281. * 表格数据处理
  282. * @param $bach_id
  283. * @param $large_str
  284. * @param $company
  285. * @param $large_num
  286. * @param $small_num
  287. * @return array
  288. * @throws \think\db\exception\DataNotFoundException
  289. * @throws \think\db\exception\ModelNotFoundException
  290. * @throws \think\exception\DbException
  291. */
  292. public function exportdata($bach_id,$large_str,$company,$large_num,$small_num)
  293. {
  294. $bach = new QcodeBach();
  295. $large = new QcodeLarge();
  296. $small = new QcodeSmall();
  297. $bachList = $bach->name($company . '_' . 'qcode_bach')->where('_id', $bach_id[0])->find();
  298. $data = [
  299. 'supplier_name' => $bachList['supplier_name'],
  300. 'supplier_no' => $bachList['supplier_code'],
  301. 'matter_name' => $bachList['matter_name'],
  302. 'matter_no' => $bachList['matter_no'],
  303. 'manufacture_date' => date('Y/m/d',strtotime('20'.$bachList['manufacture_date'])),
  304. 'print_date' => date('Y/m/d',strtotime('20'.$bachList['print_date'])),
  305. 'box_num' => $large_num,
  306. 'tray_num' => $bachList['tray_num'],
  307. 'small_num' => $small_num,
  308. 'l_reservation' => $bachList['l_reservation'],
  309. 's_reservation' => $bachList['s_reservation'],
  310. 'l_flow' => $bachList['l_flow'],
  311. 's_flow' => $bachList['s_flow'],
  312. 'l_weight' => 0,
  313. 's_weight' => $bachList['s_weight']/1000,
  314. 'code' => [],
  315. ];
  316. $large_id = explode(',', $large_str);
  317. foreach ($large_id as $k => $v) {
  318. $largeList = $large->name($company . '_' . 'qcode_large')->where('_id', $v)->find();
  319. $data['l_weight'] = $data['l_weight'] + (int)$largeList['l_weight']/100;
  320. $small_list = $small->name($company . '_' . 'qcode_small')->where('large_id', $v)->select();
  321. foreach ($small_list as $value) {
  322. $code = [
  323. 'large_code' => $largeList['code'],
  324. 'small_code' => $value['code'],
  325. ];
  326. array_push($data['code'],$code);
  327. }
  328. }
  329. return $data;
  330. }
  331. /**
  332. * 生成excel
  333. * @param $data
  334. * @return string
  335. * @throws Exception
  336. * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
  337. */
  338. public function exportExcel($data)
  339. {
  340. $objexcel = new Spreadsheet();
  341. $sheet = $objexcel->getActiveSheet();
  342. //设置全局单元格垂直居中
  343. $objexcel->getDefaultStyle()->getAlignment()->setVertical(Alignment::HORIZONTAL_CENTER);
  344. //设置全局单元格水平居中
  345. $objexcel->getDefaultStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  346. //设置全局单元格自动换行
  347. $objexcel->getDefaultStyle()->getAlignment()->setWrapText(true);
  348. //设置单元格宽度
  349. $sheet->getDefaultColumnDimension()->setWidth(50);
  350. //设置表头
  351. $sheet->setCellValue('A1', '文件流水号');
  352. $sheet->setCellValue('A2', '订单号');
  353. $sheet->setCellValue('A3', '供应商');
  354. $sheet->setCellValue('A4', '供应商代码');
  355. $sheet->setCellValue('A5', '物料名称');
  356. $sheet->setCellValue('A6', '物料代码');
  357. $sheet->setCellValue('A7', '生产日期');
  358. $sheet->setCellValue('A8', '打码日期');
  359. $sheet->setCellValue('A9', '大件数量');
  360. $sheet->setCellValue('A10', '托盘小件数量');
  361. $sheet->setCellValue('A11', '小件总数量');
  362. $sheet->setCellValue('C3', '大件预留码');
  363. $sheet->setCellValue('C5', '小件预留码');
  364. $sheet->setCellValue('C7', '大件开始流水号');
  365. $sheet->setCellValue('C9', '小件开始流水号');
  366. $sheet->setCellValue('C11', '大件重量(Kg)');
  367. $sheet->setCellValue('C13', '小件重量(Kg)');
  368. $sheet->setCellValue('A15', '大件二维码');
  369. $sheet->setCellValue('B15', '大件条码(预留)');
  370. $sheet->setCellValue('C15', '小件二维码');
  371. $sheet->setCellValue('D15', '小件条码(预留)');
  372. //插入表格数据
  373. $sheet->getCell('B3')->setValue(isset($data['supplier_name'])?$data['supplier_name']:'');
  374. $sheet->getCell('B4')->setValue(isset($data['supplier_no'])?$data['supplier_no']:'');
  375. $sheet->getCell('B5')->setValue(isset($data['matter_name'])?$data['matter_name']:'');
  376. $sheet->getCell('B6')->setValue(isset($data['matter_no'])?$data['matter_no']:'');
  377. $sheet->getCell('B7')->setValue(isset($data['manufacture_date'])?$data['manufacture_date']:'');
  378. $sheet->getCell('B8')->setValue(isset($data['print_date'])?$data['print_date']:'');
  379. $sheet->getCell('B9')->setValue(isset($data['box_num'])?$data['box_num']:'');
  380. $sheet->getCell('B10')->setValue(isset($data['tray_num'])?$data['tray_num']:'');
  381. $sheet->getCell('B11')->setValue(isset($data['small_num'])?$data['small_num']:'');
  382. $sheet->getCell('C4')->setValue(isset($data['l_reservation'])?$data['l_reservation']:'');
  383. $sheet->getCell('C6')->setValue(isset($data['s_reservation'])?$data['s_reservation']:'');
  384. $sheet->getCell('C8')->setValue(isset($data['l_flow'])?$data['l_flow']:'');
  385. $sheet->getCell('C10')->setValue(isset($data['s_flow'])?$data['s_flow']:'');
  386. $sheet->getCell('C12')->setValue(isset($data['l_weight'])?$data['l_weight']:'');
  387. $sheet->getCell('C14')->setValue(isset($data['s_weight'])?$data['s_weight']:'');
  388. foreach ($data['code'] as $k=>$v){
  389. $m = $k+16;
  390. $sheet->getCell('A'.$m)->setValue(isset($v['large_code'])?$v['large_code']:'');
  391. $sheet->getCell('B'.$m)->setValue('');
  392. $sheet->getCell('C'.$m)->setValue(isset($v['small_code'])?$v['small_code']:'');
  393. $sheet->getCell('D'.$m)->setValue('');
  394. }
  395. //文件另存
  396. $filename = date('Ymd',time()).rand(100,999).'_'.$data['supplier_name'].'_'.str_replace('/','_',$data['matter_name']).'_'.$data['small_num'].'.xlsx';
  397. // $filename = iconv("utf-8","gb2312",$filename);
  398. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  399. header('Content-Disposition:attachment;filename='.$filename);
  400. header('Cache-Control: max-age=0');
  401. header("Content-Type:text/html;charset=utf-8");
  402. if(is_dir(ROOT_PATH.'public/uploads/export/') === false)
  403. {
  404. mkdir(ROOT_PATH.'public/uploads/export/',0777,true);
  405. }
  406. $writer = IOFactory::createWriter($objexcel, 'Xlsx');
  407. $writer->save(ROOT_PATH.'public/uploads/export/'.$filename);
  408. return 'uploads/export/'.$filename;
  409. }
  410. //获取日期
  411. public function applydsit_list()
  412. {
  413. $userinfo = Session::get('admin');
  414. $mongo = \think\Db::connect('mongodb');
  415. try {
  416. // 查询数据并按日期排序
  417. $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
  418. ->order('sys_rq', 'desc')
  419. ->select();
  420. // 初始化结果数组
  421. $result = [
  422. 'code' => 0,
  423. 'msg' => '成功',
  424. 'time' => time(),
  425. 'data' => []
  426. ];
  427. // 处理数据
  428. foreach ($bach_list as $item) {
  429. if (isset($item['sys_rq'])) {
  430. $date = $item['sys_rq'];
  431. list($year, $month, $day) = explode('-', $date);
  432. // 构建日期格式
  433. $yearMonth = "$year-$month";
  434. $dayFormat = "$month-$day";
  435. // 按年-月-日分组
  436. if (!isset($result['data'][$year])) {
  437. $result['data'][$year] = [];
  438. }
  439. if (!isset($result['data'][$year][$yearMonth])) {
  440. $result['data'][$year][$yearMonth] = [];
  441. }
  442. // 添加日期,避免重复
  443. if (!in_array($dayFormat, $result['data'][$year][$yearMonth])) {
  444. $result['data'][$year][$yearMonth][] = $dayFormat;
  445. }
  446. }
  447. }
  448. // 返回JSON格式数据
  449. return json($result);
  450. } catch (\Exception $e) {
  451. // 错误处理
  452. return json([
  453. 'code' => 1,
  454. 'msg' => '查询失败: ' . $e->getMessage(),
  455. 'time' => time(),
  456. 'data' => []
  457. ]);
  458. }
  459. }
  460. //获取发货单日期
  461. public function dispatch_list()
  462. {
  463. $userinfo = Session::get('admin');
  464. $mongo = \think\Db::connect('mongodb');
  465. try {
  466. // 查询数据并按日期排序
  467. $bach_list = $mongo->name("qcode_goods")
  468. ->order('sys_rq', 'desc')
  469. ->where('delete_time','')
  470. ->select();
  471. // 初始化结果数组
  472. $result = [
  473. 'code' => 0,
  474. 'msg' => '成功',
  475. 'time' => time(),
  476. 'data' => []
  477. ];
  478. // 处理数据
  479. foreach ($bach_list as $item) {
  480. if (isset($item['sys_rq'])) {
  481. $date = $item['sys_rq'];
  482. list($year, $month, $day) = explode('-', $date);
  483. // 构建日期格式
  484. $yearMonth = "$year-$month";
  485. $dayFormat = "$month-$day";
  486. // 按年-月-日分组
  487. if (!isset($result['data'][$year])) {
  488. $result['data'][$year] = [];
  489. }
  490. if (!isset($result['data'][$year][$yearMonth])) {
  491. $result['data'][$year][$yearMonth] = [];
  492. }
  493. // 添加日期,避免重复
  494. if (!in_array($dayFormat, $result['data'][$year][$yearMonth])) {
  495. $result['data'][$year][$yearMonth][] = $dayFormat;
  496. }
  497. }
  498. }
  499. // 返回JSON格式数据
  500. return json($result);
  501. } catch (\Exception $e) {
  502. // 错误处理
  503. return json([
  504. 'code' => 1,
  505. 'msg' => '查询失败: ' . $e->getMessage(),
  506. 'time' => time(),
  507. 'data' => []
  508. ]);
  509. }
  510. }
  511. // 获取主数据
  512. public function apply()
  513. {
  514. $mongo = Db::connect('mongodb');
  515. $this->request->filter(['strip_tags', 'trim']);
  516. if (false === $this->request->isAjax()) {
  517. return $this->view->fetch();
  518. }
  519. if ($this->request->request('keyField')) {
  520. return $this->selectpage();
  521. }
  522. // 保存编辑请求
  523. if ($this->request->isPost() && $this->request->post('data')) {
  524. return $this->saveEdits();
  525. }
  526. $userinfo = Session::get('admin');
  527. $where = ['delete_time' => ''];
  528. // 处理日期筛选条件
  529. $date = $this->request->get('date', '');
  530. $month = $this->request->get('month', '');
  531. $year = $this->request->get('year', '');
  532. if ($date && $date !== 'all') {
  533. $where['sys_rq'] = $date;
  534. } elseif ($month) {
  535. $where['sys_rq'] = new \MongoDB\BSON\Regex($month, 'i');
  536. } elseif ($year) {
  537. $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
  538. } else {
  539. // 无日期参数时默认查询当天日期
  540. $where['sys_rq'] = date('Y-m-d');
  541. }
  542. // 时间范围查询(高级过滤)
  543. $filter = input('filter');
  544. $filter = json_decode($filter, true);
  545. if (isset($filter['create_time'])) {
  546. $begin = substr($filter['create_time'], 0, 19);
  547. $end = substr($filter['create_time'], 22);
  548. $begin = strtotime($begin);
  549. $end = strtotime($end);
  550. $where['create_time'] = ['between', [$begin, $end]];
  551. }
  552. $order = input('order') ?: 'desc';
  553. $offset = (int)input('offset', 0);
  554. $limit = (int)input('limit', 20);
  555. // 总数统计
  556. $total = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
  557. ->where($where)
  558. ->count([]);
  559. // 列表数据
  560. $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
  561. ->where($where)
  562. ->order('_id', $order)
  563. ->skip($offset)
  564. ->limit($limit)
  565. ->select();
  566. $list = [];
  567. foreach ($bach_list as $k => $v) {
  568. $list[$k]['bach_ids'] = $v['bach_ids'];
  569. $list[$k]['total_quantity'] = $v['total_quantity'];
  570. $list[$k]['total_boxes'] = $v['total_boxes'];
  571. $list[$k]['total_pallets'] = $v['total_pallets'];
  572. $list[$k]['product_count'] = $v['product_count'];
  573. $list[$k]['sys_rq'] = $v['sys_rq'];
  574. $list[$k]['created_at'] = $v['created_at'];
  575. $list[$k]['id'] = (string)$v['_id'];
  576. }
  577. return json(['total' => $total, 'rows' => $list]);
  578. }
  579. public function bachdelids()
  580. {
  581. $bach_ids = $this->request->param('bach_ids');
  582. if (empty($bach_ids)) {
  583. return json(['code' => 0, 'msg' => '未查询到要删除的记录']);
  584. }
  585. $userinfo = Session::get('admin');
  586. if (empty($userinfo) || !isset($userinfo['company'])) {
  587. return json(['code' => 0, 'msg' => '获取用户信息失败,请重新登录']);
  588. }
  589. $mongo = \think\Db::connect('mongodb');
  590. $company = $userinfo['company'];
  591. $collection = $company . '_qcode_bach';
  592. $bachdetails = $company . '_qcode_bachdetails';
  593. $bachsummary = $company . '_qcode_bachsummary';
  594. // 获取批次详情数据
  595. $detailData = $mongo->name($collection)
  596. ->where('bach_ids', $bach_ids)
  597. ->select();
  598. $productQuantities = [];
  599. if (!empty($detailData)) {
  600. // 按产品名称分组统计实际数量
  601. foreach ($detailData as $detail) {
  602. $matterName = $detail['cpmc'];
  603. $actualQuantity = floatval($detail['actual_quantity']);
  604. if ($matterName && $actualQuantity > 0) {
  605. if (!isset($productQuantities[$matterName])) {
  606. $productQuantities[$matterName] = 0;
  607. }
  608. $productQuantities[$matterName] += $actualQuantity;
  609. }
  610. }
  611. // 处理库存退回
  612. foreach ($productQuantities as $productName => $returnQuantity) {
  613. // 获取产品最新的库存记录
  614. $latestRecord = $mongo->name('inventory_records')
  615. ->where('cpmc', $productName)
  616. ->order('created_at', 'desc')
  617. ->find();
  618. if (!empty($latestRecord)) {
  619. // 计算新的库存数量并更新库存记录
  620. $newRemainingQuantity = floatval($latestRecord['remaining_quantity'] ?? 0) + $returnQuantity;
  621. $newTotalChuQuantity = max(0, floatval($latestRecord['total_chu_quantity'] ?? 0) - $returnQuantity);
  622. $mongo->name('inventory_records')
  623. ->where('_id', $latestRecord['_id'])
  624. ->update([
  625. 'remaining_quantity' => $newRemainingQuantity,
  626. 'total_chu_quantity' => $newTotalChuQuantity,
  627. 'update_time' => time()
  628. ]);
  629. // 更新库存汇总表
  630. // 使用cpmc字段进行查询,与文档结构保持一致
  631. $summary = $mongo->name('inventory_summary')
  632. ->where('cpmc', $productName)
  633. ->find();
  634. if ($summary) {
  635. $mongo->name('inventory_summary')
  636. ->where('_id', $summary['_id'])
  637. ->update([
  638. 'remaining_quantity' => floatval($summary['remaining_quantity'] ?? 0) + $returnQuantity,
  639. 'total_chu_quantity' => max(0, floatval($summary['total_chu_quantity'] ?? 0) - $returnQuantity),
  640. 'update_time' => time()
  641. ]);
  642. }
  643. }
  644. }
  645. }
  646. // 标记批次为删除状态
  647. $delete_time = time();
  648. $mongo->name($collection)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
  649. $mongo->name($bachdetails)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
  650. $mongo->name($bachsummary)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
  651. return json([
  652. 'code' => 1,
  653. 'msg' => '删除成功,库存已退回',
  654. 'data' => ['returned_products' => $productQuantities]
  655. ]);
  656. }
  657. /**
  658. * 明细数据 (通过 bach_ids 获取)
  659. */
  660. public function bachids()
  661. {
  662. $mongo = \think\Db::connect('mongodb');
  663. $this->request->filter(['strip_tags', 'trim']);
  664. if (false === $this->request->isAjax()) {
  665. return $this->view->fetch();
  666. }
  667. $userinfo = Session::get('admin');
  668. $bach_ids = input('bach_ids');
  669. $where = [
  670. 'bach_ids' => $bach_ids,
  671. 'delete_time' => ''
  672. ];
  673. $filter = input('filter');
  674. $filter = json_decode($filter, true);
  675. if (isset($filter['matter_name'])) {
  676. $where['matter_no'] = $filter['matter_name'];
  677. }
  678. if (isset($filter['create_time'])) {
  679. $begin = substr($filter['create_time'], 0, 19);
  680. $end = substr($filter['create_time'], 22);
  681. $begin = strtotime($begin);
  682. $end = strtotime($end);
  683. $where['create_time'] = ['between', [$begin, $end]];
  684. }
  685. $order = input('order') ?: 'desc';
  686. $offset = (int)input('offset', 0);
  687. $limit = (int)input('limit', 20);
  688. $total = $mongo->name($userinfo['company'] . '_' . "qcode_bach")
  689. ->where($where)
  690. ->count([]);
  691. // 查询数据
  692. $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bach")
  693. ->where($where)
  694. ->select(); // 去掉 order、skip、limit,让我们用 PHP 自定义排序
  695. // 自定义排序规则:按 pallet_range 起始数字升序排列
  696. usort($bach_list, function ($a, $b) {
  697. // 提取起始数字
  698. $getStart = function ($val) {
  699. if (strpos($val, '-') !== false) {
  700. return (int)explode('-', $val)[0];
  701. }
  702. return (int)$val;
  703. };
  704. return $getStart($a['pallet_range']) <=> $getStart($b['pallet_range']);
  705. });
  706. // 手动分页(如有分页需求)
  707. $total = count($bach_list);
  708. $offset = (int)input('offset', 0);
  709. $limit = (int)input('limit', 20);
  710. $pagedList = array_slice($bach_list, $offset, $limit);
  711. // 格式化返回数据
  712. $list = [];
  713. foreach ($pagedList as $k => $v) {
  714. $list[$k]['start_pallet_no'] = $v['start_pallet_no'];
  715. $list[$k]['end_pallet_no'] = $v['end_pallet_no'];
  716. $list[$k]['pallet_range'] = $v['pallet_range'];
  717. $list[$k]['total_boxes'] = $v['total_boxes'];
  718. $list[$k]['pallet_count'] = $v['pallet_count'];
  719. $list[$k]['actual_quantity'] = $v['actual_quantity'];
  720. $list[$k]['gdbh'] = $v['gdbh'];
  721. $list[$k]['matter_no'] = $v['gdbh'];
  722. $list[$k]['order_ddbh'] = $v['order_ddbh'];
  723. $list[$k]['cpbm'] = $v['cpbm'];
  724. $list[$k]['matter_name'] = $v['matter_name'];
  725. $list[$k]['remark'] = $v['remark'];
  726. $list[$k]['small_num'] = $v['small_num'];
  727. $list[$k]['tray_num'] = $v['tray_num'];
  728. $list[$k]['box_num'] = $v['box_num'];
  729. $list[$k]['tray_count'] = $v['tray_count'];
  730. $list[$k]['layer_height'] = $v['layer_height'];
  731. $list[$k]['pallet_length'] = $v['pallet_length'];
  732. $list[$k]['pallet_width'] = $v['pallet_width'];
  733. $list[$k]['sys_rq'] = $v['sys_rq'];
  734. $list[$k]['id'] = (string)$v['_id'];
  735. }
  736. return json(['total' => $total, 'rows' => $list]);
  737. }
  738. public function applydsit_add()
  739. {
  740. if ($this->request->isPost()) {
  741. // 获取前端提交的数据
  742. $params = $this->request->post();
  743. $bach_ids = $params['bach_ids'] ?? '';
  744. $pallet_nos = $params['pallet_no'] ?? [];
  745. $product_names = $params['product_name'] ?? [];
  746. $remarks = $params['remark'] ?? [];
  747. $quantities = $params['quantity'] ?? [];
  748. $unit = $params['unit'] ?? [];
  749. if (!$bach_ids) {
  750. return json(['code' => 0, 'msg' => '缺少单据编号']);
  751. }
  752. // 获取当前登录用户的公司名
  753. $userinfo = Session::get('admin');
  754. if (!$userinfo || empty($userinfo['company'])) {
  755. return json(['code' => 0, 'msg' => '未获取到用户公司信息']);
  756. }
  757. // 连接 MongoDB
  758. try {
  759. $mongo = Db::connect('mongodb');
  760. } catch (\Exception $e) {
  761. return json(['code' => 0, 'msg' => 'MongoDB 连接失败: ' . $e->getMessage()]);
  762. }
  763. // 查询汇总表
  764. $summaryTable = $userinfo['company'] . '_qcode_bachsummary';
  765. $summaryData = $mongo->name($summaryTable)->where(['bach_ids' => $bach_ids])->find();
  766. if (!$summaryData) {
  767. return json(['code' => 0, 'msg' => '未找到对应的汇总单据']);
  768. }
  769. // 写入明细表
  770. $detailTable = $userinfo['company'] . '_qcode_bach';
  771. $insertedCount = 0;
  772. foreach ($pallet_nos as $i => $palletNo) {
  773. if (empty($palletNo)) continue;
  774. $data = [
  775. 'bach_ids' => $bach_ids,//关联
  776. 'userid' => $userinfo['id'],//用户ID
  777. 'pallet_range' => $palletNo,//托盘号
  778. 'cpmc' => $product_names[$i],//产品名称
  779. 'matter_name' => $product_names[$i],//产品名称
  780. 'remark' => $remarks[$i],//备注
  781. 'total_boxes' => '',//总箱数
  782. 'actual_quantity' => (int)($quantities[$i] ?? 0),//数量
  783. 'pallet_count' => '',//托盘数
  784. 'sys_rq' => date('Y-m-d'),
  785. 'created_at' => date('Y-m-d H:i:s'),
  786. 'create_time' => time(),
  787. 'unit' => $unit[$i],//单位
  788. // 结构字段保留,但设为空
  789. 'gdbh' => '',
  790. 'order_ddbh' => '',
  791. 'cpbm' => '',
  792. 'small_num' => '',
  793. 'tray_num' => '',
  794. 'box_num' => '',
  795. 'tray_count' => '',
  796. 'layer_height' => '',
  797. 'pallet_length' => '',
  798. 'pallet_width' => '',
  799. 'pallet_type' => '',
  800. 'start_pallet_no' => '',
  801. 'end_pallet_no' => '',
  802. 'bach_status' => 0,
  803. 'delete_time' => '',
  804. ];
  805. $mongo->name($detailTable)->insert($data);
  806. $insertedCount++;
  807. }
  808. return json(['code' => 1, 'msg' => "成功插入 {$insertedCount} 条托盘信息"]);
  809. }
  810. return json(['code' => 0, 'msg' => '非法请求方式']);
  811. }
  812. /**
  813. * 保存编辑的数据
  814. */
  815. public function apply_update()
  816. {
  817. $this->request->filter(['strip_tags', 'trim']);
  818. if (!$this->request->isPost()) {
  819. $this->error('请求错误');
  820. }
  821. $userinfo = Session::get('admin');
  822. $tableName = $userinfo['company'] . '_' . "qcode_bach";
  823. $id = $this->request->post('id');
  824. $field = $this->request->post('field');
  825. $value = $this->request->post('value');
  826. // 允许前端编辑的字段
  827. $allowedFields = ['pallet_range', 'start_pallet_no', 'end_pallet_no','remark'];
  828. if (!in_array($field, $allowedFields)) {
  829. $this->error('该字段不允许编辑');
  830. }
  831. $mongo = \think\Db::connect('mongodb');
  832. $bach = $mongo->name($tableName)->where('_id', new \MongoDB\BSON\ObjectId($id))->find();
  833. if (!$bach) {
  834. $this->error('数据未找到');
  835. }
  836. // 更新字段值
  837. $bach[$field] = is_numeric($value) ? (int)$value : $value;
  838. // 整理更新字段(去除 _id)
  839. $updateData = [];
  840. foreach ($bach as $k => $v) {
  841. if ($k != '_id') {
  842. $updateData[$k] = $v;
  843. }
  844. }
  845. $result = $mongo->name($tableName)
  846. ->where('_id', new \MongoDB\BSON\ObjectId($id))
  847. ->update($updateData);
  848. if ($result) {
  849. $this->success('更新成功');
  850. } else {
  851. $this->error('更新失败');
  852. }
  853. }
  854. /**
  855. * 批次发货删除
  856. * @param $ids
  857. * @return void
  858. */
  859. public function apply_del($ids)
  860. {
  861. $export = new QcodeExport();
  862. $userinfo = Session::get('admin');
  863. $large = new QcodeLarge();
  864. if (empty($ids)){
  865. $this->error('请求错误');
  866. }
  867. $res = $export->where('_id',$ids)->update(['delete_time'=>date('Y-m-d H:i:s',time())]);
  868. if ($res === false){
  869. $this->error('删除失败');
  870. }
  871. $large_list = $export->where('_id',$ids)->find();
  872. $large_id = explode(',',$large_list['large_str']);
  873. foreach ($large_id as $v){
  874. $result = $large->name($userinfo['company'].'_'.'qcode_large')->where('_id',$v)->update(['l_status'=>0]);
  875. if ($result === 0){
  876. $this->error('删除失败');
  877. }
  878. }
  879. $this->success('成功');
  880. }
  881. /**
  882. * 司机弹窗
  883. * @param $ids
  884. */
  885. public function goods($ids)
  886. {
  887. $this->view->assign('ids',$ids);
  888. return $this->view->fetch();
  889. }
  890. public function ReplicationList()
  891. {
  892. $goods = new QcodeGoods();
  893. $userinfo = Session::get('admin');
  894. //shr_phone电话\plate_number车牌号/deliveryman司机
  895. $arr = $goods->where('user_id',$userinfo['id'])->order('create_time','desc')->where("delete_time","")->find();
  896. return json(['code' => 1, 'data' => $arr, 'msg' => '成功']);
  897. }
  898. /**
  899. * 申请发货
  900. */
  901. public function apply_add()
  902. {
  903. $goods = new QcodeGoods();
  904. $export = new QcodeExport();
  905. $userinfo = Session::get('admin');
  906. if ($this->request->isAjax() === false){
  907. $this->error('请求错误');
  908. }
  909. $ids = input('ids');
  910. $order_number = input('order_number');
  911. $deliveryman = input('deliveryman');
  912. $shr_phone = input('shr_phone');
  913. $plate_number = input('plate_number');
  914. $note = input('note');
  915. $mongo = \think\Db::connect('mongodb');
  916. $collection = $userinfo['company'] . '_qcode_bach';
  917. $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
  918. $update_status = $mongo->name($bachsummary)->where('_id',$ids)->update(
  919. [
  920. 'bach_status'=>2,
  921. 'delete_time' => date('Y-m-d H:i:s')
  922. ]);
  923. if ($update_status){
  924. $bachsummary_list = $mongo->name($bachsummary)->where('_id',$ids)->select();
  925. $daterq = date('ymd',time());
  926. $data = [
  927. 'shdh' => substr($daterq,2,2).' '.substr($daterq,2,6).mt_rand(1000,9999),//收货单号
  928. 'order_number' => $order_number,//订单号
  929. 'deliveryman' => $deliveryman,//司机名字
  930. 'shr_phone' => $shr_phone,//电话
  931. 'plate_number' => $plate_number,//车牌号
  932. 'shrq_date' => '',
  933. 'supplier_name' => $userinfo['company_name'],//供应商名称
  934. 'supplier_id' => $userinfo['id'],//供应商名称id
  935. 'user_id' => $userinfo['id'],//用户id
  936. 'status' => 0,
  937. 'qcode_bachsummary_id' => $ids,
  938. 'export_id' => '',
  939. 'create_time' => time(),
  940. 'sys_rq' => date('Y-m-d'),
  941. 'note' => $note,
  942. 'company_id' => $userinfo['company'],
  943. ];
  944. $data['qrcode_add'] = $this->Qrcode($data['shdh']);
  945. // return json(['code' => 1, 'data' => $data, 'msg' => '成功']);
  946. $res = $goods->save($data);
  947. if ($res === false){
  948. $this->error('失败');
  949. }
  950. $this->success('成功');
  951. }else{
  952. $this->error('失败');
  953. }
  954. }
  955. /**
  956. * 生成二维码
  957. * @param $url
  958. * @return string
  959. */
  960. public function Qrcode($url)
  961. {
  962. $level=2;
  963. $size=5;
  964. Vendor('phpqrcode.phpqrcode');//加载生成二维码的核心类
  965. $errorCorrectionLevel =intval($level) ;//容错级别
  966. $matrixPointSize = intval($size);//生成图片大小
  967. //生成二维码图片
  968. $object = new \QRcode();
  969. //打开缓冲区
  970. ob_start();
  971. $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
  972. //这里就是把生成的图片流从缓冲区保存到内存对象上,使用base64_encode变成编码字符串,通过json返回给页面。
  973. $imageString = base64_encode(ob_get_contents());
  974. //关闭缓冲区
  975. ob_end_clean();
  976. //把生成的base64字符串返回给前端
  977. return 'data:image/png;base64,'.$imageString;
  978. }
  979. /**
  980. * 发货单
  981. * @return string|\think\response\Json
  982. * @throws \think\Exception
  983. */
  984. public function dispatch()
  985. {
  986. $export = new QcodeGoods();
  987. $this->request->filter(['strip_tags', 'trim']);
  988. // 非Ajax请求返回视图
  989. if (false === $this->request->isAjax()) {
  990. return $this->view->fetch();
  991. }
  992. // 处理selectpage请求
  993. if ($this->request->request('keyField')) {
  994. return $this->selectpage();
  995. }
  996. // 获取用户信息
  997. $userInfo = Session::get('admin');
  998. $where = [
  999. 'company_id' => $userInfo['company'],
  1000. 'delete_time' => ''
  1001. ];
  1002. // 处理搜索条件
  1003. $search = input('search');
  1004. if (isset($search)) {
  1005. $where['order_number|supplier_name|status|plate_number|shdh|deliveryman'] =
  1006. new \MongoDB\BSON\Regex($search);
  1007. }
  1008. // 处理筛选条件
  1009. $filter = input('filter');
  1010. $filter = json_decode($filter, true) ?: [];
  1011. // 订单编号查询
  1012. if (isset($filter['order_number'])) {
  1013. $where['order_number'] = $filter['order_number'];
  1014. }
  1015. // 所属公司查询
  1016. if (isset($filter['supplier_name'])) {
  1017. $where['supplier_name'] = $filter['supplier_name'];
  1018. }
  1019. // 状态查询
  1020. if (isset($filter['status'])) {
  1021. $where['status'] = (int)$filter['status'];
  1022. }
  1023. // 处理日期筛选条件
  1024. $date = $this->request->get('date', '');
  1025. $month = $this->request->get('month', '');
  1026. $year = $this->request->get('year', '');
  1027. if ($date && $date !== 'all') {
  1028. $where['sys_rq'] = $date;
  1029. } elseif ($month) {
  1030. $where['sys_rq'] = new \MongoDB\BSON\Regex($month, 'i');
  1031. } elseif ($year) {
  1032. $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
  1033. } else {
  1034. // 无日期参数时默认查询当天日期
  1035. $where['sys_rq'] = date('Y-m-d');
  1036. }
  1037. // 分页和排序参数
  1038. $order = input('order', 'desc'); // 默认降序
  1039. $offset = input('offset', 0);
  1040. $limit = input('limit', 10); // 默认每页10条
  1041. // 查询数据
  1042. $total = $export->where($where)->count();
  1043. $export_list = $export
  1044. ->order('_id', $order)
  1045. ->where($where)
  1046. ->whereIn('status', [0, 1])
  1047. ->skip($offset)
  1048. ->limit($limit)
  1049. ->select();
  1050. // 处理批次汇总数据
  1051. $userinfo = Session::get('admin');
  1052. $mongo = \think\Db::connect('mongodb');
  1053. $bachsummary = $userinfo['company'] . '_qcode_bachsummary'; // 批次汇总表
  1054. $list = [];
  1055. foreach ($export_list as $k => $v) {
  1056. $bachsummary_list = $mongo->name($bachsummary)->where("_id", $v['qcode_bachsummary_id'])->find();
  1057. $list[$k] = [
  1058. 'bach_ids' => $bachsummary_list['bach_ids'] ?? '',
  1059. 'total_quantity' => $bachsummary_list['total_quantity'] ?? 0,
  1060. 'total_boxes' => $bachsummary_list['total_boxes'] ?? 0,
  1061. 'total_pallets' => $bachsummary_list['total_pallets'] ?? 0,
  1062. 'product_count' => $bachsummary_list['product_count'] ?? 0,
  1063. 'id' => substr(json_encode($v['_id']), 9, -2),
  1064. 'shdh' => $v['shdh'] ?? '',
  1065. 'order_number' => $v['order_number'] ?? '',
  1066. 'supplier_name' => $v['supplier_name'] ?? '',
  1067. 'deliveryman' => $v['deliveryman'] ?? '',
  1068. 'plate_number' => $v['plate_number'] ?? '',
  1069. 'create_time' => $v['create_time'] ?? 0,
  1070. 'status' => $v['status'] ?? 0
  1071. ];
  1072. }
  1073. // 返回结果
  1074. return json([
  1075. 'total' => $total,
  1076. 'rows' => $list
  1077. ]);
  1078. }
  1079. /**
  1080. * 打印发货单
  1081. */
  1082. public function printqrcode()
  1083. {
  1084. if (!$this->request->isAjax()) {
  1085. return json(['code' => 0, 'msg' => '请求错误']);
  1086. }
  1087. try {
  1088. $mongo = \think\Db::connect('mongodb');
  1089. $userinfo = Session::get('admin');
  1090. $goodsCollection = '_qcode_goods';
  1091. $bachCollection = $userinfo['company'] . '_qcode_bach';
  1092. $bachsummaryCollection = $userinfo['company'] . '_qcode_bachsummary';
  1093. $id = input('id');
  1094. // 获取发货单数据
  1095. $goodList = $mongo->name($goodsCollection)->where('_id', $id)->find();
  1096. if (empty($goodList)) {
  1097. return json(['code' => 0, 'msg' => '未找到发货单数据']);
  1098. }
  1099. // 获取批次汇总数据
  1100. $bachsummaryData = $mongo->name($bachsummaryCollection)
  1101. ->where('_id', $goodList['qcode_bachsummary_id'])
  1102. ->find();
  1103. if (empty($bachsummaryData)) {
  1104. return json(['code' => 0, 'msg' => '未找到对应的批次汇总数据']);
  1105. }
  1106. // 获取批次数据
  1107. $bachData = $mongo->name($bachCollection)
  1108. ->where('bach_ids', $bachsummaryData['bach_ids'])
  1109. ->select();
  1110. if (empty($bachData)) {
  1111. return json(['code' => 0, 'msg' => '未找到对应的批次数据']);
  1112. }
  1113. // 初始化数据变量
  1114. $groupedData = [];
  1115. $totalTray = 0;
  1116. $totalBox = 0;
  1117. $productSummary = [];
  1118. $totalTao = 0;
  1119. $totalZhang = 0;
  1120. $totalGe = 0;
  1121. // 处理每个批次数据
  1122. foreach ($bachData as $item) {
  1123. // 数据类型转换和默认值处理
  1124. $actualQty = is_numeric($item['actual_quantity']) ? (int)$item['actual_quantity'] : 0;
  1125. $boxCount = is_numeric($item['total_boxes']) ? (int)$item['total_boxes'] : 0;
  1126. $trayCount = is_numeric($item['pallet_count']) ? (int)$item['pallet_count'] : 0;
  1127. // 累计总数
  1128. $totalTray += $trayCount;
  1129. $totalBox += $boxCount;
  1130. // 按单位分类累计数量
  1131. $unit = $item['unit'] ?? '';
  1132. switch ($unit) {
  1133. case '个':
  1134. case '套':
  1135. $totalTao += $actualQty;
  1136. break;
  1137. case '张':
  1138. case '托':
  1139. case '卷':
  1140. $totalZhang += $actualQty;
  1141. break;
  1142. default:
  1143. $totalGe += $actualQty;
  1144. break;
  1145. }
  1146. // 处理产品摘要和备注去重
  1147. $productName = $item['matter_name'] ?? '';
  1148. $remark = $item['remark'] ?? '';
  1149. if (!isset($productSummary[$productName])) {
  1150. $productSummary[$productName] = ['qty' => 0, 'unit' => $unit, 'remark' => $remark];
  1151. } else {
  1152. // 备注去重处理
  1153. if ($remark && $productSummary[$productName]['remark']) {
  1154. // 合并备注并去重
  1155. $existingRemarks = explode(';', $productSummary[$productName]['remark']);
  1156. $newRemarks = explode(';', $remark);
  1157. // 合并并去除空白项
  1158. $allRemarks = array_merge($existingRemarks, $newRemarks);
  1159. $trimmedRemarks = array_map('trim', $allRemarks);
  1160. $nonEmptyRemarks = array_filter($trimmedRemarks);
  1161. // 去重并重新拼接
  1162. $uniqueRemarks = array_unique($nonEmptyRemarks);
  1163. $productSummary[$productName]['remark'] = implode('; ', $uniqueRemarks);
  1164. } else if ($remark) {
  1165. $productSummary[$productName]['remark'] = $remark;
  1166. }
  1167. }
  1168. // 累计产品数量
  1169. $productSummary[$productName]['qty'] += $actualQty;
  1170. // 计算每托箱数
  1171. $boxesPerPallet = (is_numeric($item['tray_num']) && is_numeric($item['box_num']))
  1172. ? $item['tray_num'] * $item['box_num'] : $boxCount;
  1173. // 添加到分组数据中
  1174. $groupedData[] = [
  1175. 'pallet' => $item['pallet_range'] ?? '',
  1176. 'matter_name' => $productName,
  1177. 'small_num' => $item['small_num'] ?? '',
  1178. 'total_boxes' => $boxesPerPallet,
  1179. 'tray_num' => $item['tray_num'] ?? '',
  1180. 'box_num' => $item['box_num'] ?? '',
  1181. 'pallet_height' => $item['layer_height'] ?? '',
  1182. 'pallet_length' => $item['pallet_length'] ?? '',
  1183. 'pallet_width' => $item['pallet_width'] ?? '',
  1184. 'large_num' => $trayCount,
  1185. 'larger_num' => $boxCount,
  1186. 'num' => $actualQty,
  1187. 'danwei' => $unit,
  1188. 'order_ddbh' => $item['order_ddbh'] ?? '',
  1189. 'gdbh' => $item['gdbh'] ?? '',
  1190. 'cpbm' => $item['cpbm'] ?? ''
  1191. ];
  1192. }
  1193. // 处理0值转换为空字符串的函数
  1194. $convertZeroToEmpty = function($value) {
  1195. return ($value === 0 || $value === '0') ? '' : $value;
  1196. };
  1197. // 处理groupedData中的0值
  1198. foreach ($groupedData as &$dataItem) {
  1199. foreach ($dataItem as $key => &$value) {
  1200. if (is_numeric($value)) {
  1201. $value = $convertZeroToEmpty($value);
  1202. }
  1203. }
  1204. }
  1205. // 构建响应数据
  1206. $responseData = [
  1207. '_id' => $goodList['_id'],
  1208. 'shrq_date' => date('Y-m-d'),
  1209. 'shdh' => $goodList['shdh'] ?? '',
  1210. 'order_number' => $goodList['order_number'] ?? '',
  1211. 'address' => $goodList['address'] ?? '',
  1212. 'company_id' => $convertZeroToEmpty($goodList['company_id'] ?? 0),
  1213. 'count' => $convertZeroToEmpty($goodList['count'] ?? 0),
  1214. 'create_time' => $goodList['create_time'] ?? '',
  1215. 'data' => $groupedData,
  1216. 'summary' => [
  1217. 'totalTray' => $convertZeroToEmpty($totalTray),
  1218. 'totalBox' => $convertZeroToEmpty($totalBox),
  1219. 'totalTao' => $convertZeroToEmpty($totalTao),
  1220. 'totalZhang' => $convertZeroToEmpty($totalZhang),
  1221. 'totalGe' => $convertZeroToEmpty($totalGe),
  1222. 'products' => $productSummary
  1223. ],
  1224. 'delete_time' => $goodList['delete_time'] ?? '',
  1225. 'deliveryman' => $goodList['deliveryman'] ?? '',
  1226. 'export_id' => $goodList['export_id'] ?? '',
  1227. 'note' => $goodList['note'] ?? '',
  1228. 'order_ddbh' => $goodList['order_ddbh'] ?? '',
  1229. 'plate_number' => $goodList['plate_number'] ?? '',
  1230. 'qrcode_add' => $goodList['qrcode_add'] ?? '',
  1231. 'shr_phone' => $goodList['shr_phone'] ?? '',
  1232. 'status' => $convertZeroToEmpty($goodList['status'] ?? 0),
  1233. 'supplier_id' => $convertZeroToEmpty($goodList['supplier_id'] ?? 0),
  1234. 'supplier_name' => $goodList['supplier_name'] ?? '',
  1235. 'sync_flag' => $convertZeroToEmpty($goodList['sync_flag'] ?? 0),
  1236. 'user_id' => $convertZeroToEmpty($goodList['user_id'] ?? 0)
  1237. ];
  1238. return json(['code' => 1, 'data' => $responseData]);
  1239. } catch (\Exception $e) {
  1240. return json(['code' => 0, 'msg' => '系统错误: ' . $e->getMessage()]);
  1241. }
  1242. }
  1243. // public function printqrcode()
  1244. // {
  1245. // // 1. 验证请求类型
  1246. // if (!$this->request->isAjax()) {
  1247. // return json(['code' => 0, 'msg' => '请求错误']);
  1248. // }
  1249. //
  1250. // try {
  1251. // // 2. 初始化数据库连接
  1252. // $mongo = \think\Db::connect('mongodb');
  1253. // $userinfo = Session::get('admin');
  1254. //
  1255. // if (empty($userinfo) || empty($userinfo['company'])) {
  1256. // return json(['code' => 0, 'msg' => '用户信息获取失败']);
  1257. // }
  1258. //
  1259. // // 3. 设置集合名称
  1260. // $goodsCollection = '_qcode_goods';
  1261. // $bachCollection = $userinfo['company'] . '_qcode_bach';
  1262. // $bachsummaryCollection = $userinfo['company'] . '_qcode_bachsummary';
  1263. //
  1264. // // 4. 获取请求参数
  1265. // $id = input('id');
  1266. // if (empty($id)) {
  1267. // return json(['code' => 0, 'msg' => 'ID不能为空']);
  1268. // }
  1269. //
  1270. // // 5. 查询发货单信息
  1271. // $goodList = $mongo->name($goodsCollection)
  1272. // ->where('_id', $id)
  1273. // ->find();
  1274. //
  1275. // if (empty($goodList)) {
  1276. // return json(['code' => 0, 'msg' => '未找到发货单数据']);
  1277. // }
  1278. //
  1279. // // 6. 获取批次数据
  1280. // if (isset($goodList['data']) && is_array($goodList['data'])) {
  1281. // $detailData = $goodList['data'];
  1282. // } else {
  1283. // if (empty($goodList['qcode_bachsummary_id'])) {
  1284. // return json(['code' => 0, 'msg' => '发货单缺少批次汇总ID']);
  1285. // }
  1286. //
  1287. // $bachsummaryData = $mongo->name($bachsummaryCollection)
  1288. // ->where('_id', $goodList['qcode_bachsummary_id'])
  1289. // ->find();
  1290. //
  1291. // if (empty($bachsummaryData)) {
  1292. // return json(['code' => 0, 'msg' => '未找到对应的批次汇总数据']);
  1293. // }
  1294. //
  1295. // $detailData = $mongo->name($bachCollection)
  1296. // ->where('bach_ids', $bachsummaryData['bach_ids'])
  1297. // ->select();
  1298. // }
  1299. //
  1300. // // 7. 按产品名称分组处理
  1301. // $productGroups = [];
  1302. // foreach ($detailData as $item) {
  1303. // $productName = $item['matter_name'];
  1304. // if (!isset($productGroups[$productName])) {
  1305. // $productGroups[$productName] = [];
  1306. // }
  1307. // $productGroups[$productName][] = $item;
  1308. // }
  1309. //
  1310. // // 8. 处理分组数据
  1311. // $groupedData = [];
  1312. // $totalTray = 0;
  1313. // $totalBox = 0;
  1314. // $productSummary = [];
  1315. //
  1316. // // 存储完整托盘和部分托盘
  1317. // $allFullPallets = [];
  1318. // $allPartialPallets = [];
  1319. //
  1320. // foreach ($productGroups as $productName => $items) {
  1321. // foreach ($items as $item) {
  1322. // if ($item['pallet_type'] === 'full') {
  1323. // $allFullPallets[] = [
  1324. // 'productName' => $productName,
  1325. // 'data' => $item
  1326. // ];
  1327. // } else {
  1328. // $allPartialPallets[] = [
  1329. // 'productName' => $productName,
  1330. // 'data' => $item
  1331. // ];
  1332. // }
  1333. // }
  1334. // }
  1335. //
  1336. // // 对完整托盘按产品名称和托盘序号排序
  1337. // usort($allFullPallets, function($a, $b) {
  1338. // $nameCompare = strcmp($a['productName'], $b['productName']);
  1339. // if ($nameCompare !== 0) {
  1340. // return $nameCompare;
  1341. // }
  1342. // return $a['data']['pallet_sequence'] <=> $b['data']['pallet_sequence'];
  1343. // });
  1344. //
  1345. // // 处理完整托盘
  1346. // $currentPalletNumber = 1;
  1347. // $currentProduct = null;
  1348. // $rangeStart = null;
  1349. // $rangeCount = 0;
  1350. //
  1351. // foreach ($allFullPallets as $index => $pallet) {
  1352. // if ($pallet['productName'] !== $currentProduct) {
  1353. // // 完成上一个产品范围
  1354. // if ($rangeStart !== null) {
  1355. // $first = $allFullPallets[$rangeStart]['data'];
  1356. //
  1357. // $groupedData[] = [
  1358. // 'pallet' => $currentPalletNumber . '-' . ($currentPalletNumber + $rangeCount - 1),
  1359. // 'matter_name' => $currentProduct,
  1360. // 'small_num' => $first['small_num'],
  1361. // 'total_boxes' => $first['boxes_in_pallet'],
  1362. // 'tray_num' => $first['tray_num'],
  1363. // 'box_num' => $first['box_num'],
  1364. // 'pallet_height' => $first['pallet_height'],
  1365. // 'pallet_length' => $first['pallet_length'],
  1366. // 'pallet_width' => $first['pallet_width'],
  1367. // 'large_num' => $rangeCount,
  1368. // 'larger_num' => $first['boxes_in_pallet'] * $rangeCount,
  1369. // 'num' => $first['num'] * $rangeCount,
  1370. // 'danwei' => $first['danwei']
  1371. // ];
  1372. //
  1373. // $totalTray += $rangeCount;
  1374. // $totalBox += $first['boxes_in_pallet'] * $rangeCount;
  1375. //
  1376. // if (!isset($productSummary[$currentProduct])) {
  1377. // $productSummary[$currentProduct] = [
  1378. // 'qty' => 0,
  1379. // 'unit' => $first['danwei']
  1380. // ];
  1381. // }
  1382. // $productSummary[$currentProduct]['qty'] += $first['num'] * $rangeCount;
  1383. //
  1384. // $currentPalletNumber += $rangeCount;
  1385. // }
  1386. //
  1387. // // 开始新的产品范围
  1388. // $currentProduct = $pallet['productName'];
  1389. // $rangeStart = $index;
  1390. // $rangeCount = 1;
  1391. // } else {
  1392. // $rangeCount++;
  1393. // }
  1394. // }
  1395. //
  1396. // // 处理最后一个产品范围
  1397. // if ($rangeStart !== null) {
  1398. // $first = $allFullPallets[$rangeStart]['data'];
  1399. //
  1400. // $groupedData[] = [
  1401. // 'pallet' => $currentPalletNumber . '-' . ($currentPalletNumber + $rangeCount - 1),
  1402. // 'matter_name' => $currentProduct,
  1403. // 'small_num' => $first['small_num'],
  1404. // 'total_boxes' => $first['boxes_in_pallet'],
  1405. // 'tray_num' => $first['tray_num'],
  1406. // 'box_num' => $first['box_num'],
  1407. // 'pallet_height' => $first['pallet_height'],
  1408. // 'pallet_length' => $first['pallet_length'],
  1409. // 'pallet_width' => $first['pallet_width'],
  1410. // 'large_num' => $rangeCount,
  1411. // 'larger_num' => $first['boxes_in_pallet'] * $rangeCount,
  1412. // 'num' => $first['num'] * $rangeCount,
  1413. // 'danwei' => $first['danwei']
  1414. // ];
  1415. //
  1416. // $totalTray += $rangeCount;
  1417. // $totalBox += $first['boxes_in_pallet'] * $rangeCount;
  1418. //
  1419. // if (!isset($productSummary[$currentProduct])) {
  1420. // $productSummary[$currentProduct] = [
  1421. // 'qty' => 0,
  1422. // 'unit' => $first['danwei']
  1423. // ];
  1424. // }
  1425. // $productSummary[$currentProduct]['qty'] += $first['num'] * $rangeCount;
  1426. //
  1427. // $currentPalletNumber += $rangeCount;
  1428. // }
  1429. //
  1430. // // 处理部分托盘 - 合并显示但分开产品信息
  1431. // $warning4Partial = null;
  1432. // $warning10Partial = null;
  1433. //
  1434. // // 查找可以合并的部分托盘
  1435. // foreach ($allPartialPallets as $partial) {
  1436. // if (strpos($partial['productName'], '警语4') !== false) {
  1437. // $warning4Partial = $partial;
  1438. // } elseif (strpos($partial['productName'], '警语10') !== false) {
  1439. // $warning10Partial = $partial;
  1440. // }
  1441. // }
  1442. //
  1443. // // 检查是否可以合并(7+13=20箱)
  1444. // if ($warning4Partial && $warning10Partial &&
  1445. // ($warning4Partial['data']['boxes_in_pallet'] + $warning10Partial['data']['boxes_in_pallet']) == 20) {
  1446. //
  1447. // // 警语4版本(7箱)
  1448. // $groupedData[] = [
  1449. // 'pallet' => $currentPalletNumber,
  1450. // 'matter_name' => $warning4Partial['productName'],
  1451. // 'small_num' => $warning4Partial['data']['small_num'],
  1452. // 'total_boxes' => $warning4Partial['data']['boxes_in_pallet'],
  1453. // 'tray_num' => $warning4Partial['data']['tray_num'],
  1454. // 'box_num' => $warning4Partial['data']['box_num'],
  1455. // 'pallet_height' => $warning4Partial['data']['pallet_height'],
  1456. // 'pallet_length' => $warning4Partial['data']['pallet_length'],
  1457. // 'pallet_width' => $warning4Partial['data']['pallet_width'],
  1458. // 'large_num' => 1,
  1459. // 'larger_num' => $warning4Partial['data']['boxes_in_pallet'],
  1460. // 'num' => $warning4Partial['data']['num'],
  1461. // 'danwei' => $warning4Partial['data']['danwei'],
  1462. // 'is_combined' => true
  1463. // ];
  1464. //
  1465. // // 警语10版本(13箱)
  1466. // $groupedData[] = [
  1467. // 'pallet' => $currentPalletNumber,
  1468. // 'matter_name' => $warning10Partial['productName'],
  1469. // 'small_num' => $warning10Partial['data']['small_num'],
  1470. // 'total_boxes' => $warning10Partial['data']['boxes_in_pallet'],
  1471. // 'tray_num' => $warning10Partial['data']['tray_num'],
  1472. // 'box_num' => $warning10Partial['data']['box_num'],
  1473. // 'pallet_height' => $warning10Partial['data']['pallet_height'],
  1474. // 'pallet_length' => $warning10Partial['data']['pallet_length'],
  1475. // 'pallet_width' => $warning10Partial['data']['pallet_width'],
  1476. // 'large_num' => 1,
  1477. // 'larger_num' => $warning10Partial['data']['boxes_in_pallet'],
  1478. // 'num' => $warning10Partial['data']['num'],
  1479. // 'danwei' => $warning10Partial['data']['danwei'],
  1480. // 'is_combined' => true
  1481. // ];
  1482. //
  1483. // $totalTray += 1; // 只算一个托盘
  1484. // $totalBox += 20; // 总箱数7+13=20
  1485. //
  1486. // // 产品统计
  1487. // foreach ([$warning4Partial, $warning10Partial] as $partial) {
  1488. // if (!isset($productSummary[$partial['productName']])) {
  1489. // $productSummary[$partial['productName']] = [
  1490. // 'qty' => 0,
  1491. // 'unit' => $partial['data']['danwei']
  1492. // ];
  1493. // }
  1494. // $productSummary[$partial['productName']]['qty'] += $partial['data']['num'];
  1495. // }
  1496. //
  1497. // $currentPalletNumber++;
  1498. // } else {
  1499. // // 不能合并,单独显示每个部分托盘
  1500. // foreach ($allPartialPallets as $partial) {
  1501. // $groupedData[] = [
  1502. // 'pallet' => $currentPalletNumber,
  1503. // 'matter_name' => $partial['productName'],
  1504. // 'small_num' => $partial['data']['small_num'],
  1505. // 'total_boxes' => $partial['data']['boxes_in_pallet'],
  1506. // 'tray_num' => $partial['data']['tray_num'],
  1507. // 'box_num' => $partial['data']['box_num'],
  1508. // 'pallet_height' => $partial['data']['pallet_height'],
  1509. // 'pallet_length' => $partial['data']['pallet_length'],
  1510. // 'pallet_width' => $partial['data']['pallet_width'],
  1511. // 'large_num' => 1,
  1512. // 'larger_num' => $partial['data']['boxes_in_pallet'],
  1513. // 'num' => $partial['data']['num'],
  1514. // 'danwei' => $partial['data']['danwei']
  1515. // ];
  1516. //
  1517. // $totalTray += 1;
  1518. // $totalBox += $partial['data']['boxes_in_pallet'];
  1519. //
  1520. // if (!isset($productSummary[$partial['productName']])) {
  1521. // $productSummary[$partial['productName']] = [
  1522. // 'qty' => 0,
  1523. // 'unit' => $partial['data']['danwei']
  1524. // ];
  1525. // }
  1526. // $productSummary[$partial['productName']]['qty'] += $partial['data']['num'];
  1527. //
  1528. // $currentPalletNumber++;
  1529. // }
  1530. // }
  1531. //
  1532. // // 9. 单位分类统计
  1533. // $totalTao = 0;
  1534. // $totalZhang = 0;
  1535. // $totalGe = 0;
  1536. //
  1537. // foreach ($productSummary as $product) {
  1538. // switch ($product['unit']) {
  1539. // case '套':
  1540. // $totalTao += $product['qty'];
  1541. // break;
  1542. // case '张':
  1543. // $totalZhang += $product['qty'];
  1544. // break;
  1545. // case '个':
  1546. // $totalGe += $product['qty'];
  1547. // break;
  1548. // }
  1549. // }
  1550. //
  1551. // // 10. 构造返回数据
  1552. // $responseData = [
  1553. // '_id' => $goodList['_id'],
  1554. // 'shrq_date' => date('Y-m-d'),
  1555. // 'shdh' => $goodList['shdh'] ?? '',
  1556. // 'order_number' => $goodList['order_number'] ?? '',
  1557. // 'address' => $goodList['address'] ?? '',
  1558. // 'company_id' => $goodList['company_id'] ?? 0,
  1559. // 'count' => $goodList['count'] ?? 0,
  1560. // 'create_time' => $goodList['create_time'] ?? '',
  1561. // 'data' => $groupedData,
  1562. // 'summary' => [
  1563. // 'totalTray' => $totalTray,
  1564. // 'totalBox' => $totalBox,
  1565. // 'totalTao' => $totalTao,
  1566. // 'totalZhang' => $totalZhang,
  1567. // 'totalGe' => $totalGe,
  1568. // 'products' => $productSummary
  1569. // ],
  1570. // 'delete_time' => $goodList['delete_time'] ?? '',
  1571. // 'deliveryman' => $goodList['deliveryman'] ?? '',
  1572. // 'export_id' => $goodList['export_id'] ?? '',
  1573. // 'note' => $goodList['note'] ?? '',
  1574. // 'order_ddbh' => $goodList['order_ddbh'] ?? '',
  1575. // 'plate_number' => $goodList['plate_number'] ?? '',
  1576. // 'qrcode_add' => $goodList['qrcode_add'] ?? '',
  1577. // 'shr_phone' => $goodList['shr_phone'] ?? '',
  1578. // 'status' => $goodList['status'] ?? 0,
  1579. // 'supplier_id' => $goodList['supplier_id'] ?? 0,
  1580. // 'supplier_name' => $goodList['supplier_name'] ?? '',
  1581. // 'sync_flag' => $goodList['sync_flag'] ?? 0,
  1582. // 'user_id' => $goodList['user_id'] ?? 0
  1583. // ];
  1584. //
  1585. // return json([
  1586. // 'code' => 1,
  1587. // 'data' => $responseData
  1588. // ]);
  1589. //
  1590. // } catch (\Exception $e) {
  1591. // return json([
  1592. // 'code' => 0,
  1593. // 'msg' => '系统错误: ' . $e->getMessage()
  1594. // ]);
  1595. // }
  1596. // }
  1597. /**
  1598. * 获取辅料名称
  1599. * @return \think\response\Json
  1600. * @throws \think\db\exception\DataNotFoundException
  1601. * @throws \think\db\exception\ModelNotFoundException
  1602. * @throws \think\exception\DbException
  1603. */
  1604. public function matterName()
  1605. {
  1606. // $userinfo = Session::get('admin');
  1607. // $lager = new QcodeLarge();
  1608. // $bach = new QcodeBach();
  1609. // $bach_id = $lager->name($userinfo['company'].'_'.'qcode_large')->where('delete_time','')->column('bach_id');
  1610. // $matter_name = [];
  1611. // if (!empty($bach_id)){
  1612. // foreach ($bach_id as $v){
  1613. // $bach_list = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$v)->find();
  1614. // $matter_name[$bach_list['matter_no']] = $bach_list['matter_name'];
  1615. // }
  1616. // }
  1617. // $matter_name = array_unique($matter_name);
  1618. // return json($matter_name);
  1619. }
  1620. /**
  1621. * 发货单删除
  1622. * @param $ids
  1623. * @return void
  1624. */
  1625. public function dispatch_del($ids)
  1626. {
  1627. $goods = new QcodeGoods();
  1628. $export = new QcodeExport();
  1629. if (empty($ids)){
  1630. $this->error('参数错误');
  1631. }
  1632. $res = $goods->where('_id',$ids)->update(['delete_time'=>date('Y-m-d H:i:s',time())]);
  1633. if ($res === false){
  1634. $this->error('删除失败');
  1635. }
  1636. $userinfo = Session::get('admin');
  1637. $mongo = \think\Db::connect('mongodb');
  1638. $collection = $userinfo['company'] . '_qcode_bach';
  1639. $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
  1640. $res_find = $goods->where('_id',$ids)->find();
  1641. $update_status = $mongo->name($bachsummary)->where('_id',$res_find['qcode_bachsummary_id'])->update(
  1642. [
  1643. 'bach_status'=>0,
  1644. 'delete_time' => ''
  1645. ]);
  1646. if ($update_status === false){
  1647. $this->error('删除失败');
  1648. }
  1649. $this->success('成功');
  1650. }
  1651. /**
  1652. * 收货列表
  1653. */
  1654. public function receive()
  1655. {
  1656. //当前是否为关联查询
  1657. $this->relationSearch = false;
  1658. //设置过滤方法
  1659. $this->request->filter(['strip_tags', 'trim']);
  1660. if ($this->request->isAjax()) {
  1661. //如果发送的来源是Selectpage,则转发到Selectpage
  1662. if ($this->request->request('keyField')) {
  1663. return $this->selectpage();
  1664. }
  1665. $where = [
  1666. 'delete_time'=> ''
  1667. ];
  1668. $req = input();
  1669. $req['sort'] == 'id' ? $sort = '_id' : $sort = $req['sort'];
  1670. $order = $req['order'];
  1671. $offset = $req['offset'];
  1672. $limit = $req['limit'];
  1673. // 构造模糊查询条件
  1674. // $regex = new MongoDB\BSON\Regex('.*abc.*', 'i');
  1675. // $filter = ['field' => $regex];
  1676. $filter = json_decode($req['filter'], true);
  1677. if (isset($filter['status'])){
  1678. $where['status'] = intval($filter['status']);
  1679. unset($filter['status']);
  1680. }
  1681. if (isset($filter['create_time'])){
  1682. $begin = substr($filter['create_time'],0,19);
  1683. $end = substr($filter['create_time'],22);
  1684. $begin = strtotime($begin);
  1685. $end = strtotime($end);
  1686. $where['create_time'] = ['between',[$begin,$end]];
  1687. unset($filter['create_time']);
  1688. }
  1689. foreach ($filter as $k => $v){
  1690. $where[$k] = new \MongoDB\BSON\Regex($v);
  1691. }
  1692. $goods = new QcodeGoods();
  1693. $total = $goods->where($where)->count();
  1694. $list = $goods->where($where)
  1695. ->order($sort,$order)
  1696. ->limit($limit)
  1697. ->skip($offset)
  1698. ->select();
  1699. foreach ($list as $k=>$v) {
  1700. $oid = $v['_id']->jsonSerialize();
  1701. $list[$k]['id'] = $oid['$oid'];
  1702. }
  1703. $result = array("total" => $total, "rows" => $list);
  1704. return json($result);
  1705. }
  1706. return $this->view->fetch();
  1707. }
  1708. /**
  1709. * 扫码/输入收货
  1710. */
  1711. public function receive_add()
  1712. {
  1713. $req = $this->request->param();
  1714. if(!isset($req['shdh']) || empty($req['shdh'])){
  1715. $this->error('请输入送货单号');
  1716. }
  1717. $data = [
  1718. 'shdh'=>$req['shdh'],
  1719. 'delete_time'=>'',
  1720. ];
  1721. $goods = new QcodeGoods();
  1722. $row = $goods->where($data)->find();
  1723. if (!$row) $this->error('未查询到该单号');
  1724. if ($row['status']==2) $this->error('该单号已收货');
  1725. //收货---修改status为2
  1726. $bool = $goods->where($data)->update(['status'=>2,'sync_flag'=>0]);
  1727. if ($bool){
  1728. $this->success('成功');
  1729. }else{
  1730. $this->error('失败');
  1731. }
  1732. }
  1733. /**
  1734. * 取消收货
  1735. */
  1736. public function receive_del()
  1737. {
  1738. $req = $this->request->param();
  1739. if(!isset($req['ids']) || empty($req['ids'])){
  1740. $this->error('id不能为空');
  1741. }
  1742. $data = [
  1743. '_id'=>$req['ids'],
  1744. 'delete_time'=>'',
  1745. ];
  1746. $goods = new QcodeGoods();
  1747. //收货---修改status为2
  1748. $bool = $goods->where($data)->update(['status'=>0,'sync_flag'=>0]);
  1749. if ($bool){
  1750. $this->success('成功');
  1751. }else{
  1752. $this->error('失败');
  1753. }
  1754. }
  1755. }