| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932 |
- <?php
- namespace app\admin\controller;
- use app\admin\model\QcodeLarge;
- use app\admin\model\QcodeSmall;
- use app\common\controller\Backend;
- use app\admin\model\QcodeProduct;
- use app\admin\model\QcodeCompany;
- use app\admin\model\QcodeBach;
- use app\admin\model\QcodeExport;
- use fast\Arr;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\Exception;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use app\admin\model\QcodeGoods;
- use think\Config;
- use think\Db;
- use think\Session;
- class Deliver extends Backend
- {
- /**
- * 首页
- */
- public function index()
- {
- return $this->view->fetch();
- }
- /**
- * 大件发货
- */
- public function lager()
- {
- $company = new QcodeCompany();
- $product = new QcodeProduct();
- $large = new QcodeLarge();
- $bach = new QcodeBach();
- $small = new QcodeSmall();
- $this->request->filter(['strip_tags', 'trim']);
- if (false === $this->request->isAjax()) {
- return $this->view->fetch();
- }
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- $userInfo = Session::get('admin');
- $where = ['delete_time' => ''];
- $filter = input('filter');
- $filter = json_decode($filter, true);
- $whereList = ['delete_time' => ''];
- if (isset($filter['matter_name'])) {
- $whereList['matter_no'] = $filter['matter_name'];
- }
- if (isset($filter['bach'])) {
- $whereList['bach_num'] = $filter['bach'];
- }
- if (isset($filter['manufacture_date'])) {
- $begin = substr($filter['manufacture_date'], 0, 19);
- $end = substr($filter['manufacture_date'], 22);
- $begin = (int)date('ymd', strtotime($begin));
- $end = (int)date('ymd', strtotime($end));
- $whereList['manufacture_date'] = ['between', [$begin, $end]];
- }
- // 查出相关 bach_id
- $bach_list = $bach->name($userInfo['company'].'_qcode_bach')->where($whereList)->column('_id');
- $bach_id = [];
- foreach ($bach_list as $v) {
- $id = substr(json_encode($v), 9, -2);
- $bach_id[] = $id;
- }
- // 获取分页参数
- $offset = input('offset', 0);
- $limit = input('limit', 10);
- // 获取所有大件记录用于总量判断
- $all_large_list = $large->name($userInfo['company'].'_qcode_large')
- ->where($where)
- ->where('l_status', 0)
- ->whereIn('bach_id', $bach_id)
- ->select();
- // 统计总数量
- $total = count($all_large_list);
- // 分页
- $large_list = array_slice($all_large_list, $offset, $limit);
- $list = [];
- foreach ($large_list as $k => $v) {
- $bach_detail = $bach->name($userInfo['company'].'_qcode_bach')->where('_id', $v['bach_id'])->find();
- // $num = (int)$bach_detail['num']; // 总张数
- // $small_num = (int)$bach_detail['small_num']; // 每箱张数
- // $boxes_per_pallet = (int)$bach_detail['total_boxes']; // 每托箱数
- // // 重新计算总箱数
- // $larger_num = $num / $small_num;
- // $full_pallets = floor($larger_num / $boxes_per_pallet);
- // $last_pallet_boxes = $larger_num % $boxes_per_pallet;
- $num = (float)$bach_detail['num'];
- $small_num = (float)$bach_detail['small_num'];
- $boxes_per_pallet = (float)$bach_detail['total_boxes'];
- $larger_num = $num / $small_num;
- $full_pallets = floor($larger_num / $boxes_per_pallet);
- $last_pallet_boxes = fmod($larger_num, $boxes_per_pallet); // 真正浮点取余
- $total_pallets = $full_pallets + ($last_pallet_boxes > 0 ? 1 : 0);
- // 当前是第几托(code中解析)
- $current_flow_str = substr($v['code'], 53, 6);
- $current_flow = (int) ltrim($current_flow_str, '0');
- $total_pallets = (int) $total_pallets;
- // 是否是最后一托
- $is_last = ($current_flow === $total_pallets) ? 1 : 0;
- // 修正箱数
- $total_boxes = $boxes_per_pallet;
- if ($is_last && $last_pallet_boxes > 0) {
- // 精准保留1位小数,不做四舍五入
- $total_boxes = number_format($last_pallet_boxes, 1, '.', '');
- // $total_boxes = $last_pallet_boxes;
- }
- $list[$k] = [
- 'id' => substr(json_encode($v['_id']), 9, -2),
- 'l_flow' => $current_flow,
- 'bach' => $bach_detail['bach_num'],
- 'num' => $num,
- 'small_num' => $small_num,
- 'order_ddbh' => $bach_detail['order_ddbh'],
- 'danwei' => $bach_detail['danwei'],
- 'cpbm' => $bach_detail['cpbm'],
- 'matter_name' => $bach_detail['matter_name'],
- 'total_boxes' => $total_boxes,
- 'tray_num' => $bach_detail['tray_num'],
- 'box_num' => $bach_detail['box_num'],
- 'pallet_height' => $bach_detail['pallet_height'],
- 'pallet_length' => $bach_detail['pallet_length'],
- 'pallet_width' => $bach_detail['pallet_width'],
- 'larger_num' => $larger_num,
- 'manufacture_date' => date('Y-m-d', strtotime('20' . $bach_detail['manufacture_date'])),
- 'code' => $v['code'],
- 'is_last' => $is_last,
- ];
- }
- return json(['total' => $total, 'rows' => $list]);
- }
- /**
- * 小件列表
- * @return \think\response\Json
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function smallList()
- {
- $userinfo = Session::get('admin');
- $lager = new QcodeLarge();
- $small = new QcodeSmall();
- if ($this->request->isAjax() === false){
- $this->error('请求错误');
- }
- $filter = input('filter');
- $filter = json_decode($filter,true);
- $order = input('order');
- $offset = input('offset');
- $limit = input('limit');
- $where = [
- 'delete_time' => '',
- ];
- if (isset($filter['large_id'])){
- $where['large_id'] =$filter['large_id'];
- }
- $smallList = $small->name($userinfo['company'].'_'.'qcode_small')
- ->where($where)
- ->skip($offset)
- ->limit($limit)
- ->select();
- $total = $small->name($userinfo['company'].'_'.'qcode_small')->where($where)->count();
- $list = [];
- foreach ($smallList as $k=>$v){
- $list[$k] = [
- 'code' => $v['code'],
- 'l_flow' => $v['l_flow'],
- 'print_num' => $v['p_nums'],
- 'status' => $v['status'],
- ];
- }
- return json(['total'=>$total,'rows'=>$list]);
- }
- /**
- * 导出发货
- * @return void
- * @throws \think\Exception
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function print()
- {
- $userinfo = Session::get('admin');
- $lager = new QcodeLarge();
- $bach = new QcodeBach();
- $small = new QcodeSmall();
- $export = new QcodeExport();
- if ($this->request->isAjax() === false){
- $this->error('请求错误');
- }
- $lager_id = input('lager_id');
- if ($lager_id === ''){
- $this->error('请至少选择一个大件');
- }
- $lagerId = [];
- if (strpos($lager_id,',') === false){
- $lagerId[0] = $lager_id;
- }else{
- $lagerId = explode(',',$lager_id);
- }
- $lager_num = count($lagerId);
- $bach_id = [];
- foreach ($lagerId as $k=>$v){
- $lagerList = $lager->name($userinfo['company'].'_'.'qcode_large')->where('_id',$v)->find();
- $bachList = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$lagerList['bach_id'])->find();
- $bach_id[$k] = substr(json_encode($bachList['_id']),9,-2);
- }
- $bach_id = array_unique($bach_id);
- $data = [];
- foreach ($bach_id as $k=>$v){
- $data[$k] = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$v)->field('matter_no')->find()['matter_no'];
- }
- $data = array_unique($data);
- if (count($data)>1){
- $this->error('请选择同一产品');
- }
- $n =0;
- foreach (explode(',',$lager_id) as $kk=>$vv){
- $n = $n + $small->name($userinfo['company'].'_'.'qcode_small')->where('large_id',$vv)->count();
- }
- // $bachDetail = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$bach_id[0])->find();
- $bachArray = $bach->name($userinfo['company'].'_'.'qcode_bach')
- ->where('_id', $bach_id[0])
- ->find();
- $bachDetail = $bachArray ? $bachArray->toArray() : [];
- if ($bachDetail['box_num'] === 1){
- $mater_type = 2;
- }else{
- $mater_type = 1;
- }
- $exportData = $this->exportdata($bach_id,$lager_id,$userinfo['company'],$lager_num,$n);
- $file_dir = $this->exportExcel($exportData);
- $row = [
- 'username' => $bachDetail['supplier_name'],//公司
- 'matter_no' => $bachDetail['matter_no'],
- 'order_ddbh' => $bachDetail['order_ddbh'],
- 'large_str' => $lager_id,
- 'status' => 0,
- 'bach_num' => $bachDetail['bach_num'],
- 'note' => '',
- 'user_id' => $userinfo['id'],
- 'create_time' => time(),
- 'file_dir' => $file_dir,
- 'company_id' => $userinfo['company'],
- 'large_num' => $lager_num,//你已选中 N 个大件【托盘数】
- 'small_num' => $n,//共包含了 N 个小件
- 'matter_name' => $bachDetail['matter_name'],//产品名称
- 'total_boxes' => $bachDetail['total_boxes'],//每托箱数
- 'tray_num' => $bachDetail['tray_num'],//每层箱数
- 'box_num' => $bachDetail['box_num'],//每托层数
- 'pallet_height' => $bachDetail['pallet_height'],//每托高度
- 'pallet_length' => $bachDetail['pallet_length'],//托盘规格
- 'pallet_width' => $bachDetail['pallet_width'],//托盘规格
- 'larger_num' => $bachDetail['larger_num'],//总箱数
- ];
- if ($bachDetail['box_num'] != 1){
- $row['num'] = $bachDetail['box_num'];
- $row['mater_type'] = 1;
- }else{
- $row['num'] = $bachDetail['s_weight'];
- $row['mater_type'] = 2;
- }
- $res = $export->save($row);
- if ($res === false){
- $this->error('发货失败');
- }
- $lager = new QcodeLarge();
- $lager->name($userinfo['company'].'_'.'qcode_large')->whereIn('_id',$lagerId)->update(['l_status'=>1]);
- $this->success('成功','',$file_dir);
- }
- /**
- * 表格数据处理
- * @param $bach_id
- * @param $large_str
- * @param $company
- * @param $large_num
- * @param $small_num
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function exportdata($bach_id,$large_str,$company,$large_num,$small_num)
- {
- $bach = new QcodeBach();
- $large = new QcodeLarge();
- $small = new QcodeSmall();
- $bachList = $bach->name($company . '_' . 'qcode_bach')->where('_id', $bach_id[0])->find();
- $data = [
- 'supplier_name' => $bachList['supplier_name'],
- 'supplier_no' => $bachList['supplier_code'],
- 'matter_name' => $bachList['matter_name'],
- 'matter_no' => $bachList['matter_no'],
- 'manufacture_date' => date('Y/m/d',strtotime('20'.$bachList['manufacture_date'])),
- 'print_date' => date('Y/m/d',strtotime('20'.$bachList['print_date'])),
- 'box_num' => $large_num,
- 'tray_num' => $bachList['tray_num'],
- 'small_num' => $small_num,
- 'l_reservation' => $bachList['l_reservation'],
- 's_reservation' => $bachList['s_reservation'],
- 'l_flow' => $bachList['l_flow'],
- 's_flow' => $bachList['s_flow'],
- 'l_weight' => 0,
- 's_weight' => $bachList['s_weight']/1000,
- 'code' => [],
- ];
- $large_id = explode(',', $large_str);
- foreach ($large_id as $k => $v) {
- $largeList = $large->name($company . '_' . 'qcode_large')->where('_id', $v)->find();
- $data['l_weight'] = $data['l_weight'] + (int)$largeList['l_weight']/100;
- $small_list = $small->name($company . '_' . 'qcode_small')->where('large_id', $v)->select();
- foreach ($small_list as $value) {
- $code = [
- 'large_code' => $largeList['code'],
- 'small_code' => $value['code'],
- ];
- array_push($data['code'],$code);
- }
- }
- return $data;
- }
- /**
- * 生成excel
- * @param $data
- * @return string
- * @throws Exception
- * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
- */
- public function exportExcel($data)
- {
- $objexcel = new Spreadsheet();
- $sheet = $objexcel->getActiveSheet();
- //设置全局单元格垂直居中
- $objexcel->getDefaultStyle()->getAlignment()->setVertical(Alignment::HORIZONTAL_CENTER);
- //设置全局单元格水平居中
- $objexcel->getDefaultStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- //设置全局单元格自动换行
- $objexcel->getDefaultStyle()->getAlignment()->setWrapText(true);
- //设置单元格宽度
- $sheet->getDefaultColumnDimension()->setWidth(50);
- //设置表头
- $sheet->setCellValue('A1', '文件流水号');
- $sheet->setCellValue('A2', '订单号');
- $sheet->setCellValue('A3', '供应商');
- $sheet->setCellValue('A4', '供应商代码');
- $sheet->setCellValue('A5', '物料名称');
- $sheet->setCellValue('A6', '物料代码');
- $sheet->setCellValue('A7', '生产日期');
- $sheet->setCellValue('A8', '打码日期');
- $sheet->setCellValue('A9', '大件数量');
- $sheet->setCellValue('A10', '托盘小件数量');
- $sheet->setCellValue('A11', '小件总数量');
- $sheet->setCellValue('C3', '大件预留码');
- $sheet->setCellValue('C5', '小件预留码');
- $sheet->setCellValue('C7', '大件开始流水号');
- $sheet->setCellValue('C9', '小件开始流水号');
- $sheet->setCellValue('C11', '大件重量(Kg)');
- $sheet->setCellValue('C13', '小件重量(Kg)');
- $sheet->setCellValue('A15', '大件二维码');
- $sheet->setCellValue('B15', '大件条码(预留)');
- $sheet->setCellValue('C15', '小件二维码');
- $sheet->setCellValue('D15', '小件条码(预留)');
- //插入表格数据
- $sheet->getCell('B3')->setValue(isset($data['supplier_name'])?$data['supplier_name']:'');
- $sheet->getCell('B4')->setValue(isset($data['supplier_no'])?$data['supplier_no']:'');
- $sheet->getCell('B5')->setValue(isset($data['matter_name'])?$data['matter_name']:'');
- $sheet->getCell('B6')->setValue(isset($data['matter_no'])?$data['matter_no']:'');
- $sheet->getCell('B7')->setValue(isset($data['manufacture_date'])?$data['manufacture_date']:'');
- $sheet->getCell('B8')->setValue(isset($data['print_date'])?$data['print_date']:'');
- $sheet->getCell('B9')->setValue(isset($data['box_num'])?$data['box_num']:'');
- $sheet->getCell('B10')->setValue(isset($data['tray_num'])?$data['tray_num']:'');
- $sheet->getCell('B11')->setValue(isset($data['small_num'])?$data['small_num']:'');
- $sheet->getCell('C4')->setValue(isset($data['l_reservation'])?$data['l_reservation']:'');
- $sheet->getCell('C6')->setValue(isset($data['s_reservation'])?$data['s_reservation']:'');
- $sheet->getCell('C8')->setValue(isset($data['l_flow'])?$data['l_flow']:'');
- $sheet->getCell('C10')->setValue(isset($data['s_flow'])?$data['s_flow']:'');
- $sheet->getCell('C12')->setValue(isset($data['l_weight'])?$data['l_weight']:'');
- $sheet->getCell('C14')->setValue(isset($data['s_weight'])?$data['s_weight']:'');
- foreach ($data['code'] as $k=>$v){
- $m = $k+16;
- $sheet->getCell('A'.$m)->setValue(isset($v['large_code'])?$v['large_code']:'');
- $sheet->getCell('B'.$m)->setValue('');
- $sheet->getCell('C'.$m)->setValue(isset($v['small_code'])?$v['small_code']:'');
- $sheet->getCell('D'.$m)->setValue('');
- }
- //文件另存
- $filename = date('Ymd',time()).rand(100,999).'_'.$data['supplier_name'].'_'.str_replace('/','_',$data['matter_name']).'_'.$data['small_num'].'.xlsx';
- // $filename = iconv("utf-8","gb2312",$filename);
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition:attachment;filename='.$filename);
- header('Cache-Control: max-age=0');
- header("Content-Type:text/html;charset=utf-8");
- if(is_dir(ROOT_PATH.'public/uploads/export/') === false)
- {
- mkdir(ROOT_PATH.'public/uploads/export/',0777,true);
- }
- $writer = IOFactory::createWriter($objexcel, 'Xlsx');
- $writer->save(ROOT_PATH.'public/uploads/export/'.$filename);
- return 'uploads/export/'.$filename;
- }
- //获取日期
- public function applydsit_list()
- {
- $userinfo = Session::get('admin');
- $mongo = \think\Db::connect('mongodb');
- try {
- // 查询数据并按日期排序
- $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
- ->order('sys_rq', 'desc')
- ->select();
- // 初始化结果数组
- $result = [
- 'code' => 0,
- 'msg' => '成功',
- 'time' => time(),
- 'data' => []
- ];
- // 处理数据
- foreach ($bach_list as $item) {
- if (isset($item['sys_rq'])) {
- $date = $item['sys_rq'];
- list($year, $month, $day) = explode('-', $date);
- // 构建日期格式
- $yearMonth = "$year-$month";
- $dayFormat = "$month-$day";
- // 按年-月-日分组
- if (!isset($result['data'][$year])) {
- $result['data'][$year] = [];
- }
- if (!isset($result['data'][$year][$yearMonth])) {
- $result['data'][$year][$yearMonth] = [];
- }
- // 添加日期,避免重复
- if (!in_array($dayFormat, $result['data'][$year][$yearMonth])) {
- $result['data'][$year][$yearMonth][] = $dayFormat;
- }
- }
- }
- // 返回JSON格式数据
- return json($result);
- } catch (\Exception $e) {
- // 错误处理
- return json([
- 'code' => 1,
- 'msg' => '查询失败: ' . $e->getMessage(),
- 'time' => time(),
- 'data' => []
- ]);
- }
- }
- //获取发货单日期
- public function dispatch_list()
- {
- $userinfo = Session::get('admin');
- $mongo = \think\Db::connect('mongodb');
- try {
- // 查询数据并按日期排序
- $bach_list = $mongo->name("qcode_goods")
- ->order('sys_rq', 'desc')
- ->where('delete_time','')
- ->select();
- // 初始化结果数组
- $result = [
- 'code' => 0,
- 'msg' => '成功',
- 'time' => time(),
- 'data' => []
- ];
- // 处理数据
- foreach ($bach_list as $item) {
- if (isset($item['sys_rq'])) {
- $date = $item['sys_rq'];
- list($year, $month, $day) = explode('-', $date);
- // 构建日期格式
- $yearMonth = "$year-$month";
- $dayFormat = "$month-$day";
- // 按年-月-日分组
- if (!isset($result['data'][$year])) {
- $result['data'][$year] = [];
- }
- if (!isset($result['data'][$year][$yearMonth])) {
- $result['data'][$year][$yearMonth] = [];
- }
- // 添加日期,避免重复
- if (!in_array($dayFormat, $result['data'][$year][$yearMonth])) {
- $result['data'][$year][$yearMonth][] = $dayFormat;
- }
- }
- }
- // 返回JSON格式数据
- return json($result);
- } catch (\Exception $e) {
- // 错误处理
- return json([
- 'code' => 1,
- 'msg' => '查询失败: ' . $e->getMessage(),
- 'time' => time(),
- 'data' => []
- ]);
- }
- }
- // 获取主数据
- public function apply()
- {
- $mongo = Db::connect('mongodb');
- $this->request->filter(['strip_tags', 'trim']);
- if (false === $this->request->isAjax()) {
- return $this->view->fetch();
- }
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- // 保存编辑请求
- if ($this->request->isPost() && $this->request->post('data')) {
- return $this->saveEdits();
- }
- $userinfo = Session::get('admin');
- $where = ['delete_time' => ''];
- // 处理日期筛选条件
- $date = $this->request->get('date', '');
- $month = $this->request->get('month', '');
- $year = $this->request->get('year', '');
- if ($date && $date !== 'all') {
- $where['sys_rq'] = $date;
- } elseif ($month) {
- $where['sys_rq'] = new \MongoDB\BSON\Regex($month, 'i');
- } elseif ($year) {
- $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
- } else {
- // 无日期参数时默认查询当天日期
- $where['sys_rq'] = date('Y-m-d');
- }
- // 时间范围查询(高级过滤)
- $filter = input('filter');
- $filter = json_decode($filter, true);
- if (isset($filter['create_time'])) {
- $begin = substr($filter['create_time'], 0, 19);
- $end = substr($filter['create_time'], 22);
- $begin = strtotime($begin);
- $end = strtotime($end);
- $where['create_time'] = ['between', [$begin, $end]];
- }
- $order = input('order') ?: 'desc';
- $offset = (int)input('offset', 0);
- $limit = (int)input('limit', 20);
- // 总数统计
- $total = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
- ->where($where)
- ->count([]);
- // 列表数据
- $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bachsummary")
- ->where($where)
- ->order('_id', $order)
- ->skip($offset)
- ->limit($limit)
- ->select();
- $list = [];
- foreach ($bach_list as $k => $v) {
- $list[$k]['bach_ids'] = $v['bach_ids'];
- $list[$k]['total_quantity'] = $v['total_quantity'];
- $list[$k]['total_boxes'] = $v['total_boxes'];
- $list[$k]['total_pallets'] = $v['total_pallets'];
- $list[$k]['product_count'] = $v['product_count'];
- $list[$k]['sys_rq'] = $v['sys_rq'];
- $list[$k]['created_at'] = $v['created_at'];
- $list[$k]['id'] = (string)$v['_id'];
- }
- return json(['total' => $total, 'rows' => $list]);
- }
- public function bachdelids()
- {
- $bach_ids = $this->request->param('bach_ids');
- if (empty($bach_ids)) {
- return json(['code' => 0, 'msg' => '未查询到要删除的记录']);
- }
- $userinfo = Session::get('admin');
- if (empty($userinfo) || !isset($userinfo['company'])) {
- return json(['code' => 0, 'msg' => '获取用户信息失败,请重新登录']);
- }
- $mongo = \think\Db::connect('mongodb');
- $company = $userinfo['company'];
- $collection = $company . '_qcode_bach';
- $bachdetails = $company . '_qcode_bachdetails';
- $bachsummary = $company . '_qcode_bachsummary';
- // 获取批次详情数据
- $detailData = $mongo->name($collection)
- ->where('bach_ids', $bach_ids)
- ->select();
- $productQuantities = [];
- if (!empty($detailData)) {
- // 按产品名称分组统计实际数量
- foreach ($detailData as $detail) {
- $matterName = $detail['cpmc'];
- $actualQuantity = floatval($detail['actual_quantity']);
- if ($matterName && $actualQuantity > 0) {
- if (!isset($productQuantities[$matterName])) {
- $productQuantities[$matterName] = 0;
- }
- $productQuantities[$matterName] += $actualQuantity;
- }
- }
- // 处理库存退回
- foreach ($productQuantities as $productName => $returnQuantity) {
- // 获取产品最新的库存记录
- $latestRecord = $mongo->name('inventory_records')
- ->where('cpmc', $productName)
- ->order('created_at', 'desc')
- ->find();
- if (!empty($latestRecord)) {
- // 计算新的库存数量并更新库存记录
- $newRemainingQuantity = floatval($latestRecord['remaining_quantity'] ?? 0) + $returnQuantity;
- $newTotalChuQuantity = max(0, floatval($latestRecord['total_chu_quantity'] ?? 0) - $returnQuantity);
- $mongo->name('inventory_records')
- ->where('_id', $latestRecord['_id'])
- ->update([
- 'remaining_quantity' => $newRemainingQuantity,
- 'total_chu_quantity' => $newTotalChuQuantity,
- 'update_time' => time()
- ]);
- // 更新库存汇总表
- // 使用cpmc字段进行查询,与文档结构保持一致
- $summary = $mongo->name('inventory_summary')
- ->where('cpmc', $productName)
- ->find();
- if ($summary) {
- $mongo->name('inventory_summary')
- ->where('_id', $summary['_id'])
- ->update([
- 'remaining_quantity' => floatval($summary['remaining_quantity'] ?? 0) + $returnQuantity,
- 'total_chu_quantity' => max(0, floatval($summary['total_chu_quantity'] ?? 0) - $returnQuantity),
- 'update_time' => time()
- ]);
- }
- }
- }
- }
- // 标记批次为删除状态
- $delete_time = time();
- $mongo->name($collection)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
- $mongo->name($bachdetails)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
- $mongo->name($bachsummary)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
- return json([
- 'code' => 1,
- 'msg' => '删除成功,库存已退回',
- 'data' => ['returned_products' => $productQuantities]
- ]);
- }
- /**
- * 明细数据 (通过 bach_ids 获取)
- */
- public function bachids()
- {
- $mongo = \think\Db::connect('mongodb');
- $this->request->filter(['strip_tags', 'trim']);
- if (false === $this->request->isAjax()) {
- return $this->view->fetch();
- }
- $userinfo = Session::get('admin');
- $bach_ids = input('bach_ids');
- $where = [
- 'bach_ids' => $bach_ids,
- 'delete_time' => ''
- ];
- $filter = input('filter');
- $filter = json_decode($filter, true);
- if (isset($filter['matter_name'])) {
- $where['matter_no'] = $filter['matter_name'];
- }
- if (isset($filter['create_time'])) {
- $begin = substr($filter['create_time'], 0, 19);
- $end = substr($filter['create_time'], 22);
- $begin = strtotime($begin);
- $end = strtotime($end);
- $where['create_time'] = ['between', [$begin, $end]];
- }
- $order = input('order') ?: 'desc';
- $offset = (int)input('offset', 0);
- $limit = (int)input('limit', 20);
- $total = $mongo->name($userinfo['company'] . '_' . "qcode_bach")
- ->where($where)
- ->count([]);
- // 查询数据
- $bach_list = $mongo->name($userinfo['company'] . '_' . "qcode_bach")
- ->where($where)
- ->select(); // 去掉 order、skip、limit,让我们用 PHP 自定义排序
- // 自定义排序规则:按 pallet_range 起始数字升序排列
- usort($bach_list, function ($a, $b) {
- // 提取起始数字
- $getStart = function ($val) {
- if (strpos($val, '-') !== false) {
- return (int)explode('-', $val)[0];
- }
- return (int)$val;
- };
- return $getStart($a['pallet_range']) <=> $getStart($b['pallet_range']);
- });
- // 手动分页(如有分页需求)
- $total = count($bach_list);
- $offset = (int)input('offset', 0);
- $limit = (int)input('limit', 20);
- $pagedList = array_slice($bach_list, $offset, $limit);
- // 格式化返回数据
- $list = [];
- foreach ($pagedList as $k => $v) {
- $list[$k]['start_pallet_no'] = $v['start_pallet_no'];
- $list[$k]['end_pallet_no'] = $v['end_pallet_no'];
- $list[$k]['pallet_range'] = $v['pallet_range'];
- $list[$k]['total_boxes'] = $v['total_boxes'];
- $list[$k]['pallet_count'] = $v['pallet_count'];
- $list[$k]['actual_quantity'] = $v['actual_quantity'];
- $list[$k]['gdbh'] = $v['gdbh'];
- $list[$k]['matter_no'] = $v['gdbh'];
- $list[$k]['order_ddbh'] = $v['order_ddbh'];
- $list[$k]['cpbm'] = $v['cpbm'];
- $list[$k]['matter_name'] = $v['matter_name'];
- $list[$k]['remark'] = $v['remark'];
- $list[$k]['small_num'] = $v['small_num'];
- $list[$k]['tray_num'] = $v['tray_num'];
- $list[$k]['box_num'] = $v['box_num'];
- $list[$k]['tray_count'] = $v['tray_count'];
- $list[$k]['layer_height'] = $v['layer_height'];
- $list[$k]['pallet_length'] = $v['pallet_length'];
- $list[$k]['pallet_width'] = $v['pallet_width'];
- $list[$k]['sys_rq'] = $v['sys_rq'];
- $list[$k]['id'] = (string)$v['_id'];
- }
- return json(['total' => $total, 'rows' => $list]);
- }
- public function applydsit_add()
- {
- if ($this->request->isPost()) {
- // 获取前端提交的数据
- $params = $this->request->post();
- $bach_ids = $params['bach_ids'] ?? '';
- $pallet_nos = $params['pallet_no'] ?? [];
- $product_names = $params['product_name'] ?? [];
- $remarks = $params['remark'] ?? [];
- $quantities = $params['quantity'] ?? [];
- $unit = $params['unit'] ?? [];
- if (!$bach_ids) {
- return json(['code' => 0, 'msg' => '缺少单据编号']);
- }
- // 获取当前登录用户的公司名
- $userinfo = Session::get('admin');
- if (!$userinfo || empty($userinfo['company'])) {
- return json(['code' => 0, 'msg' => '未获取到用户公司信息']);
- }
- // 连接 MongoDB
- try {
- $mongo = Db::connect('mongodb');
- } catch (\Exception $e) {
- return json(['code' => 0, 'msg' => 'MongoDB 连接失败: ' . $e->getMessage()]);
- }
- // 查询汇总表
- $summaryTable = $userinfo['company'] . '_qcode_bachsummary';
- $summaryData = $mongo->name($summaryTable)->where(['bach_ids' => $bach_ids])->find();
- if (!$summaryData) {
- return json(['code' => 0, 'msg' => '未找到对应的汇总单据']);
- }
- // 写入明细表
- $detailTable = $userinfo['company'] . '_qcode_bach';
- $insertedCount = 0;
- foreach ($pallet_nos as $i => $palletNo) {
- if (empty($palletNo)) continue;
- $data = [
- 'bach_ids' => $bach_ids,//关联
- 'userid' => $userinfo['id'],//用户ID
- 'pallet_range' => $palletNo,//托盘号
- 'cpmc' => $product_names[$i],//产品名称
- 'matter_name' => $product_names[$i],//产品名称
- 'remark' => $remarks[$i],//备注
- 'total_boxes' => '',//总箱数
- 'actual_quantity' => (int)($quantities[$i] ?? 0),//数量
- 'pallet_count' => '',//托盘数
- 'sys_rq' => date('Y-m-d'),
- 'created_at' => date('Y-m-d H:i:s'),
- 'create_time' => time(),
- 'unit' => $unit[$i],//单位
- // 结构字段保留,但设为空
- 'gdbh' => '',
- 'order_ddbh' => '',
- 'cpbm' => '',
- 'small_num' => '',
- 'tray_num' => '',
- 'box_num' => '',
- 'tray_count' => '',
- 'layer_height' => '',
- 'pallet_length' => '',
- 'pallet_width' => '',
- 'pallet_type' => '',
- 'start_pallet_no' => '',
- 'end_pallet_no' => '',
- 'bach_status' => 0,
- 'delete_time' => '',
- ];
- $mongo->name($detailTable)->insert($data);
- $insertedCount++;
- }
- return json(['code' => 1, 'msg' => "成功插入 {$insertedCount} 条托盘信息"]);
- }
- return json(['code' => 0, 'msg' => '非法请求方式']);
- }
- /**
- * 保存编辑的数据
- */
- public function apply_update()
- {
- $this->request->filter(['strip_tags', 'trim']);
- if (!$this->request->isPost()) {
- $this->error('请求错误');
- }
- $userinfo = Session::get('admin');
- $tableName = $userinfo['company'] . '_' . "qcode_bach";
- $id = $this->request->post('id');
- $field = $this->request->post('field');
- $value = $this->request->post('value');
- // 允许前端编辑的字段
- $allowedFields = ['pallet_range', 'start_pallet_no', 'end_pallet_no','remark'];
- if (!in_array($field, $allowedFields)) {
- $this->error('该字段不允许编辑');
- }
- $mongo = \think\Db::connect('mongodb');
- $bach = $mongo->name($tableName)->where('_id', new \MongoDB\BSON\ObjectId($id))->find();
- if (!$bach) {
- $this->error('数据未找到');
- }
- // 更新字段值
- $bach[$field] = is_numeric($value) ? (int)$value : $value;
- // 整理更新字段(去除 _id)
- $updateData = [];
- foreach ($bach as $k => $v) {
- if ($k != '_id') {
- $updateData[$k] = $v;
- }
- }
- $result = $mongo->name($tableName)
- ->where('_id', new \MongoDB\BSON\ObjectId($id))
- ->update($updateData);
- if ($result) {
- $this->success('更新成功');
- } else {
- $this->error('更新失败');
- }
- }
- /**
- * 批次发货删除
- * @param $ids
- * @return void
- */
- public function apply_del($ids)
- {
- $export = new QcodeExport();
- $userinfo = Session::get('admin');
- $large = new QcodeLarge();
- if (empty($ids)){
- $this->error('请求错误');
- }
- $res = $export->where('_id',$ids)->update(['delete_time'=>date('Y-m-d H:i:s',time())]);
- if ($res === false){
- $this->error('删除失败');
- }
- $large_list = $export->where('_id',$ids)->find();
- $large_id = explode(',',$large_list['large_str']);
- foreach ($large_id as $v){
- $result = $large->name($userinfo['company'].'_'.'qcode_large')->where('_id',$v)->update(['l_status'=>0]);
- if ($result === 0){
- $this->error('删除失败');
- }
- }
- $this->success('成功');
- }
- /**
- * 司机弹窗
- * @param $ids
- */
- public function goods($ids)
- {
- $this->view->assign('ids',$ids);
- return $this->view->fetch();
- }
- public function ReplicationList()
- {
- $goods = new QcodeGoods();
- $userinfo = Session::get('admin');
- //shr_phone电话\plate_number车牌号/deliveryman司机
- $arr = $goods->where('user_id',$userinfo['id'])->order('create_time','desc')->where("delete_time","")->find();
- return json(['code' => 1, 'data' => $arr, 'msg' => '成功']);
- }
- /**
- * 申请发货
- */
- public function apply_add()
- {
- $goods = new QcodeGoods();
- $export = new QcodeExport();
- $userinfo = Session::get('admin');
- if ($this->request->isAjax() === false){
- $this->error('请求错误');
- }
- $ids = input('ids');
- $order_number = input('order_number');
- $deliveryman = input('deliveryman');
- $shr_phone = input('shr_phone');
- $plate_number = input('plate_number');
- $note = input('note');
- $mongo = \think\Db::connect('mongodb');
- $collection = $userinfo['company'] . '_qcode_bach';
- $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
- $update_status = $mongo->name($bachsummary)->where('_id',$ids)->update(
- [
- 'bach_status'=>2,
- 'delete_time' => date('Y-m-d H:i:s')
- ]);
- if ($update_status){
- $bachsummary_list = $mongo->name($bachsummary)->where('_id',$ids)->select();
- $daterq = date('ymd',time());
- $data = [
- 'shdh' => substr($daterq,2,2).' '.substr($daterq,2,6).mt_rand(1000,9999),//收货单号
- 'order_number' => $order_number,//订单号
- 'deliveryman' => $deliveryman,//司机名字
- 'shr_phone' => $shr_phone,//电话
- 'plate_number' => $plate_number,//车牌号
- 'shrq_date' => '',
- 'supplier_name' => $userinfo['company_name'],//供应商名称
- 'supplier_id' => $userinfo['id'],//供应商名称id
- 'user_id' => $userinfo['id'],//用户id
- 'status' => 0,
- 'qcode_bachsummary_id' => $ids,
- 'export_id' => '',
- 'create_time' => time(),
- 'sys_rq' => date('Y-m-d'),
- 'note' => $note,
- 'company_id' => $userinfo['company'],
- ];
- $data['qrcode_add'] = $this->Qrcode($data['shdh']);
- // return json(['code' => 1, 'data' => $data, 'msg' => '成功']);
- $res = $goods->save($data);
- if ($res === false){
- $this->error('失败');
- }
- $this->success('成功');
- }else{
- $this->error('失败');
- }
- }
- /**
- * 生成二维码
- * @param $url
- * @return string
- */
- public function Qrcode($url)
- {
- $level=2;
- $size=5;
- Vendor('phpqrcode.phpqrcode');//加载生成二维码的核心类
- $errorCorrectionLevel =intval($level) ;//容错级别
- $matrixPointSize = intval($size);//生成图片大小
- //生成二维码图片
- $object = new \QRcode();
- //打开缓冲区
- ob_start();
- $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
- //这里就是把生成的图片流从缓冲区保存到内存对象上,使用base64_encode变成编码字符串,通过json返回给页面。
- $imageString = base64_encode(ob_get_contents());
- //关闭缓冲区
- ob_end_clean();
- //把生成的base64字符串返回给前端
- return 'data:image/png;base64,'.$imageString;
- }
- /**
- * 发货单
- * @return string|\think\response\Json
- * @throws \think\Exception
- */
- public function dispatch()
- {
- $export = new QcodeGoods();
- $this->request->filter(['strip_tags', 'trim']);
- // 非Ajax请求返回视图
- if (false === $this->request->isAjax()) {
- return $this->view->fetch();
- }
- // 处理selectpage请求
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- // 获取用户信息
- $userInfo = Session::get('admin');
- $where = [
- 'company_id' => $userInfo['company'],
- 'delete_time' => ''
- ];
- // 处理搜索条件
- $search = input('search');
- if (isset($search)) {
- $where['order_number|supplier_name|status|plate_number|shdh|deliveryman'] =
- new \MongoDB\BSON\Regex($search);
- }
- // 处理筛选条件
- $filter = input('filter');
- $filter = json_decode($filter, true) ?: [];
- // 订单编号查询
- if (isset($filter['order_number'])) {
- $where['order_number'] = $filter['order_number'];
- }
- // 所属公司查询
- if (isset($filter['supplier_name'])) {
- $where['supplier_name'] = $filter['supplier_name'];
- }
- // 状态查询
- if (isset($filter['status'])) {
- $where['status'] = (int)$filter['status'];
- }
- // 处理日期筛选条件
- $date = $this->request->get('date', '');
- $month = $this->request->get('month', '');
- $year = $this->request->get('year', '');
- if ($date && $date !== 'all') {
- $where['sys_rq'] = $date;
- } elseif ($month) {
- $where['sys_rq'] = new \MongoDB\BSON\Regex($month, 'i');
- } elseif ($year) {
- $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
- } else {
- // 无日期参数时默认查询当天日期
- $where['sys_rq'] = date('Y-m-d');
- }
- // 分页和排序参数
- $order = input('order', 'desc'); // 默认降序
- $offset = input('offset', 0);
- $limit = input('limit', 10); // 默认每页10条
- // 查询数据
- $total = $export->where($where)->count();
- $export_list = $export
- ->order('_id', $order)
- ->where($where)
- ->whereIn('status', [0, 1])
- ->skip($offset)
- ->limit($limit)
- ->select();
- // 处理批次汇总数据
- $userinfo = Session::get('admin');
- $mongo = \think\Db::connect('mongodb');
- $bachsummary = $userinfo['company'] . '_qcode_bachsummary'; // 批次汇总表
- $list = [];
- foreach ($export_list as $k => $v) {
- $bachsummary_list = $mongo->name($bachsummary)->where("_id", $v['qcode_bachsummary_id'])->find();
- $list[$k] = [
- 'bach_ids' => $bachsummary_list['bach_ids'] ?? '',
- 'total_quantity' => $bachsummary_list['total_quantity'] ?? 0,
- 'total_boxes' => $bachsummary_list['total_boxes'] ?? 0,
- 'total_pallets' => $bachsummary_list['total_pallets'] ?? 0,
- 'product_count' => $bachsummary_list['product_count'] ?? 0,
- 'id' => substr(json_encode($v['_id']), 9, -2),
- 'shdh' => $v['shdh'] ?? '',
- 'order_number' => $v['order_number'] ?? '',
- 'supplier_name' => $v['supplier_name'] ?? '',
- 'deliveryman' => $v['deliveryman'] ?? '',
- 'plate_number' => $v['plate_number'] ?? '',
- 'create_time' => $v['create_time'] ?? 0,
- 'status' => $v['status'] ?? 0
- ];
- }
- // 返回结果
- return json([
- 'total' => $total,
- 'rows' => $list
- ]);
- }
- /**
- * 打印发货单
- */
- public function printqrcode()
- {
- if (!$this->request->isAjax()) {
- return json(['code' => 0, 'msg' => '请求错误']);
- }
- try {
- $mongo = \think\Db::connect('mongodb');
- $userinfo = Session::get('admin');
- $goodsCollection = '_qcode_goods';
- $bachCollection = $userinfo['company'] . '_qcode_bach';
- $bachsummaryCollection = $userinfo['company'] . '_qcode_bachsummary';
- $id = input('id');
- // 获取发货单数据
- $goodList = $mongo->name($goodsCollection)->where('_id', $id)->find();
- if (empty($goodList)) {
- return json(['code' => 0, 'msg' => '未找到发货单数据']);
- }
- // 获取批次汇总数据
- $bachsummaryData = $mongo->name($bachsummaryCollection)
- ->where('_id', $goodList['qcode_bachsummary_id'])
- ->find();
- if (empty($bachsummaryData)) {
- return json(['code' => 0, 'msg' => '未找到对应的批次汇总数据']);
- }
- // 获取批次数据
- $bachData = $mongo->name($bachCollection)
- ->where('bach_ids', $bachsummaryData['bach_ids'])
- ->select();
- if (empty($bachData)) {
- return json(['code' => 0, 'msg' => '未找到对应的批次数据']);
- }
- // 初始化数据变量
- $groupedData = [];
- $totalTray = 0;
- $totalBox = 0;
- $productSummary = [];
- $totalTao = 0;
- $totalZhang = 0;
- $totalGe = 0;
- // 处理每个批次数据
- foreach ($bachData as $item) {
- // 数据类型转换和默认值处理
- $actualQty = is_numeric($item['actual_quantity']) ? (int)$item['actual_quantity'] : 0;
- $boxCount = is_numeric($item['total_boxes']) ? (int)$item['total_boxes'] : 0;
- $trayCount = is_numeric($item['pallet_count']) ? (int)$item['pallet_count'] : 0;
- // 累计总数
- $totalTray += $trayCount;
- $totalBox += $boxCount;
- // 按单位分类累计数量
- $unit = $item['unit'] ?? '';
- switch ($unit) {
- case '个':
- case '套':
- $totalTao += $actualQty;
- break;
- case '张':
- case '托':
- case '卷':
- $totalZhang += $actualQty;
- break;
- default:
- $totalGe += $actualQty;
- break;
- }
- // 处理产品摘要和备注去重
- $productName = $item['matter_name'] ?? '';
- $remark = $item['remark'] ?? '';
- if (!isset($productSummary[$productName])) {
- $productSummary[$productName] = ['qty' => 0, 'unit' => $unit, 'remark' => $remark];
- } else {
- // 备注去重处理
- if ($remark && $productSummary[$productName]['remark']) {
- // 合并备注并去重
- $existingRemarks = explode(';', $productSummary[$productName]['remark']);
- $newRemarks = explode(';', $remark);
- // 合并并去除空白项
- $allRemarks = array_merge($existingRemarks, $newRemarks);
- $trimmedRemarks = array_map('trim', $allRemarks);
- $nonEmptyRemarks = array_filter($trimmedRemarks);
- // 去重并重新拼接
- $uniqueRemarks = array_unique($nonEmptyRemarks);
- $productSummary[$productName]['remark'] = implode('; ', $uniqueRemarks);
- } else if ($remark) {
- $productSummary[$productName]['remark'] = $remark;
- }
- }
- // 累计产品数量
- $productSummary[$productName]['qty'] += $actualQty;
- // 计算每托箱数
- $boxesPerPallet = (is_numeric($item['tray_num']) && is_numeric($item['box_num']))
- ? $item['tray_num'] * $item['box_num'] : $boxCount;
- // 添加到分组数据中
- $groupedData[] = [
- 'pallet' => $item['pallet_range'] ?? '',
- 'matter_name' => $productName,
- 'small_num' => $item['small_num'] ?? '',
- 'total_boxes' => $boxesPerPallet,
- 'tray_num' => $item['tray_num'] ?? '',
- 'box_num' => $item['box_num'] ?? '',
- 'pallet_height' => $item['layer_height'] ?? '',
- 'pallet_length' => $item['pallet_length'] ?? '',
- 'pallet_width' => $item['pallet_width'] ?? '',
- 'large_num' => $trayCount,
- 'larger_num' => $boxCount,
- 'num' => $actualQty,
- 'danwei' => $unit,
- 'order_ddbh' => $item['order_ddbh'] ?? '',
- 'gdbh' => $item['gdbh'] ?? '',
- 'cpbm' => $item['cpbm'] ?? ''
- ];
- }
- // 处理0值转换为空字符串的函数
- $convertZeroToEmpty = function($value) {
- return ($value === 0 || $value === '0') ? '' : $value;
- };
- // 处理groupedData中的0值
- foreach ($groupedData as &$dataItem) {
- foreach ($dataItem as $key => &$value) {
- if (is_numeric($value)) {
- $value = $convertZeroToEmpty($value);
- }
- }
- }
- // 构建响应数据
- $responseData = [
- '_id' => $goodList['_id'],
- 'shrq_date' => date('Y-m-d'),
- 'shdh' => $goodList['shdh'] ?? '',
- 'order_number' => $goodList['order_number'] ?? '',
- 'address' => $goodList['address'] ?? '',
- 'company_id' => $convertZeroToEmpty($goodList['company_id'] ?? 0),
- 'count' => $convertZeroToEmpty($goodList['count'] ?? 0),
- 'create_time' => $goodList['create_time'] ?? '',
- 'data' => $groupedData,
- 'summary' => [
- 'totalTray' => $convertZeroToEmpty($totalTray),
- 'totalBox' => $convertZeroToEmpty($totalBox),
- 'totalTao' => $convertZeroToEmpty($totalTao),
- 'totalZhang' => $convertZeroToEmpty($totalZhang),
- 'totalGe' => $convertZeroToEmpty($totalGe),
- 'products' => $productSummary
- ],
- 'delete_time' => $goodList['delete_time'] ?? '',
- 'deliveryman' => $goodList['deliveryman'] ?? '',
- 'export_id' => $goodList['export_id'] ?? '',
- 'note' => $goodList['note'] ?? '',
- 'order_ddbh' => $goodList['order_ddbh'] ?? '',
- 'plate_number' => $goodList['plate_number'] ?? '',
- 'qrcode_add' => $goodList['qrcode_add'] ?? '',
- 'shr_phone' => $goodList['shr_phone'] ?? '',
- 'status' => $convertZeroToEmpty($goodList['status'] ?? 0),
- 'supplier_id' => $convertZeroToEmpty($goodList['supplier_id'] ?? 0),
- 'supplier_name' => $goodList['supplier_name'] ?? '',
- 'sync_flag' => $convertZeroToEmpty($goodList['sync_flag'] ?? 0),
- 'user_id' => $convertZeroToEmpty($goodList['user_id'] ?? 0)
- ];
- return json(['code' => 1, 'data' => $responseData]);
- } catch (\Exception $e) {
- return json(['code' => 0, 'msg' => '系统错误: ' . $e->getMessage()]);
- }
- }
- // public function printqrcode()
- // {
- // // 1. 验证请求类型
- // if (!$this->request->isAjax()) {
- // return json(['code' => 0, 'msg' => '请求错误']);
- // }
- //
- // try {
- // // 2. 初始化数据库连接
- // $mongo = \think\Db::connect('mongodb');
- // $userinfo = Session::get('admin');
- //
- // if (empty($userinfo) || empty($userinfo['company'])) {
- // return json(['code' => 0, 'msg' => '用户信息获取失败']);
- // }
- //
- // // 3. 设置集合名称
- // $goodsCollection = '_qcode_goods';
- // $bachCollection = $userinfo['company'] . '_qcode_bach';
- // $bachsummaryCollection = $userinfo['company'] . '_qcode_bachsummary';
- //
- // // 4. 获取请求参数
- // $id = input('id');
- // if (empty($id)) {
- // return json(['code' => 0, 'msg' => 'ID不能为空']);
- // }
- //
- // // 5. 查询发货单信息
- // $goodList = $mongo->name($goodsCollection)
- // ->where('_id', $id)
- // ->find();
- //
- // if (empty($goodList)) {
- // return json(['code' => 0, 'msg' => '未找到发货单数据']);
- // }
- //
- // // 6. 获取批次数据
- // if (isset($goodList['data']) && is_array($goodList['data'])) {
- // $detailData = $goodList['data'];
- // } else {
- // if (empty($goodList['qcode_bachsummary_id'])) {
- // return json(['code' => 0, 'msg' => '发货单缺少批次汇总ID']);
- // }
- //
- // $bachsummaryData = $mongo->name($bachsummaryCollection)
- // ->where('_id', $goodList['qcode_bachsummary_id'])
- // ->find();
- //
- // if (empty($bachsummaryData)) {
- // return json(['code' => 0, 'msg' => '未找到对应的批次汇总数据']);
- // }
- //
- // $detailData = $mongo->name($bachCollection)
- // ->where('bach_ids', $bachsummaryData['bach_ids'])
- // ->select();
- // }
- //
- // // 7. 按产品名称分组处理
- // $productGroups = [];
- // foreach ($detailData as $item) {
- // $productName = $item['matter_name'];
- // if (!isset($productGroups[$productName])) {
- // $productGroups[$productName] = [];
- // }
- // $productGroups[$productName][] = $item;
- // }
- //
- // // 8. 处理分组数据
- // $groupedData = [];
- // $totalTray = 0;
- // $totalBox = 0;
- // $productSummary = [];
- //
- // // 存储完整托盘和部分托盘
- // $allFullPallets = [];
- // $allPartialPallets = [];
- //
- // foreach ($productGroups as $productName => $items) {
- // foreach ($items as $item) {
- // if ($item['pallet_type'] === 'full') {
- // $allFullPallets[] = [
- // 'productName' => $productName,
- // 'data' => $item
- // ];
- // } else {
- // $allPartialPallets[] = [
- // 'productName' => $productName,
- // 'data' => $item
- // ];
- // }
- // }
- // }
- //
- // // 对完整托盘按产品名称和托盘序号排序
- // usort($allFullPallets, function($a, $b) {
- // $nameCompare = strcmp($a['productName'], $b['productName']);
- // if ($nameCompare !== 0) {
- // return $nameCompare;
- // }
- // return $a['data']['pallet_sequence'] <=> $b['data']['pallet_sequence'];
- // });
- //
- // // 处理完整托盘
- // $currentPalletNumber = 1;
- // $currentProduct = null;
- // $rangeStart = null;
- // $rangeCount = 0;
- //
- // foreach ($allFullPallets as $index => $pallet) {
- // if ($pallet['productName'] !== $currentProduct) {
- // // 完成上一个产品范围
- // if ($rangeStart !== null) {
- // $first = $allFullPallets[$rangeStart]['data'];
- //
- // $groupedData[] = [
- // 'pallet' => $currentPalletNumber . '-' . ($currentPalletNumber + $rangeCount - 1),
- // 'matter_name' => $currentProduct,
- // 'small_num' => $first['small_num'],
- // 'total_boxes' => $first['boxes_in_pallet'],
- // 'tray_num' => $first['tray_num'],
- // 'box_num' => $first['box_num'],
- // 'pallet_height' => $first['pallet_height'],
- // 'pallet_length' => $first['pallet_length'],
- // 'pallet_width' => $first['pallet_width'],
- // 'large_num' => $rangeCount,
- // 'larger_num' => $first['boxes_in_pallet'] * $rangeCount,
- // 'num' => $first['num'] * $rangeCount,
- // 'danwei' => $first['danwei']
- // ];
- //
- // $totalTray += $rangeCount;
- // $totalBox += $first['boxes_in_pallet'] * $rangeCount;
- //
- // if (!isset($productSummary[$currentProduct])) {
- // $productSummary[$currentProduct] = [
- // 'qty' => 0,
- // 'unit' => $first['danwei']
- // ];
- // }
- // $productSummary[$currentProduct]['qty'] += $first['num'] * $rangeCount;
- //
- // $currentPalletNumber += $rangeCount;
- // }
- //
- // // 开始新的产品范围
- // $currentProduct = $pallet['productName'];
- // $rangeStart = $index;
- // $rangeCount = 1;
- // } else {
- // $rangeCount++;
- // }
- // }
- //
- // // 处理最后一个产品范围
- // if ($rangeStart !== null) {
- // $first = $allFullPallets[$rangeStart]['data'];
- //
- // $groupedData[] = [
- // 'pallet' => $currentPalletNumber . '-' . ($currentPalletNumber + $rangeCount - 1),
- // 'matter_name' => $currentProduct,
- // 'small_num' => $first['small_num'],
- // 'total_boxes' => $first['boxes_in_pallet'],
- // 'tray_num' => $first['tray_num'],
- // 'box_num' => $first['box_num'],
- // 'pallet_height' => $first['pallet_height'],
- // 'pallet_length' => $first['pallet_length'],
- // 'pallet_width' => $first['pallet_width'],
- // 'large_num' => $rangeCount,
- // 'larger_num' => $first['boxes_in_pallet'] * $rangeCount,
- // 'num' => $first['num'] * $rangeCount,
- // 'danwei' => $first['danwei']
- // ];
- //
- // $totalTray += $rangeCount;
- // $totalBox += $first['boxes_in_pallet'] * $rangeCount;
- //
- // if (!isset($productSummary[$currentProduct])) {
- // $productSummary[$currentProduct] = [
- // 'qty' => 0,
- // 'unit' => $first['danwei']
- // ];
- // }
- // $productSummary[$currentProduct]['qty'] += $first['num'] * $rangeCount;
- //
- // $currentPalletNumber += $rangeCount;
- // }
- //
- // // 处理部分托盘 - 合并显示但分开产品信息
- // $warning4Partial = null;
- // $warning10Partial = null;
- //
- // // 查找可以合并的部分托盘
- // foreach ($allPartialPallets as $partial) {
- // if (strpos($partial['productName'], '警语4') !== false) {
- // $warning4Partial = $partial;
- // } elseif (strpos($partial['productName'], '警语10') !== false) {
- // $warning10Partial = $partial;
- // }
- // }
- //
- // // 检查是否可以合并(7+13=20箱)
- // if ($warning4Partial && $warning10Partial &&
- // ($warning4Partial['data']['boxes_in_pallet'] + $warning10Partial['data']['boxes_in_pallet']) == 20) {
- //
- // // 警语4版本(7箱)
- // $groupedData[] = [
- // 'pallet' => $currentPalletNumber,
- // 'matter_name' => $warning4Partial['productName'],
- // 'small_num' => $warning4Partial['data']['small_num'],
- // 'total_boxes' => $warning4Partial['data']['boxes_in_pallet'],
- // 'tray_num' => $warning4Partial['data']['tray_num'],
- // 'box_num' => $warning4Partial['data']['box_num'],
- // 'pallet_height' => $warning4Partial['data']['pallet_height'],
- // 'pallet_length' => $warning4Partial['data']['pallet_length'],
- // 'pallet_width' => $warning4Partial['data']['pallet_width'],
- // 'large_num' => 1,
- // 'larger_num' => $warning4Partial['data']['boxes_in_pallet'],
- // 'num' => $warning4Partial['data']['num'],
- // 'danwei' => $warning4Partial['data']['danwei'],
- // 'is_combined' => true
- // ];
- //
- // // 警语10版本(13箱)
- // $groupedData[] = [
- // 'pallet' => $currentPalletNumber,
- // 'matter_name' => $warning10Partial['productName'],
- // 'small_num' => $warning10Partial['data']['small_num'],
- // 'total_boxes' => $warning10Partial['data']['boxes_in_pallet'],
- // 'tray_num' => $warning10Partial['data']['tray_num'],
- // 'box_num' => $warning10Partial['data']['box_num'],
- // 'pallet_height' => $warning10Partial['data']['pallet_height'],
- // 'pallet_length' => $warning10Partial['data']['pallet_length'],
- // 'pallet_width' => $warning10Partial['data']['pallet_width'],
- // 'large_num' => 1,
- // 'larger_num' => $warning10Partial['data']['boxes_in_pallet'],
- // 'num' => $warning10Partial['data']['num'],
- // 'danwei' => $warning10Partial['data']['danwei'],
- // 'is_combined' => true
- // ];
- //
- // $totalTray += 1; // 只算一个托盘
- // $totalBox += 20; // 总箱数7+13=20
- //
- // // 产品统计
- // foreach ([$warning4Partial, $warning10Partial] as $partial) {
- // if (!isset($productSummary[$partial['productName']])) {
- // $productSummary[$partial['productName']] = [
- // 'qty' => 0,
- // 'unit' => $partial['data']['danwei']
- // ];
- // }
- // $productSummary[$partial['productName']]['qty'] += $partial['data']['num'];
- // }
- //
- // $currentPalletNumber++;
- // } else {
- // // 不能合并,单独显示每个部分托盘
- // foreach ($allPartialPallets as $partial) {
- // $groupedData[] = [
- // 'pallet' => $currentPalletNumber,
- // 'matter_name' => $partial['productName'],
- // 'small_num' => $partial['data']['small_num'],
- // 'total_boxes' => $partial['data']['boxes_in_pallet'],
- // 'tray_num' => $partial['data']['tray_num'],
- // 'box_num' => $partial['data']['box_num'],
- // 'pallet_height' => $partial['data']['pallet_height'],
- // 'pallet_length' => $partial['data']['pallet_length'],
- // 'pallet_width' => $partial['data']['pallet_width'],
- // 'large_num' => 1,
- // 'larger_num' => $partial['data']['boxes_in_pallet'],
- // 'num' => $partial['data']['num'],
- // 'danwei' => $partial['data']['danwei']
- // ];
- //
- // $totalTray += 1;
- // $totalBox += $partial['data']['boxes_in_pallet'];
- //
- // if (!isset($productSummary[$partial['productName']])) {
- // $productSummary[$partial['productName']] = [
- // 'qty' => 0,
- // 'unit' => $partial['data']['danwei']
- // ];
- // }
- // $productSummary[$partial['productName']]['qty'] += $partial['data']['num'];
- //
- // $currentPalletNumber++;
- // }
- // }
- //
- // // 9. 单位分类统计
- // $totalTao = 0;
- // $totalZhang = 0;
- // $totalGe = 0;
- //
- // foreach ($productSummary as $product) {
- // switch ($product['unit']) {
- // case '套':
- // $totalTao += $product['qty'];
- // break;
- // case '张':
- // $totalZhang += $product['qty'];
- // break;
- // case '个':
- // $totalGe += $product['qty'];
- // break;
- // }
- // }
- //
- // // 10. 构造返回数据
- // $responseData = [
- // '_id' => $goodList['_id'],
- // 'shrq_date' => date('Y-m-d'),
- // 'shdh' => $goodList['shdh'] ?? '',
- // 'order_number' => $goodList['order_number'] ?? '',
- // 'address' => $goodList['address'] ?? '',
- // 'company_id' => $goodList['company_id'] ?? 0,
- // 'count' => $goodList['count'] ?? 0,
- // 'create_time' => $goodList['create_time'] ?? '',
- // 'data' => $groupedData,
- // 'summary' => [
- // 'totalTray' => $totalTray,
- // 'totalBox' => $totalBox,
- // 'totalTao' => $totalTao,
- // 'totalZhang' => $totalZhang,
- // 'totalGe' => $totalGe,
- // 'products' => $productSummary
- // ],
- // 'delete_time' => $goodList['delete_time'] ?? '',
- // 'deliveryman' => $goodList['deliveryman'] ?? '',
- // 'export_id' => $goodList['export_id'] ?? '',
- // 'note' => $goodList['note'] ?? '',
- // 'order_ddbh' => $goodList['order_ddbh'] ?? '',
- // 'plate_number' => $goodList['plate_number'] ?? '',
- // 'qrcode_add' => $goodList['qrcode_add'] ?? '',
- // 'shr_phone' => $goodList['shr_phone'] ?? '',
- // 'status' => $goodList['status'] ?? 0,
- // 'supplier_id' => $goodList['supplier_id'] ?? 0,
- // 'supplier_name' => $goodList['supplier_name'] ?? '',
- // 'sync_flag' => $goodList['sync_flag'] ?? 0,
- // 'user_id' => $goodList['user_id'] ?? 0
- // ];
- //
- // return json([
- // 'code' => 1,
- // 'data' => $responseData
- // ]);
- //
- // } catch (\Exception $e) {
- // return json([
- // 'code' => 0,
- // 'msg' => '系统错误: ' . $e->getMessage()
- // ]);
- // }
- // }
- /**
- * 获取辅料名称
- * @return \think\response\Json
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function matterName()
- {
- // $userinfo = Session::get('admin');
- // $lager = new QcodeLarge();
- // $bach = new QcodeBach();
- // $bach_id = $lager->name($userinfo['company'].'_'.'qcode_large')->where('delete_time','')->column('bach_id');
- // $matter_name = [];
- // if (!empty($bach_id)){
- // foreach ($bach_id as $v){
- // $bach_list = $bach->name($userinfo['company'].'_'.'qcode_bach')->where('_id',$v)->find();
- // $matter_name[$bach_list['matter_no']] = $bach_list['matter_name'];
- // }
- // }
- // $matter_name = array_unique($matter_name);
- // return json($matter_name);
- }
- /**
- * 发货单删除
- * @param $ids
- * @return void
- */
- public function dispatch_del($ids)
- {
- $goods = new QcodeGoods();
- $export = new QcodeExport();
- if (empty($ids)){
- $this->error('参数错误');
- }
- $res = $goods->where('_id',$ids)->update(['delete_time'=>date('Y-m-d H:i:s',time())]);
- if ($res === false){
- $this->error('删除失败');
- }
- $userinfo = Session::get('admin');
- $mongo = \think\Db::connect('mongodb');
- $collection = $userinfo['company'] . '_qcode_bach';
- $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
- $res_find = $goods->where('_id',$ids)->find();
- $update_status = $mongo->name($bachsummary)->where('_id',$res_find['qcode_bachsummary_id'])->update(
- [
- 'bach_status'=>0,
- 'delete_time' => ''
- ]);
- if ($update_status === false){
- $this->error('删除失败');
- }
- $this->success('成功');
- }
- /**
- * 收货列表
- */
- public function receive()
- {
- //当前是否为关联查询
- $this->relationSearch = false;
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- $where = [
- 'delete_time'=> ''
- ];
- $req = input();
- $req['sort'] == 'id' ? $sort = '_id' : $sort = $req['sort'];
- $order = $req['order'];
- $offset = $req['offset'];
- $limit = $req['limit'];
- // 构造模糊查询条件
- // $regex = new MongoDB\BSON\Regex('.*abc.*', 'i');
- // $filter = ['field' => $regex];
- $filter = json_decode($req['filter'], true);
- if (isset($filter['status'])){
- $where['status'] = intval($filter['status']);
- unset($filter['status']);
- }
- if (isset($filter['create_time'])){
- $begin = substr($filter['create_time'],0,19);
- $end = substr($filter['create_time'],22);
- $begin = strtotime($begin);
- $end = strtotime($end);
- $where['create_time'] = ['between',[$begin,$end]];
- unset($filter['create_time']);
- }
- foreach ($filter as $k => $v){
- $where[$k] = new \MongoDB\BSON\Regex($v);
- }
- $goods = new QcodeGoods();
- $total = $goods->where($where)->count();
- $list = $goods->where($where)
- ->order($sort,$order)
- ->limit($limit)
- ->skip($offset)
- ->select();
- foreach ($list as $k=>$v) {
- $oid = $v['_id']->jsonSerialize();
- $list[$k]['id'] = $oid['$oid'];
- }
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 扫码/输入收货
- */
- public function receive_add()
- {
- $req = $this->request->param();
- if(!isset($req['shdh']) || empty($req['shdh'])){
- $this->error('请输入送货单号');
- }
- $data = [
- 'shdh'=>$req['shdh'],
- 'delete_time'=>'',
- ];
- $goods = new QcodeGoods();
- $row = $goods->where($data)->find();
- if (!$row) $this->error('未查询到该单号');
- if ($row['status']==2) $this->error('该单号已收货');
- //收货---修改status为2
- $bool = $goods->where($data)->update(['status'=>2,'sync_flag'=>0]);
- if ($bool){
- $this->success('成功');
- }else{
- $this->error('失败');
- }
- }
- /**
- * 取消收货
- */
- public function receive_del()
- {
- $req = $this->request->param();
- if(!isset($req['ids']) || empty($req['ids'])){
- $this->error('id不能为空');
- }
- $data = [
- '_id'=>$req['ids'],
- 'delete_time'=>'',
- ];
- $goods = new QcodeGoods();
- //收货---修改status为2
- $bool = $goods->where($data)->update(['status'=>0,'sync_flag'=>0]);
- if ($bool){
- $this->success('成功');
- }else{
- $this->error('失败');
- }
- }
- }
|