| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175 | <?phpnamespace App\Service;use App\Model\BasicType;use App\Model\Construction;use App\Model\ConstructionFile;use App\Model\ConstructionInfo;use App\Model\ConstructionProductInfo;use App\Model\Customer;use App\Model\CustomerInfo;use App\Model\DeliveryNote;use App\Model\Depart;use App\Model\Employee;use App\Model\EmployeeDepartPermission;use App\Model\Oa;use App\Model\OaSub;use App\Model\OaSubEmployee;use App\Model\OaSubReportEmployee;use App\Model\OaSubRule;use App\Model\Product;use App\Model\ReturnExchangeOrder;use App\Model\ReturnExchangeOrderProductInfo;use App\Model\SalesOrder;use App\Model\SalesOrderInfo;use App\Model\SalesOrderProductInfo;use App\Model\ScheduleInfo;use App\Model\SeeRange;use App\Model\Storehouse;use Illuminate\Support\Facades\DB;//use Barryvdh\DomPDF\Facade as PDF;use Barryvdh\DomPDF\PDF;/** * 施工订单 */class ConstructionService extends Service{    /**     * 施工订单编辑     * @param $data     * @param $user     * @return array     */    public function constructionEdit($data,$user){        list($status,$msg) = $this->constructionRule($data, $user, false);        if(!$status) return [$status,$msg];        $params = $this->getDataFile($data);        (new OperationLogService())->setOperationList($params,$user,2);        try {            DB::beginTransaction();            $model = Construction::where('id', $data['id'])->first();            $model->model_type = $data['model_type'];            $model->order_number = $data['order_number'];            $model->title = $data['title'] ?? '';            $model->customer_id = $data['customer_id'] ?? 0;            $model->customer_contact_id = $data['customer_contact_id'] ?? 0;            $model->install_method = $data['install_method'] ?? 0;            $model->install_position = $data['install_position'] ?? 0;            $model->sales_order_id = $data['sales_order_id'] ?? 0;            $model->construction_fee = $data['construction_fee'] ?? 0;            $model->service_price = $data['service_price'] ?? 0;            $model->construction_time = $data['construction_time'] ?? 0;            $model->handover_time = $data['handover_time'] ?? 0;            $model->urgency = $data['urgency'] ?? 0;            $model->mark = $data['mark'] ?? '';            $model->address1 = ! empty($data['address1']) ? json_encode($data['address1']) : '';            $model->address2 = $data['address2'] ?? '';            $model->introduction = $data['introduction'] ?? '';            $model->storehouse_id = $data['storehouse_id'] ?? 0;            $model->start_time = $data['start_time'] ?? 0;            $model->end_time = $data['end_time'] ?? 0;            $model->schedule_id = $data['schedule_id'] ?? 0;            $model->day_stamp = $data['day_stamp'] ?? 0;            $model->day_start_stamp = $data['day_start_stamp'] ?? 0;            $model->day_end_stamp = $data['day_end_stamp'] ?? 0;            $model->product_introduction = $data['product_introduction'] ?? "";            $model->vin_no = $data['vin_no'] ?? "";            $model->save();            $time = time();            ConstructionInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => $time]);            ConstructionProductInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => $time]);            $old = ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->select('file')                ->get()->toArray();            $old = array_column($old,'file');            ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => $time]);            if(! empty($data['construction_contact'])){                $insert = [];                foreach ($data['construction_contact'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'contact_type' => $value['id'],                        'contact_info' => $value['info'],                        'type' => ConstructionInfo::type_one,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['employee_one'])){                $insert = [];                foreach ($data['employee_one'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'employee_id' => $value,                        'type' => ConstructionInfo::type_two,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['product'])){                $insert = [];                foreach ($data['product'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'product_id' => $value['product_id'],                        'number' => $value['number'],                        'cost' => $value['cost'] ?? 0,                        'retail_price' => $value['retail_price'] ?? 0,                        'mark' => $value['mark'] ?? '',                        'crt_time' => $time,                        'storehouse_id' => $data['storehouse_id'] ?? 0,                        'basic_type_id' => $value['basic_type_id'],                        'price' => $value['price'],                        'final_amount' => $value['final_amount'] ?? 0,                    ];                }                ConstructionProductInfo::insert($insert);                //锁定库存                ProductInventoryService::changeLockNumber($user,$msg[0],$msg[1]);            }            if(! empty($data['schedule_info_id'])) ScheduleInfo::where('id',$data['schedule_info_id'])->update(['is_use' => 1]);            $new = [];            if(! empty($data['file'])){                $insert = [];                foreach ($data['file'] as $value){                    $insert[] = [                        'order_number' => $data['order_number'],                        'construction_id' => $data['id'],                        'file' => $value['url'],                        'name' => $value['name'],                        'mark' => $value['mark'] ?? "",                        'crt_time' => $time,                    ];                    $new[]= $value['url'];                }                ConstructionFile::insert($insert);            }            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            return [false,$exception->getMessage()];        }        $this->delStorageFile($old, $new);        if(! empty($data['check'])) {            list($status,$msg) = (new CheckService())->checkAll([                "id" => $model->id,                "order_number" => $data['order_number'],                "opt_case" => CheckService::five,                "menu_id" => $data['menu_id']            ],$user);            if(! $status) return [true, '保存成功,施工单确认失败,异常信息:' . $msg];        }        return [true,''];    }    /**     * 施工订单新增     * @param $data     * @param $user     * @return array     */    public function constructionAdd($data,$user){        list($status,$msg) = $this->constructionRule($data,$user);        if(!$status) return [$status,$msg];        try {            DB::beginTransaction();            $model = new Construction();            $model->model_type = $data['model_type'];            $model->order_number = $data['order_number'];            $model->title = $data['title'] ?? '';            $model->customer_id = $data['customer_id'] ?? 0;            $model->customer_contact_id = $data['customer_contact_id'] ?? 0;            $model->install_method = $data['install_method'] ?? 0;            $model->install_position = $data['install_position'] ?? 0;            $model->sales_order_id = $data['sales_order_id'] ?? 0;            $model->construction_fee = $data['construction_fee'] ?? 0;            $model->service_price = $data['service_price'] ?? 0;            $model->construction_time = $data['construction_time'] ?? 0;            $model->handover_time = $data['handover_time'] ?? 0;            $model->urgency = $data['urgency'] ?? 0;            $model->mark = $data['mark'] ?? '';            $model->address1 = ! empty($data['address1']) ? json_encode($data['address1']) : '';            $model->address2 = $data['address2'] ?? '';            $model->introduction = $data['introduction'] ?? '';            $model->crt_id = $user['id'];            $model->depart_id = $data['depart_id'] ?? 0;            $model->top_depart_id = $data['top_depart_id'] ?? 0;            $model->storehouse_id = $data['storehouse_id'] ?? 0;            $model->start_time = $data['start_time'] ?? 0;            $model->end_time = $data['end_time'] ?? 0;            $model->schedule_id = $data['schedule_id'] ?? 0;            $model->day_stamp = $data['day_stamp'] ?? 0;            $model->day_start_stamp = $data['day_start_stamp'] ?? 0;            $model->day_end_stamp = $data['day_end_stamp'] ?? 0;            $model->product_introduction = $data['product_introduction'] ?? "";            $model->vin_no = $data['vin_no'] ?? "";            $model->save();            $time = time();            if(! empty($data['construction_contact'])){                $insert = [];                foreach ($data['construction_contact'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'contact_type' => $value['id'],                        'contact_info' => $value['info'],                        'type' => ConstructionInfo::type_one,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['employee_one'])){                $insert = [];                foreach ($data['employee_one'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'employee_id' => $value,                        'type' => ConstructionInfo::type_two,                        'crt_time' => $time,                    ];                }                ConstructionInfo::insert($insert);            }            if(! empty($data['product'])){                $insert = [];                foreach ($data['product'] as $value){                    $insert[] = [                        'construction_id' => $model->id,                        'product_id' => $value['product_id'],                        'number' => $value['number'],                        'cost' => $value['cost'] ?? 0,                        'retail_price' => $value['retail_price'] ?? 0,                        'mark' => $value['mark'] ?? '',                        'crt_time' => $time,                        'storehouse_id' => $data['storehouse_id'] ?? 0,                        'basic_type_id' => $value['basic_type_id'],                        'price' => $value['price'],                        'final_amount' => $value['final_amount'] ?? 0,                    ];                }                ConstructionProductInfo::insert($insert);                //锁定库存                ProductInventoryService::changeLockNumber($user,$msg[0],[]);            }            if(! empty($data['schedule_info_id'])) ScheduleInfo::where('id',$data['schedule_info_id'])->update(['is_use' => 1]);            if(! empty($data['file'])){                $insert = [];                foreach ($data['file'] as $value){                    $insert[] = [                        'order_number' => $data['order_number'],                        'construction_id' => $model->id,                        'file' => $value['url'],                        'name' => $value['name'],                        'mark' => $value['mark'] ?? "",                        'crt_time' => $time,                    ];                }                ConstructionFile::insert($insert);            }            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            return [false,$exception->getMessage()];        }        (new OperationLogService())->setOperationList($data,$user);        if(! empty($data['check'])) {            list($status,$msg) = (new CheckService())->checkAll([                "id" => $model->id,                "order_number" => $data['order_number'],                "opt_case" => CheckService::five,                "menu_id" => $data['menu_id']            ],$user);            if(! $status) return [true, '保存成功,施工单确认失败,异常信息:' . $msg];        }        return [true,''];    }    /**     * 施工订单删除     * @param $data     * @return array     */    public function constructionDel($data,$user){        if($this->isEmpty($data,'id')) return [false,'请选择数据!'];        $construction = Construction::where('del_time',0)->where('id',$data['id'])->first();        if(empty($construction)) return [false,'施工单不存在或已被删除'];        $construction = $construction->toArray();        if($construction['state'] > Construction::STATE_ZERO) return [false,'请确认施工单状态,操作失败'];        $product_save = $this->getSaveDetail($data['id']);        try {            DB::beginTransaction();            Construction::where('id',$data['id'])->update([                'del_time'=> time()            ]);            ConstructionInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            $old = ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->select('file')                ->get()->toArray();            $old = array_column($old,'file');            ConstructionFile::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            ConstructionProductInfo::where('del_time',0)                ->where('construction_id',$data['id'])                ->update(['del_time' => time()]);            (new RangeService())->RangeDelete($data['id'],SeeRange::type_two);            //锁定库存释放            ProductInventoryService::changeLockNumber($user,[],$product_save);            //排班修改//            $schedule = ScheduleInfo::where('del_time',0)//                ->where('schedule_id',$construction['schedule_id'])//                ->where('start_time',$construction['day_start_stamp'])//                ->where('end_time',$construction['day_end_stamp'])//                ->where('is_use','>', ScheduleInfo::not_use)//                ->first();//            if(! empty($schedule)) ScheduleInfo::where('id',$schedule->id)->update(['is_use' => ScheduleInfo::not_use]);            DB::commit();        }catch (\Exception $exception){            DB::rollBack();            return [false,$exception->getMessage()];        }        $this->delStorageFile($old);        return [true,''];    }    /**     * 施工订单详情     * @param $data     * @return array     */    public function detail($data){        if(empty($data['id']) && empty($data['order_number'])) return [false,'请选择数据!'];        if(! empty($data['id'])){            $construction = Construction::where('del_time',0)                ->where('id',$data['id'])                ->first();        }else{            $construction = Construction::where('del_time',0)                ->where('order_number',$data['order_number'])                ->first();            $data['id'] = empty($construction->id) ? 0 : $construction->id;        }        if(empty($construction)) return [false,'施工订单不存在或已被删除'];        $construction = $construction->toArray();        $construction['state_title'] = Construction::$name[$construction['state']] ?? '';        $address_map = config('address');        $address_str = [];        if(! empty($construction['address1'])) {            $tmp = json_decode($construction['address1'],true);            $construction['address1'] = $tmp;            $this->findLabelsByValue($address_map,$tmp,$address_str);            $tmp = implode(' ',$address_str);            $tmp .= ' ' . $construction['address2'];            $address = $tmp;        }else{            $address = $construction['address2'];        }        $construction['address'] = $address;        $start_time = $construction['start_time'] ? date("Y-m-d H:i",$construction['start_time']) : '';        $end_time = $construction['end_time'] ? date("Y-m-d H:i",$construction['end_time']) : '';        $construction['construction_period'] = $start_time . '——' . $end_time;        $sales = SalesOrder::where('id',$construction['sales_order_id'])->value('order_number');        $construction['sales_order_number'] = $sales;        $customer_title = Customer::where('id',$construction['customer_id'])->value('title');        $construction['customer_title'] = $customer_title ?? "";        $info = CustomerInfo::from('customer_info as a')            ->leftJoin('basic_type as b','b.id','a.contact_type')            ->where('a.del_time',0)            ->where('a.customer_id',$construction['customer_id'])            ->where('a.contact_type','>',0)            ->select('b.title','a.contact_info')            ->get()->toArray();        $construction['customer_array'] = $info;        $info = CustomerInfo::from('customer_info as a')            ->leftJoin('basic_type as b','b.id','a.contact_type')            ->where('a.del_time',0)            ->where('a.customer_id',$construction['customer_id'])            ->where('a.contact_type','>',0)            ->select('b.title','a.contact_info')            ->get()->toArray();        $construction['customer_array'] = $info;        $construction['storehouse_title'] = Storehouse::where('id',$construction['storehouse_id'])->value('title');        $emp_title = Employee::where('id',$construction['customer_contact_id'])->value('emp_name');        $construction['customer_contact_title'] = $emp_title;        $construction['employee_two'] = $construction['employee_one'] = $construction['construction_contact'] = $construction['product'] = [];        $array = [            $construction['install_method'],            $construction['install_position'],            $construction['urgency'],        ];        $basic_map = BasicType::whereIn('id',$array)            ->pluck('title','id')            ->toArray();        $construction = [$construction];        foreach ($construction as $key => $value){            $construction[$key]['install_method_title'] = $basic_map[$value['install_method']] ?? '';            $construction[$key]['install_position_title'] = $basic_map[$value['install_position']] ?? '';            $construction[$key]['urgency_title'] = $basic_map[$value['urgency']] ?? '';        }        $construction = $construction[0];        $construction['file'] = [];        $file = ConstructionFile::where('del_time',0)            ->where('construction_id',$construction['id'])            ->select('id','construction_id','file','name','mark')            ->get()->toArray();        foreach ($file as $value){            $construction['file'][] = [                'url' => $value['file'],                'name' => $value['name'],                'mark' => $value['mark'],            ];        }        $construction_info = ConstructionInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->select('id','construction_id','employee_id','type','contact_type','contact_info')            ->get()->toArray();        $emp_map = Employee::whereIn('id',array_unique(array_merge_recursive([$construction['crt_id']],array_column($construction_info,'employee_id'))))            ->pluck('emp_name','id')            ->toArray();        $basic_map2 = BasicType::whereIn('id',array_unique(array_column($construction_info,'contact_type')))            ->pluck('title','id')            ->toArray();        foreach ($construction_info as $value){            if($value['type'] == ConstructionInfo::type_one){                $tmp = [                    'id' => $value['contact_type'],                    'title' => $basic_map2[$value['contact_type']] ?? '',                    'info' => $value['contact_info']                ];                $construction['construction_contact'][] = $tmp;            }elseif ($value['type'] == ConstructionInfo::type_two){                $tmp = [                    'id' => $value['employee_id'],                    'name' => $emp_map[$value['employee_id']] ?? '',                ];                $construction['employee_one'][] = $tmp;            }elseif ($value['type'] == ConstructionInfo::type_three){                $tmp = [                    'id' => $value['employee_id'],                    'name' => $emp_map[$value['employee_id']] ?? '',                ];                $construction['employee_two'][] = $tmp;            }        }        $p_info = ConstructionProductInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->get()->toArray();        $basic_price = BasicType::whereIn('id',array_unique(array_column($p_info,'basic_type_id')))->pluck('title','id')->toArray();        $map = (new ProductService())->getProductDetail(array_column($p_info,'product_id'));        foreach ($p_info as $value){            $tmp = $map[$value['product_id']] ?? [];            $value['title'] = $tmp['title'] ?? "";            $value['code'] = $tmp['code'] ?? "";            $value['size'] = $tmp['size'] ?? "";            $value['unit'] = $tmp['unit'] ?? "";            $value['bar_code'] = $tmp['bar_code'] ?? "";            $value['basic_type_title'] = $basic_price[$value['basic_type_id']] ?? "";            $construction['product'][] = $value;        }        $construction['crt_name'] = $emp_map[$construction['crt_id']] ?? '';        $construction['crt_time'] = $construction['crt_time'] ? date("Y-m-d H:i:s",$construction['crt_time']): '';        //可见范围        $return = (new RangeService())->RangeDetail($data['id'],SeeRange::type_two);        $construction['depart'] = $return[0] ?? [];        $construction['employee'] = $return[1] ?? [];        return [true, $construction];    }    /**     * 施工订单列表     * @param $data     * @param $user     * @return array     */    public function constructionList($data,$user){        $model = Construction::Clear($user,$data);        $model = $model->where('del_time',0)            ->select('title','id','model_type','order_number','customer_id','customer_contact_id','install_method','install_position','sales_order_id','construction_fee','construction_time','handover_time','urgency','crt_id','crt_time','mark','state','address1','address2','introduction','service_price','storehouse_id','start_time','end_time','pq_state','day_start_stamp','day_end_stamp')            ->orderby('id', 'desc');        if(isset($data['state'])) $model->where('state', $data['state']);        if(isset($data['pq_state'])) $model->where('pq_state', $data['pq_state']);        if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');        if(! empty($data['model_type'])) $model->where('model_type',$data['model_type']);        if(! empty($data['time_type'])) {            if($data['time_type'] == 1) {                $start = strtotime('today');                $end = strtotime('tomorrow') - 1;            }elseif ($data['time_type'] == 2){                $start = strtotime('this week',strtotime('today'));                $end = strtotime('this week +6 days 23:59:59', strtotime('today'));            }            if(! empty($start) && ! empty($end)) {                $model->where('crt_time','>=',$start);                $model->where('crt_time','<=',$end);            }        }        if(! empty($data['construction_period'][0]) && ! empty($data['construction_period'][1])) {            $return = $this->changeDateToTimeStampAboutRange($data['construction_period']);            $model->where('start_time','>=',$return[0]);            $model->where('end_time','<=',$return[1]);        }        if(! empty($data['pq_period'][0]) && ! empty($data['pq_period'][1])) {            $model->where('day_start_stamp','>=',$this->changeDateToDateMin($data['pq_period'][0]));            $model->where('day_end_stamp','<=',$this->changeDateToDateMin($data['pq_period'][1]));        }        if(! empty($data['sale_order'])){            $model2 = SalesOrder::Clear($user,$data);            $sale = $model2->where('del_time',0)                ->where('order_number', 'LIKE', '%'.$data['sale_order'].'%')                ->select('id')                ->get()->toArray();            $model->whereIn('sales_order_id',array_unique(array_column($sale,'id')));        }        if(! empty($data['install_method'])) $model->where('install_method',$data['install_method']);        if(! empty($data['install_position'])) $model->where('install_position',$data['install_position']);        if(! empty($data['order_number'])) $model->where('order_number', 'LIKE', '%'.$data['order_number'].'%');        $list = $this->limit($model,'',$data);        $list = $this->fillData($list);        return [true, $list];    }    /**     * 参数规则     * @param $data     * @param $user     * @param $is_add     * @return array     */    public function constructionRule(&$data, $user, $is_add = true){        if(empty($data['model_type'])) return [false,'工单模板类型不能为空'];        if(! in_array($data['model_type'],Construction::$model_type)) return [false,'工单模板类型错误'];        if(empty($data['order_number'])) return [false,'工单编号不能为空'];        if(empty($data['storehouse_id'])) return [false,'请选择仓库'];        if(empty($data['sales_order_id'])) return [false,'请选择合同'];        $sale = SalesOrder::where('del_time',0)->where('id',$data['sales_order_id'])->first();        if(empty($sale)) return [false,'合同不存在或已被删除'];        $sale = $sale->toArray();        if($sale['state'] < SalesOrder::State_two) return [false,'合同未通过确认,不允许新建施工单'];        if($sale['state'] >= SalesOrder::State_seven) return [false,'请确认合同状态,新建施工单失败'];        if($sale['top_depart_id'] == $user['head']['id']){            //总社的订单 需要派单 才能建施工            if($sale['state'] < SalesOrder::State_four) return [false,'合同未门店派单,不允许新建施工单'];        }        list($status,$msg) = $this->limitingSendRequestBackgExpire("construction" . $sale['order_number']);        if(! $status) return [false, $msg];        if(empty($data['product'])) return [false,'请选择产品'];        if(empty($data['construction_period'][0]) || empty($data['construction_period'][1])) return [false,'请填写施工时间范围'];        $data['start_time'] = $this->changeDateToDateMin($data['construction_period'][0]);        $data['end_time'] = $this->changeDateToDateMin($data['construction_period'][1]);        if(! empty($data['construction_fee'])){            $res = $this->checkNumber($data['construction_fee']);            if(! $res) return [false,'施工费用请输入不超过两位小数并且大于0的数值'];        }        if(! empty($data['service_price'])){            $res = $this->checkNumber($data['service_price']);            if(! $res) return [false,'服务价格请输入不超过两位小数并且大于0的数值'];        }        if(! empty($data['construction_time'])) $data['construction_time'] = $this->changeDateToDateMin($data['construction_time']);        if(! empty($data['handover_time'])) $data['handover_time'] = $this->changeDateToDateMin($data['handover_time']);        if($data['model_type'] == Construction::Model_type_one){//            if(empty($data['install_method'])) return [false,'安装方式不能为空'];//            if(empty($data['install_position'])) return [false,'安装地点不能为空'];        }else{//            if(empty($data['construction_contact'])) return [false,'联系方式不能为空'];//            if(empty($data['address1']) || empty($data['address2'])) return [false,'地址不能为空'];        }        //所属部门 以及  顶级部门        if(empty($data['depart_id'])) {            $data['depart_id'] = $this->getDepart($user);            $data['top_depart_id'] = $user['depart_map'][$data['depart_id']] ?? 0;        }        $product_submit = $product_id = [];        foreach ($data['product'] as $value){            if(empty($value['number'])) return [false,'产品数量不能为空'];            $res = $this->checkNumber($value['number']);            if(! $res) return [false,'请输入正确的产品数量'];            $key = $value['product_id'] . ',' .$data['storehouse_id'];            if(isset($product_submit[$key])){                $product_submit[$key] += $value['number'];            }else{                $product_submit[$key] = $value['number'];            }            $product_id[] = $value['product_id'];        }        //剩余能施工        $id = $data['id'] ?? 0;        $s_product = $this->getSaveReturnCompareMessage($id, $data['sales_order_id']);        //比较        foreach ($product_submit as $pro => $number){            $tmp = explode(',',$pro);            $p = $tmp[0];            if(! isset($s_product[$p])) return [false,'施工产品错误,合同中不存在该产品'];            $s_number = $s_product[$p];            if($number > $s_number) return [false,'施工产品数量不能超过合同产品数据(包含已退货产品)'];        }        $id = $data['id'] ?? 0;        $product_save = $this->getSaveDetail($id);        //是否校验库存        ProductInventoryService::is_check($user,$data);        list($status,$msg) = (new ProductInventoryService())->compareStock($user,$product_id, $product_submit, $product_save);        if(! $status) return [false, $msg];        $start_time = date("Y-m-d H:i",$data['start_time']);        $end_time = date("Y-m-d H:i",$data['end_time']);        if($is_add){            $bool = Construction::where('del_time',0)                ->where('order_number',$data['order_number'])                ->exists();            if($bool) return [false,'工单编号已存在,请重新获取'];//            $bool = Construction::where('del_time',0)//                ->where('sales_order_id',$data['sales_order_id'])//                ->where('start_time', '<=', $data['end_time'])//                ->where('end_time', '>=', $data['start_time'])//                ->exists();//            if($bool) return [false,'合同:' . $sale['order_number'] . '在' . $start_time . '——' . $end_time . '已下施工单'];        }else{            if(empty($data['id'])) return [false,'ID不能为空'];//            $bool = Construction::where('del_time',0)//                ->where('id','<>',$data['id'])//                ->where('sales_order_id',$data['sales_order_id'])//                ->where('start_time', '<=', $data['end_time'])//                ->where('end_time', '>=', $data['start_time'])//                ->exists();//            if($bool)  return [false,'合同:' . $sale['order_number'] . '在' . $start_time . '——' . $end_time . '已下施工单'];        }        return [true, [$product_submit, $product_save]];    }    /**     * 数据拼接     * @param $data     * @return array     */    public function fillData($data){        if(empty($data['data'])) return $data;        $array = array_unique(array_merge_recursive(array_column($data['data'],'install_method'),array_column($data['data'],'urgency'),array_column($data['data'],'install_position')));        $basic_map = BasicType::whereIn('id',$array)            ->pluck('title','id')            ->toArray();        $emp = Employee::whereIn('id',array_unique(array_merge_recursive(array_column($data['data'],'crt_id'),array_column($data['data'],'customer_contact_id'))))            ->pluck('emp_name','id')            ->toArray();        $customer = Customer::whereIn('id',array_unique(array_column($data['data'],'customer_id')))            ->pluck('title','id')            ->toArray();        $sales_map = SalesOrder::whereIn('id',array_unique(array_column($data['data'],'sales_order_id')))->pluck('order_number','id')->toArray();        $storehouse = Storehouse::whereIn('id',array_unique(array_column($data['data'],'storehouse_id')))            ->pluck('title','id')            ->toArray();        //分派的总社或分社        $dispatch = $this->getDispatchData($data['data']);        //施工产品        $product_map = $this->getProduct($data['data']);        $address_map = config('address');        foreach ($data['data'] as $key => $value){            $address_str = [];            $product_tmp = $product_map[$value['id']] ?? [];            $data['data'][$key]['product_detail'] = implode(',',$product_tmp);            if(! empty($value['address1'])) {                $tmp = json_decode($value['address1'],true);                $this->findLabelsByValue($address_map,$tmp,$address_str);                $tmp = implode(' ',$address_str);                $tmp .= ' ' . $value['address2'];                $address = $tmp;            }else{                $address = $value['address2'];            }            $start_time = $value['start_time'] ? date("Y-m-d H:i",$value['start_time']) : '';            $end_time = $value['end_time'] ? date("Y-m-d H:i",$value['end_time']) : '';            $data['data'][$key]['construction_period'] = $start_time . '——' . $end_time;            $data['data'][$key]['address'] = $address;            $data['data'][$key]['model_type_title'] = Construction::$model_type_title[$value['model_type']] ?? '';            $data['data'][$key]['install_position_title'] = $basic_map[$value['install_position']] ?? '';            $data['data'][$key]['install_method_title'] = $basic_map[$value['install_method']] ?? '';            $data['data'][$key]['urgency_title'] = $basic_map[$value['urgency']] ?? '';            $data['data'][$key]['customer_title'] = $customer[$value['customer_id']] ?? '';            $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';            $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';            $data['data'][$key]['customer_contact_title'] = $emp[$value['customer_contact_id']] ?? '';            $data['data'][$key]['state_title'] = Construction::$name[$value['state']] ?? '';            $tmp_sales = $sales_map[$value['sales_order_id']] ?? "";//            $tmp_sales_time = $tmp_sales['handover_time'] ? date("Y-m-d") : "";            $data['data'][$key]['sales_order_number'] = $tmp_sales;            $data['data'][$key]['handover_time'] = $value['handover_time'] ? date("Y-m-d",$value['handover_time']) : "";            $data['data'][$key]['storehouse_title'] = $storehouse[$value['storehouse_id']] ?? '';            $data['data'][$key]['dispatch_company'] = $dispatch[$value['sales_order_id']] ?? '';//            $data['data'][$key]['pq_state_title'] = Construction::$pq_name[$value['pq_state']] ?? '';//            $str = "";//            $start_time = $value['day_start_stamp'] ? date("Y-m-d H:i",$value['day_start_stamp']) : '';//            $end_time = $value['day_end_stamp'] ? date("Y-m-d H:i",$value['day_end_stamp']) : '';//            if(! empty($start_time) && ! empty($end_time)) $str = $start_time . '——' . $end_time;//            $data['data'][$key]['pq_period'] = $str;        }        return $data;    }    public function getProduct($data){        $search_id = array_column($data,'id');        if(empty($search_id)) return [];        $product = ConstructionProductInfo::where('del_time',0)            ->whereIn('construction_id',$search_id)            ->select('product_id','construction_id')            ->get()->toArray();        $product_map = Product::whereIn('id',array_unique(array_column($product,'product_id')))->pluck('title','id')->toArray();        $return = [];        foreach ($product as $value){            $product_tmp = $product_map[$value['product_id']] ?? "";            if($product_tmp) $return[$value['construction_id']][] = $product_tmp;        }        return $return;    }    public function getDispatchData($data){        $search_id = [];        foreach ($data as $value){            $search_id[] = $value['sales_order_id'];        }        if(empty($search_id)) return [];        $see = SeeRange::where('del_time',0)            ->whereIn('data_id',$search_id)            ->where('data_type',SeeRange::type_seven)            ->where('type',SeeRange::data_three)            ->select('data_id','param_id')            ->get()->toArray();        $map = Depart::whereIn('id',array_unique(array_column($see,'param_id')))            ->pluck('title','id')            ->toArray();        $see_array = [];        foreach ($see as $value){            $see_array[$value['data_id']] = $map[$value['param_id']] ?? "";        }        return $see_array;    }    /**     * 获取施工单号     * @param $data     * @return array     */    public function constructionGet($data){        if(empty($data['model_type'])) return [false,'工单模板类型不能为空'];        if(! isset(Construction::$prefix[$data['model_type']])) return [false,'工单模板类型错误'];        $prefix = Construction::$prefix[$data['model_type']];        $order_number = OrderNoService::createConstructionOrderNumber($prefix);        if(! $order_number) return [false,'工单编号生成失败!'];        return [true,['order_number' => $order_number]];    }    /**     * 获取保存详情     * @param $id     * @return array     */    public function getSaveDetail($id){        $product_save = [];        if(empty($id)) return $product_save;        $sub = ConstructionProductInfo::where('construction_id',$id)            ->where('del_time',0)            ->get()->toArray();        foreach ($sub as $value){            $key = $value['product_id'] . ',' . $value['storehouse_id'];            if(isset($product_save[$key])){                $product_save[$key] += $value['number'];            }else{                $product_save[$key] = $value['number'];            }        }        return $product_save;    }    public function getSaveReturnCompareMessage($id = 0, $sales_order_id = 0){        $construction = Construction::where('del_time',0)            ->where('sales_order_id',$sales_order_id)            ->select('id')->get()->toArray();        $construction_id = array_column($construction,'id');        $product_save = [];        $sub = ConstructionProductInfo::where('del_time',0)            ->whereIn('construction_id',$construction_id)            ->when(! empty($id), function ($query) use ($id) {                return $query->where('construction_id', '<>',$id);            })            ->get()->toArray();        foreach ($sub as $value){            if(isset($product_save[$value['product_id']])){                $product_save[$value['product_id']] += $value['number'];            }else{                $product_save[$value['product_id']] = $value['number'];            }        }        $product_save2 = [];        $sub1 = ReturnExchangeOrder::where('del_time',0)            ->where('type',ReturnExchangeOrder::Order_type)            ->where('model_type',ReturnExchangeOrder::Model_type_one)            ->where('data_id',$sales_order_id)            ->get()->toArray();        $sub1_array = ReturnExchangeOrderProductInfo::where('del_time',0)            ->whereIn('return_exchange_id',array_column($sub1,'id'))            ->get()->toArray();        foreach ($sub1_array as $value){            if(isset($product_save2[$value['product_id']])){                $product_save2[$value['product_id']] += $value['number'];            }else{                $product_save2[$value['product_id']] = $value['number'];            }        }        $sales_order_product = [];        $sales_product = SalesOrderProductInfo::where('del_time',0)            ->where('sales_order_id',$sales_order_id)            ->get()->toArray();        foreach ($sales_product as $value){            $product_save_tmp = $product_save[$value['product_id']] ?? 0;            $product_save_tmp2 = $product_save2[$value['product_id']] ?? 0;            if(isset($sales_order_product[$value['product_id']])){                $sales_order_product[$value['product_id']] += $value['number'];            }else{                $sales_order_product[$value['product_id']] = $value['number'] - $product_save_tmp - $product_save_tmp2;            }        }        return $sales_order_product;    }    public function deliveryNoteEdit($data,$user){        $id = $user['id'];        if(isset($data['id'])) {            $model = DeliveryNote::where('id',$data['id'])->first();            if($model->img3) return [false,'客户已签字,无法编辑!'];            if(DeliveryNote::where('del_time',0)->where('construction_order_number',$data['construction_order_number'])->where('id','<>',$data['id'])->first()) return [false,'施工单客户确认单已存在!'];        }        else {            $model = new DeliveryNote();            $model->crt_id = $id;        }        try {            $model->upd_id = $id;            $model->construction_order_number = $data['construction_order_number'] ?? '';            $model->start_time = $data['start_time'] ?? '';            $model->end_time = $data['end_time'] ?? '';            $model->vin_no = $data['vin_no'] ?? '';            $model->system = $data['system'] ?? '';            $model->mile = $data['mile'] ?? '';            $model->is_wait = $data['is_wait'] ?? '';            $model->customer_name = $data['customer_name'] ?? '';            $model->customer_mobile = $data['customer_mobile'] ?? '';            $model->sale_man = $data['sale_man'] ?? '';            $model->install_man = $data['install_man'] ?? '';            $model->is_brash = $data['is_brash'] ?? '';            $model->is_chong = $data['is_chong'] ?? '';            $model->service_mark = $data['service_mark'] ?? '';            $model->mark = $data['mark'] ?? '';            $model->break = $data['break'] ? json_encode($data['break']):json_encode([]);            $model->break_mark = $data['break_mark'] ? json_encode($data['break_mark']):json_encode([]);            $model->project_id = $data['project_id'] ? json_encode($data['project_id']):json_encode([]);            $model->other_project_mark = $data['other_project_mark'] ?? '';            $model->img = $data['img'] ?? '';            $model->img1 = $data['img1'] ?? '';            $model->img2 = $data['img2'] ?? '';            $model->img3 = $data['img3'] ?? '';            $model->save();            return [true,'保存成功!'];        }catch (\Throwable $e){            return [true,'保存成功!'];        }    }    public function deliveryNoteList($data)    {        $list = DeliveryNote::where('del_time',0);        $list = $this->limit($list,'*',$data);        return [true,$list];    }    public function deliveryNoteDetail($data){        if(isset($data['id'])) $model = DeliveryNote::where('id',$data['id'])->where('del_time',0)->first();        if(isset($data['construction_order_number'])) $model = DeliveryNote::where('id',$data['construction_order_number'])->where('del_time',0)->first();        if(empty($model)) return [false,'数据不存在!'];        $employee_key_list = Employee::pluck('emp_name','id')->toArray();        $detail = $model->toArray();        $detail['install_man_title'] = $employee_key_list[$detail['install_man']] ?? "";        $detail['sale_man_title'] = $employee_key_list[$detail['sale_man']] ?? "";        $img_list = ConstructionFile::where('order_number',$detail['construction_order_number'])->where('del_time',0)->select('file as url','name','mark')->get()->toArray();        $detail['file'] = $img_list;        return [true,$detail];    }    public function deliveryNoteDel($data,$user){        DeliveryNote::where('id',$data['id'])->update(            [                'del_time' => time(),                'upd_id' => $user['id'],            ]        );        return [true,'删除成功!'];    }    public function constructionPdf($data, $user){        if(empty($data['id'])) return [false, '请选择下载的施工单'];        $construction = Construction::where('del_time',0)            ->where('id',$data['id'])            ->first();        if(empty($construction)) return [false, '施工单不存在或已被删除'];        $construction = $construction->toArray();        $customer_title = Customer::where('id',$construction['customer_id'])->value('title');        $construction['customer_title'] = $customer_title ?? "";        $construction['sales_order_number'] = SalesOrder::where('id',$construction['sales_order_id'])->value('order_number') ?? '';        $construction['handover_time'] = $construction['handover_time'] ? date("Y-m-d H:i:s",$construction['handover_time']): '';        $construction['crt_time'] = $construction['crt_time'] ? date("Y-m-d H:i:s",$construction['crt_time']): '';        $construction_info = ConstructionInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->where('type',CustomerInfo::type_two)            ->select('id','employee_id')            ->get()->toArray();        $emp_list = Employee::whereIn('id',array_unique(array_merge_recursive([$construction['crt_id']],array_column($construction_info,'employee_id'))))            ->select('emp_name','id','mobile')            ->get()->toArray();        $emp_map = [];        foreach ($emp_list as $value){            $emp_map[$value['id']] = [                'name' => $value['emp_name'],                'mobile' => $value['mobile'],            ];        }        $emp_message = EmployeeDepartPermission::from('employee_depart_permission as a')            ->leftJoin('depart as b', 'b.id', 'a.depart_id')            ->select('a.employee_id', 'b.title')            ->whereIn('employee_id',array_column($emp_list,'id'))            ->get()->toArray();        $emp_message_map = [];        foreach ($emp_message as $value){            if(isset($emp_message_map[$value['employee_id']])){                $emp_message_map[$value['employee_id']] .= ',' . $value['title'];            }else{                $emp_message_map[$value['employee_id']] = $value['title'];            }        }        $crt_name = ($emp_map[$construction['crt_id']]['name'] ?? '') . '  ' . ($emp_message_map[$construction['crt_id']] ?? '') . '  ' . ($emp_map[$construction['crt_id']]['mobile'] ?? '');        $construction['crt_name'] = $crt_name;        $xt_name = "";        foreach ($construction_info as $value){            $xt_name .=  ($emp_map[$value['employee_id']]['name'] ?? '') . '  ' . ($emp_message_map[$value['employee_id']] ?? '') . '  ' . ($emp_map[$value['employee_id']]['mobile'] ?? '') . " | ";        }        $xt_name = rtrim($xt_name, " | ");        $construction['xt_name'] = $xt_name;        $p_info = ConstructionProductInfo::where('del_time',0)            ->where('construction_id',$construction['id'])            ->get()->toArray();        $map = (new ProductService())->getProductDetail(array_column($p_info,'product_id'));        $unit_map = BasicType::whereIn('id',array_column($map,'unit'))            ->pluck('title','id')->toArray();        $product = [];        $count = 0;        foreach ($p_info as $value){            $tmp = $map[$value['product_id']] ?? [];            $value['count'] = $count+1;            $value['title'] = $tmp['title'] ?? "";            $value['code'] = $tmp['code'] ?? "";            $value['size'] = $tmp['size'] ?? "";            $value['unit'] = $unit_map[$tmp['unit']] ?? "";            $product[] = $value;        }        //工单进展        $detail  = $this->getOaJz($data,$user);        $order_message = ['order' => $construction, 'product' => $product,'detail'=> $detail];        $pdf = app('dompdf.wrapper')->loadView('pdf.construction', $order_message);        $file_name = time().rand(1000,9999);        $filename =  '施工单_' . $file_name.'.' . 'pdf';        $pdf->save(storage_path('app/public/export/' . $filename));        return [true, ['file' => $filename]];    }    public function getOaJz($data,$user)    {        $oa = Oa::where('menu_id', 34)            ->where('del_time',0)            ->where('channel',$user['depart_top'][0]['depart_id'])            ->first();        if(empty($oa)) return [];        $oa = $oa->toArray();        $list = OaSub::where('oa_id', $oa['id'])->where('del_time', 0)->get()->toArray();        $oa_sub_ids = [];        foreach ($list as $v) {            $oa_sub_ids[] = $v['id'];        }        $oaEmployee = OaSubEmployee::wherein('oa_sub_id', $oa_sub_ids)->get()->toArray();        $emp_list = Employee::whereIn('id',array_column($oaEmployee,'employee_id'))            ->select('emp_name','id','mobile')            ->get()->toArray();        $emp_map = [];        foreach ($emp_list as $value){            $emp_map[$value['id']] = [                'name' => $value['emp_name'],                'mobile' => $value['mobile'],            ];        }        $emp_message = EmployeeDepartPermission::from('employee_depart_permission as a')            ->leftJoin('depart as b', 'b.id', 'a.depart_id')            ->whereIn('a.employee_id',array_column($emp_list,'id'))            ->select('a.employee_id', 'b.title')            ->get()->toArray();        $emp_message_map = [];        foreach ($emp_message as $value){            if(isset($emp_message_map[$value['employee_id']])){                $emp_message_map[$value['employee_id']] .= ',' . $value['title'];            }else{                $emp_message_map[$value['employee_id']] = $value['title'];            }        }        $oaEmployeeKey = [];        foreach ($oaEmployee as $v) {            $str = "";            $tmp = $emp_map[$v['employee_id']] ?? [];            $tmp2 = $emp_message_map[$v['employee_id']] ?? "";            $str = $tmp['name'] . " " . $tmp2 . " " . $tmp['mobile'];            $oaEmployeeKey[$v['oa_sub_id']][] = [                'id' => $v['employee_id'],                'emp_name' => $str,            ];        }        $return = [];        foreach ($list as $v) {            $return[$v['sort']][] = [                'emp_id' => $oaEmployeeKey[$v['id']],                'index' => $v['h5_key'],            ];        }        $detail = [];        foreach ($return as $v) {            $children = "";            foreach ($v as $vv) {                $children .= implode('|',array_column($vv['emp_id'],'emp_name')) . ',';            }            $detail[] = rtrim($children,',');        }        return $detail;    }    public function constructionOperation($data, $user){        if(empty($data['order_number'])) return [false, '施工单号不能为空'];        if(empty($data['type'])) return [false, '操作类型不能为空'];        $order = Construction::where('del_time',0)            ->where('order_number',$data['order_number'])            ->first();        if(empty($order)) return [false,'施工单不存在或已被删除,操作失败'];        $order = $order->toArray();        if($data['type'] == 1){            if($order['state'] != Construction::STATE_TWO) return [false, '请确认施工单单据状态,操作完结失败'];            $state = Construction::STATE_THREE;        }else{            if($order['state'] != Construction::STATE_THREE) return [false, '请确认施工单单据状态,操作待确认失败'];            $state = Construction::STATE_FOUR;        }        Construction::where('order_number',$data['order_number'])            ->update(['state' => $state]);        return [true, ''];    }}
 |