diff --git a/app/common/controller/BrandController.php b/app/common/controller/BrandController.php deleted file mode 100644 index 2abe3cb..0000000 --- a/app/common/controller/BrandController.php +++ /dev/null @@ -1,90 +0,0 @@ -service = new BrandService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (!empty($data['logo'])) - $data['logo_full'] = (new OssService)->generatePrivateUrl($data['logo']); - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (empty($data['logo'])) - $data['logo_full'] = (new OssService)->generatePrivateUrl($data['logo']); - return $data; - } - - /** - * 抓取品牌系列 - * @param Request $request - * @return \support\Response - */ - public function crawlSeries(Request $request){ - try { - $result = $this->service->crawlSeries($request); - if($result){ - return $this->success($result,'成功'); - }else{ - return $this->error('抓取任务提交失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 创建被抓取且选中的品牌系列 - * @param Request $request - * @return \support\Response - */ - public function crawlSeriesCreate(Request $request){ - try { - $result = $this->service->crawlSeriesCreate($request); - if($result){ - return $this->success([],$result); - }else{ - return $this->error('创建失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/BrandSeriesController.php b/app/common/controller/BrandSeriesController.php deleted file mode 100644 index 3cd32d3..0000000 --- a/app/common/controller/BrandSeriesController.php +++ /dev/null @@ -1,121 +0,0 @@ -service = new BrandSeriesService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - /** - * 抓取系列车型 - * @param Request $request - * @return \support\Response - */ - public function crawlModels(Request $request){ - try { - $result = $this->service->crawlModel($request); - if($result){ - return $this->success($result,'抓取成功'); - }else{ - return $this->error('抓取任务失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 保存抓取的系列车型 - * @param Request $request - * @return \support\Response - */ - public function crawlModelCreate(Request $request){ - try { - $result = $this->service->crawlModelCreate($request); - if($result){ - return $this->success($result,'成功'); - }else{ - return $this->error('创建失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 关键词抓取品牌、车系、车型 - * @param Request $request - * @return \support\Response - */ - public function crawlKeyword(Request $request){ - try { - $result = $this->service->crawlKeyword($request); - if($result){ - return $this->success($result,'抓取成功'); - }else{ - return $this->error('抓取任务失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 保存抓取的系列车型 - * @param Request $request - * @return \support\Response - */ - public function crawlKeywordCreate(Request $request){ - try { - $result = $this->service->crawlKeywordCreate($request); - if($result){ - return $this->success($result,'成功'); - }else{ - return $this->error('创建失败'); - } - } catch (\Exception $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/FinPaymentApplyController.php b/app/common/controller/FinPaymentApplyController.php deleted file mode 100644 index 98c49c2..0000000 --- a/app/common/controller/FinPaymentApplyController.php +++ /dev/null @@ -1,181 +0,0 @@ -service = new FinPaymentApplyService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['doc_user_id'])) //内勤 - $data['doc_user_name'] = User::where('id', $data['doc_user_id'])->value('name')??''; - if (isset($data['sales_user_id'])) //业务员 - $data['sales_user_name'] = User::where('id', $data['doc_user_id'])->value('name')??''; - if (isset($data['corp_id'])) //公司(渠道) - $data['corp_name'] = SysDictItem::where('id', $data['corp_id'])->value('item_label')??''; - if (isset($data['account_id'])){ //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - $OssService = new OssService(); - if (!empty($data['submit_files'])){ - $data['submit_files'] = json_decode($data['submit_files'], true); - foreach ($data['submit_files'] as $key => $value) { - $data['submit_files'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['submit_files'] = []; - } - - if (!empty($data['voucher_file'])){ - $data['voucher_file'] = json_decode($data['voucher_file'], true); - foreach ($data['voucher_file'] as $key => $value) { - $data['voucher_file'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['voucher_file'] = []; - } - - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['claimed_at'])){ - $data['enter_file_last'] = date('Y-m-d H:i:s', ($data['claimed_at']+86400)); //入账资料最后提交时间 - $data['claimed_at'] = date('Y-m-d H:i:s', $data['claimed_at']); //认领时间 - } - if (isset($data['id'])){ - $finPaymentStock = FinPaymentStock::where('payment_apply_id', $data['id'])->get(); - $stock = []; - $stock_order_no = []; - foreach ($finPaymentStock as $v) { - $stock[$v['pi_no']]['pi_no'] = $v['pi_no']; - $stock[$v['pi_no']]['stock_id'][] = [$v['stock_id']]; - $stockOrders = StockOrders::where('id', $v['stock_id'])->first(); - $stock_order_no[] = $stockOrders['order_no']; - } - $data['stock'] = array_values($stock); - $data['stock_order_no'] = $stock_order_no; - } - - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - public function showFormat($data) - { - if (isset($data['doc_user_id'])) //内勤 - $data['doc_user_name'] = User::where('id', $data['doc_user_id'])->value('name')??''; - if (isset($data['sales_user_id'])) //业务员 - $data['sales_user_name'] = User::where('id', $data['doc_user_id'])->value('name')??''; - if (isset($data['corp_id'])) //公司(渠道) - $data['corp_name'] = SysDictItem::where('id', $data['corp_id'])->value('item_label')??''; - if (isset($data['account_id'])){ //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - $OssService = new OssService(); - if (!empty($data['submit_files'])){ - $data['submit_files'] = json_decode($data['submit_files'], true); - foreach ($data['submit_files'] as $key => $value) { - $data['submit_files'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['submit_files'] = []; - } - - if (!empty($data['voucher_file'])){ - $data['voucher_file'] = json_decode($data['voucher_file'], true); - foreach ($data['voucher_file'] as $key => $value) { - $data['voucher_file'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['voucher_file'] = []; - } - - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - - $finPaymentStock = FinPaymentStock::where('payment_apply_id', $data['id'])->get(); - $stock = []; - foreach ($finPaymentStock as $v) { - $stock[$v['pi_no']]['pi_no'] = $v['pi_no']; - $stock[$v['pi_no']]['stock_id'][] = [$v['stock_id']]; - } - $data['stock'] = array_values($stock); - return $data; - } - - /** - * 作废 - * @param Request $request - * @return \support\Response - */ - public function delete(Request $request) - { - try { - $id = $request->input('id'); - $raw = $this->service->delete($id); - return $this->success($raw); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/FinReceiptController.php b/app/common/controller/FinReceiptController.php deleted file mode 100644 index 4c73b7a..0000000 --- a/app/common/controller/FinReceiptController.php +++ /dev/null @@ -1,195 +0,0 @@ -service = new FinReceiptService(); - } - - /** - * 确认入账 - * @param Request $request - * @return \support\Response - */ - public function credit(Request $request) - { - try { - $id = $request->input('id'); - $exchange_rate = $request->input('exchange_rate'); - if(empty($exchange_rate) || !is_numeric($exchange_rate)){ - return $this->error('请输入汇率'); - } - $raw = $this->service->credit($id,$exchange_rate); - return $this->success($raw); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function show(Request $request) - { - try { - $raw = $this->service->serviceShow($request); - $data = $this->transformData($raw, method_exists($this, 'showFormat') - ? [$this, 'showFormat'] - : null); - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 更新 - * - * @param Request $request 请求对象 - * @return mixed 返回更新成功的数据或信息 - */ - public function payment(Request $request) - { - try { - $data = $this->validate($this->service->getValidator(), $request->post(), 'update'); - $res = $this->service->serviceUpdatePayment($request, $data); - return $this->success([], '更新成功'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])){ - $data['claim_timeout'] = (($data['created_at'] < (time()-86400)) && empty($data['payment_apply_id'])) ?1:0; - $data['claim_timeout_time'] = date('Y-m-d H:i:s', $data['created_at']+86400); - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - } - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['arrived_at'])) - $data['arrived_at'] = date('Y-m-d H:i:s', $data['arrived_at']); - if (isset($data['received_at'])){ - $data['received_at'] = date('Y-m-d H:i:s', $data['received_at']); - $voucher_no_timeout_hour = redis::get('voucher_no_timeout_hour'); - if(!empty($voucher_no_timeout_hour)){ - $data['voucher_no_timeout_time'] = date('Y-m-d H:i:s', time()+(60*60*$voucher_no_timeout_hour)); - } - } - if (isset($data['account_id'])) { //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - - $OssService = new OssService(); - if (!empty($data['fx_receipt_file'])){ - $data['fx_receipt_file'] = json_decode($data['fx_receipt_file'], true); - foreach ($data['fx_receipt_file'] as $key => $value) { - $data['fx_receipt_file'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['fx_receipt_file'] = []; - } - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['arrived_at'])) - $data['arrived_at'] = date('Y-m-d H:i:s', $data['arrived_at']); - if (isset($data['received_at'])) - $data['received_at'] = date('Y-m-d H:i:s', $data['received_at']); - if (isset($data['account_id'])) { //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - - $OssService = new OssService(); - if (!empty($data['fx_receipt_file'])){ - $data['fx_receipt_file'] = json_decode($data['fx_receipt_file'], true); - foreach ($data['fx_receipt_file'] as $key => $value) { - $data['fx_receipt_file'][$key] = [ - 'file_src' => $value['file_src'], - 'file_full' => $OssService->generatePrivateUrl($value['file_src']), - 'file_name' => $value['file_name'], - ]; - } - }else{ - $data['fx_receipt_file'] = []; - } - - //查询关联的付款记录 - if (!empty($data['payment_apply_id'])) { - $paymentApply = FinPaymentApply::where('id', $data['payment_apply_id'])->first(); - if(!$paymentApply) - return $data; - $paymentApply = $paymentApply->toArray(); - $paymentApply['created_at'] = strtotime($paymentApply['created_at']); - $paymentApply['updated_at'] = strtotime($paymentApply['updated_at']); - $paymentApply = (new FinPaymentApplyController())->showFormat($paymentApply); - $data['payment_apply'] = $paymentApply; - } - return $data; - } - - /** - * 收款记录统计 - * @param Request $request - * @return \support\Response - */ - public function statistics(Request $request) - { - try { - $raw = $this->service->statistics(); - return $this->success($raw); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/FinReceiptHisController.php b/app/common/controller/FinReceiptHisController.php deleted file mode 100644 index 7adcf0d..0000000 --- a/app/common/controller/FinReceiptHisController.php +++ /dev/null @@ -1,98 +0,0 @@ -service = new FinReceiptHisService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['arrived_at'])) - $data['arrived_at'] = date('Y-m-d H:i:s', $data['arrived_at']); - if (isset($data['received_at'])) - $data['received_at'] = date('Y-m-d H:i:s', $data['received_at']); - if (isset($data['account_id'])) { //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - if (!empty($data['fx_receipt_file'])){ - $data['fx_receipt_file_full'] = (new OssService)->generatePrivateUrl($data['fx_receipt_file']); - }elseif (isset($data['fx_receipt_file'])){ - $data['fx_receipt_file_full'] = ''; - } - - if (isset($data['created_by'])) - $data['created_by'] = User::where('id', $data['created_by'])->value('name')??''; - if (isset($data['updated_by'])) - $data['updated_by'] = User::where('id', $data['updated_by'])->value('name')??''; - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['arrived_at'])) - $data['arrived_at'] = date('Y-m-d H:i:s', $data['arrived_at']); - if (isset($data['received_at'])) - $data['received_at'] = date('Y-m-d H:i:s', $data['received_at']); - if (isset($data['account_id'])){ //收款账号 - $data['account_name'] = SysAccount::where('id', $data['account_id'])->value('account_name')??''; - $data['account_short_desc'] = SysAccount::where('id', $data['account_id'])->value('short_desc')??''; - } - if (isset($data['country_id'])) //付款来源国家 - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr')??''; - if (isset($data['currency_id'])) //付款币种 - $data['currency_name'] = SysCurrency::where('id', $data['currency_id'])->value('currency_name')??''; - if (!empty($data['fx_receipt_file'])){ - $data['fx_receipt_file_full'] = (new OssService)->generatePrivateUrl($data['fx_receipt_file']); - }elseif (isset($data['fx_receipt_file'])){ - $data['fx_receipt_file_full'] = ''; - } - - if (isset($data['created_by'])) - $data['created_by'] = User::where('id', $data['created_by'])->value('name')??''; - if (isset($data['updated_by'])) - $data['updated_by'] = User::where('id', $data['updated_by'])->value('name')??''; - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/InvRequisitionApproveController.php b/app/common/controller/InvRequisitionApproveController.php deleted file mode 100644 index 75d419d..0000000 --- a/app/common/controller/InvRequisitionApproveController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new InvRequisitionApproveService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/InvRequisitionAttachmentController.php b/app/common/controller/InvRequisitionAttachmentController.php deleted file mode 100644 index 8ba33e9..0000000 --- a/app/common/controller/InvRequisitionAttachmentController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new InvRequisitionAttachmentService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/InvRequisitionItemController.php b/app/common/controller/InvRequisitionItemController.php deleted file mode 100644 index bf1897c..0000000 --- a/app/common/controller/InvRequisitionItemController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new InvRequisitionItemService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/InvRequisitionItemReturnAttachmentController.php b/app/common/controller/InvRequisitionItemReturnAttachmentController.php deleted file mode 100644 index 8580b28..0000000 --- a/app/common/controller/InvRequisitionItemReturnAttachmentController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new InvRequisitionItemReturnAttachmentService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/InvRequisitionItemReturnController.php b/app/common/controller/InvRequisitionItemReturnController.php deleted file mode 100644 index 7623719..0000000 --- a/app/common/controller/InvRequisitionItemReturnController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new InvRequisitionItemReturnService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/MessageNotificationsController.php b/app/common/controller/MessageNotificationsController.php deleted file mode 100644 index 19341fc..0000000 --- a/app/common/controller/MessageNotificationsController.php +++ /dev/null @@ -1,52 +0,0 @@ -service = new MessageNotificationsService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - return $data; - } - - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - return $data; - } - - - public function push(Request $request) - { - try { - $data = $this->validate($this->service->getValidator(), $request->post(), 'store'); - $res = $this->service->servicePush($request, $data); - return $this->success($res, '推送成功'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/MessageUserStatusController.php b/app/common/controller/MessageUserStatusController.php deleted file mode 100644 index 9a896a1..0000000 --- a/app/common/controller/MessageUserStatusController.php +++ /dev/null @@ -1,95 +0,0 @@ -service = new MessageUserStatusService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['read_at']) && $data['read_at'] !== null) { - $data['read_at'] = date('Y-m-d H:i:s', $data['read_at']); - } else { - $data['read_at'] = ' - '; - } - - if (isset($data['message'])) - $data['message']['created_at'] = date('Y-m-d H:i:s', $data['message']['created_at']); - return $data; - } - - protected function showFormat($data) - { - if (isset($data['read_at']) && $data['read_at'] !== null) { - $data['read_at'] = date('Y-m-d H:i:s', $data['read_at']); - } else { - $data['read_at'] = ' - '; - } - - if (isset($data['message'])) - $data['message']['created_at'] = date('Y-m-d H:i:s', $data['message']['created_at']); - return $data; - } - - protected function unReadFormat($data) - { - foreach ($data as &$item) { - if (isset($item['read_at']) && $item['read_at'] !== null) { - $item['read_at'] = date('Y-m-d H:i:s', $item['read_at']); - } else { - $item['read_at'] = ' - '; - } - - if (isset($item['message'])) { - $item['message']['created_at'] = date('Y-m-d H:i:s', $item['message']['created_at']); - } - } - return $data; - } - - public function read(Request $request) - { - try { - $data = $this->validate($this->service->getValidator(), $request->post(), 'read'); - $this->service->serviceRead($request, $data); - return $this->success([], '操作成功'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function listUnRead(Request $request) - { - try { - $raw = $this->service->serviceListUnRead($request); - $data = $this->transformData($raw, method_exists($this, 'unReadFormat') - ? [$this, 'unReadFormat'] - : null); - $data = [ - 'list' => $data, - 'counts' => count($data) - ]; - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/PresetController.php b/app/common/controller/PresetController.php deleted file mode 100644 index bd92d2f..0000000 --- a/app/common/controller/PresetController.php +++ /dev/null @@ -1,233 +0,0 @@ -getList(); - return $this->success($result, '获取公司列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - - public function feishuApp(Request $request) - { - try { - $corpId = $request->get('corp_id'); - $systemId = $request->get('system_id'); - $result = (new CorpFeishuAppService())->getFeishuApp($corpId, $systemId); - return $this->success($result, '获取飞书应用信息'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - - public function systems() - { - try { - $result = (new SystemsService())->getList(); - return $this->success($result, '获取系统列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function users(Request $request) - { - try { - $result = (new UserService())->getList($request); - return $this->success($result, '获取用户列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function roles() - { - try { - $result = (new RoleService)->getList(); - return $this->success($result, '获取角色列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function currency() - { - try { - $result = (new SysCurrencyService)->getList(); - return $this->success($result, '获取货币列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function brand() - { - try { - $result = (new BrandService)->getList(); - return $this->success($result, '获取品牌列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function series(Request $request) - { - try { - $params = $request->all(); - $result = (new BrandSeriesService)->getList($params); - return $this->success($result, '获取车系列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function account() - { - try { - $result = (new SysAccountService)->getList(); - return $this->success($result, '获取账号列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function dict() - { - try { - $result = (new SysDictService)->getList(); - return $this->success($result, '获取字典列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function dictItem(Request $request) - { - try { - $params = $request->all(); - $result = (new SysDictItemService)->getList($params); - return $this->success($result, '获取字典项列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function port(Request $request) - { - try { - $params = $request->all(); - $result = (new SysPortService)->getList($params); - return $this->success($result, '获取港口列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function color(Request $request) - { - try { - $params = $request->all(); - $result = (new VehColorService)->getList($params); - return $this->success($result, '获取颜色列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function modification() - { - try { - $result = (new VehModificationService)->getList(); - return $this->success($result, '获取货币列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function cacheClear() - { - try { - Cache::clear(); - return $this->success([], '操作成功'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function menus(Request $request) - { - try { - $uid = $request->user->uid; - $systemCode = $request->system_code; - $permService = new PermService(); - $menuTree = $permService->getMenuTree($uid, $systemCode); - $permissionCodes = $permService->getPermissionCodes($uid, $systemCode); - $result = [ - 'menu' => $menuTree, - 'permissions' => $permissionCodes - ]; - return $this->success($result, '获取菜单权限'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function userGroup(Request $request) - { - try { - $result = (new UserGroupService)->userGroup($request); - return $this->success($result, '获取分组'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function userGroupScene(Request $request) - { - try { - $result = (new UserGroupService)->userGroupScene($request); - return $this->success($result, '获取分组场景'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/PurchaseOrderItemsController.php b/app/common/controller/PurchaseOrderItemsController.php deleted file mode 100644 index e602109..0000000 --- a/app/common/controller/PurchaseOrderItemsController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new PurchaseOrderItemsService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/PurchaseOrdersController.php b/app/common/controller/PurchaseOrdersController.php deleted file mode 100644 index 5b86f47..0000000 --- a/app/common/controller/PurchaseOrdersController.php +++ /dev/null @@ -1,137 +0,0 @@ -service = new PurchaseOrdersService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['records']) && count($data['records']) > 0) { - foreach ($data['records'] as &$record) { - $contractFile = $record['contract_file'] ? explode(',', $record['contract_file']) : []; - $contractFileUrl = []; - if (count($contractFile) > 0) { - foreach ($contractFile as $file) { - $contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file); - } - } - $result = [ - 'id' => $record['id'], - 'order_no' => $record['order_no'], - 'pi_no' => $record['pi_no'], - 'buyer_id' => $record['buyer_id'], - 'buyer_name' => $record['buyer_name'], - 'contract_file' => $contractFile, - 'contract_file_url' => $contractFileUrl, - 'status' => $record['status'], - 'status_text' => array_flip(\app\common\service\SysDictService::pluckKeyValueByCode('purchase_status'))[$record['status']], - 'remark' => $record['remark'], - 'created_at' => date('Y-m-d H:i:s', $record['created_at']), - 'updated_at' => date('Y-m-d H:i:s', $record['updated_at']), - ]; - $record = $result; - } - unset($record); - } - return $data; - } - - /** - * 详情页数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - $contractFile = $data['contract_file'] ? explode(',', $data['contract_file']) : []; - $contractFileUrl = []; - if (count($contractFile) > 0) { - foreach ($contractFile as $file) { - $contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file); - } - } - $result = [ - 'id' => $data['id'], - 'order_no' => $data['order_no'], - 'pi_no' => $data['pi_no'], - 'buyer_id' => $data['buyer_id'], - 'buyer_name' => $data['buyer_name'], - 'contract_file' => $contractFile, - 'contract_file_url' => $contractFileUrl, - 'status' => $data['status'], - 'remark' => $data['remark'] - ]; - $temps = []; - if (isset($data['items']) && count($data['items']) > 0) { - foreach ($data['items'] as $record) { - if (!in_array($record['stockOrder']['id'], array_keys($temps))) { - $temps[$record['stockOrder']['id']] = [ - 'id' => $record['stockOrder']['id'], - 'order_no' => $record['stockOrder']['order_no'], - 'salesperson_snapshot' => $record['stockOrder']['salesperson_snapshot'], - 'biz_date' => date('Y-m-d', $record['stockOrder']['biz_date']) - ]; - } - $temps[$record['stockOrder']['id']]['stock_order_items'][] =[ - 'id' => $record['stockOrderItems']['id'], - 'model_snapshot' => $record['stockOrderItems']['model_snapshot'], - 'unique_id' => $record['stockOrderItems']['unique_id'], - ]; - } - } - $result['stock_order'] = array_values($temps); - return $result; - } - - /** - * 前置查询处理 - * - * @param Request $request - * @return array - */ - public function preQueryData(Request $request) - { - try { - $data = $this->service->preQueryData($request->all()); - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 重提 - * - * @param Request $request - * @return mixed - */ - public function resubmit(Request $request) - { - try { - $raw = $this->service->serviceResubmit($request, $request->all()); - return $this->success($raw); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/ResourceController.php b/app/common/controller/ResourceController.php deleted file mode 100644 index 5fd35b9..0000000 --- a/app/common/controller/ResourceController.php +++ /dev/null @@ -1,82 +0,0 @@ -service = new ResourceService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function allFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - /** - * 资源树形结构 - */ - public function listTree(Request $request) - { - try { - $raw = $this->service->serviceListAll($request); - $data = $this->transformData($raw, method_exists($this, 'allFormat') - ? [$this, 'allFormat'] - : null); - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 菜单 - */ - public function menuList(Request $request) - { - try { - $raw = $this->service->serviceMenuList($request); - $data = $this->transformData($raw, method_exists($this, 'allFormat') - ? [$this, 'allFormat'] - : null); - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - /** - * 菜单 - */ - public function menuTreeList(Request $request) - { - try { - $raw = $this->service->serviceMenuTreeList($request); - $data = $this->transformData($raw, method_exists($this, 'allFormat') - ? [$this, 'allFormat'] - : null); - return $this->success($data); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } -} \ No newline at end of file diff --git a/app/common/controller/StockOrdersFilesController.php b/app/common/controller/StockOrdersFilesController.php deleted file mode 100644 index dfb6a23..0000000 --- a/app/common/controller/StockOrdersFilesController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new StockOrdersFilesService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/SysOpLogController.php b/app/common/controller/SysOpLogController.php deleted file mode 100644 index 525232e..0000000 --- a/app/common/controller/SysOpLogController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new SysOpLogService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/SysPortController.php b/app/common/controller/SysPortController.php deleted file mode 100644 index a5cc59d..0000000 --- a/app/common/controller/SysPortController.php +++ /dev/null @@ -1,53 +0,0 @@ -service = new SysPortService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['country_id'])) - if (isset($data['country_id'])) - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr'); - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - $data['country_name'] = Country::where('id', $data['country_id'])->value('cn_addr'); - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/SysUpdateLogController.php b/app/common/controller/SysUpdateLogController.php deleted file mode 100644 index 56a3218..0000000 --- a/app/common/controller/SysUpdateLogController.php +++ /dev/null @@ -1,35 +0,0 @@ -service = new SysUpdateLogService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['update_time'])) - $data['update_time'] = date('Y-m-d H:i:s', $data['update_time']); - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/UsedcarCrawlResultsController.php b/app/common/controller/UsedcarCrawlResultsController.php deleted file mode 100644 index bdeac97..0000000 --- a/app/common/controller/UsedcarCrawlResultsController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new UsedcarCrawlResultsService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/UsedcarCrawlResultsImagesController.php b/app/common/controller/UsedcarCrawlResultsImagesController.php deleted file mode 100644 index 5560fda..0000000 --- a/app/common/controller/UsedcarCrawlResultsImagesController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new UsedcarCrawlResultsImagesService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/VehColorController.php b/app/common/controller/VehColorController.php deleted file mode 100644 index 4473c44..0000000 --- a/app/common/controller/VehColorController.php +++ /dev/null @@ -1,56 +0,0 @@ -service = new VehColorService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['created_by']) && $data['created_by']) - $data['created_by_name'] = User::where('id', $data['created_by'])->value('name'); - if (isset($data['updated_by']) && $data['updated_by']) - $data['updated_by_name'] = User::where('id', $data['updated_by'])->value('name'); - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - if (isset($data['created_by']) && $data['created_by']) - $data['created_by_name'] = User::where('id', $data['created_by'])->value('name'); - if (isset($data['updated_by']) && $data['updated_by']) - $data['updated_by_name'] = User::where('id', $data['updated_by'])->value('name'); - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/VehDictI18nController.php b/app/common/controller/VehDictI18nController.php deleted file mode 100644 index 6a87c9f..0000000 --- a/app/common/controller/VehDictI18nController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new VehDictI18nService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/VehDictMappingController.php b/app/common/controller/VehDictMappingController.php deleted file mode 100644 index d1a1dfe..0000000 --- a/app/common/controller/VehDictMappingController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new VehDictMappingService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/VehModificationController.php b/app/common/controller/VehModificationController.php deleted file mode 100644 index 314ca40..0000000 --- a/app/common/controller/VehModificationController.php +++ /dev/null @@ -1,47 +0,0 @@ -service = new VehModificationService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - /** - * 数据格式化 - * - * @param array $data - * @return array - */ - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } -} \ No newline at end of file diff --git a/app/common/controller/VehMoneyValueController.php b/app/common/controller/VehMoneyValueController.php deleted file mode 100644 index b96d3f9..0000000 --- a/app/common/controller/VehMoneyValueController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new VehMoneyValueService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/VehVehicleListingController.php b/app/common/controller/VehVehicleListingController.php deleted file mode 100644 index 59d49aa..0000000 --- a/app/common/controller/VehVehicleListingController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new VehVehicleListingService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/controller/VehVehicleSkuController.php b/app/common/controller/VehVehicleSkuController.php deleted file mode 100644 index 9c41686..0000000 --- a/app/common/controller/VehVehicleSkuController.php +++ /dev/null @@ -1,223 +0,0 @@ -service = new VehVehicleSkuService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - protected function indexFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - protected function showFormat($data) - { - if (isset($data['created_at'])) - $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - if (isset($data['updated_at'])) - $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - return $data; - } - - - public function store(Request $request) - { - return $this->error('请优先抓取车辆信息,如抓取不到相应车型请联系管理员,暂停手动录入车辆信息'); - try { - $data = $this->validate($this->service->getValidator(), $request->post(), 'store'); - $res = $this->service->serviceStore($request, $data); - return $this->success($res, '创建成功'); - } catch (\PDOException $e) { - $errorCode = $e->getCode(); - $errorMessage = $e->getMessage(); - if ($errorCode == '23000') { - if (strpos($errorMessage, "Duplicate entry") !== false && strpos($errorMessage, "uk_fingerprint") !== false) { - return $this->error("该车辆指纹已存在,请勿重复提交"); - } - // 其他类型的完整性约束错误 - throw new BusinessException("数据完整性错误", 0, $e); - } - // 重新抛出其他类型的异常 - throw $e; - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function update(Request $request) - { - try { - $data = $this->validate($this->service->getValidator(), $request->post(), 'update'); - $res = $this->service->serviceUpdate($request, $data); - return $this->success([], '更新成功'); - } catch (\PDOException $e) { - $errorCode = $e->getCode(); - $errorMessage = $e->getMessage(); - if ($errorCode == '23000') { - if (strpos($errorMessage, "Duplicate entry") !== false && strpos($errorMessage, "uk_fingerprint") !== false) { - return $this->error("该车辆指纹已存在,请勿重复提交"); - } - // 其他类型的完整性约束错误 - throw new BusinessException("数据完整性错误", 0, $e); - } - // 重新抛出其他类型的异常 - throw $e; - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - public function preset(Request $request){ - - - try { - $series_id = $request->input('series_id'); - $series_code = BrandSeries::where('id', $series_id)->value('series_code'); - $data = [ - 'series_code' => $series_code, - ]; - $result = $this->service->getList($data); - return $this->success($result, '获取车型列表'); - } catch (\Throwable $e) { - return $this->error($e->getMessage()); - } - } - - - public function fields_desc(Request $request) - { - $data = [ - 'sku_code' , // 'SKU编码,系统生成', - 'fingerprint' , // '规格指纹(sha256)去重', - 'brand_code' , // '品牌代码,如 BYD、HYUNDAI、KIA', - 'brand_name' , // '品牌名称展示,如 比亚迪、现代、起亚', - 'series_code' , // '车系代码,如 ELANTRA、SONGPLUS', - 'series_name' , // '车系名称展示', - 'model_code' , // '车型/配置代码(工厂/内部编码)', - 'model_name' , // '车型/配置名称(可读,如 伊兰特 1.5L、海狮07)', - 'model_year' , // '年款(YYYY)', - 'trim_code' , // '版型代码(TRIM)', - 'trim_level_code' , // '配置等级代码(TRIM_LEVEL)', - 'edition_code' , // '特别版代码(EDITION)', - 'trim' , // '版型/细分配置(如 TOP旗舰版、荣耀版)', - 'trim_level' , // '配置等级(豪华型/旗舰型等,便于筛选)', - 'edition_name' , // '特别版/纪念版(如 荣耀版、致敬版等)', - 'body_type_code' , // '车身类型:SEDAN/SUV/HB/MPV/Pickup', - 'drive_type_code' , // '驱动:FWD/RWD/AWD/4WD', - 'motor_layout_code' , // '电驱/电机布置(MOTOR_LAYOUT):FWD/RWD/AWD/DM-i/DM-p 等', - 'fuel_type_code' , // '能源:GAS/HEV/PHEV/EV/EREV', - 'engine_disp_l' , // '排量(L),如 1.5;纯电为空', - 'engine_turbo' , // '0' COMMENT '是否涡轮(0/1)', - 'engine_power_kw' , // '最大功率(kW)', - 'battery_kwh' , // '电池容量(kWh)', - 'transmission_code' , // '变速箱:MT/AT/CVT/DCT/1SPEED', - 'gears' , // '挡位数(EV多为1)', - 'range_km' , // '续航里程(km)', - 'range_std_code' , // '续航标准:CLTC/WLTP/EPA/NEDC', - 'doors' , // '门数', - 'seats' , // '座位数', - 'weight_kg' , // '整备质量(kg)', - 'dimensions_mm' , // '尺寸(mm):{length,width,height,wheelbase}', - 'color_exterior_code' , // '外观色代码', - 'color_exterior_text' , // '外观色名称', - 'color_interior_code' , // '内饰色代码', - 'color_interior_text' , // '内饰色名称', - 'options_official' , // '官方选装(结构化 JSON)', - 'features' , // '功能/安全/智能配置(结构化 JSON)', - 'emission_std_code' , // '排放标准:CHN6/EURO6/EPA', - 'origin_country' , // '原产国 ISO-3166-1 alpha-2', - 'currency' , // 'CNY' COMMENT '币种 ISO-4217', - 'msrp' , // '建议零售价/参考价', - 'is_active' , // '1' COMMENT '启用(1)/禁用(0)', - 'corp_id' , // '0' COMMENT '租户/公司(全局库可写0)', - 'remark' , // '备注', - 'created_by' , // '0', - 'updated_by' , // '0', - ]; - - - $data = [ - 'fingerprint' , // '规格指纹(sha256)去重', - 'brand_name' , // '品牌名称展示,如 比亚迪、现代、起亚', - 'series_name' , // '车系名称展示', - 'model_name' , // '车型/配置名称(可读,如 伊兰特 1.5L、海狮07)', - 'model_year' , // '年款(YYYY)', - 'trim' , // '版型/细分配置(如 TOP旗舰版、荣耀版)', - 'trim_level' , // '配置等级(豪华型/旗舰型等,便于筛选)', - 'edition_name' , // '特别版/纪念版(如 荣耀版、致敬版等)', - 'engine_disp_l' , // '排量(L),如 1.5;纯电为空', - 'engine_turbo' , // '0' COMMENT '是否涡轮(0/1)', - 'engine_power_kw' , // '最大功率(kW)', - 'battery_kwh' , // '电池容量(kWh)', - 'gears' , // '挡位数(EV多为1)', - 'range_km' , // '续航里程(km)', - 'doors' , // '门数', - 'seats' , // '座位数', - 'weight_kg' , // '整备质量(kg)', - 'dimensions_mm' , // '尺寸(mm):{length,width,height,wheelbase}', - 'color_exterior_text' , // '外观色名称', - 'color_interior_text' , // '内饰色名称', - 'options_official' , // '官方选装(结构化 JSON)', - 'features' , // '功能/安全/智能配置(结构化 JSON)', - 'origin_country' , // '原产国 ISO-3166-1 alpha-2', - 'currency' , // 'CNY' COMMENT '币种 ISO-4217', - 'msrp' , // '建议零售价/参考价', - 'is_active' , // '1' COMMENT '启用(1)/禁用(0)', - 'corp_id' , // '0' COMMENT '租户/公司(全局库可写0)', - 'remark' , // '备注', - 'created_by' , // '0', - 'updated_by' , // '0', - - 'body_type', // '车身类型' - 'drive_type', // '驱动:FWD/RWD/AWD/4WD', - 'motor_layout', // '电机布置(MOTOR_LAYOUT):FWD/RWD/AWD/DM-i/DM-p 等' - 'fuel_type', // '能源:GAS/HEV/PHEV/EV/EREV' - 'transmission', // '变速箱:MT/AT/CVT/DCT/1SPEED' - 'range_std', // '续航标准:CLTC/WLTP/EPA/NEDC' - 'emission_std', // '排放标准:CHN6/EURO6/EPA' - - 'sku_code' , // 'SKU编码,系统生成', - 'brand_code' , // '品牌代码,如 BYD、HYUNDAI、KIA', - 'series_code' , // '车系代码,如 ELANTRA、SONGPLUS', - 'model_code' , // '车型/配置代码(工厂/内部编码)', - 'trim_code' , // '版型代码(TRIM)', - 'trim_level_code' , // '配置等级代码(TRIM_LEVEL)', - 'edition_code' , // '特别版代码(EDITION)', - 'color_exterior_code' , // '外观色代码', - 'color_interior_code' , // '内饰色代码', - - 'body_type_code' , // '车身类型:SEDAN/SUV/HB/MPV/Pickup', - 'drive_type_code' , // '驱动:FWD/RWD/AWD/4WD', - 'motor_layout_code' , // '电驱/电机布置(MOTOR_LAYOUT):FWD/RWD/AWD/DM-i/DM-p 等', - 'fuel_type_code' , // '能源:GAS/HEV/PHEV/EV/EREV', - 'transmission_code' , // '变速箱:MT/AT/CVT/DCT/1SPEED', - 'range_std_code' , // '续航标准:CLTC/WLTP/EPA/NEDC', - 'emission_std_code' , // '排放标准:CHN6/EURO6/EPA', - ]; - } -} \ No newline at end of file diff --git a/app/common/controller/VehVehicleUnitController.php b/app/common/controller/VehVehicleUnitController.php deleted file mode 100644 index 3d2e7e2..0000000 --- a/app/common/controller/VehVehicleUnitController.php +++ /dev/null @@ -1,33 +0,0 @@ -service = new VehVehicleUnitService(); - } - - /** - * 列表页数据格式化 - * - * @param array $data - * @return array - */ - // protected function indexFormat($data) - // { - // if (isset($data['created_at'])) - // $data['created_at'] = date('Y-m-d H:i:s', $data['created_at']); - // if (isset($data['updated_at'])) - // $data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']); - // return $data; - // } -} \ No newline at end of file diff --git a/app/common/logic/ApprovalFlowsLogic.php b/app/common/logic/ApprovalFlowsLogic.php deleted file mode 100644 index 2157d28..0000000 --- a/app/common/logic/ApprovalFlowsLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -validateUser($data['account'], $data['password']); - $system = $this->validateSystem($data['system_code']); - $this->validateSystemPermission($user, $system); - - return $this->generateTokensAndReturn($user, $system, $data); - } - - /** - * 飞书登录 - * 如果用户不存在则新增用户信息 - */ - public function feishuLogin(array $data): array - { - $feishuUserInfo = $this->getFeishuUserInfo($data); - return $feishuUserInfo; - $user = $this->getOrCreateUser($feishuUserInfo); - - $system = $this->validateSystem($data['system_code']); - if ($user->isLogin) { - $this->validateSystemPermission($user, $system); - } - - return $this->generateTokensAndReturn($user, $system, $data); - } - - /** - * 注册 - */ - public function register(array $data) - { - try { - // 获取可用用户编号 - $sn = $this->getAvailableUserSn(); - $data['sn'] = $sn->user_sn; - - // 对密码进行哈希处理 - $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT); - - // 获取企业ID - $corpInfo = $this->validateCorp($data['corp_abbr']); - $data['corp_id'] = $corpInfo->id; - - // 处理账户 - $data = $data + normalizeAccount($data['account']); - - // 创建用户记录 - $user = $this->createUser($data); - - // 更新用户编号的用户 ID - $this->updateUserId($user->id, $sn->user_sn); - - $system = $this->validateSystem($data['system_code']); - return $this->generateTokensAndReturn($user, $system, $data); - } catch (\Throwable $e) { - throw $e; - } - } - - /** - * 查找或创建飞书用户 - */ - private function getOrCreateUser(array $feishuUserInfo) - { - try { - $phone = $this->sanitizePhone($feishuUserInfo['mobile'] ?? ''); - $email = $feishuUserInfo['enterprise_email']; - // $user = User::where('corp_id', $feishuUserInfo['corp_id']) - // ->where(function($query) use ($phone, $email) { - // $query->where('phone', $phone) - // ->orWhere('email', $email); - // }) - // ->first(); - $userByPhone = User::where('corp_id', $feishuUserInfo['corp_id']) - ->where('phone', $phone) - ->where('phone', '!=', '') - ->first(); - $userByEmail = User::where('corp_id', $feishuUserInfo['corp_id']) - ->where('email', $email) - ->where('email', '!=', '') - ->first(); - $user = $userByPhone ?: $userByEmail; - if (!$user) { - // 获取编号 - $userSn = $this->getAvailableUserSn(); - // 创建用户 - $user = User::create([ - 'name' => $feishuUserInfo['name'], - 'avatar' => $feishuUserInfo['avatar_middle'], - 'phone' => $this->sanitizePhone($feishuUserInfo['mobile'] ?? ''), - 'email' => $feishuUserInfo['enterprise_email'], - 'union_id' => $feishuUserInfo['union_id'], - 'user_id' => $feishuUserInfo['user_id'], - 'open_id' => $feishuUserInfo['open_id'], - 'tenant_key' => $feishuUserInfo['tenant_key'], - 'corp_id' => $feishuUserInfo['corp_id'], - 'password' => password_hash($userSn->user_sn, PASSWORD_DEFAULT) - ]); - // 更新使用 - $this->updateUserId($user->id, $userSn->user_sn); - // 更新编号 - if (!$user->update(['sn'=>$userSn->user_sn])) { - throw new BusinessException('编号绑定失败'); - } - // 是否登陆 - $user->isLogin = false; - - $options = [ - 'corp_id' => $user->corp_id, - 'user_id' => $user->id - ]; - \Webman\RedisQueue\Redis::send('perm-agt', $options); - } else { - $updated = [ - 'union_id' => $feishuUserInfo['union_id'], - 'user_id' => $feishuUserInfo['user_id'], - 'open_id' => $feishuUserInfo['open_id'], - 'tenant_key' => $feishuUserInfo['tenant_key'] - ]; - if ($phone && $phone == $user->phone) { - $updated['phone'] = $phone; - } - if ($phone && $phone == $user->phone) { - $updated['email'] = $email; - } - // 更新飞书信息 - $user->update($updated); - // 是否登陆 - $user->isLogin = true; - } - return $user; - } catch (\Throwable $e) { - throw $e; - } - } - - /** - * 过滤和格式化手机号 - */ - private function sanitizePhone($mobile) - { - return isset($mobile) ? str_replace('+86', '', $mobile) : ''; - } - - /** - * 生成并记录token,返回包含token的响应数据 - */ - private function generateTokensAndReturn(User $user, Systems $system, array $data): array - { - $payload = $this->buildJwtPayload($user, $system); - $token = $this->generateAccessToken($payload); - $refreshToken = $this->generateRefreshToken($user->id, $data['system_code']); - $homeUrl = $this->getHome($system->id, $payload); - - // 记录 token 到 Redis 和 MySQL - $this->recordUserToken($user->id, $token, $data['system_code']); - - return [ - 'access_token' => $token, - 'refresh_token' => $refreshToken, - 'expires_in' => config('jwt.jwt_expiration'), - 'system_code' => $data['system_code'], - 'corp_abbr' => $data['corp_abbr'], - 'login_type' => $data['login_type'], - 'home_url' => $homeUrl, - // 'payload' => $payload, - ]; - } - - /** - * 获取飞书用户信息 - */ - private function getFeishuUserInfo(array $data) - { - $app = [ - 'cli_a8033d607cba500d' => 'OZW2UOeJ0g4HJfXKSn6skcymCOyYIdDR', - ]; - if(empty($app[$data['app_id']])){ - throw new BusinessException('app_id非法'); - } - $fsAppInfo = CorpFeishuApp::where('app_id', $data['app_id'])->first(); - $feishu = new Feishu($data['app_id'], $fsAppInfo['app_secret']); - - //回调地址 - $redirect_uri = $fsAppInfo['r_url']; - - $userAccessToken = $feishu->userAccessToken($data['feishu_code'], $redirect_uri); - $userInfo = $feishu->userInfo($userAccessToken['access_token']); - - if ($userInfo['code'] != 0) { - throw new BusinessException('授权失败,请重试'); - } - - - User::firstOrCreate(['union_id'=>$userInfo['data']['union_id']],[ - 'union_id'=>$userInfo['data']['union_id'], - 'name'=>$userInfo['data']['name'], - 'app_id'=>$data['app_id'] - ]); - return $userInfo['data'] + $data; - } - - /** - * 更新用户编号 - */ - private function updateUserId($userId, $userSn) - { - $updated = UserSn::where('user_sn', $userSn) - ->update(['user_id' => $userId]); - - if ($updated === 0) { - throw new BusinessException('用户编号不存在或更新失败'); - } - - return $updated; - } - - /** - * 记录用户token到 Redis 和 MySQL - */ - protected function recordUserToken(int $userId, string $token, string $systemCode) - { - $request = request(); - $ip = $request ? $request->getRealIp() : ''; - $ua = $request ? $request->header('user-agent', '') : ''; - $now = time(); - $expireAt = $now + config('jwt.jwt_expiration'); - - // Redis Set 用户token集合 - Redis::sAdd("user_tokens:{$userId}:{$systemCode}", $token); - Redis::expire("user_tokens:{$userId}:{$systemCode}", config('jwt.jwt_expiration')); - - // Redis Hash token元信息 - $meta = [ - 'system_code' => $systemCode, - 'login_ip' => $ip, - 'user_agent' => $ua, - 'login_time' => $now, - 'expired_at' => $expireAt, - ]; - Redis::hMSet("user_token_meta:{$token}", $meta); - Redis::expire("user_token_meta:{$token}", config('jwt.jwt_expiration')); - - // 可选:MySQL 持久化 - try { - UserTokenLog::create([ - 'user_id' => $userId, - 'token' => $token, - 'system_code'=> $systemCode, - 'login_ip' => $ip, - 'user_agent' => $ua, - 'login_time' => $now, - 'expired_at' => $expireAt, - 'is_valid' => 1, - ]); - } catch (\Throwable $e) { - Log::error('Token log write failed: '.$e->getMessage()); - } - } - - /** - * 校验token有效性 - */ - public function verifyToken(string $token, string $systemCode): array - { - if (!$systemCode) throw new BusinessException('缺少system_code', 422); - - $payload = (new Jwt())->verifyToken($token); - - // 校验黑名单 - if (Redis::has("token_blacklist:{$token}")) { - throw new BusinessException('token已失效', 403); - } - - // 强制校验aud(系统隔离) - if ($systemCode && $payload['aud'] != $systemCode && $payload['aud'] != ($payload['system_code'] ?? '')) { - throw new BusinessException('token不属于当前系统', 403); - } - - return (array)$payload; - } - - /** - * 获取飞书应用信息 - */ - public function feishuAppInfo(string $app_id, string $systemCode) - { - $fsAppInfo = CorpFeishuApp::where('app_id', $app_id)->first(); - return [ - 'app_id' => $fsAppInfo->app_id, - 'app_secret' => $fsAppInfo->app_secret, - 'r_url' => $fsAppInfo->r_url, - 'scope' => $fsAppInfo->scopes, - 'state' => $fsAppInfo->state, - ]; - } - - /** - * 验证用户信息 - */ - private function validateUser(string $account, string $password) - { - $user = User::byAccount($account)->first(); - if (!$user || !password_verify($password, $user->password)) { - throw new BusinessException('账号或密码错误', 401); - } - if ($user->status != 1) { - throw new BusinessException('账号已禁用', 403); - } - return $user; - } - - /** - * 验证系统信息 - */ - private function validateSystem(string $systemCode) - { - $system = Systems::where('code', $systemCode)->first(); - if (!$system) { - throw new BusinessException('系统不存在', 403); - } - return $system; - } - - /** - * 验证公司信息 - */ - private function validateCorp(string $corpAbbr) - { - $corp = Corp::where('abbr', $corpAbbr)->first(); - if (!$corp) { - throw new BusinessException('公司不存在', 403); - } - return $corp; - } - - /** - * 验证飞书应用信息 - */ - private function validateFeishuApp(int $corpId, int $systemId) - { - $feishuAppInfo = CorpFeishuApp::where('corp_id', $corpId)->where('system_id', $systemId)->first(); - if (!$feishuAppInfo) { - throw new BusinessException('飞书应用不存在', 403); - } - return $feishuAppInfo; - } - - /** - * 验证用户系统权限 - */ - private function validateSystemPermission(User $user, Systems $system) - { - if ($system->is_role) { - $systemIds = $user->systems->pluck('id')->toArray(); - if (!in_array($system->id, $systemIds)) { - throw new BusinessException('无该系统权限', 403); - } - } - } - - /** - * 获取可用的用户编号 - * - * @return \app\common\model\UserSn 用户编号模型实例 - * @throws BusinessException 当未找到适用编号时抛出 - */ - private function getAvailableUserSn(): \app\common\model\UserSn - { - $userSnModel = new UserSn(); - $sn = $userSnModel->where('user_id', '=', 0)->inRandomOrder()->first(); - if (!$sn) { - Log::error('用户注册时未找到适用编号'); - throw new BusinessException('未找到适用编号'); - } - return $sn; - } - - /** - * 创建用户记录 - * - * @param array $data 包含用户信息的数组 - * @return \app\common\model\User 用户模型实例 - */ - private function createUser(array $data): \app\common\model\User - { - try { - return User::create($data); - } catch (\Throwable $e) { - Log::error('用户注册时创建用户记录失败', [ - 'data' => $data, - 'error' => $e->getMessage() - ]); - throw new BusinessException('用户注册失败,请稍后重试', 500); - } - } - - /** - * JWT payload 构建 - * 可扩展 payload 字段 - */ - private function buildJwtPayload(User $user, ?Systems $system = null): array - { - $now = time(); - $exp = $now + config('jwt.jwt_expiration'); - $system_ids = $user->systems ? $user->systems->pluck('id')->toArray() : []; - $role_ids = $user->roles ? $user->roles->pluck('id')->toArray() : []; - - return [ - 'sub' => 'user_' . $user->id, - 'aud' => $system->code, - 'iat' => $now, - 'nbf' => $now, - 'exp' => $exp, - 'typ' => 'access', - 'uid' => $user->id, - 'uname' => $user->name, - 'role_ids' => $role_ids, - 'system_ids' => $system_ids - ]; - } - - /** - * JWT签发 - */ - private function generateAccessToken(array $payload) - { - return (new Jwt())->generateToken($payload); - } - - /** - * 刷新令牌生成 - */ - private function generateRefreshToken(int $userId, string $systemCode) - { - $refreshToken = bin2hex(random_bytes(32)); - // user_id+system_code只允许一个refresh_token生效 - Redis::set("refresh_token:{$userId}:{$systemCode}", $refreshToken, config('jwt.jwt_refresh_token_expiration')); - // 建立refresh_token到user_id+system_code映射,便于校验 - Redis::set("refresh_token_map:{$refreshToken}:{$systemCode}", $userId, config('jwt.jwt_refresh_token_expiration')); - return $refreshToken; - } - - - /** - * 刷新token - * @param string $refreshToken - * @param string|null $systemCode 可选,指定系统 - * @return array - */ - public function refreshToken(string $refreshToken, ?string $systemCode = null): array - { - if (!$systemCode) throw new BusinessException('缺少system_code', 422); - - // 校验refresh_token - $userId = Redis::get("refresh_token_map:{$refreshToken}:{$systemCode}"); - if (!$userId) { - throw new BusinessException('refresh_token无效或已过期', 401); - } - - $validToken = Redis::get("refresh_token:{$userId}:{$systemCode}"); - if ($validToken !== $refreshToken) { - throw new BusinessException('refresh_token无效或已过期', 401); - } - - $user = User::find($userId); - if (!$user || $user->status != 1) { - throw new BusinessException('用户无效', 403); - } - - $system = $this->validateSystem($systemCode); - $this->validateSystemPermission($user, $system); - - $payload = $this->buildJwtPayload($user, $system); - $token = $this->generateAccessToken($payload); - $refreshToken = $this->generateRefreshToken($user->id, $systemCode); - $this->recordUserToken($user->id, $token, $systemCode); - - return [ - 'access_token' => $token, - 'refresh_token' => $refreshToken, - 'expires_in' => config('jwt.jwt_expiration'), - // 'payload' => $payload, - ]; - } - - /** - * 登出/失效token - */ - public function logout(?string $token, ?string $systemCode = null) - { - if ($token) { - Redis::set("token_blacklist:{$token}", 1, config('jwt.jwt_expiration')); - $payload = null; - try { $payload = (new Jwt())->verifyToken($token); } catch (\Throwable $e) {} - $userId = $payload['uid'] ?? null; - $aud = $payload['aud'] ?? null; - $sc = $systemCode ?? $aud; - if ($userId && $sc) { - Redis::sRem("user_tokens:{$userId}:{$sc}", $token); - } - Redis::del("user_token_meta:{$token}"); - UserTokenLog::where('token', $token)->update(['is_valid'=>0]); - } - } - - /** - * 强制拉黑token - */ - public function blockToken(string $token, ?string $systemCode = null) - { - if (!$token) { - throw new BusinessException('token不能为空', 422); - } - Redis::set("token_blacklist:{$token}", 1, config('jwt.jwt_expiration')); - $payload = null; - try { $payload = (new Jwt())->verifyToken($token); } catch (\Throwable $e) {} - $userId = $payload['uid'] ?? null; - $aud = $payload['aud'] ?? null; - $sc = $systemCode ?? $aud; - if ($userId && $sc) { - Redis::sRem("user_tokens:{$userId}:{$sc}", $token); - } - Redis::del("user_token_meta:{$token}"); - UserTokenLog::where('token', $token)->update(['is_valid'=>0]); - } - - - public function getHome($systemId, $data) - { - // 2025.10.30 临时处理 ====== start - if ($systemId == 1) { - if (in_array(1, $data['role_ids'])) { - return '/dashboard/console'; - } - if (count($data['role_ids']) == 1 && in_array(5, $data['role_ids'])) { - return '/dashboard/console/backoffice'; - } - if (count($data['role_ids']) == 1 && in_array(6, $data['role_ids'])) { - return '/dashboard/console/finance'; - } - } - // 2025.10.30 临时处理 ====== end - - $info = Resource::where('system_id', $systemId) - ->where('is_home', 1) - ->first(); - - if (!$info) { - return '/dashboard/console'; - } - - // 递归拼接 URL - $url = $this->buildParentUrl($info); - - return $url ?: '/dashboard/console'; - } - - /** - * 递归构建父级 URL - * @param Resource $resource - * @return string - */ - protected function buildParentUrl(Resource $resource) - { - $url = $resource->url ?? ''; - - // 如果存在父级,则递归拼接 - if ($resource->parent_id != 0) { - $parent = Resource::find($resource->parent_id); - if ($parent) { - $parentUrl = $this->buildParentUrl($parent); - $url = $parentUrl . ($url ? '/' . ltrim($url, '/') : ''); - } - } - - return $url; - } -} \ No newline at end of file diff --git a/app/common/logic/BrandLogic.php b/app/common/logic/BrandLogic.php deleted file mode 100644 index ef46a5a..0000000 --- a/app/common/logic/BrandLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -orderBy('hot','desc')->orderBy('sort','desc')->get(['id', 'brand_code', 'brand_name', 'logo', 'description']); - } - -} \ No newline at end of file diff --git a/app/common/logic/BrandSeriesLogic.php b/app/common/logic/BrandSeriesLogic.php deleted file mode 100644 index 956ca55..0000000 --- a/app/common/logic/BrandSeriesLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -where($where)->orderBy('sort','desc')->get(['id', 'series_code', 'series_name', 'description']); - } - -} \ No newline at end of file diff --git a/app/common/logic/CorpLogic.php b/app/common/logic/CorpLogic.php deleted file mode 100644 index 60e46e6..0000000 --- a/app/common/logic/CorpLogic.php +++ /dev/null @@ -1,21 +0,0 @@ -orderBy('sort', 'asc')->get(['id', 'name', 'abbr', 'tenant_key']); - } -} \ No newline at end of file diff --git a/app/common/logic/CountryLogic.php b/app/common/logic/CountryLogic.php deleted file mode 100644 index 0a753ee..0000000 --- a/app/common/logic/CountryLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -update($data); - } -} \ No newline at end of file diff --git a/app/common/logic/FinanceReconDubaiFilesLogic.php b/app/common/logic/FinanceReconDubaiFilesLogic.php deleted file mode 100644 index 360f23f..0000000 --- a/app/common/logic/FinanceReconDubaiFilesLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -['msrp']]); // 可选排除 - */ -class Fingerprint -{ - /** 你的 veh_vehicle_sku 所有列(保持与表结构一致,顺序无关但建议完整) */ - public const COLS = [ - 'id','sku_code','fingerprint', - 'brand_code','brand_name','series_code','series_name', - 'model_code','model_name','model_year', - 'trim_code','trim_level_code','edition_code', - 'trim','trim_level','edition_name', - 'body_type_code','drive_type_code','motor_layout_code','fuel_type_code', - 'engine_disp_l','engine_turbo','engine_power_kw','battery_kwh', - 'transmission_code','gears','range_km','range_std_code', - 'doors','seats','weight_kg','dimensions_mm', - 'color_exterior_code','color_exterior_text', - 'color_interior_code','color_interior_text', - 'options_official','features','emission_std_code', - 'origin_country','currency','msrp', - 'is_active','corp_id','remark', - 'created_by','updated_by','created_at','updated_at', - ]; - - /** 默认剔除:技术/循环依赖字段 */ - public const EXCLUDE_DEFAULT = [ - 'id','sku_code','fingerprint', 'dimensions_mm', 'options_official', 'features', - 'origin_country','currency','msrp', - 'is_active','corp_id','remark', - 'created_by','updated_by','created_at','updated_at' - ]; - - /** 识别为“code类”的字段模式(统一大写) */ - private const CODE_FIELD_REGEX = '/(_code|_country|^currency)$/i'; - - /** 识别为 JSON 字段 */ - private const JSON_FIELDS = ['dimensions_mm','options_official','features']; - - /** - * 从 Eloquent 模型生成 - */ - public static function makeFromModel($model, array $opts = []): string - { - return self::makeFromArray($model->toArray(), $opts); - } - - /** - * 从数组生成指纹 - * @param array $row 一般为 $_POST 合并后的业务数据或 $model->toArray() - * @param array $opts ['exclude'=>[], 'extra'=>[], 'salt'=>string] - * - exclude: 额外排除的字段(默认仅排除 id,fingerprint) - * - extra : 额外拼入的键值(例如上下文、租户策略),会参与计算 - * - salt : 额外加盐字符串 - */ - public static function makeFromArray(array $row, array $opts = []): string - { - $exclude = array_values(array_unique(array_merge(self::EXCLUDE_DEFAULT, $opts['exclude'] ?? []))); - $extra = $opts['extra'] ?? []; - $salt = $opts['salt'] ?? ''; - - // 1) 统一抽取“表中定义的字段” + extra,缺失字段也要纳入(值按 NULL 处理) - $data = []; - foreach (self::COLS as $col) { - if (in_array($col, $exclude, true)) continue; - $data[$col] = array_key_exists($col, $row) ? $row[$col] : null; - } - // extra 也参与 - foreach ($extra as $k => $v) { - if (!is_string($k) || $k === '') continue; - $data['__extra__'.$k] = $v; - } - - // 2) 规范化(按字段特征) - $canon = []; - foreach ($data as $k => $v) { - $canon[$k] = self::normalize($k, $v); - } - - // 3) 键名排序,确保顺序无关 - ksort($canon, SORT_STRING); - - // 4) 拼成稳定串: key=value | key=value... - $parts = []; - foreach ($canon as $k => $v) { - // 为空也必须占位,避免 key 消失影响其他键的意义 - $parts[] = $k.'='.$v; - } - if ($salt !== '') { - $parts[] = '__salt__='.$salt; - } - $plain = implode('|', $parts); - - // 5) sha256 - return hash('sha256', $plain); - } - - /** - * 规范化单个字段 - * - NULL -> 特殊占位 "∅"(避免与空串混淆) - * - 布尔/整数/浮点 -> 统一数字字符串 - * - code类字段 -> 去首尾空白 & 转大写 - * - 普通字符串 -> trim & 压缩连续空白为单空格 - * - JSON字段 -> 解析后做“键排序 + 值规范化 + 索引数组可排序”,再无空白编码 - */ - private static function normalize(string $field, $value): string - { - if ($value === null) return '∅'; - - // 数值类型 - if (is_int($value)) return (string)$value; - if (is_bool($value)) return $value ? '1' : '0'; - - if (is_float($value) || (is_string($value) && is_numeric($value) && self::looksLikeNumberField($field))) { - // 统一浮点格式,最多 6 位小数并去尾零 - $num = (float)$value; - $s = number_format($num, 6, '.', ''); - $s = rtrim(rtrim($s, '0'), '.'); - return $s === '' ? '0' : $s; - } - - // JSON 字段 - if (in_array($field, self::JSON_FIELDS, true)) { - return self::normalizeJson($value); - } - - // 字符串 - if (is_string($value)) { - $s = trim($value); - // code类:统一大写 - if (preg_match(self::CODE_FIELD_REGEX, $field)) { - $s = mb_strtoupper($s, 'UTF-8'); - } else { - // 普通文本:压缩连续空白 - $s = preg_replace('/\s+/u', ' ', $s); - } - return $s === '' ? '' : $s; - } - - // 数组(极少出现,按 JSON 处理) - if (is_array($value)) { - return self::normalizeJson($value); - } - - // 其他类型(对象等):转 JSON 后处理 - return self::normalizeJson($value); - } - - /** 判断这个字段是否“看起来像数值字段” */ - private static function looksLikeNumberField(string $field): bool - { - static $numKeys = [ - 'engine_disp_l','engine_power_kw','battery_kwh','gears', - 'range_km','doors','seats','weight_kg','msrp','model_year', - 'created_at','updated_at','corp_id','is_active' - ]; - return in_array($field, $numKeys, true); - } - - /** - * JSON 规范化: - * - 字符串:若能 json_decode 则按 JSON;否则当普通字符串再规范化 - * - 对象:键名排序;值递归规范化 - * - 索引数组:元素递归规范化后,按字符串值排序(视为集合,避免顺序抖动) - * - 最终 json_encode(JSON_UNESCAPED_UNICODE|UNESCAPED_SLASHES) - */ - private static function normalizeJson($val): string - { - // 已是数组/对象 - if (is_array($val)) { - $normalized = self::canonArray($val); - return json_encode($normalized, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - } - - // 字符串尝试解析 - if (is_string($val)) { - $val = trim($val); - if ($val === '') return '""'; - $decoded = json_decode($val, true); - if (json_last_error() === JSON_ERROR_NONE) { - $normalized = self::canonArray($decoded); - return json_encode($normalized, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - } - // 非 JSON 字符串,按普通字符串规范化 - $s = preg_replace('/\s+/u', ' ', $val); - return json_encode($s, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - } - - // 其他类型:直接编码 - return json_encode($val, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - } - - /** 递归规范化数组/对象 */ - private static function canonArray($arr) - { - if (!is_array($arr)) return $arr; - - // 关联数组(对象) - if (self::isAssoc($arr)) { - $out = []; - ksort($arr, SORT_STRING); - foreach ($arr as $k => $v) { - $out[(string)$k] = self::canonValue($v); - } - return $out; - } - - // 索引数组(当集合处理:元素字符串化后排序) - $tmp = []; - foreach ($arr as $v) { - $tmp[] = self::canonValue($v); - } - // 将元素转为字符串再排序,确保稳定 - usort($tmp, function($a, $b) { - $sa = is_scalar($a) ? (string)$a : json_encode($a, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - $sb = is_scalar($b) ? (string)$b : json_encode($b, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); - return strcmp($sa, $sb); - }); - return $tmp; - } - - private static function canonValue($v) - { - if (is_array($v)) return self::canonArray($v); - if (is_bool($v)) return $v ? 1 : 0; - if (is_int($v)) return $v; - if (is_float($v)) { - $s = number_format($v, 6, '.', ''); - $s = rtrim(rtrim($s, '0'), '.'); - return $s === '' ? '0' : $s; - } - if (is_string($v)) { - $s = trim($v); - $s = preg_replace('/\s+/u', ' ', $s); - return $s; - } - return $v; - } - - private static function isAssoc(array $arr): bool - { - // 有任意一个键不是 0..n 的递增整数,就视为关联数组 - $i = 0; - foreach ($arr as $k => $_) { - if ($k !== $i++) return true; - } - return false; - } -} \ No newline at end of file diff --git a/app/common/logic/InquiryTransmitConfigLogic.php b/app/common/logic/InquiryTransmitConfigLogic.php deleted file mode 100644 index 3c6782d..0000000 --- a/app/common/logic/InquiryTransmitConfigLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -orderBy('sort','desc')->get(); - } -} \ No newline at end of file diff --git a/app/common/logic/InvRequisitionApproveLogic.php b/app/common/logic/InvRequisitionApproveLogic.php deleted file mode 100644 index 4f1f795..0000000 --- a/app/common/logic/InvRequisitionApproveLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -logicShow($config); - if ($msg) { - // 删除关联的用户状态记录 - $msg->userStatuses()->delete(); - // 删除消息本身 - $msg->delete(); - } - return true; - } -} \ No newline at end of file diff --git a/app/common/logic/MessageUserStatusLogic.php b/app/common/logic/MessageUserStatusLogic.php deleted file mode 100644 index ea4b63e..0000000 --- a/app/common/logic/MessageUserStatusLogic.php +++ /dev/null @@ -1,17 +0,0 @@ - 15L - if (!empty($s['engine_turbo']) && (int)$s['engine_turbo'] === 1) $key[] = 'T'; - if (!empty($s['transmission_code'])) $key[] = self::tok($s['transmission_code']); - break; - - case 'HEV': - case 'PHEV': - case 'EREV': - $key[] = $fuel; - if (!empty($s['engine_disp_l'])) $key[] = self::dispToken($s['engine_disp_l']); - if (!empty($s['motor_layout_code'])) $key[] = self::tok($s['motor_layout_code']); // 如 DM-I/DM-P/AWD - break; - - default: - $key[] = $fuel; - } - - if (!empty($s['drive_type_code'])) $key[] = self::tok($s['drive_type_code']); - - $parts[] = implode('_', array_filter($key)); - return strtoupper(implode('_', array_filter($parts))); - } - - /** 生成中文可读的 model_name(走快照中文,不依赖 i18n) */ - public static function buildModelName(array $s): string - { - $seriesName = trim((string)($s['series_name'] ?? $s['series_code'] ?? '')); - $yearPart = !empty($s['model_year']) ? ($s['model_year'] . '款 ') : ''; - - $fuel = strtoupper($s['fuel_type_code'] ?? ''); - $tail = ''; - - if ($fuel === 'EV') { - $range = !empty($s['range_km']) ? (int)$s['range_km'] . 'KM ' : ''; - $drive = trim((string)($s['drive_type'] ?? $s['drive_type_code'] ?? '')); - $tail = "EV {$range}{$drive}"; - } elseif ($fuel === 'GAS') { - $disp = (!empty($s['engine_disp_l'])) - ? rtrim(rtrim(number_format((float)$s['engine_disp_l'], 1, '.', ''), '0'), '.') . 'L ' - : ''; - $trans = trim((string)($s['transmission'] ?? $s['transmission_code'] ?? '')); - $tail = "{$disp}{$trans}"; - } else { - $tail = trim((string)($s['fuel_type'] ?? $fuel)); - } - - $extras = []; - foreach (['trim','trim_level','edition_name'] as $k) { - if (!empty($s[$k])) $extras[] = trim((string)$s[$k]); - } - $extraStr = $extras ? ' ' . implode(' ', $extras) : ''; - - return trim($seriesName . ' ' . $yearPart . $tail . $extraStr); - } - - /* ===== Helpers ===== */ - - private static function tok($v): string - { - $v = strtoupper((string)$v); - return preg_replace('/[^A-Z0-9_]/', '', $v ?? ''); - } - - private static function numToken($v): string - { - return preg_replace('/[^0-9]/', '', (string)$v); - } - - /** 1.5L -> 15L;2.0L -> 20L(便于 code 稳定检索) */ - private static function dispToken($l): string - { - $x = (float)$l; - return (string)round($x * 10) . 'L'; - } -} \ No newline at end of file diff --git a/app/common/logic/PermLogic.php b/app/common/logic/PermLogic.php deleted file mode 100644 index 808cb15..0000000 --- a/app/common/logic/PermLogic.php +++ /dev/null @@ -1,144 +0,0 @@ -first(); - - // 获取用户及其关联角色资源和直接分配的资源 - $user = User::with(['roles.resources', 'resources'])->find($userId); - - if (!$user) { - return collect(); - } - - $all = collect(); - // 遍历用户的所有角色,合并每个角色所拥有的资源 - foreach ($user->roles as $role) { - $all = $all->merge( - // 过滤当前角色的资源列表 - $role->resources->filter(function ($resource) use($system) { - // 资源过滤条件: - // 1. !$resource->no_auth:资源需要权限认证(排除公共资源) - // 2. 系统匹配条件: - // - $system->id == $resource->system_id:资源属于当前系统 - // - $resource->system_id == 0:资源为全局公共资源(所有系统可用) - return !$resource->no_auth && ($system->id == $resource->system_id || $resource->system_id == 0); - }) - ); - } - - // 合并用户直接分配的资源,排除不需要权限认证的资源 - $all = $all->merge( - $user->resources->filter(function ($resource) { - // 只保留需要权限认证的资源(或公共资源) - return !$resource->no_auth; - }) - ); - - // 加入公共菜单,公共菜单不管是否授权,所有人都能访问 - $publicResources = Resource::where('no_auth', 1) - ->orderBy('sort', 'asc') // 按 sort 字段升序排序 - ->get(); - - // 合并所有公共资源 - $all = $all->merge($publicResources); - - // 返回唯一的资源列表,并按 id 排序 - // 使用 sortBy('sort') 来确保最终结果根据 'sort' 字段排序 - return $all->unique('id')->values()->sortBy('sort'); - } - - /** - * 构建目录/菜单树 - * - * @param \Illuminate\Support\Collection $resources 全部资源集合 - * @param int $parentId 当前父级资源 ID - * @param string $parentPath 父级完整路径(用于递归) - * @return array - */ - public function buildTree($resources, int $parentId = 0, string $parentPath = ''): array - { - $tree = []; - foreach ($resources as $node) { - if ($node->parent_id !== $parentId) continue; - - // 拼接完整路径 - $currentPath = $parentPath; - if ($currentPath && substr($currentPath, -1) === '/') { - $currentPath = rtrim($currentPath, '/'); - } - if (!empty($node->url)) { - if (!$currentPath) { - $currentPath = $node->url; - } else { - $url = ltrim($node->url, '/'); - $currentPath = $currentPath . '/' . $url; - } - } - - // 子节点递归 - $children = []; - if ($node->type === 'directory') { - $children = $this->buildTree($resources, $node->id, $currentPath); - } - - // 权限 - $authList = $resources - ->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id) - ->map(fn($r) => [ - 'id' => $r->id, - 'title' => $r->name, - 'auth_mark' => $r->code, - ])->values()->all(); - - // 判断是否有子级菜单(非权限) - $hasChildrenMenu = collect($resources)->where('parent_id', $node->id) - ->whereIn('type', ['directory', 'menu'])->isNotEmpty(); - - $componentValue = $hasChildrenMenu ? '/index/index' : $currentPath; - - $tree[] = [ - 'id' => $node->id, - 'name' => $node->name, - 'path' => $node->url, - 'component' => $componentValue, - 'meta' => [ - 'title' => $node->name, - 'icon' => $node->icon, - 'keepAlive' => $node->keep_alive == 1 ? true : false, - 'authList' => $authList, - 'openType' => $node->open_type, - 'isHide' => $node->is_hide == 0 ? false : true, - 'isHideTab' => $node->is_hide_tab == 0 ? false : true - ], - 'children' => $children, - ]; - } - return $tree; - } - - /** - * 获取用户所有权限code - */ - public function getPermissionCodes(int $userId, string $systemCode): array - { - $resources = $this->getUserResources($userId, $systemCode); - return $resources - ->filter(fn($res) => $res->type === 'permission') - ->pluck('code') - ->unique() - ->values() - ->all(); - } -} \ No newline at end of file diff --git a/app/common/logic/PurchaseOrderItemsLogic.php b/app/common/logic/PurchaseOrderItemsLogic.php deleted file mode 100644 index 6c5702d..0000000 --- a/app/common/logic/PurchaseOrderItemsLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -where('pi_no', '!=', '') - ->select('pi_no', 'salesperson_snapshot') - ->distinct() - ->get(); - } - - /** - * 根据PI号获取备货单 - */ - public function getOrderNoListByPiNo($piNo) - { - return (new StockOrders())->where('pi_no', $piNo) - ->where('approval_status', 2) - ->select('order_no', 'biz_date', 'salesperson_snapshot', 'id as stock_orders_id', 'salesperson_id') - ->get(); - } - - /** - * 根据备货单号获取备货单明细 - */ - public function getOrderItemsListByOrderNo($stockOrdersId) - { - return (new StockOrderItems())->where('order_id', $stockOrdersId) - ->select('model_snapshot', 'color_interior_snapshot', 'color_exterior_snapshot', 'unique_id', 'id as stock_order_items_id') - ->get(); - } -} \ No newline at end of file diff --git a/app/common/logic/ResourceLogic.php b/app/common/logic/ResourceLogic.php deleted file mode 100644 index ddf6423..0000000 --- a/app/common/logic/ResourceLogic.php +++ /dev/null @@ -1,37 +0,0 @@ -logicListAll($config); - - if ($request->get('role_id')) { - $selected = (new RoleLogic())->getRoleResources($request->get('role_id')); - } else if ($request->get('user_id')) { - $selected = (new RoleLogic())->getUserResources($request->get('user_id')); - } else { - $selected = []; - } - - foreach ($data as &$item) { - $item['selected'] = in_array($item['id'], $selected) ? true : false; - } - - return $data; - } -} \ No newline at end of file diff --git a/app/common/logic/RoleLogic.php b/app/common/logic/RoleLogic.php deleted file mode 100644 index 0898b10..0000000 --- a/app/common/logic/RoleLogic.php +++ /dev/null @@ -1,85 +0,0 @@ -where('role_id', $roleId)->delete(); - - // 批量插入新角色资源关联 - if (!empty($resources)) { - $insertData = []; - foreach ($resources as $resourceId) { - $insertData[] = [ - 'role_id' => $roleId, - 'resource_id' => $resourceId - ]; - } - Db::table('role_resources')->insert($insertData); - } - - Db::commit(); - return true; - } catch (\Throwable $exception) { - Db::rollBack(); - return false; - } - } - - /** - * 获取角色资源 - * - * @param int $roleId 角色ID - * @return array 资源ID列表 - */ - public function getRoleResources(int $roleId): array - { - if (empty($roleId)) { - return []; - } - - return Db::table('role_resources') - ->where('role_id', $roleId) - ->pluck('resource_id') - ->toArray(); - } - - /** - * 获取用户资源 - * - * @param int $userId 用户ID - * @return array 资源ID列表 - */ - public function getUserResources(int $userId): array - { - if (empty($userId)) { - return []; - } - - return Db::table('user_resources') - ->where('user_id', $userId) - ->pluck('resource_id') - ->toArray(); - } -} diff --git a/app/common/logic/SkuCodeBuilder.php b/app/common/logic/SkuCodeBuilder.php deleted file mode 100644 index 823b8dc..0000000 --- a/app/common/logic/SkuCodeBuilder.php +++ /dev/null @@ -1,233 +0,0 @@ - 'FLG', - 'PREMIUM' => 'PRM', - 'STANDARD' => 'STD', - 'DELUXE' => 'DLX', - // edition - 'HONOR' => 'HNR', - 'CHAMPION' => 'CHP', - 'ANNIV' => 'ANV', - // trans - '1SPEED' => '1SP', - // drive/fuel/body 等一般已短,不必压缩 - ]; - - /** 入口:生成 sku_code */ - public static function build(array $s, array $opts = []): string - { - $maxLen = $opts['max_len'] ?? 40; - $ensureUnique = $opts['ensure_unique'] ?? true; - - $tokens = [ - 'brand' => self::tok($s['brand_code'] ?? ''), - 'series' => self::tok($s['series_code'] ?? ''), - 'year' => isset($s['model_year']) ? (string)intval($s['model_year']) : '', - 'fuel' => self::tok($s['fuel_type_code'] ?? ''), - 'drive' => self::tok($s['drive_type_code'] ?? ''), - 'spec' => self::buildSpec($s, self::tok($s['fuel_type_code'] ?? '')), - 'level' => self::abbr(self::tok($s['trim_level_code'] ?? '')), - 'edition' => self::abbr(self::tok($s['edition_code'] ?? '')), - ]; - - // 过滤空段并按既定顺序拼接 - $order = ['brand','series','year','fuel','drive','spec','level','edition']; - $parts = []; - foreach ($order as $k) { - if (!empty($tokens[$k])) $parts[$k] = $tokens[$k]; - } - - $sku = self::normalizeSku(implode('-', $parts)); - - if (strlen($sku) > $maxLen) { - $sku = self::shrink($parts, $maxLen); // 传入“带键名的 parts” - } - - if ($ensureUnique) { - $sku = self::ensureUnique($sku, $maxLen); - } - return $sku; - } - - /** 构造规格位(SPEC),按能源类型差异化 */ - private static function buildSpec(array $s, string $fuel): string - { - $fuel = strtoupper($fuel); - if ($fuel === 'EV') { - if (!empty($s['range_km'])) { - $r = (int)$s['range_km']; - $r10 = (int)round($r / 10) * 10; // 到 10 位 - return (string)$r10; - } - if (!empty($s['battery_kwh'])) { - return self::numToken($s['battery_kwh']) . 'KWH'; - } - return ''; - } - - if ($fuel === 'GAS') { - $bits = []; - if (!empty($s['engine_disp_l'])) { - $bits[] = self::dispToken($s['engine_disp_l']); // 1.5L -> 15L - } - if (!empty($s['engine_turbo']) && intval($s['engine_turbo']) === 1) { - $bits[] = 'T'; - } - if (!empty($s['transmission_code'])) { - $bits[] = self::abbr(self::tok($s['transmission_code'])); - } - return implode('', $bits); // 如 15LTCVT - } - - // HEV/PHEV/EREV 等 - $bits = []; - if (!empty($s['engine_disp_l'])) { - $bits[] = self::dispToken($s['engine_disp_l']); // 可空 - } - if (!empty($s['motor_layout_code'])) { - $bits[] = self::tok($s['motor_layout_code']); // 如 AWD / DM-I / DM-P - } - return implode('', $bits); - } - - /** 冲突检测并追加短校验(全局唯一) */ - private static function ensureUnique(string $sku, int $maxLen): string - { - if (!VehVehicleSku::where('sku_code', $sku)->exists()) { - return $sku; - } - // 用 crc32 生成 5~6 位 base36 校验(稳定且短) - $crc = self::base36Crc($sku); - $suffix = '-X' . $crc; - - if (strlen($sku . $suffix) > $maxLen) { - $sku = substr($sku, 0, max(0, $maxLen - strlen($suffix))); - $sku = rtrim($sku, '-'); // 避免尾部 '-' - } - $sku .= $suffix; - - // 若极端情况下仍冲突,追加递增计数 - $i = 2; - $candidate = $sku; - while (VehVehicleSku::where('sku_code', $candidate)->exists()) { - $extra = '-'.$i; - $cut = max(0, $maxLen - strlen($extra)); - $candidate = substr($sku, 0, $cut) . $extra; - $i++; - } - return $candidate; - } - - /** 把 token 数组尽量压到 maxLen(逐步压缩策略) */ - private static function shrink(array $partsByKey, int $maxLen): string - { - // 1) 先对 series/level/edition 做激进压缩 - $p = $partsByKey; - foreach (['series','level','edition'] as $k) { - if (!empty($p[$k])) $p[$k] = self::heavyAbbr($p[$k]); - } - $sku = self::normalizeSku(implode('-', $p)); - if (strlen($sku) <= $maxLen) return $sku; - - // 2) 依次移除不太关键的信息:edition → level(若存在) - if (!empty($p['edition'])) { unset($p['edition']); } - $sku = self::normalizeSku(implode('-', $p)); - if (strlen($sku) <= $maxLen) return $sku; - - if (!empty($p['level'])) { unset($p['level']); } - $sku = self::normalizeSku(implode('-', $p)); - if (strlen($sku) <= $maxLen) return $sku; - - // 3) 压缩 spec(如去 KM/KWH,仅保留核心) - if (!empty($p['spec'])) { $p['spec'] = self::compactSpec($p['spec']); } - $sku = self::normalizeSku(implode('-', $p)); - if (strlen($sku) <= $maxLen) return $sku; - - // 4) 仍超长:从右向左截断次要段(spec/drive/year),保留前三段(brand/series/fuel)优先 - $dropOrder = ['spec','drive','year']; - $q = $p; - foreach ($dropOrder as $k) { - if (!empty($q[$k])) { unset($q[$k]); } - $sku = self::normalizeSku(implode('-', $q)); - if (strlen($sku) <= $maxLen) return $sku; - } - - // 5) 最后兜底:硬截到 maxLen,后续 ensureUnique 会追加 -X 校验并避免冲突 - return substr(self::normalizeSku(implode('-', $p)), 0, $maxLen); - } - - /* ===== Helpers ===== */ - - private static function tok($v): string - { - $v = strtoupper((string)$v); - return preg_replace('/[^A-Z0-9_]/', '', $v ?? ''); - } - - private static function abbr(string $t): string - { - return self::ABBR[$t] ?? $t; - } - - private static function heavyAbbr(string $t): string - { - // 更激进:去除元音,连字符化 - $t = str_replace(['STANDARD','FLAGSHIP','PREMIUM','DELUXE'], ['STD','FLG','PRM','DLX'], $t); - $t = preg_replace('/[AEIOU]/', '', $t); - return $t; - } - - private static function compactSpec(string $s): string - { - // 规则:去 KM/KWH 等单位,只保留数字与核心字母 - $s = strtoupper($s); - $s = str_replace(['KM','KWH'], '', $s); - return $s; - } - - private static function numToken($v): string - { - return preg_replace('/[^0-9]/', '', (string)$v); - } - - /** 1.5L -> 15L;2.0L -> 20L */ - private static function dispToken($l): string - { - $x = (float)$l; - return (string)round($x * 10) . 'L'; - } - - private static function base36Crc(string $s): string - { - $crc = sprintf('%u', crc32($s)); // 无符号 - $n = (int)$crc; - $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $res = ''; - do { - $res = $chars[$n % 36] . $res; - $n = intdiv($n, 36); - } while ($n > 0); - return substr($res, -6); // 取后6位足够 - } - - private static function normalizeSku(string $s): string - { - // 连续的 '-' 合并,首尾修剪 - $s = preg_replace('/-+/', '-', $s); - $s = trim($s, '-'); - return $s; - } -} \ No newline at end of file diff --git a/app/common/logic/StockOrderAccountsLogic.php b/app/common/logic/StockOrderAccountsLogic.php deleted file mode 100644 index b76c961..0000000 --- a/app/common/logic/StockOrderAccountsLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -orderBy('sort','desc')->get(['id', 'account_name', 'currency_id', 'account_number', 'bank_name', 'bank_branch', 'description', 'short_desc']); - } - -} \ No newline at end of file diff --git a/app/common/logic/SysConfigLogic.php b/app/common/logic/SysConfigLogic.php deleted file mode 100644 index 633d177..0000000 --- a/app/common/logic/SysConfigLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -where('config_key', $key)->get(['id', 'config_key', 'config_value']); - } -} \ No newline at end of file diff --git a/app/common/logic/SysCurrencyLogic.php b/app/common/logic/SysCurrencyLogic.php deleted file mode 100644 index 4de7559..0000000 --- a/app/common/logic/SysCurrencyLogic.php +++ /dev/null @@ -1,21 +0,0 @@ -get(['id', 'country_id', 'currency_code', 'currency_name', 'currency_symbol', 'exchange_rate', 'float_percent_up', 'float_percent_down']); - } -} \ No newline at end of file diff --git a/app/common/logic/SysDictItemLogic.php b/app/common/logic/SysDictItemLogic.php deleted file mode 100644 index d6efc72..0000000 --- a/app/common/logic/SysDictItemLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -where($where)->orderBy('sort','desc')->get(['id', 'item_label', 'item_value', 'remark', 'dict_id']); - } - -} \ No newline at end of file diff --git a/app/common/logic/SysDictLogic.php b/app/common/logic/SysDictLogic.php deleted file mode 100644 index 6447ed3..0000000 --- a/app/common/logic/SysDictLogic.php +++ /dev/null @@ -1,27 +0,0 @@ -where('code', $code)->orderBy('sort','desc')->first(['id']); - } - - public function getList() - { - return SysDict::where('status', 1)->get(['id', 'dict_name', 'dict_code', 'description']); - } - -} \ No newline at end of file diff --git a/app/common/logic/SysOpLogLogic.php b/app/common/logic/SysOpLogLogic.php deleted file mode 100644 index ec454cd..0000000 --- a/app/common/logic/SysOpLogLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -where($where)->orderBy('sort','desc')->get(['id', 'port_code', 'port_name', 'port_name_en', 'country_id', 'description']); - } - -} \ No newline at end of file diff --git a/app/common/logic/SysUpdateLogLogic.php b/app/common/logic/SysUpdateLogLogic.php deleted file mode 100644 index 6bec427..0000000 --- a/app/common/logic/SysUpdateLogLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -orderBy('sort', 'asc')->get(['id', 'name', 'code', 'type', 'type']); - } -} \ No newline at end of file diff --git a/app/common/logic/UsedcarCrawlResultsImagesLogic.php b/app/common/logic/UsedcarCrawlResultsImagesLogic.php deleted file mode 100644 index 428bc16..0000000 --- a/app/common/logic/UsedcarCrawlResultsImagesLogic.php +++ /dev/null @@ -1,17 +0,0 @@ - 0) { - foreach ($data['user_ids'] as $member) { - $this->addUserGroupMembers($member, $created->id); - } - } - if ((int)$data['leader_id'] > 0) { - $leader = UserGroupMembers::where('user_id', $data['leader_id'])->where('group_id', $created->id)->first(); - if ($leader) { - $leader->is_leader = 1; - $leader->save(); - } else { - $this->addUserGroupMembers($data['leader_id'], $created->id, 1); - } - } - return $created; - } - - - public function updateGroup(UserGroup $userGroup, array $data) - { - $userGroup->title = $data['title']; - $userGroup->sort = $data['sort'] ?? 0; - $userGroup->status = $data['status']; - $userGroup->scenario_code = $data['scenario_code'] ?? ''; - $userGroup->save(); - - // 删除所有成员 - UserGroupMembers::where('group_id', $userGroup->id)->delete(); - - if (isset($data['user_ids']) && is_array($data['user_ids']) && count($data['user_ids']) > 0) { - foreach ($data['user_ids'] as $member) { - $this->addUserGroupMembers($member, $userGroup->id); - } - } - if ((int)$data['leader_id'] > 0) { - $leader = UserGroupMembers::where('user_id', $data['leader_id'])->where('group_id', $userGroup->id)->first(); - if ($leader) { - $leader->is_leader = 1; - $leader->save(); - } else { - $this->addUserGroupMembers($data['leader_id'], $userGroup->id, 1); - } - } - return $userGroup; - } - - - public function addUserGroupMembers(int $userId, int $groupId, int $isLeader = 0) - { - $udata = [ - 'user_id' => $userId, - 'group_id' => $groupId, - 'is_leader' => $isLeader - ]; - return UserGroupMembers::create($udata); - } -} \ No newline at end of file diff --git a/app/common/logic/UserGroupMembersLogic.php b/app/common/logic/UserGroupMembersLogic.php deleted file mode 100644 index 831c3ca..0000000 --- a/app/common/logic/UserGroupMembersLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -delete(); - } -} \ No newline at end of file diff --git a/app/common/logic/VehColorLogic.php b/app/common/logic/VehColorLogic.php deleted file mode 100644 index 7a36811..0000000 --- a/app/common/logic/VehColorLogic.php +++ /dev/null @@ -1,22 +0,0 @@ -where($where)->orderBy('sort','desc')->get(['id', 'color_code', 'color_text']); - } - -} \ No newline at end of file diff --git a/app/common/logic/VehDictI18nLogic.php b/app/common/logic/VehDictI18nLogic.php deleted file mode 100644 index f25b50b..0000000 --- a/app/common/logic/VehDictI18nLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -orderBy('sort','desc')->get(['id', 'code', 'name', 'type', 'price']); - } - -} \ No newline at end of file diff --git a/app/common/logic/VehMoneyValueLogic.php b/app/common/logic/VehMoneyValueLogic.php deleted file mode 100644 index 5006eaa..0000000 --- a/app/common/logic/VehMoneyValueLogic.php +++ /dev/null @@ -1,17 +0,0 @@ -orderBy('id','desc')->get(['id', 'sku_code', 'brand_code', 'brand_code', 'series_code', 'series_name', 'model_code', 'model_name', 'model_year', 'msrp']); - } -} \ No newline at end of file diff --git a/app/common/logic/VehVehicleUnitLogic.php b/app/common/logic/VehVehicleUnitLogic.php deleted file mode 100644 index 45a1038..0000000 --- a/app/common/logic/VehVehicleUnitLogic.php +++ /dev/null @@ -1,17 +0,0 @@ - 'array', - ]; -} \ No newline at end of file diff --git a/app/common/model/ApprovalInstances.php b/app/common/model/ApprovalInstances.php deleted file mode 100644 index e683eb4..0000000 --- a/app/common/model/ApprovalInstances.php +++ /dev/null @@ -1,122 +0,0 @@ - 'array', // 自动转换 JSON 字段为数组 - 'finished_at' => 'datetime', - 'deadline_at' => 'datetime', - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; - - - - // ====== ====== ====== 映射业务表 ====== ====== ====== - protected const BIZ_CLASS = [ - 'stock_orders' => \app\common\model\StockOrders::class, - 'stock_orders_nullify' => \app\common\model\StockOrders::class, - 'purchase_orders' => \app\common\model\PurchaseOrders::class, - ]; - - public function getBizTypeAttribute($value) - { - return self::BIZ_CLASS[$value] ?? $value; - } - - public function bizInfo() - { - return $this->morphTo('bizInfo', 'biz_type', 'biz_id')->withTrashed(); - } - // ====== ====== ====== 映射表业务 ====== ====== ====== - - - - public function records() - { - return $this->hasMany(ApprovalRecords::class, 'instance_id', 'id'); - } - - public function flows() - { - return $this->belongsTo(ApprovalFlows::class, 'flow_type', 'type'); - } - - public function initiator() - { - return $this->belongsTo(User::class, 'initiator_id', 'id'); - } - - // public function bizInfo2() - // { - // return $this->belongsTo(StockOrders::class, 'biz_id', 'id'); - // } - - /** - * 获取当前步骤的所有审批记录(pending 状态) - */ - public function currentStepRecords() - { - return $this->approvalRecords()->where('step_index', $this->current_step)->where('status', 'pending'); - } -} \ No newline at end of file diff --git a/app/common/model/ApprovalRecords.php b/app/common/model/ApprovalRecords.php deleted file mode 100644 index 88a820e..0000000 --- a/app/common/model/ApprovalRecords.php +++ /dev/null @@ -1,79 +0,0 @@ - 'datetime', - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; - - public function instance() - { - return $this->belongsTo(ApprovalInstances::class, 'instance_id', 'id'); - } - - - public function approver() - { - return $this->belongsTo(User::class, 'approver_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/Brand.php b/app/common/model/Brand.php deleted file mode 100644 index 22c4704..0000000 --- a/app/common/model/Brand.php +++ /dev/null @@ -1,49 +0,0 @@ -code)) { - $customer->code = self::generateCustomerCode($customer); - // 使用saveQuietly避免递归调用 - $customer->saveQuietly(); - } - }); - } - - public static function generateCustomerCode($customer) - { - // 生成唯一16位code,CM+14位 - $unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 8, 6)); - $code = 'CM' . date('Ymd') .$unique; - return $code; - } - - // 静默保存方法,不触发事件 - public function saveQuietly(array $options = []) - { - return static::withoutEvents(function () use ($options) { - return $this->save($options); - }); - } -} \ No newline at end of file diff --git a/app/common/model/CustomerAudit.php b/app/common/model/CustomerAudit.php deleted file mode 100644 index 4e52267..0000000 --- a/app/common/model/CustomerAudit.php +++ /dev/null @@ -1,49 +0,0 @@ -hasOne(FinReceipt::class, 'payment_apply_id', 'id'); - } - - /** - * 关联的备货单(通过中间表) - */ - public function stocks() - { - return $this->belongsToMany(StockOrders::class, 'fin_payment_stock', 'payment_apply_id', 'stock_id'); - } - - /** - * 查询 submit_files 不为空的记录 - */ - public function scopeWithNonEmptyFiles($query) - { - return $query->whereNotNull('submit_files') - ->whereRaw('JSON_LENGTH(submit_files) > 0'); - } -} \ No newline at end of file diff --git a/app/common/model/FinPaymentStock.php b/app/common/model/FinPaymentStock.php deleted file mode 100644 index d5b3d10..0000000 --- a/app/common/model/FinPaymentStock.php +++ /dev/null @@ -1,67 +0,0 @@ -belongsTo(FinPaymentApply::class, 'payment_apply_id', 'id'); - } - - // 收款记录 - public function receipt() - { - return $this->belongsTo(FinReceipt::class, 'receipt_id', 'id'); - } - - // 备货单 - public function stock() - { - return $this->belongsTo(StockOrders::class, 'stock_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/FinReceipt.php b/app/common/model/FinReceipt.php deleted file mode 100644 index 88d3090..0000000 --- a/app/common/model/FinReceipt.php +++ /dev/null @@ -1,81 +0,0 @@ -belongsTo(FinPaymentApply::class, 'payment_apply_id', 'id'); - } - - /** - * 关联的备货单(通过中间表) - */ - public function stocks() - { - return $this->belongsToMany(StockOrders::class, 'fin_payment_stock', 'receipt_id', 'stock_id'); - } - - /** - * 关联付款申请 - */ -// public function finPaymentApply() -// { -// return $this->hasOne(FinPaymentApply::class, 'receipt_id', 'id'); -// } - - /** - * 关联付款申请表 - */ - public function paymentApply() - { - return $this->belongsTo(FinPaymentApply::class, 'payment_apply_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/FinReceiptHis.php b/app/common/model/FinReceiptHis.php deleted file mode 100644 index 8a036b3..0000000 --- a/app/common/model/FinReceiptHis.php +++ /dev/null @@ -1,49 +0,0 @@ -hasOne(User::class, 'id', 'enter_user_id'); - } - - // public function recipientInfo() - // { - // return $this->hasOne(User::class, 'id', 'recipient')->where('status', 1); - // } - public function recipientInfo() - { - return $this->hasOne(User::class, 'id', 'recipient'); - } - - public function channelInfo() - { - return $this->hasOne(InquiryChannel::class, 'id', 'channel'); - } - - public function countryInfo() - { - return $this->hasOne(Country::class, 'id', 'country'); - } -} \ No newline at end of file diff --git a/app/common/model/InquiryTransmit.php b/app/common/model/InquiryTransmit.php deleted file mode 100644 index b02048d..0000000 --- a/app/common/model/InquiryTransmit.php +++ /dev/null @@ -1,49 +0,0 @@ - '系统消息', - self::SCENE1 => '系统通知' - ]; - const SCENE0 = 0; - const SCENE1 = 1; - - // 推送方式 - const PUSH_METHOD = [ - self::PUSH_METHOD0 => '系统推送', - self::PUSH_METHOD1 => '手动推送' - ]; - const PUSH_METHOD0 = 0; - const PUSH_METHOD1 = 1; - - - /** - * 关联用户消息状态 (一对多) - */ - public function userStatuses() - { - return $this->hasMany(MessageUserStatus::class, 'msg_id', 'id'); - } - - /** - * 获取已读用户状态 - */ - public function readUsers() - { - return $this->hasMany(MessageUserStatus::class, 'msg_id', 'id') - ->where('status', 1); - } - - /** - * 获取未读用户状态 - */ - public function unreadUsers() - { - return $this->hasMany(MessageUserStatus::class, 'msg_id', 'id') - ->where('status', 0); - } - - public function sender() - { - return $this->belongsTo(User::class, 'sender_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/MessageUserStatus.php b/app/common/model/MessageUserStatus.php deleted file mode 100644 index 0e73ef5..0000000 --- a/app/common/model/MessageUserStatus.php +++ /dev/null @@ -1,66 +0,0 @@ -belongsTo(MessageNotifications::class, 'msg_id', 'id'); - } - - /** - * 关联用户 (假设你有 User 模型) - */ - public function user() - { - return $this->belongsTo(User::class, 'uid', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/PurchaseOrderItems.php b/app/common/model/PurchaseOrderItems.php deleted file mode 100644 index 3648865..0000000 --- a/app/common/model/PurchaseOrderItems.php +++ /dev/null @@ -1,71 +0,0 @@ -belongsTo(PurchaseOrders::class, 'purchase_order_id', 'id'); - } - - - public function stockOrder() - { - return $this->belongsTo(StockOrders::class, 'stock_id', 'id'); - } - - public function stockOrderItems() - { - return $this->belongsTo(StockOrderItems::class, 'stock_items_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/PurchaseOrders.php b/app/common/model/PurchaseOrders.php deleted file mode 100644 index f51349a..0000000 --- a/app/common/model/PurchaseOrders.php +++ /dev/null @@ -1,64 +0,0 @@ -hasMany(PurchaseOrderItems::class, 'purchase_order_id', 'id'); - } - - public function buyer() - { - return $this->hasOne(User::class, 'id', 'buyer_id'); - } -} \ No newline at end of file diff --git a/app/common/model/Resource.php b/app/common/model/Resource.php deleted file mode 100644 index bff7b0a..0000000 --- a/app/common/model/Resource.php +++ /dev/null @@ -1,49 +0,0 @@ -belongsToMany(User::class, 'user_roles', 'role_id', 'user_id'); - } - - // 角色拥有的资源(权限点、菜单) - public function resources() - { - return $this->belongsToMany(Resource::class, 'role_resources', 'role_id', 'resource_id'); - } -} diff --git a/app/common/model/SalesAnnualTargets.php b/app/common/model/SalesAnnualTargets.php deleted file mode 100644 index 387ceaf..0000000 --- a/app/common/model/SalesAnnualTargets.php +++ /dev/null @@ -1,49 +0,0 @@ -belongsTo(StockOrders::class, 'order_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/StockOrderItemOptions.php b/app/common/model/StockOrderItemOptions.php deleted file mode 100644 index e6f8122..0000000 --- a/app/common/model/StockOrderItemOptions.php +++ /dev/null @@ -1,58 +0,0 @@ -belongsTo(StockOrderItems::class, 'order_item_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/StockOrderItems.php b/app/common/model/StockOrderItems.php deleted file mode 100644 index f45c532..0000000 --- a/app/common/model/StockOrderItems.php +++ /dev/null @@ -1,99 +0,0 @@ -moneyLatest('unit_price')?->amount; } - public function getHandlingFeeAmountAttribute() { return $this->moneyLatest('handling_fee')?->amount; } - public function getFobTransportFeeAmountAttribute() { return $this->moneyLatest('fob_transport_fee')?->amount; } - public function getPortMiscFeeAmountAttribute() { return $this->moneyLatest('port_misc_fee')?->amount; } - public function getRetrofitFeeAmountAttribute() { return $this->moneyLatest('retrofit_fee')?->amount; } - public function getTotalPriceAmountAttribute() { return $this->moneyLatest('total_price')?->amount; } - - - /** - * 关联主订单 - */ - public function order() - { - return $this->belongsTo(StockOrders::class, 'order_id', 'id'); - } - - /** - * 关联订单项选项 - */ - public function options() - { - return $this->hasMany(StockOrderItemOptions::class, 'order_item_id', 'id'); - } - - - /** - * 关联货币价值信息(一个订单项可以有多个货币价值记录) - */ - public function moneyValues() - { - return $this->hasMany(VehMoneyValue::class, 'object_id', 'id') - ->where('object_scene', 'stock_order_items'); // 场景标识区分不同对象类型 - } -} \ No newline at end of file diff --git a/app/common/model/StockOrders.php b/app/common/model/StockOrders.php deleted file mode 100644 index cc2d076..0000000 --- a/app/common/model/StockOrders.php +++ /dev/null @@ -1,126 +0,0 @@ -hasMany(StockOrderItems::class, 'order_id', 'id'); - } - - /** - * 关联订单账户信息 - */ - public function accounts() - { - return $this->hasMany(StockOrderAccounts::class, 'order_id', 'id'); - } - - /** - * 关联货币价值信息(一个订单可以有多个货币价值记录) - */ - public function moneyValues() - { - return $this->hasMany(VehMoneyValue::class, 'object_id', 'id')->where('object_scene', 'stock_orders'); - } - - /** - * 关联订单文件附件 - */ - public function files() - { - return $this->hasMany(StockOrdersFiles::class, 'order_id', 'id'); - } - - - public function salesperson() - { - return $this->hasOne(User::class, 'id', 'salesperson_id'); - } - - /** - * 客户的标签 - */ - public function payment() - { - return $this->belongsToMany(FinPaymentApply::class, 'fin_payment_stock', 'stock_id', 'payment_apply_id'); - } - - /** - * 关联收款记录(多对多,经由中间表) - */ - public function receipts() - { - return $this->belongsToMany(FinReceipt::class, 'fin_payment_stock', 'stock_id', 'receipt_id'); - } -} \ No newline at end of file diff --git a/app/common/model/StockOrdersFiles.php b/app/common/model/StockOrdersFiles.php deleted file mode 100644 index 3b78e5c..0000000 --- a/app/common/model/StockOrdersFiles.php +++ /dev/null @@ -1,60 +0,0 @@ - '合同', - self::TRANSACTION_SLIP => '水单', - self::PI_DOC => 'PI', - ]; -} \ No newline at end of file diff --git a/app/common/model/SysAccount.php b/app/common/model/SysAccount.php deleted file mode 100644 index 38e48fa..0000000 --- a/app/common/model/SysAccount.php +++ /dev/null @@ -1,49 +0,0 @@ -hasMany(SysDictItem::class, 'dict_id', 'id'); - } - - - public function category() - { - return $this->belongsTo(SysDictCategory::class, 'category_id', 'id'); - } - - /** - * 一个字典有多个字典项 - */ - public function items() - { - return $this->hasMany(SysDictItem::class, 'dict_id', 'id'); - } - - /** - * 通过 dict_code 快速获取所有 item_value - */ - public function scopeGetItemValuesByCode($query, $dictCode) - { - return $query->where('dict_code', $dictCode) - ->with('items') // 预加载关联项 - ->first()?->items->pluck('item_value'); // 返回 item_value 数组 - } - - /** - * 通过 dict_code 获取完整字典项(含 label + value) - */ - public function scopeGetItemsByCode($query, $dictCode) - { - return $query->where('dict_code', $dictCode) - ->with('items') - ->first()?->items; - } -} \ No newline at end of file diff --git a/app/common/model/SysDictCategory.php b/app/common/model/SysDictCategory.php deleted file mode 100644 index cbca49a..0000000 --- a/app/common/model/SysDictCategory.php +++ /dev/null @@ -1,58 +0,0 @@ -hasMany(SysDict::class, 'category_id', 'id') - ->where('status', 1) - ->whereNull('deleted_at') - ->orderBy('id', 'asc'); - } -} \ No newline at end of file diff --git a/app/common/model/SysDictItem.php b/app/common/model/SysDictItem.php deleted file mode 100644 index 8fbceb9..0000000 --- a/app/common/model/SysDictItem.php +++ /dev/null @@ -1,67 +0,0 @@ -belongsTo(SysDict::class, 'dict_id', 'id'); - } - - /** - * 字典项属于一个字典 - */ - public function dict() - { - return $this->belongsTo(SysDict::class, 'dict_id', 'id'); - } -} \ No newline at end of file diff --git a/app/common/model/SysDictItemTranslation.php b/app/common/model/SysDictItemTranslation.php deleted file mode 100644 index 8d33913..0000000 --- a/app/common/model/SysDictItemTranslation.php +++ /dev/null @@ -1,49 +0,0 @@ -hasMany(UserGroupMembers::class, 'group_id', 'id'); - } - -} \ No newline at end of file diff --git a/app/common/model/UserGroupMembers.php b/app/common/model/UserGroupMembers.php deleted file mode 100644 index 7d3d57a..0000000 --- a/app/common/model/UserGroupMembers.php +++ /dev/null @@ -1,60 +0,0 @@ -hasOne(User::class, 'id', 'user_id'); - } - - public function group() - { - return $this->hasOne(UserGroup::class, 'id', 'group_id'); - } -} \ No newline at end of file diff --git a/app/common/model/UserRoles.php b/app/common/model/UserRoles.php deleted file mode 100644 index 97005ce..0000000 --- a/app/common/model/UserRoles.php +++ /dev/null @@ -1,47 +0,0 @@ - 'integer', - 'enabled' => 'integer', - 'sort_order' => 'integer', - 'created_at' => 'integer', - 'updated_at' => 'integer', - ]; - - protected $fillable = [ - 'field','dict','required','enabled','sort_order', - 'remark','created_at','updated_at' - ]; -} \ No newline at end of file diff --git a/app/common/model/VehModification.php b/app/common/model/VehModification.php deleted file mode 100644 index d3bd16e..0000000 --- a/app/common/model/VehModification.php +++ /dev/null @@ -1,49 +0,0 @@ - 'string', - 'exchange_rate' => 'string', - ]; - - /** 按本行汇率换到结算币;无汇率返回 null */ - public function amountInSettlement(int $scale = 2): ?string - { - if ($this->exchange_rate === null) return null; - return (string) bcmul((string)$this->amount, (string)$this->exchange_rate, $scale); - } - - - /** - * 关联订单 - */ - public function order() - { - return $this->belongsTo(StockOrders::class, 'object_id', 'id'); - } - - /** - * 关联订单项(一个货币价值记录可能关联到订单项) - */ - public function orderItem() - { - return $this->belongsTo(StockOrderItems::class, 'object_id', 'id'); - } - - /** - * 限定查询特定对象类型的货币价值记录 - */ - public function scopeOfScene($query, $scene) - { - return $query->where('object_scene', $scene); - } -} \ No newline at end of file diff --git a/app/common/model/VehMoneyValue_bak.php b/app/common/model/VehMoneyValue_bak.php deleted file mode 100644 index 50de155..0000000 --- a/app/common/model/VehMoneyValue_bak.php +++ /dev/null @@ -1,49 +0,0 @@ - 'array', - 'features' => 'array', - 'dimensions_mm' => 'array', - 'model_year' => 'integer', - 'engine_turbo' => 'integer', - 'gears' => 'integer', - 'range_km' => 'integer', - 'doors' => 'integer', - 'seats' => 'integer', - 'weight_kg' => 'integer', - 'msrp' => 'float', - 'battery_kwh' => 'float', - 'engine_disp_l' => 'float', - 'is_active' => 'integer', - 'corp_id' => 'integer', - 'created_at' => 'integer', - 'updated_at' => 'integer', - ]; - - protected $fillable = [ - 'sku_code','fingerprint', - 'brand_code','brand_name', - 'series_code','series_name', - 'model_code','model_name','model_year', - 'trim_code','trim_level_code','edition_code', - 'trim','trim_level','edition_name', - 'body_type_code','drive_type_code','motor_layout_code', - 'fuel_type_code','engine_disp_l','engine_turbo','engine_power_kw', - 'battery_kwh','transmission_code','gears', - 'range_km','range_std_code', - 'doors','seats','weight_kg','dimensions_mm', - 'color_exterior_code','color_exterior_text', - 'color_interior_code','color_interior_text', - 'options_official','features','emission_std_code', - 'origin_country','currency','msrp', - 'is_active','corp_id','remark', - 'created_by','updated_by','created_at','updated_at', - 'body_type', 'drive_type', 'motor_layout', 'fuel_type', 'transmission', - 'range_std', 'emission_std' - ]; -} \ No newline at end of file diff --git a/app/common/model/VehVehicleUnit.php b/app/common/model/VehVehicleUnit.php deleted file mode 100644 index 28e38f1..0000000 --- a/app/common/model/VehVehicleUnit.php +++ /dev/null @@ -1,49 +0,0 @@ -validator; - } - - - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - - -} \ No newline at end of file diff --git a/app/common/service/ApprovalInstancesService.php b/app/common/service/ApprovalInstancesService.php deleted file mode 100644 index 5096321..0000000 --- a/app/common/service/ApprovalInstancesService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/ApprovalRecordsService.php b/app/common/service/ApprovalRecordsService.php deleted file mode 100644 index 61c026e..0000000 --- a/app/common/service/ApprovalRecordsService.php +++ /dev/null @@ -1,194 +0,0 @@ -validator; - } - - - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - $config['order']['id'] = 'desc'; - - $config['with'] = [ - 'instance', - 'approver', - 'instance.flows', - 'instance.initiator', - 'instance.bizInfo' - ]; - - // $config['dataLimit']['type'] = 'relation'; - // $config['dataLimit']['userId'] = $request->user->uid; - // $config['dataLimit']['userField'] = 'approver_id'; - break; - case 'todo': - - if ($p['scene'] === 'todo') { - if (!in_array(1, $request->user->role_ids)) { - $config['where']['approver_id'] = $request->user->uid; - } - $config['where']['status'] = 'pending'; - $config['where']['instance.status'] = 'processing'; - } - - if ($p['scene'] === 'history') { - if (!in_array(1, $request->user->role_ids)) { - $config['where']['approver_id'] = $request->user->uid; - } - $config['where']['status'] = ['!=', 'pending']; - } - - $config['order']['id'] = 'desc'; - - $config['with'] = [ - 'instance', - 'approver', - 'instance.flows', - 'instance.initiator', - 'instance.bizInfo' - ]; - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - case 'logs': - $config['where']['instance_id'] = $p['instance_id']; - $config['order']['id'] = 'desc'; - break; - case 'border': - $config['where']['id'] = $p['id']; - $config['order']['id'] = 'desc'; - $config['with'] = [ - 'instance', - 'approver', - 'instance.flows', - 'instance.initiator', - 'instance.bizInfo' - ]; - break; - } - - return $config; - } - - - public function serviceApprove(Request $request) - { - $param = $request->all(); - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - return $appro->approve($param['instance_id'], $request->user->uid, $param['action'], $param['comment']); - } - - - public function serviceLogs(Request $request) - { - $config = $this->buildQueryConfig($request, 'logs'); - $item = $this->logicListAll($config); - return $this->postProcess('Logs', $item); - } - - - public function serviceBusinessOrder(Request $request, array $data = []) - { - $config = $this->buildQueryConfig($request, 'border'); - $config = $this->borderConfig($config, $data['flow_type']); - $item = $this->logicShow($config); - $bizInfo = []; - $service = match ($data['flow_type']) { - 'stock_orders' => new \app\common\service\StockOrdersService(), - 'stock_orders_nullify' => new \app\common\service\StockOrdersService(), - 'purchase_orders' => new \app\common\service\PurchaseOrdersService(), - default => new \app\common\service\StockOrdersService() - }; - $bizInfo = $service->formatData($item->instance->bizInfo); - return $this->postProcess('Border', $bizInfo); - } - - public function borderConfig($config, $type = 'stock_orders') - { - $with = match ($type) { - 'stock_orders' => [ - 'instance.bizInfo.items', - 'instance.bizInfo.items.options', - 'instance.bizInfo.items.moneyValues', - 'instance.bizInfo.accounts', - 'instance.bizInfo.moneyValues', - 'instance.bizInfo.salesperson', - ], - 'stock_orders_nullify' => [ - 'instance.bizInfo.items', - 'instance.bizInfo.items.options', - 'instance.bizInfo.items.moneyValues', - 'instance.bizInfo.accounts', - 'instance.bizInfo.moneyValues', - 'instance.bizInfo.salesperson', - ], - 'purchase_orders' => [ - 'instance.bizInfo.items', - 'instance.bizInfo.items.stockOrder', - 'instance.bizInfo.items.stockOrderItems' - ] - }; - $config['with'] = array_merge($config['with'], $with); - return $config; - } - - - public function transferApproval(Request $request, array $data = []) - { - $service = new \app\common\utils\approval\service\ApprovalFlowService(); - $result = $service->transferApproval($data['instance_id'], $data['step_index'], $request->user->uid, $data['to_uid'], $data['reason'], 'name'); - return $result; - } - - - public function serviceApprovalTimeline(Request $request, array $data = []) - { - $instance = \app\common\model\ApprovalInstances::where('biz_id', $data['id'])->where('flow_type', $data['flow_type'])->first(); - if (!$instance) { - return []; - } - $result = \app\common\model\ApprovalRecords::where('instance_id', $instance->id)->with('approver')->orderBy('id', 'desc')->get(); - return $result; - } -} \ No newline at end of file diff --git a/app/common/service/BrandSeriesService.php b/app/common/service/BrandSeriesService.php deleted file mode 100644 index ae91723..0000000 --- a/app/common/service/BrandSeriesService.php +++ /dev/null @@ -1,34 +0,0 @@ -logic = (new BrandSeriesLogic()); - } - - /** - * 获取系统list - */ - public function getList($params) - { - if (empty($params['brand_id'])) - throw new BusinessException('品牌id不能为空'); - $where = []; - if(isset($params['brand_id']) && $params['brand_id']) - $where[] = ['brand_id', '=', $params['brand_id']]; - return $this->logic->getList($where); - } -} \ No newline at end of file diff --git a/app/common/service/BrandService.php b/app/common/service/BrandService.php deleted file mode 100644 index c3430fe..0000000 --- a/app/common/service/BrandService.php +++ /dev/null @@ -1,24 +0,0 @@ -logic = (new BrandLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/CrawlService.php b/app/common/service/CrawlService.php deleted file mode 100644 index f437ba6..0000000 --- a/app/common/service/CrawlService.php +++ /dev/null @@ -1,90 +0,0 @@ -find('div.card-name')->texts()->map(function($item) use(&$series) { - $series[] = $item; - }); - return $series; - } - - public function seriesModel($series) - { - $href = $this->modelSearch($series); - - //例如 $seriesUrl = "https://www.dongchedi.com/auto/series/4865?anchorId=carModels" - if (empty($href)) { - return []; - } - - $seriesUrl = (strpos($href, 'http') === 0) ? $href : ("https://www.dongchedi.com" . $href); - $ql = QueryList::get($seriesUrl); - - $nodes = $ql->find('div.tw-grid div.tw-relative div.tw-items-center>a'); - $texts = $nodes->texts()->all(); - $links = $nodes->attrs('href')->all(); - $nodes = $ql->find('div.tw-grid div.tw-text-color-gray-800'); - $price = $nodes->texts()->all(); - - $results = []; - foreach ($texts as $index => $text) { - $link = $links[$index] ?? ''; - if (!empty($link) && strpos($link, 'http') !== 0) { - $link = 'https://www.dongchedi.com' . $link; - } - $results[] = [ - 'title' => trim($text), - 'link' => $link, - 'msrp' => (int)(str_replace("万", "", $price[$index]) * 10000) ?? 0, - ]; - } - - return $results; - } - -// public function modelDesc(array $models) -// { -// -// } - - /** - * 返回车系地址 - * @param $series - * @return mixed|string - */ - public function modelSearch($series) - { - $url = "https://www.dongchedi.com/search?keyword=".$series; - $ql = QueryList::get($url ); - $href = ''; - $ql->find('a.fold-btn')->attrs('href') - ->map(function ($item) use(&$href) { - $href = $item; - }); - return $href; - } - - /** - * 关键词搜索的更多页面,通过面包屑抓取品牌与系列 - * @param $series - * @return mixed|string - */ - public function crawlBrandSeries($series) - { - $url = "https://www.dongchedi.com/auto/series/" . $series . "?anchorId=carModels"; - $ql = QueryList::get($url); - $result = $ql->find('div.breadcrumb_wrap__2GLeU span')->texts()->all(); - - return ['brand' => $result[2], 'series' => $result[3]]; - } -} \ No newline at end of file diff --git a/app/common/service/FinPaymentApplyService.php b/app/common/service/FinPaymentApplyService.php deleted file mode 100644 index 42cae9a..0000000 --- a/app/common/service/FinPaymentApplyService.php +++ /dev/null @@ -1,293 +0,0 @@ -validator; - } - - /** - * 构建查询条件 - */ - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - // ====== ====== 排序 ====== ====== - $config['order']['id'] = 'desc'; - - // ====== ====== 筛选 ====== ====== - // 汇款国家 - if (isset($p['country_id']) && !empty($p['country_id'])) { - $config['where']['country_id'] = $p['country_id']; - } - - // 收款账户筛选 - if (isset($p['account_id']) && !empty($p['account_id'])) { - $config['where']['account_id'] = $p['account_id']; - } - - // 入账资料超时 - if (isset($p['scene']) && $p['scene'] == 'file_timeout') { - $config['where']['claimed_at'] = ['between', [1, time()-24*60*60]]; - } - - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - $config['orWhere'][] = ['remitter', 'like', $k]; - } - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'update': - case 'destroy': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - } - - return $config; - } - - public function beforeServiceStore($data, Request $request) - { - $data['apply_no'] = $this->generateUniqueApplyNo(); - $data['doc_user_id'] = $request->user->uid; - $data['voucher_file'] = json_encode($data['voucher_file']); - $data['submit_files'] = json_encode($data['submit_files']); - redis::set('stock_' . $data['doc_user_id'], json_encode($request->post('stock')), 'EX', 30); - unset($data['stock']); - if($data['voucher_file'] == '[]' || $data['voucher_file'] == '{}' || $data['voucher_file'] == '""') - $data['voucher_file'] = ''; - if($data['submit_files'] == '[]' || $data['submit_files'] == '{}' || $data['submit_files'] == '""') - $data['submit_files'] = ''; - return $data; - } - - - public function afterServiceStore($res) - { - $data = [ - 'payment_apply_id' => $res['id'], - ]; - $piStock = json_decode(redis::get('stock_' . $res['doc_user_id']), true); - redis::del('stock' . $res['doc_user_id']); - foreach ($piStock as $stock) { - foreach ($stock['stock_id'] as $v) { - $data['stock_id'] = $v; - $data['pi_no'] = $stock['pi_on']; - FinPaymentStock::create($data); - } - } - } - - public function beforeServiceUpdate($data, Request $request) - { - unset($data['stock']); - $data['submit_files'] = json_encode($data['submit_files']); - if($data['submit_files'] == '[]' || $data['submit_files'] == '{}' || $data['submit_files'] == '""') - $data['submit_files'] = ''; - $data['voucher_file'] = json_encode($data['voucher_file']); - if($data['voucher_file'] == '[]' || $data['voucher_file'] == '{}' || $data['voucher_file'] == '""') - $data['voucher_file'] = ''; - return $data; - } - - - public function afterServiceUpdate($res, Request $request) - { - if($res->submit_files != '' && $res->receipt_id != 0) - FinReceipt::where('id', $res->receipt_id)->update(['submit_files' => $res->submit_files]); - } - - /** - * 生成唯一的付款申请编码 - * 格式:PA + 日期 + 6位字母数字组合 - * - * @return string 唯一编码 - */ - public function generateUniqueApplyNo() - { - $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $maxAttempts = 10; // 防止无限循环 - $secondChar = 'PA' . date('Ymd'); - - for ($attempt = 0; $attempt < $maxAttempts; $attempt++) { - // 生成后6位随机字符 - $suffix = ''; - for ($i = 0; $i < 6; $i++) { - $suffix .= $chars[rand(0, strlen($chars) - 1)]; - } - - $applyNo = $secondChar . $suffix; - - // 检查是否已存在 - $existing = FinPaymentApply::where('apply_no', $applyNo)->first(); - if (!$existing) { - return $applyNo; - } - } - - // 如果1000次尝试后仍然重复,使用时间戳确保唯一性 - $timestamp = substr(time(), -6); - return $secondChar . $timestamp; - } - - /** - * 根据相似度排序付款记录 - * @param Request $request - * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Pagination\LengthAwarePaginator - */ - public function complexQueryIndex(Request $request) - { - $limit = (int)$request->get('size', 15); - $page = (int)$request->get('current', 1); - $param = $request->all(); - - $where = []; - $orWhere = []; - - // 汇款国家 - if (isset($param['country_id']) && !empty($param['country_id'])) { - $where[] = ['country_id', $param['country_id']]; - } - // 收款账户筛选 - if (isset($param['account_id']) && !empty($param['account_id'])) { - $where[] = ['account_id', $param['account_id']]; - } - - // 入账资料超时 - if (isset($param['scene']) && $param['scene'] == 'file_timeout') { - $where[] = ['submit_files', '']; - $where[] = ['claimed_at', '<', time()-24*60*60]; - $where[] = ['claimed_at', '>', 1]; - } - - // 关键字 - if (isset($param['keyword']) && $param['keyword']) { - $k = '%' . $param['keyword'] . '%'; - $where[] = ['remitter', 'like', $k]; - } - - // 构建查询 - $query = $this->modelClass::where($where); - - // 是否已关联收款记录的筛选 - $correlation = $param['correlation']??''; - if ($correlation === 'receipt') { //已关联 - $query->whereHas('receipt'); - } elseif ($correlation === 'unbind') { //未关联 - $query->whereDoesntHave('receipt'); - } - - if(isset($param['scene']) && $param['scene'] == 'pending'){ //待入账列表 - $query->where('receipt_id', '>' ,'0'); - $query->where('submit_files','!=',''); - $query->whereNull('received_at'); - } - - if($param['scene'] == 'delete'){ //查询作废数据 - $query->onlyTrashed(); - }elseif ($param['scene'] == 'all'){ //查询包含作废数据的全量数据 - $query->withTrashed(); - } - - if ((isset($param['scene']) && ($param['scene'] == 'list' || $param['scene'] == 'pending'))|| empty($param['receipt_id']) ) { - return $query->orderBy('id','desc')->paginate($limit, ['*'], 'page', $page); - } - - $receipt = FinReceipt::where('id', $param['receipt_id'])->first(); - $account_id = $receipt->account_id; - $currency_id = $receipt->currency_id; - $remitter = $receipt->remitter; - $amount = $receipt->amount; - - // 计算十天前的时间戳 - $sevenDaysAgo = time() - (10 * 24 * 60 * 60); - - // 构建相似度排序逻辑 - $similarityOrder = []; - - // 如果有传入参数,计算相似度 - if (!empty($account_id)) { - $similarityOrder[] = "CASE WHEN account_id = {$account_id} THEN 0 ELSE 1 END"; - } - - if (!empty($currency_id)) { - $similarityOrder[] = "CASE WHEN currency_id = {$currency_id} THEN 0 ELSE 1 END"; - } - - if (!empty($remitter)) { - $similarityOrder[] = "CASE WHEN remitter = '{$remitter}' THEN 0 ELSE 1 END"; - } - - if (!empty($amount)) { - $amount = (float)$amount; - $similarityOrder[] = "ABS(amount - {$amount})"; - $similarityOrder[] = "CASE WHEN (ABS(amount - {$amount}) / {$amount} * 100) <= 5 THEN 0 ELSE 1 END"; - } - - // 构建排序SQL - $orderByClause = ""; - if (!empty($similarityOrder)) { - $orderByClause = "CASE - WHEN created_at >= {$sevenDaysAgo} THEN - (" . implode(' + ', $similarityOrder) . ") - ELSE 0 - END ASC, "; - } - - $orderByClause .= "CASE - WHEN created_at > {$sevenDaysAgo} THEN id - ELSE 999999 - END DESC, "; - - $orderByClause .= "id DESC"; - - $query->orderByRaw($orderByClause); - - return $query->paginate($limit, ['*'], 'page', $page); - } - - public function delete($id) - { - $res = FinPaymentApply::where('id', $id)->delete(); - return $res; - } - - -} \ No newline at end of file diff --git a/app/common/service/FinReceiptHisService.php b/app/common/service/FinReceiptHisService.php deleted file mode 100644 index f43f77b..0000000 --- a/app/common/service/FinReceiptHisService.php +++ /dev/null @@ -1,62 +0,0 @@ -validator; - } - - /** - * 构建查询条件 - */ - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - if(empty($p['receipt_id'])){ - throw new BusinessException('receipt_id不能为空'); - } - // ====== ====== 排序 ====== ====== - $config['order']['id'] = 'desc'; - - // ====== ====== 筛选 ====== ====== - $config['where']['receipt_id'] = $p['receipt_id']; - - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } -} \ No newline at end of file diff --git a/app/common/service/FinReceiptService.php b/app/common/service/FinReceiptService.php deleted file mode 100644 index df236ea..0000000 --- a/app/common/service/FinReceiptService.php +++ /dev/null @@ -1,335 +0,0 @@ -logic = (new FinReceiptLogic()); - } - - /** - * 获取验证器 - */ - public function getValidator() - { - return new $this->validator; - } - - - /** - * 构建查询条件 - */ - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - // ====== ====== 排序 ====== ====== - $config['order']['id'] = 'desc'; - - // ====== ====== 筛选 ====== ====== - // 汇款国家 - if (isset($p['country_id']) && !empty($p['country_id'])) { - $config['where']['country_id'] = $p['country_id']; - } - - // 没有付款记录的收款记录 - if (isset($p['payment_apply']) && $p['payment_apply'] == 'not') { //未认领 - $config['where']['payment_apply_id'] = 0; - } elseif (isset($p['payment_apply']) && $p['payment_apply'] == 'already') { //已认领 - $config['where']['payment_apply_id'] = ['>', 0]; - } elseif (isset($p['payment_apply']) && $p['payment_apply'] == 'timeout') { //超时未认领 - $config['where']['payment_apply_id'] = 0; - $config['where']['created_at'] = ['<' ,time() - 24*60*60]; - } - - // 收款申请筛选 - if (isset($p['payment_apply_id']) && !empty($p['payment_apply_id'])) { - $config['where']['payment_apply_id'] = $p['payment_apply_id']; - } - - // 收款账户筛选 - if (isset($p['account_id']) && !empty($p['account_id'])) { - $config['where']['account_id'] = $p['account_id']; - } - - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - $config['orWhere'][] = ['remitter', 'like', $k]; - } - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'update': - case 'payment': - case 'destroy': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - } - - return $config; - } - - public function beforeServiceStore($data, Request $request) - { - if(isset($data['payment_apply_id']) && empty($data['payment_apply_id'])){ - unset($data['payment_apply_id']); - } - $data['receipt_no'] = $this->generateUniqueReceipt(); - $data['arrived_at'] = strtotime( $data['arrived_at']); - $data['created_by'] = $request->user->uid; - $data['updated_by'] = $request->user->uid; - $data['fx_receipt_file'] = json_encode($data['fx_receipt_file']); - if($data['fx_receipt_file'] == '[]' || $data['fx_receipt_file'] == '{}' || $data['fx_receipt_file'] == '""') - $data['fx_receipt_file'] = ''; - return $data; - } - - public function afterServiceStore($res) - { - $receipt = FinReceipt::where('id',$res->id)->first()->toArray(); - $receipt = array_merge($receipt,['receipt_id' => $res->id]); - unset($receipt['id']); - FinReceiptHis::create($receipt); - } - - public function beforeServiceUpdate($data, Request $request) - { - $data['updated_by'] = $request->user->uid; - if(isset($data['arrived_at'])) - $data['arrived_at'] = strtotime($data['arrived_at']); - if(isset($data['received_at'])) - $data['received_at'] = strtotime($data['received_at']); - - $data['fx_receipt_file'] = json_encode($data['fx_receipt_file']); - if($data['fx_receipt_file'] == '[]' || $data['fx_receipt_file'] == '{}' || $data['fx_receipt_file'] == '""') - $data['fx_receipt_file'] = ''; - return $data; - } - public function afterServiceUpdate($res) - { - $receipt = FinReceipt::where('id',$res['id'])->first()->toArray(); - $receipt = array_merge($receipt,['receipt_id' => $res['id']]); - unset($receipt['id']); - FinReceiptHis::create($receipt); - } - - - /** - * 生成唯一的付款申请编码 - * 格式:PA + 日期 + 6位字母数字组合 - * - * @return string 唯一编码 - */ - public function generateUniqueReceipt() - { - $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $maxAttempts = 10; // 防止无限循环 - $secondChar = 'RE' . date('Ymd'); - - for ($attempt = 0; $attempt < $maxAttempts; $attempt++) { - // 生成后6位随机字符 - $suffix = ''; - for ($i = 0; $i < 6; $i++) { - $suffix .= $chars[rand(0, strlen($chars) - 1)]; - } - - $ReceiptNo = $secondChar . $suffix; - - // 检查是否已存在 - $existing = FinReceipt::where('receipt_no', $ReceiptNo)->first(); - if (!$existing) { - return $ReceiptNo; - } - } - - // 如果1000次尝试后仍然重复,使用时间戳确保唯一性 - $timestamp = substr(time(), -6); - return $secondChar . $timestamp; - } - - /** - * 根据相似度排序付款记录 - * @param Request $request - * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Pagination\LengthAwarePaginator - */ - public function complexQueryIndex(Request $request) - { - $limit = (int)$request->get('size', 15); - $page = (int)$request->get('current', 1); - $param = $request->all(); - - if(isset($param['voucher_no_timeout_hour'])){ - redis::set('voucher_no_timeout_hour', $param['voucher_no_timeout_hour'], 'EX', 30); - } - - $where = []; - - // 汇款国家 - if (isset($param['country_id']) && !empty($param['country_id'])) { - $where[] = ['country_id', $param['country_id']]; - } - // 收款账户筛选 - if (isset($param['account_id']) && !empty($param['account_id'])) { - $where[] = ['account_id', $param['account_id']]; - } - // 收款申请筛选 - if (isset($param['payment_apply_id']) && !empty($param['payment_apply_id'])) { - $where[]['payment_apply_id'] = $param['payment_apply_id']; - } - - // 关键字 - if (isset($param['keyword']) && $param['keyword']) { - $k = '%' . $param['keyword'] . '%'; - $where[] = ['remitter', 'like', $k]; - } - - // 构建查询 - $query = $this->modelClass::where($where); - - // 收款记录绑定情况 - if (isset($param['payment_apply']) && $param['payment_apply'] == 'not') { - $query->where('payment_apply_id', 0); - } elseif (isset($param['payment_apply']) && $param['payment_apply'] == 'already') { - $query->where('payment_apply_id', '>', 0); - } elseif (isset($param['payment_apply']) && $param['payment_apply'] == 'timeout') { //超时未认领 - $query->where('payment_apply_id', 0); - $query->where('created_at', '<' ,time() - 24*60*60); - } - - if(isset($param['scene']) && $param['scene'] == 'pending'){ //待入账列表 - $query->where('payment_apply_id', '>' ,'0'); - $query->where('submit_files','!=',''); - } - - if (isset($param['scene']) && ($param['scene'] == 'list' ||$param['scene'] == 'pending')) { - return $query->paginate($limit, ['*'], 'page', $page); - } - - // 计算七天前的时间戳 - $sevenDaysAgo = time() - (10 * 24 * 60 * 60); - - // 构建相似度排序逻辑 - $similarityOrder = []; - - // 如果有传入参数,计算相似度 - if (isset($param['account_id']) && !empty($param['account_id'])) { - $similarityOrder[] = "CASE WHEN account_id = {$param['account_id']} THEN 0 ELSE 1 END"; - } - - if (isset($param['country_id']) && !empty($param['country_id'])) { - $similarityOrder[] = "CASE WHEN country_id = {$param['country_id']} THEN 0 ELSE 1 END"; - } - - if (isset($param['keyword']) && $param['keyword']) { - $keyword = addslashes($param['keyword']); - $similarityOrder[] = "CASE WHEN remitter LIKE '%{$keyword}%' THEN 0 ELSE 1 END"; - } - - if (isset($param['amount']) && !empty($param['amount'])) { - $amount = (float)$param['amount']; - $similarityOrder[] = "ABS(amount - {$amount})"; - } - - // 构建排序SQL - $orderByClause = ""; - if (!empty($similarityOrder)) { - $orderByClause = "CASE - WHEN created_at >= {$sevenDaysAgo} THEN - (" . implode(' + ', $similarityOrder) . ") - ELSE 999999 - END ASC, "; - } - - $orderByClause .= "CASE - WHEN created_at < {$sevenDaysAgo} THEN id - ELSE 0 - END DESC"; - - $query->orderByRaw($orderByClause); - - return $query->paginate($limit, ['*'], 'page', $page); - } - - public function credit($id, $exchange_rate) - { - $finReceipt = FinReceipt::find($id); - if(!empty($finReceipt->received_at)){ - throw new BusinessException('该记录已将确认入账'); - } - - $data = [ - 'received_at' => time(), - 'exchange_rate' => $exchange_rate, - 'total_amount_cny' => round($finReceipt['amount']*$exchange_rate,2), - ]; - $res = $this->logic->credit($id,$data); - FinPaymentApply::where('id', $finReceipt->payment_apply_id)->update(['received_at' => $data['received_at']]); - $this->afterServiceUpdate(['id'=>$id]); - return $res; - } - - /** - * 更新:绑定收款记录,计算折让金额 - * @param Request $request - * @param array $data - * @param string $scene - * @return mixed - */ - public function serviceUpdatePayment(Request $request, array $data = [], string $scene = 'payment') - { - $payment_apply_id = $request->input('payment_apply_id'); - - $id = $request->input('id'); - $data = $this->preProcess(ucfirst($scene), $data, $request); - $config = $this->buildQueryConfig($request, $scene); - FinPaymentApply::where('id', $payment_apply_id)->update(['receipt_id' => $id, 'claimed_at' => time(), 'claimed_by' => $request->user->uid]); - FinPaymentStock::where('payment_apply_id', $payment_apply_id)->update(['receipt_id' => $id]); - - //折让金额 - $payment = FinPaymentApply::where('id', $payment_apply_id)->first(); - $receipt = FinReceipt::find($id); - $data['discount_amount'] = $payment->amount - $receipt->amount ?? 0; - $data['submit_files'] = $payment->submit_files ?? ''; - - $updated = $this->logicUpdateBy($config, $data); - return $this->postProcess(ucfirst($scene), $data); - } - -} \ No newline at end of file diff --git a/app/common/service/FinanceReconDubaiFilesService.php b/app/common/service/FinanceReconDubaiFilesService.php deleted file mode 100644 index 33f9b64..0000000 --- a/app/common/service/FinanceReconDubaiFilesService.php +++ /dev/null @@ -1,290 +0,0 @@ -generatePrivateUrl() 完成 - */ -class FinanceReconDubaiFilesService -{ - use CrudServiceTrait; - use ExcelImportTrait; // 复用通用导入方法 - - /** 指定当前要操作的模型(用于 CrudServiceTrait) */ - protected string $modelClass = FinanceReconDubaiFiles::class; - - /** 验证器 */ - protected $validator = FinanceReconDubaiFilesValidate::class; - - /** 获取验证器实例 */ - public function getValidator() - { - return new $this->validator; - } - - /** - * 写入前置:将上传组件的结构转为 *_url / *_name,并记录创建人 - */ - public function beforeServiceStore($data, Request $request) - { - $data['created_by'] = $request->user->uid ?? 0; - $data['caiwu_file_url'] = $data['caiwu_file']['url'] ?? ''; - $data['caiwu_file_name'] = $data['caiwu_file']['name'] ?? ''; - $data['dubai_file_url'] = $data['dubai_file']['url'] ?? ''; - $data['dubai_file_name'] = $data['dubai_file']['name'] ?? ''; - return $data; - } - - /* ============================================================ - * 一、M项目对账明细 导入配置(sheet: M项目对账明细) - * ============================================================ */ - - /** 中文表头 => 目标字段名 */ - protected array $headerMapM = [ - '车架号' => 'vin', - '开票价' => 'invoice_price', - '实际采购价' => 'actual_purchase_price', - '开票价和实际采购价差额' => 'invoice_vs_purchase_diff', - '车源中介费' => 'source_broker_fee', - '配件' => 'parts_fee', - '停车费' => 'parking_fee', - '保险费' => 'insurance_fee', - '车辆手续费' => 'vehicle_service_fee', - '检测费' => 'inspection_fee', - '购置税' => 'purchase_tax', - '汽车其他费用' => 'other_vehicle_fee', - '转移待出口' => 'transfer_to_export', - '国际运费' => 'freight_international', - '国内运费1' => 'freight_domestic_1', - '国内运费2' => 'freight_domestic_2', - '报关费及港杂费' => 'customs_port_fee', - '注销费' => 'cancellation_fee', - '车船税' => 'vehicle_vessel_tax', - '其他财务费用' => 'other_finance_fee', - '汽车小额杂费' => 'minor_vehicle_misc', - '上牌费' => 'registration_fee', - '其他保险费' => 'other_insurance_fee', - '油补' => 'fuel_subsidy', - '快递费' => 'express_fee', - '国内成本合计' => 'domestic_cost_total', - '退税额' => 'tax_refund_amount', - 'cif杰贝阿里成本价' => 'cif_jebel_ali_cost', - '范经理发车看板CIF' => 'fan_manager_cif', - '财务-范经理 差额' => 'finance_vs_fan_diff', - ]; - - /** 需要转为 decimal 的目标字段 */ - protected array $decimalFieldsM = [ - 'invoice_price','actual_purchase_price','invoice_vs_purchase_diff', - 'source_broker_fee','parts_fee','parking_fee','insurance_fee','vehicle_service_fee','inspection_fee', - 'purchase_tax','other_vehicle_fee','transfer_to_export', - 'freight_international','freight_domestic_1','freight_domestic_2','customs_port_fee', - 'cancellation_fee','vehicle_vessel_tax','other_finance_fee','minor_vehicle_misc', - 'registration_fee','other_insurance_fee','fuel_subsidy','express_fee', - 'domestic_cost_total','tax_refund_amount','cif_jebel_ali_cost','fan_manager_cif','finance_vs_fan_diff', - ]; - - /** - * M项目对账明细导入 - * - * @param string $file 可为“签名 URL”或“OSS 对象键” - * @param bool $isUrl 若传入的是已签名 URL,请设 true;若是对象键,设 false - * @param bool $insertToDb 是否立即入库 - * - * 返回:['sheet','total_rows','skipped','errors','to_import','inserted','preview_3',('error'?)] - */ - public function mImport(string $file, bool $isUrl = true, bool $insertToDb = true): array - { - $sheet = 'M项目对账明细'; - - // 允许传对象键:当 isUrl=false 且非 http(s) 时,自动用 OssService 签名 - if ($isUrl === false && !preg_match('#^https?://#i', $file)) { - $file = $this->ossSignedUrl($file); - $isUrl = true; - } - - $rows = $this->readSheetRows($file, $sheet, $isUrl, headerRow: 1); - $mapped = []; - $skipped = 0; - $errors = 0; - - foreach ($rows as $row) { - try { - if ($this->shouldSkipByVinAliases($row, ['车架号'])) { $skipped++; continue; } - $rec = $this->mapAndNormalizeRow($row, $this->headerMapM, $this->decimalFieldsM); - $this->stamp($rec); - $mapped[] = $rec; - } catch (\Throwable $e) { - // 单行异常不阻断全局导入 - $errors++; continue; - } - } - - $result = [ - 'sheet' => $sheet, - 'total_rows' => count($rows), - 'skipped' => $skipped, - 'errors' => $errors, - 'to_import' => count($mapped), - ]; - - if ($insertToDb) { - // 注意表名:按你的业务这里写入 finance_recon_m_detail - $ret = $this->batchInsert('finance_recon_m_detail', $mapped); - $result['inserted'] = $ret['inserted']; - if ($ret['error']) $result['error'] = 'Database insert error: ' . $ret['error']; - } else { - $result['inserted'] = 0; - } - - $result['preview_3'] = array_slice($mapped, 0, 3); - return $result; - } - - /** M项目对账明细:从 OSS 对象键导入(语义化便捷入口) */ - public function mImportFromOssKey(string $objectKey, bool $insertToDb = true): array - { - $signedUrl = $this->ossSignedUrl($objectKey); - return $this->mImport($signedUrl, true, $insertToDb); - } - - /** M项目对账明细:从已签名 URL 导入(语义化便捷入口) */ - public function mImportFromSignedUrl(string $signedUrl, bool $insertToDb = true): array - { - return $this->mImport($signedUrl, true, $insertToDb); - } - - /* ============================================================ - * 二、迪拜两表合并 导入配置(sheets: Stock in Jebel Ali / Under shipping) - * ============================================================ */ - - /** 表头映射(已兼容不一致列名:VIN NO/车架号、国际运费和杂费/SHIPPING COST) */ - protected array $headerMapDubai = [ - 'VIN NO' => 'vin', '车架号' => 'vin', - '开票价' => 'invoice_price', - '中介费' => 'broker_fee', - '购置税' => 'purchase_tax', - '退税' => 'tax_refund', - '不含税车价' => 'price_ex_vat', - '费用' => 'fee_total', - '国内运费' => 'domestic_freight', - 'FCA成本价' => 'fca_cost', - 'FCA成本价汇率' => 'fca_fx', - '国际运费和杂费' => 'shipping_cost', - 'SHIPPING COST' => 'shipping_cost', - '运费汇率' => 'shipping_fx', - 'CIF 杰贝阿里成本价' => 'cif_jebel_ali_cost', - 'CIF RMB' => 'cif_rmb', // Under shipping 没有该列,将在逻辑中推导 - ]; - - /** 需要转为 decimal 的目标字段(汇率字段使用 DECIMAL(18,6) 建表) */ - protected array $decimalFieldsDubai = [ - 'invoice_price','broker_fee','purchase_tax','tax_refund','price_ex_vat', - 'fee_total','domestic_freight','fca_cost','fca_fx', - 'shipping_cost','shipping_fx','cif_jebel_ali_cost','cif_rmb', - ]; - - /** - * 迪拜两表合并导入(Stock in Jebel Ali / Under shipping) - * - * 缺失值规则: - * - Under shipping 无 “CIF RMB”,尝试:cif_rmb = cif_jebel_ali_cost × shipping_fx - * 若运费汇率缺失则用 fca_fx 兜底,都没有则置 NULL。 - * - * 返回:['sheets','total_rows','skipped','to_import','inserted','preview_5',('error'?)] - */ - public function dImport(string $file, bool $isUrl = false, bool $insertToDb = true): array - { - // 允许传对象键:当 isUrl=false 且非 http(s) 时,自动用 OssService 签名 - if ($isUrl === false && !preg_match('#^https?://#i', $file)) { - $file = $this->ossSignedUrl($file); - $isUrl = true; - } - - $sheets = ['Stock in Jebel Ali', 'Under shipping']; - $parsed = []; - - // 逐 Sheet 读取 - foreach ($sheets as $sheet) { - $parsed[$sheet] = $this->readSheetRows($file, $sheet, $isUrl, headerRow: 1); - } - - // 行处理与合并 - $rowsAll = []; - $skipped = 0; - - foreach ($sheets as $sheet) { - foreach ($parsed[$sheet] as $row) { - if ($this->shouldSkipByVinAliases($row, ['VIN NO','车架号'])) { $skipped++; continue; } - - // 映射 + 数值规范化 - $rec = $this->mapAndNormalizeRow($row, $this->headerMapDubai, $this->decimalFieldsDubai); - - // Under shipping 无 CIF RMB:尝试用汇率推导 - if (empty($rec['cif_rmb'])) { - $cif = $rec['cif_jebel_ali_cost'] ?? null; - $fx = $rec['shipping_fx'] ?? null; - if ($cif !== null && $fx !== null) { - $rec['cif_rmb'] = round($cif * $fx, 2); - } elseif ($cif !== null && !empty($rec['fca_fx'])) { - $rec['cif_rmb'] = round($cif * (float)$rec['fca_fx'], 2); - } else { - $rec['cif_rmb'] = null; - } - } - - // 统一 VIN 与来源 - $rec['vin'] = $this->pickFirstNonEmpty($row, ['VIN NO','车架号']); - $rec['source_sheet'] = $sheet; - - $this->stamp($rec); - $rowsAll[] = $rec; - } - } - - // 结果与入库 - $result = [ - 'sheets' => $sheets, - 'total_rows' => array_sum(array_map('count', $parsed)), - 'skipped' => $skipped, - 'to_import' => count($rowsAll), - ]; - - if ($insertToDb) { - // 注意表名:按你的业务这里写入 finance_recon_d_detail - $ret = $this->batchInsert('finance_recon_d_detail', $rowsAll); - $result['inserted'] = $ret['inserted']; - if ($ret['error']) $result['error'] = 'Database insert error: ' . $ret['error']; - } else { - $result['inserted'] = 0; - } - - $result['preview_5'] = array_slice($rowsAll, 0, 5); - return $result; - } - - /** 迪拜两表:从 OSS 对象键导入(语义化便捷入口) */ - public function dImportFromOssKey(string $objectKey, bool $insertToDb = true): array - { - $signedUrl = $this->ossSignedUrl($objectKey); - return $this->dImport($signedUrl, true, $insertToDb); - } - - /** 迪拜两表:从已签名 URL 导入(语义化便捷入口) */ - public function dImportFromSignedUrl(string $signedUrl, bool $insertToDb = true): array - { - return $this->dImport($signedUrl, true, $insertToDb); - } -} \ No newline at end of file diff --git a/app/common/service/InquiryTransmitConfigService.php b/app/common/service/InquiryTransmitConfigService.php deleted file mode 100644 index 930124a..0000000 --- a/app/common/service/InquiryTransmitConfigService.php +++ /dev/null @@ -1,67 +0,0 @@ -validator; - } - - /** - * 构造 CrudUtil 查询配置 - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'default': - $config['where']['status'] = 1; - $config['order']['id'] = 'desc'; - break; - case 'index': - $config['where']['status'] = 1; - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['where']['status'] = 1; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } -} \ No newline at end of file diff --git a/app/common/service/InquiryTransmitService.php b/app/common/service/InquiryTransmitService.php deleted file mode 100644 index 7b0fed4..0000000 --- a/app/common/service/InquiryTransmitService.php +++ /dev/null @@ -1,92 +0,0 @@ -validator; - } - - /** 创建 */ - public function serviceStore(Request $request, array $data = [], string $domain = '') - { - $data['email'] = $data['Email']; - $data['name'] = $data['Name']; - $data['tel'] = $data['Tel']; - $data['company'] = $data['Company']; - $data['country'] = $data['Country']; - $data['form_Url'] = $data['Form Url']; - $data['message'] = $data['Message']; - $data['ip_location'] = $data['IpLocation']; - $data['ip'] = $data['Ip']; - $data['domain'] = $domain; - - return InquiryTransmit::create($data); - } - - /** - * 构造 CrudUtil 查询配置 - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'default': - $config['order']['id'] = 'desc'; - break; - case 'index': - // 域名 - if (isset($p['domain']) && !empty($p['domain'])) { - $config['where']['domain'] = $p['domain']; - } - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['email', 'name', 'tel', 'country', 'message', 'form_url'] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } -} \ No newline at end of file diff --git a/app/common/service/InvItemService.php b/app/common/service/InvItemService.php deleted file mode 100644 index 5a4b8f1..0000000 --- a/app/common/service/InvItemService.php +++ /dev/null @@ -1,199 +0,0 @@ -logic = (new InvItemLogic()); - } - /** - * 获取验证器 - */ - public function getValidator() - { - return new $this->validator; - } - - /** - * 构造 CrudUtil 查询配置 - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'default': - $config['where']['status'] = 1; - $config['order']['sort'] = 'desc'; - $config['order']['id'] = 'desc'; - break; - case 'index': - $config['where']['status'] = 1; - - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['item_name'] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - - $config['order']['sort'] = 'desc'; - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['where']['status'] = 1; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - /** - * 生成 8-12 位的物品编码(默认10位) - * - * @param int $length 编码长度,默认为10(范围 8-12) - * @return string 返回大写的字母数字组合编码 - */ - private function generateItemCode($length = 10) - { - // 排除易混淆字符:0, O, o, 1, I, l - $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; - $code = ''; - $maxIndex = strlen($chars) - 1; - - for ($i = 0; $i < $length; $i++) { - $code .= $chars[mt_rand(0, $maxIndex)]; - } - - return $code; - } - - - public function beforeServiceStore($data, Request $request): array - { - $data['item_code'] = $this->generateItemCode(); - $data['category_id'] = 0; - $data['spec_model'] = ''; - $data['unit'] = '件'; - $data['is_consumable'] = 0; - $data['stock_qty'] = $data['stock_qty']??1; - $data['location'] = ''; - return $data; - } - - - /** - * 变动物品库存数量 - * - * @param int $itemId 物品ID - * @param int $changeQty 变动数量:>0 入库,<0 出库 - * @param bool $allowNegative 是否允许库存变成负数,默认不允许 - * - * @return InvItem 最新的物品记录 - * @throws BusinessException - */ - public function changeStock(int $itemId, int $changeQty, bool $allowNegative = false): InvItem - { - if ($changeQty === 0) { - throw new BusinessException('库存变动数量不能为 0'); - } - - $now = time(); - - // 构建查询 - $query = InvItem::query()->where('id', $itemId); - - // 如果不允许负数,并且是出库场景(变动为负) - if (! $allowNegative && $changeQty < 0) { - // 要保证:当前 stock_qty >= 出库数量 - $query->where('stock_qty', '>=', -$changeQty); - } - - // 使用 increment 实现:UPDATE inv_item SET stock_qty = stock_qty + ?, updated_at = ? WHERE ... - $affected = $query->increment('stock_qty', $changeQty, [ - 'updated_at' => $now, - ]); - - if ($affected === 0) { - // 更新不到行: - // 1) 物品不存在 - // 2) 或者库存不足(不允许负数时) - $exists = InvItem::query()->where('id', $itemId)->exists(); - if (! $exists) { - throw new BusinessException('物品不存在'); - } - throw new BusinessException('库存不足,无法完成库存变动'); - } - - // 再查一次最新数据返回(在外层事务中也会保持一致) - /** @var InvItem $item */ - $item = InvItem::query()->find($itemId); - return $item; - } - - /** - * 出库(减库存,默认不允许负数) - */ - public function stockOut(int $itemId, int $qty, bool $allowNegative = false): InvItem - { - if ($qty <= 0) { - throw new BusinessException('出库数量必须大于 0'); - } - return $this->changeStock($itemId, -$qty, $allowNegative); - } - - /** - * 入库(加库存) - */ - public function stockIn(int $itemId, int $qty): InvItem - { - if ($qty <= 0) { - throw new BusinessException('入库数量必须大于 0'); - } - return $this->changeStock($itemId, $qty, true); - } - - /** - * 获取车型list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionApproveService.php b/app/common/service/InvRequisitionApproveService.php deleted file mode 100644 index 07571a0..0000000 --- a/app/common/service/InvRequisitionApproveService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionAttachmentService.php b/app/common/service/InvRequisitionAttachmentService.php deleted file mode 100644 index aeec408..0000000 --- a/app/common/service/InvRequisitionAttachmentService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionItemReturnAttachmentService.php b/app/common/service/InvRequisitionItemReturnAttachmentService.php deleted file mode 100644 index fd70cd1..0000000 --- a/app/common/service/InvRequisitionItemReturnAttachmentService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionItemReturnService.php b/app/common/service/InvRequisitionItemReturnService.php deleted file mode 100644 index a90f199..0000000 --- a/app/common/service/InvRequisitionItemReturnService.php +++ /dev/null @@ -1,449 +0,0 @@ -validator; - } - - /** - * 将二维数组按指定 key 重组为关联数组,该 key 的值作为新数组的键, - * 其余元素组成子数组作为值。 - * - * @param array $array 原始二维数组 - * @param string $keyField 用作新键的字段名(如 'id') - * @return array 重组后的数组 - */ - private function groupArrayByKey($array, $keyField = 'id') - { - $result = []; - foreach ($array as $item) { - if (!isset($item[$keyField])) { - continue; // 跳过没有该 key 的项 - } - $key = $item[$keyField]; - // 移除用作键的字段 - unset($item[$keyField]); - $result[$key] = $item; - } - return $result; - } - - - /** - * 创建物品归还申请前置处理 - * - * @param array $data 归还申请数据 - * @param Request $request 请求对象 - * @return array 处理后的数据 - */ - public function beforeServiceStore($data, Request $request): array - { - try { - // // 模拟数据 - // $data = [ - // [ - // 'requisition_item_id' => 9, - // 'return_qty' => 1, - // 'apply_remark' => '申请备注', - // 'attachment' => [ - // [ - // 'original_name' => '附件1.jpg', - // 'file_path' => '/uploads/2023/07/01/attachment1.jpg' - // ], - // [ - // 'original_name' => '附件2.jpg', - // 'file_path' => '/uploads/2023/07/01/attachment2.jpg' - // ] - // ] - // ] - // ]; - - // 获取所有申请项ID - $reqItemIds = array_column($data, 'requisition_item_id'); - - // 参数校验 - if (empty($reqItemIds)) { - throw new BusinessException('未提供有效的申请项ID'); - } - - // 将申请项按 ID 重组为关联数组 - $newReqItems = $this->groupArrayByKey($data, 'requisition_item_id'); - - // 获取申请项明细 - $reqItemsArr = InvRequisitionItem::whereIn('id', $reqItemIds)->get()->toArray(); - - // 检查是否获取到有效数据 - if (empty($reqItemsArr)) { - throw new BusinessException('未找到对应的申请项'); - } - - // 获取用户信息 - $userService = new UserService(); - $user = $userService->getUserInfo($request->user->uid, ''); - - $arr = []; - foreach ($reqItemsArr as $reqItem) { - $reqItemId = $reqItem['id']; - - // 检查是否有对应的新申请项数据 - if (!isset($newReqItems[$reqItemId])) { - continue; - } - - $arr[] = [ - 'requisition_id' => $reqItem['requisition_id'], - 'requisition_item_id' => $reqItemId, - 'item_id' => $reqItem['item_id'], - 'apply_user_id' => $user['user']['id'], - 'apply_user_name' => $user['user']['name'], - 'return_qty' => $newReqItems[$reqItemId]['return_qty'], - 'apply_remark' => $newReqItems[$reqItemId]['apply_remark'] ?? '', - 'attachment' => $newReqItems[$reqItemId]['attachment'], - 'return_at' => time() - ]; - } - - return $arr; - } catch (BusinessException $e) { - throw $e; - } catch (\Throwable $th) { - throw new BusinessException('创建物品归还申请失败:' . $th->getMessage()); - } - } - - /** - * 处理物品申请 - * - * @param Request $request - * @param array $data - * @return array - */ - public function serviceStore(Request $request, array $data, string $scene = '') - { - try { - // 关联表增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Store', $data, $request); - $dl = $this->getDataLimitFromRequest($request); - foreach ($data as $item) { - $created = $this->logicCreate($item, $dl); - $this->processRequisitionItemReturnAttachment($created, $item['attachment']); - } - return $this->postProcess('Store', $created); - }); - } catch (\Throwable $e) { - throw new BusinessException("创建物品申请失败:" . $e->getMessage()); - } - } - - - /** - * 更新物品归还申请前置处理 - * - * @param array $data 归还申请数据 - * @param Request $request 请求对象 - * @return array 处理后的数据 - */ - public function beforeServiceUpdate($data, Request $request): array - { - // // 模拟数据 - // $data = [ - // 'id' => 1, - // 'requisition_item_id' => 9, - // 'return_qty' => 1, - // 'apply_remark' => '申请备注22', - // 'attachment' => [ - // [ - // 'original_name' => '附件1.jpg', - // 'file_path' => '/uploads/2023/07/01/attachment1.jpg' - // ], - // [ - // 'original_name' => '附件2.jpg', - // 'file_path' => '/uploads/2023/07/01/attachment2.jpg' - // ], - // [ - // 'original_name' => '附件3.jpg', - // 'file_path' => '/uploads/2023/07/01/attachment3.jpg' - // ] - // ] - // ]; - - $data['return_at'] = time(); - return $data; - } - - /** - * 更新物品归还申请 - * - * @param Request $request - * @param array $data - * @return array - */ - public function serviceUpdate(Request $request, array $data, string $scene = '') - { - try { - // 关联表增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Update', $data, $request); - $config = $this->buildQueryConfig($request, 'update'); - - $attachment = $data['attachment']; - unset($data['attachment']); - - $this->logicUpdateBy($config, $data); - // 获取更新后的完整记录 - $updated = $this->logicShow($config); - // 处理附件更新 - $this->processRequisitionItemReturnAttachment($updated, $attachment, true); - return $this->postProcess('Update', $updated); - }); - } catch (\Throwable $e) { - throw new BusinessException("更新物品归还申请失败:" . $e->getMessage()); - } - } - - /** - * 处理物品申请附件 - * - * @param Model $created - * @param array $items - * @param bool $isUpdate - * @return void - */ - private function processRequisitionItemReturnAttachment(Model $created, array $attachment, bool $isUpdate = false): void - { - if ($isUpdate) { - $this->clearRequisitionItemReturnAttachment($created->id); - } - - foreach ($attachment as $file) { - $attachmentData = [ - 'return_id' => $created->id, - 'file_name' => $file['original_name'], - 'file_path' => $file['file_path'] - ]; - InvRequisitionItemReturnAttachment::create($attachmentData); - } - } - - /** - * 清空物品申请附件 - * - * @param int $returnId - * @return void - */ - private function clearRequisitionItemReturnAttachment(int $returnId): void - { - InvRequisitionItemReturnAttachment::where('return_id', $returnId)->delete(); - } - - /** - * 物品领用归还确认 - * - * @param Request $request - * @param array $data - * @param string $scene - * @return array|bool - * @throws BusinessException - */ - public function serviceReturnConfirm(Request $request, array $data, string $scene = 'returnConfirm') - { - try { - // 归还确认是业务顶层方法,这里统一使用事务 - return Db::transaction(function () use ($request, $data, $scene) { - - // 1. 当前操作人信息 - $userInfo = (new UserService())->getUserInfo($request->user->uid, ''); - if (empty($userInfo['user']['id']) || empty($userInfo['user']['name'])) { - throw new BusinessException('无法获取当前用户信息'); - } - - $handlerId = (int)$userInfo['user']['id']; - $handlerName = (string)$userInfo['user']['name']; - - $data['handler_id'] = $handlerId; - $data['handler_name'] = $handlerName; - - // 确认状态:1=通过,2=拒绝 (按你现在用法) - $status = isset($data['status']) ? (int)$data['status'] : null; - if (!in_array($status, [1, 2], true)) { - throw new BusinessException('非法的归还处理状态'); - } - - // 2. 构建查询配置,定位到这条归还记录 - $config = $this->buildQueryConfig($request, $scene); - - // 更新时不允许前端覆盖主键 - unset($data['requisition_item_return_id']); - - // 3. 获取现有记录 - /** @var \app\model\InvRequisitionItemReturn|null $existingRecord */ - $existingRecord = $this->logicShow($config); - - if (!$existingRecord) { - throw new BusinessException('未找到对应的归还申请记录'); - } - - // 已处理校验:只要归还记录的 status 已经是「通过或拒绝」,就不能再处理 - $existingStatus = (int)($existingRecord->status ?? 0); - if (in_array($existingStatus, [1, 2], true) || !empty($existingRecord->handler_id)) { - throw new BusinessException('该归还申请已经被处理过了'); - } - - // 4. 更新归还记录(状态 + 审核人 + 备注等) - $updateResult = $this->logicUpdateBy($config, $data); - if ($updateResult === 0) { - throw new BusinessException('更新归还申请失败,可能记录不存在或已被处理'); - } - - // 5. 若是拒绝,直接返回(不改库存、不改已归还数量) - if ($status === 2) { - // 拒绝:这里你返回 true 或者返回更新后的记录都可以 - return true; - } - - // 6. 审核通过:继续处理领用明细 & 库存 & 领用单状态 - // 注意:requisition_item_id、item_id、return_qty 等字段在本次确认流程中不会被修改, - // 所以可以直接使用 $existingRecord 中的值(都是只读字段) - $requisitionItemId = (int)$existingRecord->requisition_item_id; - $itemId = (int)$existingRecord->item_id; - $returnQty = (int)$existingRecord->return_qty; - $requisitionId = (int)$existingRecord->requisition_id; - - if ($requisitionItemId <= 0 || $itemId <= 0 || $returnQty <= 0 || $requisitionId <= 0) { - throw new BusinessException('归还申请记录缺少必要字段,无法处理'); - } - - // 6.1 处理领用明细 - /** @var \app\model\InvRequisitionItem|null $item */ - $item = InvRequisitionItem::find($requisitionItemId); - if (!$item) { - throw new BusinessException('未找到对应的领用明细记录'); - } - - $approvedQty = (int)($item->approved_qty ?? 0); - $returnedQty = (int)($item->returned_qty ?? 0); - - if ($approvedQty <= 0) { - throw new BusinessException('该物品尚未审批出库,无法归还'); - } - - if ($returnedQty + $returnQty > $approvedQty) { - throw new BusinessException('归还数量超过已借数量,无法确认'); - } - - $item->returned_qty = $returnedQty + $returnQty; - if ($item->returned_qty >= $approvedQty) { - $item->is_finished = 1; - } - $item->updated_at = time(); - - if ($item->save() === false) { - throw new BusinessException('更新领用明细失败'); - } - - // 6.2 处理库存(入库) - (new InvItemService())->stockIn($itemId, $returnQty); - - // 6.3 检查整张单是否已全部归还(只看非耗材) - $notFinishedCount = InvRequisitionItem::query() - ->where('requisition_id', $requisitionId) - ->where('is_consumable_snap', 0) - ->where('is_finished', 0) - ->count(); - - if ($notFinishedCount === 0) { - // 全部非耗材都已归还 - $affected = InvRequisition::where('id', $requisitionId)->update([ - 'is_returned' => 1, - 'updated_at' => time(), - ]); - - // Eloquent::update 返回的是影响行数,0 表示未更新到任何行 - if ($affected === 0) { - throw new BusinessException('更新领用单状态失败,可能记录不存在'); - } - } - - // 7. 返回处理结果(保持你原来的 postProcess 习惯) - return $this->postProcess(ucfirst($scene), $existingRecord); - }); - - } catch (BusinessException $e) { - throw $e; - } catch (\Throwable $e) { - throw new BusinessException("确认归还物品失败:" . $e->getMessage()); - } - } - - /** - * 构建查询配置 - * - * @param Request $request - * @param string $scene - * @return array - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'returnConfirm': - $config['where']['id'] = $p['requisition_item_return_id']; - break; - case 'index': - $config['where']['status'] = 1; - $config['order']['sort'] = 'desc'; - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['where']['status'] = 1; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionItemService.php b/app/common/service/InvRequisitionItemService.php deleted file mode 100644 index 13206b3..0000000 --- a/app/common/service/InvRequisitionItemService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/InvRequisitionService.php b/app/common/service/InvRequisitionService.php deleted file mode 100644 index 6c4e8e2..0000000 --- a/app/common/service/InvRequisitionService.php +++ /dev/null @@ -1,212 +0,0 @@ -validator; - } - - - /** - * 创建物品申请 前置 - * - * @param array $data - * @param Request $request - * @return array - */ - public function beforeServiceStore($data, Request $request): array - { - $user = (new UserService())->getUserInfo($request->user->uid, ''); - - if (empty($user['user']['id']) || empty($user['user']['name'])) { - throw new BusinessException('无法获取当前用户信息'); - } - - $data['order_no'] = $this->generateOrderNo(); - $data['applicant_id'] = (int)$user['user']['id']; - $data['applicant_name'] = (string)$user['user']['name']; - $data['leader_id'] = $user['user']['report_to']; - $data['status'] = InvRequisition::STATUS_LEADER; - - return $data; - } - - /** - * 处理物品申请 - * - * @param Request $request - * @param array $data - * @return array - */ - public function serviceStore(Request $request, array $data, string $scene = '') - { - try { - // 关联表增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Store', $data, $request); - $dl = $this->getDataLimitFromRequest($request); - $created = $this->logicCreate($data, $dl); - // 处理物品申请项 - $this->processRequisitionItems($created, $data['items']); - // 处理物品申请附件 - $this->processRequisitionAttachmentItems($created, $data['attachment']); - return $this->postProcess('Store', $created); - }); - } catch (\Throwable $e) { - throw new BusinessException("创建物品申请失败:" . $e->getMessage()); - } - } - - /** - * 更新物品申请 - * - * @param Request $request - * @param array $data - * @return array - */ - public function serviceUpdate(Request $request, array $data, string $scene = '') - { - try { - // 关联表增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Update', $data, $request); - $config = $this->buildQueryConfig($request, 'update'); - - // 获取申请项/附件 - $items = $data['items']; - $attachment = $data['attachment']; - unset($data['items']); - unset($data['attachment']); - - // 执行更新操作 - $this->logicUpdateBy($config, $data); - - // 获取更新后的完整记录 - $updated = $this->logicShow($config); - - // 重新创建新的申请项 - $this->processRequisitionItems((object)$updated, $items, true); - - // 重新创建新的附件 - $this->processRequisitionAttachmentItems((object)$updated, $attachment, true); - - return $this->postProcess('Update', $updated); - }); - } catch (\Throwable $e) { - throw new BusinessException("更新物品申请失败:" . $e->getMessage()."|".$e->getLine()."|".$e->getFile()); - } - } - - /** - * 处理物品申请项 - * - * @param Model $created - * @param array $items - * @return void - */ - private function processRequisitionItems(Model $created, array $items, bool $isUpdate = false): void - { - if ($isUpdate) { - $this->clearRequisitionItems($created->id); - } - - foreach ($items as $item) { - $itemData = [ - 'requisition_id' => $created->id, - 'item_id' => $item['item_id'], - 'item_name_snap' => $item['item_name_snap'], // 修改:使用 snap 字段 - 'spec_model_snap' => $item['spec_model_snap'], // 修改:使用 snap 字段 - 'unit_snap' => $item['unit_snap'], // 修改:使用 snap 字段 - 'is_consumable_snap' => $item['is_consumable_snap'], // 修改:使用 snap 字段 - 'request_qty' => (int) $item['request_qty'] ?? 1, // 动态获取数量,转为整型 - 'approved_qty' => (int) $item['request_qty'] ?? 1, // 初始审批数量等于申请数量 - 'remark' => $item['remark'] ?? '' - ]; - InvRequisitionItem::create($itemData); - } - } - - /** - * 处理物品申请项 - * - * @param Model $created - * @param array $items - * @return void - */ - private function processRequisitionAttachmentItems(Model $created, array $attachment, bool $isUpdate = false): void - { - if ($isUpdate) { - $this->clearRequisitionAttachmentItems($created->id); - } - - foreach ($attachment as $file) { - $attachmentData = [ - 'requisition_id' => $created->id, - 'file_name' => $file['original_name'], - 'file_path' => $file['file_path'] - ]; - InvRequisitionAttachment::create($attachmentData); - } - } - - /** - * 删除申请项 - * - * @param int $requisitionId - * @return void - */ - public function clearRequisitionItems(int $requisitionId): void - { - InvRequisitionItem::where('requisition_id', $requisitionId)->delete(); - } - - /** - * 删除申请项 - * - * @param int $requisitionId - * @return void - */ - public function clearRequisitionAttachmentItems(int $requisitionId): void - { - InvRequisitionAttachment::where('requisition_id', $requisitionId)->delete(); - } - - /** - * 生成申请单号 - * - * @return string - */ - private function generateOrderNo(): string - { - return 'RQ' . date('Ymd') . strtoupper(substr(uniqid(), -6)); - } -} \ No newline at end of file diff --git a/app/common/service/MenuBadgeService.php b/app/common/service/MenuBadgeService.php deleted file mode 100644 index e46997b..0000000 --- a/app/common/service/MenuBadgeService.php +++ /dev/null @@ -1,178 +0,0 @@ -叶),每一级返回“完整url + 角标” - * @param int $menuId 叶子或中间节点ID(directory/menu均可) - * @param int $leafCount 该节点需要向上累加的消息数(正数可表示新增) - * @param bool $includeHidden 是否包含隐藏/禁用菜单(默认 false:过滤 status != 1) - * @return array - */ - public static function buildBadgeChain( - int $menuId, - int $leafCount, - bool $includeHidden = false, - bool $forceIncludeSelf = true - ): array { - // 取到从“叶->根”的节点列表 - $nodes = self::getAncestorNodesIterative($menuId, $includeHidden, $forceIncludeSelf); - if (empty($nodes)) { - return []; - } - - // 调整为“根->叶” - $nodes = array_reverse($nodes); - $segments = []; - $result = []; - $leafId = $menuId; - - foreach ($nodes as $n) { - $isLeaf = ((int)$n['id'] === $leafId); - - // 中间层的 permission 不展示(但若有内部url段,仍需累计到segments) - if (($n['type'] ?? '') === 'permission' && !$isLeaf) { - // 若这是 internal 且有 url 段,仍拼到段里,便于子级正确拼接 - $openType = strtolower((string)($n['open_type'] ?? 'internal')); - if ($openType === 'internal') { - $seg = trim((string)($n['url'] ?? ''), '/'); - if ($seg !== '') { - $segments[] = $seg; - } - } - continue; - } - - // 计算完整URL(internal 按段拼接;external/iframe 直接用 link/url) - $fullUrl = self::composeFullUrl($segments, $n); - - // 叶子(传入ID)必须返回;其他节点照常 - if ($isLeaf || ($n['type'] ?? '') !== 'permission') { - $result[] = [ - 'id' => (int)$n['id'], - 'name' => (string)$n['name'], - 'type' => (string)$n['type'], - 'url' => $fullUrl, - 'badge' => (int)$leafCount, - ]; - } - } - - return $result; - } - - /** - * 批量聚合多个叶子节点的角标,把同一路径处的角标相加(父级=所有子级之和) - * @param array $items - * @param bool $includeHidden - * @return array - */ - public static function aggregateChains(array $items, bool $includeHidden = false): array - { - $acc = []; // key = url - - foreach ($items as $it) { - $menuId = (int)($it['menu_id'] ?? 0); - $leafCount = (int)($it['count'] ?? 0); - if ($menuId <= 0 || $leafCount === 0) { - continue; - } - - $chain = self::buildBadgeChain($menuId, $leafCount, $includeHidden); - foreach ($chain as $node) { - $key = $node['url']; - if (!isset($acc[$key])) { - $acc[$key] = ['url' => $node['url'], 'badge' => 0]; - } - $acc[$key]['badge'] += $node['badge']; - } - } - - // 父级在前(更短的路径在前),便于前端逐级渲染 - usort($acc, function ($a, $b) { - return substr_count($a['url'], '/') <=> substr_count($b['url'], '/'); - }); - - return array_values($acc); - } - - /** - * 迭代法:从叶子一路查到根(MySQL版本无关) - * $forceIncludeSelf=true 时,无论叶子 status 是否为1,都会把叶子纳入; - * 但祖先节点仍按 $includeHidden 规则过滤。 - */ - private static function getAncestorNodesIterative( - int $id, - bool $includeHidden = false, - bool $forceIncludeSelf = true - ): array { - $cols = ['id', 'parent_id', 'name', 'type', 'url', 'open_type', 'link', 'is_hide', 'status']; - $nodes = []; - $seen = []; - $cur = $id; - $maxHop = 32; // 防环 - - $isFirst = true; - for ($i = 0; $i < $maxHop && $cur > 0; $i++) { - /** @var object|null $row */ - $row = Db::table('resources')->select($cols)->where('id', $cur)->first(); - if (!$row) break; - - $rowArr = (array)$row; - - if (!$includeHidden) { - // 叶子节点:若 $forceIncludeSelf=true 则无视 status 过滤;祖先照常过滤 - if (!$isFirst && (int)$rowArr['status'] !== 1) { - break; - } - if ($isFirst && !$forceIncludeSelf && (int)$rowArr['status'] !== 1) { - // 如果明确不强制包含叶子,叶子也按规则过滤 - break; - } - } - - $nodes[] = $rowArr; - - if (in_array($cur, $seen, true)) { - break; // 防环 - } - $seen[] = $cur; - - $cur = (int)$rowArr['parent_id']; - $isFirst = false; - } - - return $nodes; // 叶 -> 根 - } - - /** - * 组装“完整路由” - * - internal:把父级段 + 自身 url 段拼成形如 /a/b/c - * - external/iframe:直接用 link(若无则退回自身 url) - * - 忽略空段(避免出现重复斜杠) - */ - private static function composeFullUrl(array &$segments, array $node): string - { - $openType = strtolower((string)($node['open_type'] ?? 'internal')); - - // 外链或 iframe:直接返回 link/url,不再参与分段拼接 - if ($openType !== 'internal') { - $target = trim((string)($node['link'] ?? ''), " \t\r\n"); - if ($target === '') { - $target = (string)($node['url'] ?? ''); - } - return $target; - } - - // internal:把自身 url 作为一个“段”拼到前面来的 segments - $seg = trim((string)($node['url'] ?? ''), '/'); - if ($seg !== '') { - $segments[] = $seg; - } - - return '/' . implode('/', $segments); - } -} \ No newline at end of file diff --git a/app/common/service/MessageNotificationsService.php b/app/common/service/MessageNotificationsService.php deleted file mode 100644 index 3d49a6a..0000000 --- a/app/common/service/MessageNotificationsService.php +++ /dev/null @@ -1,286 +0,0 @@ -validator; - } - - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - - public function serviceDestroy(Request $request) - { - $config = $this->buildQueryConfig($request, 'destroy'); - $deleted = (new MessageNotificationsLogic())->logicDeleteBy($config); - return $this->postProcess('Destroy', $deleted); - } - - /** - * 添加前置处理 - */ - public function servicePush(Request $request, $data) - { - $pushData = [ - 'sender_id' => $request->user->uid, - 'sender_type' => 'admin', - 'title' => $data['title'], - 'content' => $data['content'], - 'scene' => 1, - 'recipient' => $data['recipient'], - 'push_method' => 1 - ]; - $msgId = (new MessageNotificationsService())->pushNotice($pushData); - return ['msg_id' => $msgId]; - } - - public function afterServiceIndex($data) - { - $data->each(function (&$item) { - $temp = explode(',', $item->recipient); - $item->recipient_list = User::whereIn('id', $temp)->pluck('name')->toArray(); - $item->scene_name = MessageNotifications::SCENE[$item->scene]; - $item->push_method_name = MessageNotifications::PUSH_METHOD[$item->push_method]; - }); - unset($item); - return $data; - } - - public function afterServiceShow($data) - { - $temp = explode(',', $data->recipient); - $data->recipient_list = User::whereIn('id', $temp)->pluck('name')->toArray(); - $data->scene_name = MessageNotifications::SCENE[$data->scene]; - $data->push_method_name = MessageNotifications::PUSH_METHOD[$data->push_method]; - return $data; - } - - - - // ====== ====== ====== 通知操作的处理 ====== ====== ====== - /** - * 推送消息 - */ - public function pushNotice(array $data = [], string $scene = "Default"): int - { - // 拼装数据(可能需要处理 消息标题、内容等等数据,可自行处理) - $pushData = $this->assemblyProcess($scene, $data); - // 写入消息 - $msgId = $this->insertMessage($pushData); - // 推送 - $this->pushWs($msgId, $pushData); - return $msgId; - } - - /** - * 执行推送 - */ - public function pushWs(int $msgId, array $pushData) - { - foreach ($pushData['recipient'] as $userId) { - // 查询消息数据 - $config['model'] = MessageUserStatus::class; - $config['order']['id'] = 'desc'; - $config['with']['message'] = ['sender_id', 'sender_type', 'msg_no', 'title', 'content', 'scene', 'created_at']; - $config['where']['uid'] = $userId; - $config['where']['msg_id'] = $msgId; - $config['where']['status'] = 0; - $wsData = (new MessageUserStatusService())->logicShow($config)->toArray(); - - // 组装数据 - if (isset($wsData['message']) && $wsData['message']) { - $wsData['message']['sender_name'] = User::where('id', $wsData['message']['sender_id'])->value('name') ?: '系统'; - $wsData['message']['scene_name'] = MessageNotifications::SCENE[$wsData['message']['scene']]; - $wsData['message']['created_at'] = date('Y-m-d H:i:s', $wsData['message']['created_at']); - } - - // 获取未读消息数 - $counts = MessageUserStatus::where('uid', $userId)->where('status', 0)->count('id'); - $data = [ - 'notice_data' => $wsData, - 'unread_counts' => $counts - ]; - - // 执行推送 - (new \app\common\utils\WsEvents())->pushWebsocket('notify.receive', $userId, $data); - } - return true; - } - - /** - * 插入消息 - * @param array $data - * @return int - */ - public function insertMessage(array $data): int - { - // 写消息 - $msgId = $this->createMessage([ - 'sender_id' => $data['sender_id'], - 'sender_type' => $data['sender_type'], - 'title' => $data['title'], - 'content' => $data['content'], - 'scene' => $data['scene'], - 'recipient' => implode(',', $data['recipient']), - 'push_method' => $data['push_method'], - ]); - // 写用户状态 - $this->addUserStatus($msgId, $data['recipient']); - return $msgId; - } - - /** - * 数据拼装方法调用 - */ - protected function assemblyProcess(string $op, mixed $data): mixed - { - $hook = "assembly{$op}"; - return method_exists($this, $hook) - ? $this->{$hook}($data) - : $data; - } - - /** - * 默认数据拼装 - */ - public function assemblyDefault(array $data) - { - return [ - 'sender_id' => isset($data['sender_id']) && $data['sender_id'] ? $data['sender_id'] : 0, - 'sender_type' => isset($data['sender_type']) && $data['sender_type'] ? $data['sender_type'] : 'system', - 'title' => isset($data['title']) && $data['title'] ? $data['title'] : '系统通知', - 'content' => isset($data['content']) && $data['content'] ? $data['content'] : '系统通知-默认', - 'scene' => isset($data['scene']) && $data['scene'] ? $data['scene'] : 1, - 'recipient' => isset($data['recipient']) && count($data['recipient']) > 0 ? $data['recipient'] : $this->getAllUserIds(), - 'push_method' => isset($data['push_method']) && $data['push_method'] ? $data['push_method'] : 0, - ]; - } - - // *** *** 可以扩展数据组拼装方法 *** *** - - // ====== ====== ====== 通知操作的基础方法 ====== ====== ====== - - /** - * 创建一条消息 - */ - public function createMessage(array $data): int - { - $msgId = Db::table('message_notifications')->insertGetId([ - 'msg_no' => generateMsgId(), - 'sender_id' => $data['sender_id'], - 'sender_type' => $data['sender_type'], - 'title' => $data['title'], - 'content' => $data['content'], - 'scene' => $data['scene'], - 'recipient' => $data['recipient'], - 'push_method' => $data['push_method'], - 'created_at' => time(), - ]); - - return $msgId; - } - - /** - * 批量插入用户消息状态 - */ - public function addUserStatus(int $msgId, array $uids) - { - $rows = []; - foreach ($uids as $uid) { - $rows[] = [ - 'msg_id' => $msgId, - 'uid' => $uid, - 'status' => 0, - 'read_at' => null - ]; - } - if ($rows) { - Db::table('message_user_status')->insert($rows); - } - } - - /** - * 标记消息已读 - */ - public function markAsRead(array|string $msgIds, int $uid) - { - $query = Db::table('message_user_status')->where('uid', $uid)->where('status', 0); - if (is_array($msgIds)) { - $query->whereIn('msg_id', $msgIds); - } - return $query->update([ - 'status' => 1, - 'read_at' => time() - ]); - } - - /** - * 获取所有用户ID - */ - public function getAllUserIds(): array - { - return User::where('status', 1)->pluck('id')->toArray(); - } - - - public function getUserEmailsById(array $con = []): array - { - $user = User::where('status', 1); - if (count($con) > 0) { - return $user->whereIn('id', $con)->where('email', '!=', '')->pluck('email')->toArray(); - } - return $user->where('email', '!=', '')->pluck('email')->toArray(); - } -} \ No newline at end of file diff --git a/app/common/service/MessageUserStatusService.php b/app/common/service/MessageUserStatusService.php deleted file mode 100644 index ca324dc..0000000 --- a/app/common/service/MessageUserStatusService.php +++ /dev/null @@ -1,136 +0,0 @@ -validator; - } - - - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'unread': - $config['order']['id'] = 'desc'; - $config['with']['message'] = ['sender_id', 'sender_type', 'msg_no', 'title', 'content', 'scene', 'created_at']; - $config['where']['uid'] = $request->user->uid; - $config['where']['status'] = 0; - break; - case 'index': - $config['order']['id'] = 'desc'; - $config['with']['message'] = ['sender_id', 'sender_type', 'msg_no', 'title', 'content', 'scene', 'created_at']; - $config['where']['uid'] = $request->user->uid; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['with']['message'] = ['sender_id', 'sender_type', 'msg_no', 'title', 'content', 'scene', 'created_at']; - $config['where']['uid'] = $request->user->uid; - break; - case 'store': - break; - case 'update': - case 'read': - $config['where']['id'] = $p['id']; - $config['where']['msg_id'] = $p['msg_id']; - $config['where']['uid'] = $request->user->uid; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - $config['where']['uid'] = $request->user->uid; - break; - } - - return $config; - } - - public function serviceListUnRead(Request $request) - { - $config = $this->buildQueryConfig($request, 'unread'); - $result = $this->logicListAll($config); - return $this->postProcess('ListUnRead', $result); - } - - public function serviceRead(Request $request, array $data = []) - { - return $this->noticeRead($request->post('msg_ids'), $request->user->uid); - } - - public function noticeRead(array|string $msgIds, int $uid): bool - { - $model = MessageUserStatus::where('uid', $uid)->where('status', 0); - if (is_array($msgIds)) { - $model->whereIn('msg_id', $msgIds); - } - $udata['read_at'] = time(); - $udata['status'] = 1; - return $model->update($udata); - } - - - protected function afterServiceIndex($res) - { - $res->each(function (&$item) { - if (isset($item->message)) { - $item->message->sender_name = User::where('id', $item->message->sender_id)->value('name') ?: '系统'; - $item->message->scene_name = MessageNotifications::SCENE[$item->message->scene]; - } - }); - unset($item); - return $res; - } - - protected function afterServiceShow($res) - { - if (isset($res->message)) { - $res->message->sender_name = User::where('id', $res->message->sender_id)->value('name') ?: '系统'; - $res->message->scene_name = MessageNotifications::SCENE[$res->message->scene]; - } - // 标记已读 - if ($res->status == 0) { - $this->noticeRead([$res->msg_id], $res->uid); - } - return $res; - } - - protected function afterServiceListUnRead($res) - { - $res->each(function (&$item) { - if (isset($item->message)) { - $item->message->sender_name = User::where('id', $item->message->sender_id)->value('name') ?: '系统'; - $item->message->scene_name = MessageNotifications::SCENE[$item->message->scene]; - } - }); - unset($item); - return $res; - } -} \ No newline at end of file diff --git a/app/common/service/PermService.php b/app/common/service/PermService.php deleted file mode 100644 index 16030b1..0000000 --- a/app/common/service/PermService.php +++ /dev/null @@ -1,65 +0,0 @@ -logic = (new PermLogic()); - } - - // 用户资源缓存key - protected static function cacheKey(int $userId, string $systemCode): string - { - return "user_resources_{$userId}_{$systemCode}"; - } - - /** - * 获取用户所有资源(合并角色+直接分配),结果缓存 - */ - public function getUserResources(int $userId, string $systemCode) - { - $cacheKey = self::cacheKey($userId, $systemCode); - $cached = Cache::get($cacheKey); - if ($cached !== null) { - return $cached; - } - // 调用 Logic 层获取资源 - $resources = $this->logic->getUserResources($userId, $systemCode); - // 缓存结果 - Cache::set($cacheKey, $resources, 3600); - return $resources; - } - - /** - * 构建目录/菜单树,节点包含权限与打开方式 - */ - public function getMenuTree(int $userId, string $systemCode): array - { - // 调用 Logic 层处理菜单构建 - $resources = $this->getUserResources($userId, $systemCode); - return $this->logic->buildTree($resources); - } - - /** - * 获取用户所有权限code - */ - public function getPermissionCodes(int $userId, string $systemCode): array - { - return $this->logic->getPermissionCodes($userId, $systemCode); - } - - /** - * 清除资源相关缓存 - */ - public function clearCache(int $userId, string $systemCode): void - { - Cache::delete(self::cacheKey($userId, $systemCode)); - } -} \ No newline at end of file diff --git a/app/common/service/PermService_bak.php b/app/common/service/PermService_bak.php deleted file mode 100644 index a2dcc27..0000000 --- a/app/common/service/PermService_bak.php +++ /dev/null @@ -1,109 +0,0 @@ -find($userId); - if (!$user) { - return collect(); - } - - $all = collect(); - foreach ($user->roles as $role) { - $all = $all->merge($role->resources); - } - $all = $all->merge($user->resources); - $unique = $all->unique('id')->values(); - - Cache::set($cacheKey, $unique, 3600); - return $unique; - } - - /** - * 构建目录/菜单树,节点包含权限与打开方式 - */ - public static function getMenuTree(int $userId): array - { - $resources = self::getUserResources($userId); - $menus = $resources - ->filter(fn($r) => in_array($r->type, ['directory','menu'])) - ->values(); - return self::buildTree($menus, $resources); - } - - protected static function buildTree($nodes, $allResources, int $parentId = 0): array - { - $tree = []; - foreach ($nodes as $node) { - if ($node->parent_id !== $parentId) continue; - - $children = self::buildTree($nodes, $allResources, $node->id); - - $authList = $allResources - ->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id) - ->map(fn($r) => [ - 'id' => $r->id, - 'title' => $r->name, - 'auth_mark' => $r->code, - ])->values()->all(); - - $tree[] = [ - 'id' => $node->id, - 'name' => $node->name, - 'path' => $node->url, - 'meta' => [ - 'title' => $node->name, - 'icon' => $node->icon, - 'keepAlive' => true, - 'authList' => $authList, - 'openType' => $node->open_type, // 'internal' | 'external' | 'iframe' - ], - 'children' => $children, - ]; - } - return $tree; - } - - /** - * 获取用户所有权限code - */ - public static function getPermissionCodes(int $userId): array - { - return self::getUserResources($userId) - ->filter(fn($res) => $res->type === 'permission') - ->pluck('code') - ->unique() - ->values() - ->all(); - } - - /** - * 清除资源相关缓存 - */ - public static function clearCache(int $userId): void - { - Cache::delete(self::cacheKey($userId)); - } -} \ No newline at end of file diff --git a/app/common/service/PurchaseOrderItemsService.php b/app/common/service/PurchaseOrderItemsService.php deleted file mode 100644 index 3ead14c..0000000 --- a/app/common/service/PurchaseOrderItemsService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/PurchaseOrdersService.php b/app/common/service/PurchaseOrdersService.php deleted file mode 100644 index 64ca27e..0000000 --- a/app/common/service/PurchaseOrdersService.php +++ /dev/null @@ -1,357 +0,0 @@ -validator; - } - - - public function getLogic() - { - return new PurchaseOrdersLogic(); - } - - /** - * 获取前置预处理数据 - * - * @param array $data 原始返回值 - * @return array 处理后的返回值 - */ - public function preQueryData(array $data) - { - $result = match ($data['scene']) { - 'pi_no' => $this->getLogic()->getPiList(), - 'order_no' => $this->getLogic()->getOrderNoListByPiNo($data['pi_no']), - 'order_items' => $this->getLogic()->getOrderItemsListByOrderNo($data['order_id']), - default => $data, - }; - return $this->postProcess('PreData', $result->toArray()); - } - - public function afterServicePreData(array $data) - { - foreach ($data as $key => &$item) { - if (isset($item['biz_date'])) { - $item['biz_date'] = date('Y-m-d', $item['biz_date']); - } - } - unset($item); - return $data; - } - - public function beforeServiceStore(array $data, Request $request) - { - $data['order_no'] = generateStockNo('CG'); - $data['buyer_id'] = $request->user->uid; - $data['buyer_name'] = User::where('id', $request->user->uid)->value('name'); - if ($data['is_draft'] == 0) { - $data['status'] = 1; - } - return $data; - } - - public function serviceStore(Request $request, array $data = [], string $scene = 'store') - { - // 使用事务确保数据一致性 - return Db::transaction(function () use ($request, $data, $scene) { - $data = $this->preProcess(ucfirst($scene), $data, $request); - $dl = $this->getDataLimitFromRequest($request); - // 创建采购单 - $created = $this->logicCreate($data, $dl); - if (isset($data['stock_order'])) { - foreach ($data['stock_order'] as $order) { - foreach ($order['stock_items'] as $item) { - // 创建采购单明细 - PurchaseOrderItems::create([ - 'purchase_order_id' => $created->id, - 'stock_id' => $order['stock_orders_id'], - 'stock_items_id' => $item['stock_order_items_id'], - 'stock_items_uqid' => $item['unique_id'], - ]); - } - } - } - return $this->postProcess(ucfirst($scene), $created); - }); - } - - /** - * 构建查询配置 - * - * @param Request $request - * @param string $scene - * @return array - */ - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - - switch ($scene) { - case 'index': - $config['order']['id'] = 'desc'; - break; - case 'update': - $config['where']['id'] = $p['id'] ?? 0; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['with'] = [ - 'items', 'items.stockOrder', 'items.stockOrderItems' - ]; - break; - } - - return $config; - } - - /** - * 删除采购订单 - * - * @param Request $request - * @return mixed - */ - public function serviceDestroy(Request $request) - { - // 使用事务确保数据一致性 - return Db::transaction(function () use ($request) { - // 构建查询条件 - $config = $this->buildQueryConfig($request, 'show'); - - // 软删除采购单明细 - $order = $this->logicShow($config); - if ($order && $order->items) { - foreach ($order->items as $item) { - $item->delete(); - } - } - - // 软删除采购单主表 - $res = $order->delete(); - - return $this->postProcess('Destroy', $res); - }); - } - - /** - * 创建采购单成功后处理 - */ - protected function afterServiceStore($res) - { - if ($res->is_draft == 0) { - $this->startApproval($res, ['resubmitted'=>0]); - } - return $res; - } - - public function startApproval($item) - { - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - $appro->start('purchase_orders', 'purchase_orders', $item->id, ['resubmitted'=>0], $item->buyer_id); - } - - public function beforeServiceUpdate(array $data, Request $request) - { - if ($data['is_draft'] == 0) { - $data['status'] = 1; - } - return $data; - } - - /** - * 更新采购单 - * - * @param Request $request - * @param array $data - * @return mixed - */ - public function serviceUpdate(Request $request, array $data = [], string $scene = 'update') - { - // 使用事务确保数据一致性 - return Db::transaction(function () use ($request, $data, $scene) { - $data = $this->preProcess(ucfirst($scene), $data, $request); - - // 构建查询条件 - $config = $this->buildQueryConfig($request, $scene); - - // 更新主表信息 - $udata = $data; - unset($udata['stock_order']); - unset($udata['is_resubmit']); - unset($udata['approval_desc']); - $this->logicUpdateBy($config, $udata); - - // 获取更新后的数据 - $order = $this->logicShow($config); - - // 更新采购单明细 - if (isset($data['stock_order'])) { - // 先删除原有的明细 - PurchaseOrderItems::where('purchase_order_id', $order->id)->delete(); - - // 重新创建明细 - foreach ($data['stock_order'] as $orderData) { - foreach ($orderData['stock_items'] as $item) { - PurchaseOrderItems::create([ - 'purchase_order_id' => $order->id, - 'stock_id' => $orderData['stock_orders_id'], - 'stock_items_id' => $item['stock_order_items_id'], - 'stock_items_uqid' => $item['unique_id'], - ]); - } - } - } - - return $this->postProcess( - ucfirst($scene), - $order, - [ - 'is_resubmit'=>$data['is_resubmit'], - 'approval_desc'=>$data['approval_desc'] - ] - ); - }); - } - - protected function afterServiceUpdate($res, $data) - { - if ($data['is_resubmit'] == 0 && $res->status == 1) { - $this->startApproval($res); - } - if ($data['is_resubmit'] == 1) { - $instance = \app\common\model\ApprovalInstances::where('biz_id', $res->id)->where('flow_type', 'purchase_orders')->first(); - if ( $instance === null) { - throw new BusinessException('未找到审批实例'); - } - // 审批服务 - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - // 重新提交 - $appro->resubmit($instance->id, $instance->initiator_id, ['resubmitted'=>1], $data['approval_desc']); - // 添加到讨论 - if (!empty($data['approval_desc'])) { - $appro->postDiscussion($instance->id, $instance->initiator_id, $data['approval_desc'], false, [], 'name'); - } - } - return $res; - } - - - public function serviceResubmit(Request $request, array $data = []) - { - $p = $request->all(); - $config = []; - $config['model'] = $this->modelClass; - $config['where']['id'] = $p['id']; - $config['where']['buyer_id'] = $request->user->uid; - $info = $this->logicShow($config); - if ($info === null) { - throw new BusinessException('未找到采购单'); - } - if ($info->status != 3) { - throw new BusinessException('该状态不能重新提交'); - } - $instance = \app\common\model\ApprovalInstances::where('biz_id', $info->id)->where('flow_type', 'purchase_orders')->first(); - if ( $instance === null) { - throw new BusinessException('未找到审批实例'); - } - // 审批服务 - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - // 重新提交 - $result = $appro->resubmit($instance->id, $instance->initiator_id, ['resubmitted'=>1], $data['remark']); - // 添加到讨论 - if (!empty($data['remark'])) { - $appro->postDiscussion($instance->id, $instance->initiator_id, $data['remark'], false, [], 'name'); - } - - $info->status = 1; - $info->save(); - return $result; - } - - - public function updateStatus(array $data = []) - { - - $info = PurchaseOrders::where('id', $data['id'])->first(); - if ($info === null) { - throw new BusinessException('未找到采购单'); - } - $info->status = $data['status']; - return $info->save(); - } - - - public function formatData($data) - { - $contractFile = $data['contract_file'] ? explode(',', $data['contract_file']) : []; - $contractFileUrl = []; - if (count($contractFile) > 0) { - foreach ($contractFile as $file) { - $contractFileUrl[] = (new \app\common\service\OssService)->generatePrivateUrl($file); - } - } - $result = [ - 'id' => $data['id'], - 'order_no' => $data['order_no'], - 'pi_no' => $data['pi_no'], - 'buyer_id' => $data['buyer_id'], - 'buyer_name' => $data['buyer_name'], - 'contract_file' => $contractFile, - 'contract_file_url' => $contractFileUrl, - 'status' => $data['status'], - 'remark' => $data['remark'] - ]; - $temps = []; - if (isset($data['items']) && count($data['items']) > 0) { - foreach ($data['items'] as $record) { - if (!in_array($record['stockOrder']['id'], array_keys($temps))) { - $temps[$record['stockOrder']['id']] = [ - 'id' => $record['stockOrder']['id'], - 'order_no' => $record['stockOrder']['order_no'], - 'salesperson_snapshot' => $record['stockOrder']['salesperson_snapshot'], - 'biz_date' => date('Y-m-d', $record['stockOrder']['biz_date']) - ]; - } - $temps[$record['stockOrder']['id']]['stock_order_items'][] =[ - 'id' => $record['stockOrderItems']['id'], - 'model_snapshot' => $record['stockOrderItems']['model_snapshot'], - 'unique_id' => $record['stockOrderItems']['unique_id'], - ]; - } - } - $result['stock_order'] = array_values($temps); - return $result; - } -} \ No newline at end of file diff --git a/app/common/service/ResourceService.php b/app/common/service/ResourceService.php deleted file mode 100644 index 2d093f8..0000000 --- a/app/common/service/ResourceService.php +++ /dev/null @@ -1,130 +0,0 @@ -validator; - } - - - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'default': - $config['where']['system_id'] = ['in', [0, $p['system_id']]]; - $config['where']['status'] = 1; - $config['order']['sort'] = 'asc'; - $config['order']['id'] = 'asc'; - break; - case 'menuList': - $config['where']['status'] = 1; - $config['where']['type'] = ['!=', 'permission']; - $config['order']['sort'] = 'asc'; - $config['order']['id'] = 'asc'; - break; - case 'menuTreeList': - $config['where']['system_id'] = ['in', [0, $p['system_id']]]; - $config['where']['status'] = 1; - $config['order']['sort'] = 'asc'; - $config['order']['id'] = 'asc'; - break; - case 'index': - $config['where']['status'] = 1; - $config['order']['sort'] = 'asc'; - $config['order']['id'] = 'asc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['where']['status'] = 1; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - public function serviceMenuList(Request $request) - { - $config = $this->buildQueryConfig($request, 'menuList'); - $result = $this->logicListAll($config); - return $this->postProcess('MenuList', $result); - } - - public function serviceMenuTreeList(Request $request) - { - $config = $this->buildQueryConfig($request, 'menuTreeList'); - $result = (new ResourceLogic())->logicListAllResources($request, $config); - return $this->postProcess('MenuTreeList', $result); - } - - - protected function afterServiceDefault($data) - { - $data = Tree::buildMenuTreeWithReference($data->toArray()); - return $data; - } - - protected function afterServiceMenuList($data) - { - $data = Tree::buildMenuTree($data->toArray()); - return $data; - } - - protected function afterServiceMenuTreeList($data) - { - $data = Tree::buildMenuTree($data->toArray()); - return $data; - } - - - public function beforeServiceStore($data, Request $request) - { - $data['parent_id'] = $data['parent_id'] != '' ? $data['parent_id'] : 0; - $data['system_id'] = $data['system_id'] != '' ? $data['system_id'] : 0; - return $data; - } - - public function beforeServiceUpdate($data, Request $request) - { - $data['parent_id'] = $data['parent_id'] != '' ? $data['parent_id'] : 0; - $data['system_id'] = $data['system_id'] != '' ? $data['system_id'] : 0; - return $data; - } -} \ No newline at end of file diff --git a/app/common/service/StockOrderAccountsService.php b/app/common/service/StockOrderAccountsService.php deleted file mode 100644 index cc455a7..0000000 --- a/app/common/service/StockOrderAccountsService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/StockOrderItemOptionsService.php b/app/common/service/StockOrderItemOptionsService.php deleted file mode 100644 index 2e6e48e..0000000 --- a/app/common/service/StockOrderItemOptionsService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/StockOrderItemsService.php b/app/common/service/StockOrderItemsService.php deleted file mode 100644 index 9130bdc..0000000 --- a/app/common/service/StockOrderItemsService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/StockOrdersFilesService.php b/app/common/service/StockOrdersFilesService.php deleted file mode 100644 index 3b8c91b..0000000 --- a/app/common/service/StockOrdersFilesService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/StockOrdersService.php b/app/common/service/StockOrdersService.php deleted file mode 100644 index 7ee30a4..0000000 --- a/app/common/service/StockOrdersService.php +++ /dev/null @@ -1,1132 +0,0 @@ -validator; - } - - - protected function buildQueryConfig(Request $request, string $scene = 'index'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - - // ====== ====== 筛选 ====== ====== - // 业务id - if (isset($p['salesperson_id']) && $p['salesperson_id']) { - $config['where']['salesperson_id'] = $p['salesperson_id']; - } - // 初、终版 - $config['where']['is_final'] = $p['is_final'] ?? 0; - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['pi_no', 'order_no', 'customer_snapshot'] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - - $config['order']['id'] = 'desc'; - - // $config['where']['salesperson_id'] = $request->user->uid; - break; - case 'print': - case 'approval': - $config['where']['id'] = $p['id']; - $config['with'][] = 'files'; // 添加文件附件关联 - break; - case 'detail': - case 'show': - $config['where']['id'] = $p['id']; - - $config['with'][] = 'items'; - $config['with'][] = 'items.options'; - $config['with'][] = 'items.moneyValues'; - $config['with'][] = 'accounts'; - $config['with'][] = 'moneyValues'; - $config['with'][] = 'salesperson'; - $config['with'][] = 'files'; // 添加文件附件关联 - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - public function beforeServiceStore($data, Request $request) - { - $userId = $request->user->uid; - // 检查绑定 - (new UserService())->checkBind($userId); - // 保存不检查文件上传 - if ($data['approval_status'] != 0) { - $this->validateRequiredFiles($data); - } - // 终版备货单时,至少一个车辆填写了vin - if ($data['is_final'] == 1) { - $hasVin = false; - foreach ($data['veh_list'] as $k => $v) { - if ($v['vin'] != '') { - $hasVin = true; - break; - } - } - if (!$hasVin) { - throw new BusinessException('至少需要为一辆车辆填写vin,才能提交审核'); - } - } - $data['order_no'] = generateStockNo(); - $data['biz_date'] = strtotime($data['biz_date']); - $data['eta_ship_date'] = strtotime($data['eta_ship_date']); - $data['latest_arrival_date'] = strtotime($data['latest_arrival_date']); - $data['salesperson_id'] = $userId; - $data['salesperson_snapshot'] = User::where('id', $userId)->value('name') ?? ''; - $data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0; - $data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0; - $data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0; - return $data; - } - - /** - * 验证创建备货单时必需的文件是否已提供 - * - * @param array $data 提交的数据 - * @throws BusinessException 当必需的文件缺失或为空时抛出异常 - */ - private function validateRequiredFiles(array $data): void - { - $requiredFiles = [ - 'contract' => '合同', - 'transaction_slip' => '水单', - 'pi_doc' => 'PI' - ]; - - foreach ($requiredFiles as $fileType => $fileLabel) { - if (!isset($data[$fileType]) || !is_array($data[$fileType]) || empty($data[$fileType])) { - throw new BusinessException("创建备货单时{$fileLabel}文件不能为空"); - } - - // 检查文件数组中的每个条目是否都有有效的URL - $hasValidFile = false; - foreach ($data[$fileType] as $fileInfo) { - if (isset($fileInfo['url']) && !empty($fileInfo['url'])) { - $hasValidFile = true; - break; - } - } - - if (!$hasValidFile) { - throw new BusinessException("创建备货单时{$fileLabel}文件不能为空"); - } - } - } - - /** - * 验证备货单审批时必需的文件是否存在 - * - * @param StockOrders $item 备货单对象 - * @throws BusinessException 当必需的文件缺失或为空时抛出异常 - */ - private function validateRequiredFilesForApproval($item): void - { - // 确保已加载文件关联 - if (!isset($item->files)) { - $item->load('files'); - } - - $requiredFiles = [ - \app\common\model\StockOrdersFiles::CONTRACT => '合同', - \app\common\model\StockOrdersFiles::TRANSACTION_SLIP => '水单', - \app\common\model\StockOrdersFiles::PI_DOC => 'PI' - ]; - - // 按文件类型分组现有文件 - $existingFiles = []; - foreach ($item->files as $file) { - if (!isset($existingFiles[$file->file_code])) { - $existingFiles[$file->file_code] = []; - } - $existingFiles[$file->file_code][] = $file; - } - - // 检查每种必需文件是否存在 - foreach ($requiredFiles as $fileCode => $fileLabel) { - if (!isset($existingFiles[$fileCode]) || empty($existingFiles[$fileCode])) { - throw new BusinessException("提交审批前必须上传{$fileLabel}文件"); - } - - // 检查文件中是否有有效的URL - $hasValidFile = false; - foreach ($existingFiles[$fileCode] as $file) { - if (!empty($file->file_url)) { - $hasValidFile = true; - break; - } - } - - if (!$hasValidFile) { - throw new BusinessException("提交审批前必须上传有效的{$fileLabel}文件"); - } - } - } - - protected function afterServiceStore($res) - { - // 处理原单 - if ($res->is_final == 1 && $res->object_id > 0) { - $order = StockOrders::find($res->object_id); - $order->is_use = 1; - $order->object_id = $res->id; - if (!$order->save()) { - flg('备货单【'.$order->order_no.'】创建终版成功,但更新原单失败'); - } - } - // 启动审批 - if ($res->approval_status == 1) { - $this->startApproval($res); - } - return $res; - } - - /** - * 启动审批 - */ - public function startApproval($item) - { - // 启动审批 - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - $formData = $this->checkNewOrUsedVehicles($item->id); - $appro->start('stock_orders', 'stock_orders', $item->id, $formData, $item->salesperson_id); - // 异步生成pdf文件 - \Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$item->id]); - } - - /** - * 创建PDF文件 - */ - public function createdPdfFile($id) - { - $config = []; - $config['model'] = $this->modelClass; - $config['where']['id'] = $id; - $config['with'][] = 'items'; - $config['with'][] = 'items.options'; - $config['with'][] = 'items.moneyValues'; - $config['with'][] = 'accounts'; - $config['with'][] = 'moneyValues'; - $config['with'][] = 'salesperson'; - $item = $this->logicShow($config); - $pdfData = $this->formatData($item); - - // 渲染模板为最终HTML - $tplPath = app_path('common/utils/pdf/template/stockOrder.stub'); - $html = \app\common\utils\pdf\service\PdfHelper::render($tplPath, ['data' => $pdfData]); - - // 生成PDF - $driver = new \app\common\utils\pdf\service\MpdfDriver(); - $pdfBin = $driver->htmlToPdf($html); - - // 存储 - $dir = public_path('pdf').'/'; - $fileName = ($pdfData['order_no'] ?? date('YmdHis')) . '.pdf'; - - // 本地保存 - \app\common\utils\pdf\service\PdfStorage::saveBinary( - $pdfBin, - $dir, - $fileName - ); - - // 上传云端 - $param = [ - 'path' => $dir . $fileName, - 'scene' => 'stock_orders', - 'category' => 'pdf', - 'original_name' => $fileName - ]; - $up = new \app\common\service\UploadService(); - $res = $up->uploadLocalFile($param); - - @unlink($dir . $fileName); - - // 更新文件地址 - $item->file_url = $res['file_name']; - $item->save(); - - return $res; - } - - - /** - * 查询审批 - */ - public function queryAppro($bizId) - { - $instances = ApprovalInstances::where('biz_id', $bizId)->where('biz_type', 'stock_orders')->where('status', 'approved')->first(); - if (!$instances) { - return []; - } - - $records = ApprovalRecords::where('instance_id', $instances->id)->where('action', 'approve')->orderBy('step_index', 'asc')->pluck('approver_id')->toArray(); - if (count($records) == 0) { - return []; - } - - $signImgs = []; - foreach ($records as $k => $v) { - $signImg = User::where('id', $v)->value('sign_img'); - $signImgs[$k] = (!empty($signImg))?(new \app\common\service\OssService)->generatePrivateUrl($signImg):''; - } - - return $signImgs; - } - - /** - * 打印数据 - */ - public function servicePrint(Request $request) - { - $config = $this->buildQueryConfig($request, 'show'); - $item = $this->logicShow($config); - return $this->postProcess('Print', $item); - } - - public function serviceDetail(Request $request) - { - $config = $this->buildQueryConfig($request, 'detail'); - $item = $this->logicShow($config); - $detail = $this->formatData($item); - return $this->postProcess('Detail', $detail); - } - - /** - * 审批 - */ - public function serviceApproval(Request $request) - { - $config = $this->buildQueryConfig($request, 'approval'); - $item = $this->logicShow($config); - - // 检查备货单是否包含必需的文件 - $this->validateRequiredFilesForApproval($item); - - $this->logicUpdateBy($config, [ - 'approval_status' => 1 - ]); - $this->startApproval($item); - return $this->postProcess('Approval', $item); - } - - /** - * 作废审批 - */ - public function serviceApprovalNullify(Request $request) - { - $config = $this->buildQueryConfig($request, 'approval'); - $item = $this->logicShow($config); - $this->approvalNullify($item); - return $this->postProcess('Approval', $item); - } - - /** - * 审批作废 - */ - public function approvalNullify($item) - { - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - $formData = $this->checkNewOrUsedVehicles($item->id); - $appro->startNullify('stock_orders_nullify', 'stock_orders', $item->id, $formData, $item->salesperson_id); - } - - /** - * 撤销审批 - */ - public function serviceApprovalRevoke(Request $request) - { - $config = $this->buildQueryConfig($request, 'approval'); - $item = $this->logicShow($config); - $this->approvalRevoke($item); - return $this->postProcess('Approval', $item); - } - - public function approvalRevoke($item) - { - $instance = \app\common\model\ApprovalInstances::where('biz_id', $item->id)->where('flow_type', 'stock_orders')->first(); - $appro = new \app\common\utils\approval\service\ApprovalFlowService(); - $appro->revoke($instance->id, $item->salesperson_id); - } - - /** - * 创建 - * - * @param Request $request - * @param array $data - * @return mixed - */ - public function serviceStore(Request $request, array $data = []) - { - // 关联表较多,增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Store', $data, $request); - $dl = $this->getDataLimitFromRequest($request); - $created = $this->logicCreate($data, $dl); - // 添加金额 - $created->addMoney('cif_total', $data['cif_total']['currency'], $data['cif_total']['amount'], $data['cif_total']['rate'], '合计到岸价'); - // 处理车辆和账户信息 - $this->processOrderItems($created, $data); - // 处理文件附件 - $this->processOrderFiles($created, $data); - return $this->postProcess('Store', $created); - }); - } - - protected function onlyFillableData(Model|string $model, array $data, array $extraWhitelist = []): array - { - $m = \is_string($model) ? new $model : $model; - $keys = $m->getFillable(); - if (empty($keys)) { - $keys = $m->getConnection() - ->getSchemaBuilder() - ->getColumnListing($m->getTable()); - } - if ($extraWhitelist) { - $keys = array_merge($keys, $extraWhitelist); - } - return array_intersect_key($data, array_flip($keys)); - } - - /** - * 更新前处理 - * - * @param array $data - * @param Request $request - * @return array - */ - public function beforeServiceUpdate($data, Request $request) - { - // 检查必填文件是否已上传 - // $this->validateRequiredFiles($data); - - $data['biz_date'] = strtotime($data['biz_date']); - $data['eta_ship_date'] = strtotime($data['eta_ship_date']); - $data['latest_arrival_date'] = strtotime($data['latest_arrival_date']); - $data['approval_status'] = $data['approval_status'] == 1 ? 1 : 0; - - $data['pick_up_date'] = $data['pick_up_date'] ? strtotime($data['pick_up_date']) : 0; - $data['collect_all_date'] = $data['collect_all_date'] ? strtotime($data['collect_all_date']) : 0; - return $data; - } - - /** - * 更新后处理 - * - * @param mixed $res - * @return mixed - */ - protected function afterServiceUpdate($res) - { - // 启动审批 - if ($res->approval_status == 1) { - $this->startApproval($res); - } - return $res; - } - - /** - * 更新 - * - * @param Request $request - * @param array $data - * @return mixed - */ - public function serviceUpdate(Request $request, array $data = []) - { - // 关联表较多,增加事务处理 - return Db::transaction(function () use ($request, $data) { - $data = $this->preProcess('Update', $data, $request); - $config = $this->buildQueryConfig($request, 'update'); - // 过滤掉非库字段 - $dbData = $this->onlyFillableData($config['model'], $data); - // 更新主表 - $this->logicUpdateBy($config, $dbData); - // 获取更新后的数据 - $order = $this->logicShow($config); - // 处理车辆和账户信息 - $this->processOrderItems($order, $data, true); - // 添加金额 - $order->addMoney('cif_total', $data['cif_total']['currency'], $data['cif_total']['amount'], $data['cif_total']['rate'], '合计到岸价'); - // 处理文件附件 - $this->processOrderFiles($order, $data, true); - return $this->postProcess('Update', $order); - }); - } - - /** - * 处理订单项(车辆和账户) - * @param StockOrders $order 订单对象 - * @param array $data 数据 - * @param bool $isUpdate 是否为更新操作 - */ - private function processOrderItems($order, array $data, bool $isUpdate = false): void - { - // 如果是更新操作,先删除原有的关联数据 - if ($isUpdate) { - $this->clearExistingOrderItems($order->id); - } - // 处理车辆项 - $this->processVehicleItems($order, $data['veh_list'] ?? []); - // 处理账户项 - $this->processAccountItems($order, $data['account_list'] ?? []); - } - - /** - * 处理订单文件附件 - * @param StockOrders $order 订单对象 - * @param array $data 数据 - * @param bool $isUpdate 是否为更新操作 - */ - private function processOrderFiles($order, array $data, bool $isUpdate = false): void - { - // 如果是更新操作,先删除原有的文件附件 - if ($isUpdate) { - $this->clearExistingOrderFiles($order->id); - } - - // 处理文件附件项 - $this->processFileItems($order, $data); - } - - /** - * (更新时)清除已存在的订单文件附件 - * @param int $orderId 订单ID - */ - private function clearExistingOrderFiles(int $orderId): void - { - StockOrdersFiles::where('order_id', $orderId)->delete(); - } - - /** - * 处理文件附件项 - */ - private function processFileItems($order, array $data): void - { - // 定义支持的文件类型 - $fileTypes = [ - 'contract' => StockOrdersFiles::CONTRACT, - 'transaction_slip' => StockOrdersFiles::TRANSACTION_SLIP, - 'pi_doc' => StockOrdersFiles::PI_DOC - ]; - - // 遍历每种文件类型 - foreach ($fileTypes as $field => $fileCode) { - // 检查数据中是否存在该字段且为数组 - if (!empty($data[$field]) && is_array($data[$field])) { - // 处理该字段下的每个文件 - foreach ($data[$field] as $fileInfo) { - $fileData = [ - 'order_id' => $order->id, - 'file_code' => $fileCode, - 'file_url' => $fileInfo['url'] ?? '', - 'file_name' => StockOrdersFiles::FILE_CODE[$fileCode], - 'original_name' => $fileInfo['original_name'] ?? StockOrdersFiles::FILE_CODE[$fileCode], - ]; - - // 只有当file_url不为空时才创建记录 - if (!empty($fileData['file_url'])) { - StockOrdersFiles::create($fileData); - } - } - } - } - } - - /** - * (更新时)清除已存在的订单项 - * @param int $orderId 订单ID - */ - private function clearExistingOrderItems(int $orderId): void - { - // 删除车辆改装项 - StockOrderItemOptions::whereHas('item', function ($query) use ($orderId) { - $query->where('order_id', $orderId); - })->delete(); - - // 删除车辆项及其相关金额记录 - $orderItems = StockOrderItems::where('order_id', $orderId)->get(); - foreach ($orderItems as $item) { - // 删除车辆项的金额记录 - Db::table('veh_money_value') - ->where('object_scene', 'stock_order_items') - ->where('object_id', $item->id) - ->delete(); - } - - // 删除车辆项 - StockOrderItems::where('order_id', $orderId)->delete(); - - // 删除订单本身的金额记录 - Db::table('veh_money_value') - ->where('object_scene', 'stock_orders') - ->where('object_id', $orderId) - ->delete(); - - // 删除账户项 - StockOrderAccounts::where('order_id', $orderId)->delete(); - } - - /** - * 处理车辆项 - */ - private function processVehicleItems($order, array $vehList): void - { - $profitTotalAmount = 0.00; - $profitCurrency = ''; - $profitRate = 0; - foreach ($vehList as $veh) { - $veh['order_id'] = $order->id; - $veh['unique_id'] = $this->generateVehicleUniqueId($veh); - - $item = StockOrderItems::create($veh); - - // 处理金额信息 - $this->processVehiclePrices($item, $veh); - - // 累计到岸价 - $profitCurrency === '' ? $profitCurrency = $veh['profit']['currency'] ?? '' : ''; - $profitRate === 0 ? $profitRate = $veh['profit']['rate'] ?? 0 : ''; - $profitTotalAmount += $veh['profit']['amount'] ?? 0; - - // 处理改装项 - $this->processModificationItems($item->id, $veh['modify_list'] ?? []); - } - // 利润 - $order->addMoney('profit_total', $profitCurrency, $profitTotalAmount, $profitRate, '总利润'); - } - - /** - * 生成车辆唯一标识 - */ - private function generateVehicleUniqueId(array $veh): string - { - $keysToRemove = ['remark', 'modify_list', 'order_id']; - $array = array_diff_key($veh, array_flip($keysToRemove)); - $uniqueIdStr = json_encode($array); - return md5($uniqueIdStr); - } - - /** - * 处理车辆价格信息 - */ - private function processVehiclePrices($item, array $veh): void - { - // unit_price 单价/成交价/收款价 - // total_price 总价 - // handling_fee 手续费 - // fob_transport_fee FOB运输费 - // port_misc_fee 港杂 - // retrofit_fee 改装费 - // ocean_freight 海运费 - // commission 佣金 - // purchase_tax 购置税 - // tax_refund 预估退税 - // clearance_price 报关价 - // profit 利润 - // official_price 官方指导价 - // discount_price 优惠价 - // listing_price 二手挂牌价 - // reduction_price 二手减价/优惠价 - // retention_price 留款/挂账 - // car_price 车价 - // accessory_price 配件费 - // increase_price 加价 - - // 基础费用 - $priceFields = [ - 'unit_price' => '收款价', - 'total_price' => '总价', - 'handling_fee' => '手续费', - 'fob_transport_fee' => 'FOB运输费', - 'port_misc_fee' => '港杂', - 'retrofit_fee' => '改装费', - 'ocean_freight' => '海运费', - 'commission' => '佣金', - 'purchase_tax' => '购置税', - 'tax_refund' => '预估退税', - 'clearance_price' => '报关价', - 'profit' => '利润', - 'retention_price' => '挂账', - 'car_price' => '车价', - 'accessory_price' => '配件费', - 'increase_price' => '加价' - ]; - - foreach ($priceFields as $field => $description) { - $item->addMoney( - $field, - $veh[$field]['currency'], - (float)$veh[$field]['amount'], - $veh[$field]['rate'], - $description - ); - } - - // 根据里程处理新车或二手车价格 - if (!empty($veh['mileage']) && $veh['mileage'] > 0) { - // 二手车 - $item->addMoney( - 'listing_price', - $veh['listing_price']['currency'], - (float)$veh['listing_price']['amount'], - $veh['listing_price']['rate'], - '二手挂牌价' - ); - $item->addMoney( - 'reduction_price', - $veh['reduction_price']['currency'], - (float)$veh['reduction_price']['amount'], - $veh['reduction_price']['rate'], - '二手优惠价' - ); - } else { - // 新车 - $item->addMoney( - 'official_price', - $veh['official_price']['currency'], - (float)$veh['official_price']['amount'], - $veh['official_price']['rate'], - '官方指导价' - ); - $item->addMoney( - 'discount_price', - $veh['discount_price']['currency'], - (float)$veh['discount_price']['amount'], - $veh['discount_price']['rate'], - '优惠价' - ); - } - } - - /** - * 处理改装项 - */ - private function processModificationItems(int $orderItemId, array $modifyList): void - { - if (empty($modifyList)) { - return; - } - - foreach ($modifyList as $modify) { - $modify['order_item_id'] = $orderItemId; - StockOrderItemOptions::create($modify); - } - } - - /** - * 处理账户项 - */ - private function processAccountItems($order, array $accountList): void - { - if (empty($accountList)) { - return; - } - - foreach ($accountList as $account) { - $account['order_id'] = $order->id; - if (!empty($account['remit_date'])) { - $account['remit_date'] = strtotime($account['remit_date']); - } - StockOrderAccounts::create($account); - } - } - - - // ====== ======= ====== ======= ====== 信息处理 ======= ====== ======= ====== ======= - - // PDF数据 - public function formatData($item) - { - // 提取车辆列表信息 - $vehListData = $this->prepareVehicleListData($item); - - // 提取订单金额信息 - $moneyValues = $this->prepareOrderMoneyValues($item); - - // 提取账户列表信息 - $accountList = $this->prepareAccountList($item); - - // 提取文件附件列表信息 - $fileList = $this->prepareFileList($item); - - // 构建返回数据 - $veh = [ - // 基本信息 - 'order_no' => $item->order_no, - 'salesperson_snapshot' => $item->salesperson_snapshot, - 'sign_img_url' => $this->getSignatureImageUrl($item->salesperson->sign_img ?? null), - 'created_at' => date('Y-m-d', strtotime($item->created_at)), - - 'pi_no' => $item->pi_no, - 'biz_date' => date('Y-m-d', $item->biz_date), - 'clearance_country_snapshot' => $item->clearance_country_snapshot, - 'customer_source_snapshot' => $item->customer_source_snapshot, - 'customer_snapshot' => $item->customer_snapshot, - 'customer_country_snapshot' => $item->customer_country_snapshot, - - // 订单项 - 'veh_list' => array_values($vehListData['list']), - 'contract_exchange_rate' => $item->contract_exchange_rate, - 'profit_total' => $moneyValues['profit_total'] ?? [], - 'cif_total' => $moneyValues['cif_total'] ?? [], - - // 运输和交付信息 - 'declarant_name' => $item->declarant_name, - 'eta_ship_date' => date('Y-m-d', $item->eta_ship_date), - 'shipping_method_snapshot' => $item->shipping_method_snapshot, - 'domestic_port_snapshot' => $item->domestic_port_snapshot, - 'trade_term_snapshot' => $item->trade_term_snapshot, - 'clearance_port_snapshot' => $item->clearance_port_snapshot, - 'latest_arrival_date' => date('Y-m-d', $item->latest_arrival_date), - 'pick_up_date' => date('Y-m-d', $item->pick_up_date), - 'collect_all_date' => date('Y-m-d', $item->collect_all_date), - 'is_final' => $item->is_final, - - // 账户信息 - 'account_list' => $accountList, - 'acc_index' => count($accountList) + 1, - 'currency_symbol' => $item->settlement_currency, - 'sign_imgs' => $this->queryAppro($item->id), - 'contract_url' => $this->getContractUrl($item->contract ?? null), - - // 文件附件信息 - 'file_list' => $fileList - ]; - - return $veh; - } - - /** - * 准备车辆列表数据 - */ - private function prepareVehicleListData($item): array - { - $vehList = []; - $index = 0; - foreach ($item->items as $v) { - // 如果已存在相同车辆,增加数量 - if (isset($vehList[$v->unique_id])) { - $this->incrementVehicleCount($vehList[$v->unique_id]); - // 拼接 remark 值 - if (!empty($v->remark)) { - if (!empty($vehList[$v->unique_id]['remark'])) { - $vehList[$v->unique_id]['remark'] .= "
" . $v->remark; - } else { - $vehList[$v->unique_id]['remark'] = $v->remark; - } - } - continue; - } - $index++; - // 处理金额信息 - $moneyValues = $this->processItemMoneyValues($v); - // 构建车辆信息 - $vehList[$v->unique_id] = [ - 'index' => $index, - 'model_snapshot' => $v->model_snapshot, - 'color_interior_snapshot' => $v->color_interior_snapshot, - 'color_exterior_snapshot' => $v->color_exterior_snapshot, - 'num' => 1, - 'mileage' => $v->mileage, - 'remark' => $v->remark, - 'vin' => $v->vin, - ] + $moneyValues; - } - return ['list' => $vehList]; - } - - /** - * 处理单项金额值 - */ - private function processItemMoneyValues($item): array - { - $moneyValues = []; - foreach ($item->moneyValues as $money) { - $moneyValues[$money->field] = [ - 'currency' => $money->currency, - 'amount' => $money->amount, - 'rate' => $money->exchange_rate, - 'currency_info' => $this->formatCurrency($money->amount, $money->currency) - ]; - } - return $moneyValues; - } - - /** - * 获取改装文本 - */ - private function getModificationText($options): string - { - $modificationText = ''; - foreach ($options as $option) { - $modificationText .= $option->option_name_snapshot . ' '; - } - return trim($modificationText); - } - - /** - * 增加车辆数量并更新相关金额显示 - */ - private function incrementVehicleCount(array &$vehicleData): void - { - $vehicleData['num'] += 1; - - // ** 11.11 remove 价格*数量 - // $fieldList = [ - // 'fob_transport_fee', - // 'car_price', - // 'ocean_freight', - // 'commission', - // 'retention_price', - // 'port_misc_fee', - // 'total_price', - // 'clearance_price', - // 'profit' - // ]; - - // foreach ($vehicleData as $field => $value) { - // if (in_array($field, $fieldList)) { - // $amount = $vehicleData[$field]['amount'] * $vehicleData['num']; - // $currencySymbol = SysCurrency::where('currency_code', $vehicleData[$field]['currency'])->value('currency_symbol'); - // $vehicleData[$field]['currency_info'] = $currencySymbol . number_format($amount, 2, '.', ','); - // } - // } - } - - /** - * 准备订单金额值 - */ - private function prepareOrderMoneyValues($item): array - { - $moneyValues = []; - foreach ($item->moneyValues as $money) { - $moneyValues[$money->field] = [ - 'currency' => $money->currency, - 'amount' => $money->amount, - 'rate' => $money->exchange_rate, - 'currency_info' => $this->formatCurrency($money->amount, $money->currency) - ]; - } - return $moneyValues; - } - - /** - * 准备账户列表 - */ - private function prepareAccountList($item): array - { - $accountList = []; - foreach ($item->accounts as $k => $account) { - $accountList[] = [ - 'index' => '收款' . ($k + 1), - 'remit_country_name_snapshot' => $account->remit_country_name_snapshot, - 'remit_date' => date('Y-m-d', $account->remit_date), - 'currency_name_snapshot' => $account->currency_name_snapshot, - 'account_name_snapshot' => $account->account_name_snapshot, - 'remitter_name' => $account->remitter_name, - 'amount' => $account->amount, - ]; - } - return $accountList; - } - - /** - * 准备文件附件列表 - */ - private function prepareFileList($item): array - { - $fileList = []; - - // 按file_code分组文件 - $groupedFiles = []; - foreach ($item->files as $file) { - if (!isset($groupedFiles[$file->file_code])) { - $groupedFiles[$file->file_code] = []; - } - $groupedFiles[$file->file_code][] = [ - 'id' => $file->id, - 'file_url' => $file->file_url, - 'file_full_url' => $this->getFileUrl($file->file_url), - 'original_name' => $file->original_name, - ]; - } - - // 定义支持的文件类型 - $fileTypes = [ - 'contract' => StockOrdersFiles::CONTRACT, - 'transaction_slip' => StockOrdersFiles::TRANSACTION_SLIP, - 'pi_doc' => StockOrdersFiles::PI_DOC - ]; - - // 按前端需要的字段组织数据 - foreach ($fileTypes as $field => $fileCode) { - if (isset($groupedFiles[$fileCode])) { - $fileList[$field] = $groupedFiles[$fileCode]; - } else { - $fileList[$field] = []; - } - } - - return $fileList; - } - - /** - * 获取货币信息 - */ - private function getCurrencyInfo(string $currencyCode): array - { - return SysCurrency::where('currency_code', $currencyCode) - ->first(['currency_symbol', 'currency_name']) - ->toArray(); - } - - /** - * 格式化货币显示 - */ - private function formatCurrency(float $amount, string $currencyCode): string - { - $currencySymbol = SysCurrency::where('currency_code', $currencyCode)->value('currency_symbol'); - return $currencySymbol . number_format($amount, 2, '.', ','); - } - - /** - * 获取签名图片URL - */ - private function getSignatureImageUrl(?string $signImg): string - { - if (empty($signImg)) { - return ''; - } - return (new \app\common\service\OssService)->generatePrivateUrl($signImg); - } - - /** - * 获取合同URL - */ - private function getContractUrl(?string $contract): string - { - if (empty($contract)) { - return ''; - } - return (new \app\common\service\OssService)->generatePrivateUrl($contract); - } - - /** - * 获取文件URL - */ - private function getFileUrl(?string $fileUrl): string - { - if (empty($fileUrl)) { - return ''; - } - return (new \app\common\service\OssService)->generatePrivateUrl($fileUrl); - } - - /** - * 检查备货单中的车辆是新车还是二手车 - * @param int $stockOrderId 备货单ID - * @return array 返回包含has_new和has_used的数组 - */ - public function checkNewOrUsedVehicles(int $stockOrderId): array - { - // 获取备货单关联的所有车辆项 - $vehicles = StockOrderItems::where('order_id', $stockOrderId)->get(); - - $hasNew = false; - $hasUsed = false; - $submitNote = ''; - - foreach ($vehicles as $vehicle) { - // 判断是否为二手车(mileage > 0) - if ($vehicle->mileage > 0) { - $hasUsed = true; - $submitNote = '本单只有二手车'; - } else { - $hasNew = true; - $submitNote = '本单只有新车'; - } - - // 如果两种类型都已经存在,可以提前退出循环 - if ($hasNew && $hasUsed) { - $submitNote = '本单包含新车和二手车'; - break; - } - } - - return [ - 'has_new' => $hasNew ? 1 : 0, - 'has_used' => $hasUsed ? 1 : 0, - 'submit_note' => $submitNote - ]; - } - - - public function serviceDestroy(Request $request, string $scene = 'destroy') - { - $config = $this->buildQueryConfig($request, $scene); - $item = $this->logicShow($config); - if (!$item) { - throw new BusinessException('数据不存在'); - } - if ($item->approval_status == 1 || $item->approval_status == 2) { - throw new BusinessException('审核中或者已审核的订单不能删除'); - } - $deleted = $this->logicDeleteBy($config); - return $this->postProcess(ucfirst($scene), $deleted); - } -} \ No newline at end of file diff --git a/app/common/service/SysAccountService.php b/app/common/service/SysAccountService.php deleted file mode 100644 index b9c59ad..0000000 --- a/app/common/service/SysAccountService.php +++ /dev/null @@ -1,28 +0,0 @@ -logic = (new SysAccountLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/SysConfigService.php b/app/common/service/SysConfigService.php deleted file mode 100644 index d52972f..0000000 --- a/app/common/service/SysConfigService.php +++ /dev/null @@ -1,37 +0,0 @@ -logic = (new SysConfigLogic()); - } - - /** - * 获取系统list - */ - public static function getConfig(string $config_key) - { - $value = Redis::get($config_key); - if (empty($value)) { - $config = (new SysConfigLogic())->findByKey($config_key); - if (empty($config)) { - return null; - } - $value = $config->config_value; - Redis::set($config->config_key, $value, 'EX', 7200); - } - - return $value; - } -} \ No newline at end of file diff --git a/app/common/service/SysCurrencyService.php b/app/common/service/SysCurrencyService.php deleted file mode 100644 index f0108d0..0000000 --- a/app/common/service/SysCurrencyService.php +++ /dev/null @@ -1,25 +0,0 @@ -logic = (new SysCurrencyLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/SysDictItemService.php b/app/common/service/SysDictItemService.php deleted file mode 100644 index c1e51ed..0000000 --- a/app/common/service/SysDictItemService.php +++ /dev/null @@ -1,42 +0,0 @@ -logic = (new SysDictItemLogic()); - } - - /** - * 获取系统list - */ - public function getList($params) - { - if (empty($params['dict_id']) && empty($params['dict_code'])) - throw new BusinessException('未明确要查询的字典组'); - $where = []; - if(isset($params['dict_id']) && $params['dict_id']) - $where[] = ['dict_id', '=', $params['dict_id']]; - if(isset($params['dict_code']) && $params['dict_code']){ - $dict = (new SysDictLogic)->getDictByCode($params['dict_code']); - if (empty($dict['id'])) - throw new BusinessException('字典组code错误'); - $where[] = ['dict_id', '=', $dict['id']]; - } - - return $this->logic->getList($where); - } -} \ No newline at end of file diff --git a/app/common/service/SysDictService.php b/app/common/service/SysDictService.php deleted file mode 100644 index 4918017..0000000 --- a/app/common/service/SysDictService.php +++ /dev/null @@ -1,52 +0,0 @@ -logic = (new SysDictLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } - - - - public static function pluckValuesByCode(string $dictCode): array - { - return SysDict::where('dict_code', $dictCode) - ->where('status', 1) - ->first()?->items() - ->where('status', 1) - ->orderBy('sort') - ->pluck('item_value') - ->toArray() ?? []; - } - - public static function pluckKeyValueByCode(string $dictCode): array - { - return SysDict::where('dict_code', $dictCode) - ->where('status', 1) - ->first()?->items() - ->where('status', 1) - ->orderBy('sort') - ->pluck('item_value', 'item_label') - ->toArray() ?? []; - } -} \ No newline at end of file diff --git a/app/common/service/SysOpLogService.php b/app/common/service/SysOpLogService.php deleted file mode 100644 index ee19817..0000000 --- a/app/common/service/SysOpLogService.php +++ /dev/null @@ -1,78 +0,0 @@ -validator; - } - - - /** - * 构建查询条件 - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - // ====== ====== 排序 ====== ====== - $config['order']['id'] = 'desc'; - - // ====== ====== 筛选 ====== ====== - // 状态 - if (isset($p['user_id']) && $p['user_id']) { - $config['where']['user_id'] = $p['user_id']; - } - // ip - if (isset($p['ip']) && $p['ip']) { - $config['where']['ip'] = $p['ip']; - } - // ip - if (isset($p['method']) && $p['method']) { - $config['where']['method'] = $p['method']; - } - // 关键字 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['user_name', 'route', 'params_brief'] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - //$config['where']['status'] = 1; - break; - case 'show': - $config['where']['id'] = $p['id']; - //$config['where']['status'] = 1; - break; - } - - return $config; - } -} \ No newline at end of file diff --git a/app/common/service/SysPortService.php b/app/common/service/SysPortService.php deleted file mode 100644 index 5235638..0000000 --- a/app/common/service/SysPortService.php +++ /dev/null @@ -1,34 +0,0 @@ -logic = (new SysPortLogic()); - } - - /** - * 获取系统list - */ - public function getList($params) - { - $where = []; - if(isset($params['scene']) && $params['scene']) { - if($params['scene'] == 'domestic'){ - $where['country_id'] = 45; - } - } - return $this->logic->getList($where); - } -} \ No newline at end of file diff --git a/app/common/service/SysUpdateLogService.php b/app/common/service/SysUpdateLogService.php deleted file mode 100644 index c93c350..0000000 --- a/app/common/service/SysUpdateLogService.php +++ /dev/null @@ -1,77 +0,0 @@ -validator; - } - - /** - * 构造 CrudUtil 查询配置 - */ - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'index': - $config['order']['id'] = 'desc'; - break; - case 'show': - $config['where']['id'] = $p['id']; - break; - case 'store': - break; - case 'update': - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - /** - * 添加前置处理 - */ - public function beforeServiceStore($data, Request $request) - { - $data['update_time'] = !empty($data['update_time'])?strtotime($data['update_time']):0; - return $data; - } - - /** - * 添加前置处理 - */ - public function beforeServiceupdate($data, Request $request) - { - $data['update_time'] = !empty($data['update_time'])?strtotime($data['update_time']):0; - return $data; - } -} \ No newline at end of file diff --git a/app/common/service/SystemsService.php b/app/common/service/SystemsService.php deleted file mode 100644 index 10b80a3..0000000 --- a/app/common/service/SystemsService.php +++ /dev/null @@ -1,24 +0,0 @@ -logic = (new SystemsLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/UsedcarCrawlResultsImagesService.php b/app/common/service/UsedcarCrawlResultsImagesService.php deleted file mode 100644 index b080fa2..0000000 --- a/app/common/service/UsedcarCrawlResultsImagesService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/UsedcarCrawlResultsService.php b/app/common/service/UsedcarCrawlResultsService.php deleted file mode 100644 index 5aa1cdd..0000000 --- a/app/common/service/UsedcarCrawlResultsService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/VehColorService.php b/app/common/service/VehColorService.php deleted file mode 100644 index 2060efe..0000000 --- a/app/common/service/VehColorService.php +++ /dev/null @@ -1,33 +0,0 @@ -logic = (new VehColorLogic()); - } - - /** - * 获取系统list - */ - public function getList($params) - { - if (empty($params['type'])) - throw new BusinessException('类型不能为空'); - $where = []; - if(isset($params['type']) && $params['type']) - $where[] = ['type', '=', $params['type']]; - return $this->logic->getList($where); - } -} \ No newline at end of file diff --git a/app/common/service/VehDictI18nService.php b/app/common/service/VehDictI18nService.php deleted file mode 100644 index 1c738d2..0000000 --- a/app/common/service/VehDictI18nService.php +++ /dev/null @@ -1,75 +0,0 @@ -validator; - } - - - /** 本进程缓存:[dict][code] => labels array */ - protected static array $labelsCache = []; - - public static function label(string $dict=null, ?string $code=null, string $locale='zh-CN', ?string $fallbackZh=null): ?string - { - if (!$dict || !$code) return $fallbackZh; - - $labels = self::labels($dict, $code); - if (!$labels) return $fallbackZh ?? $code; - - return $labels[$locale] ?? $labels['zh-CN'] ?? $code; - } - - /** 返回 labels 数组,命中缓存 */ - public static function labels(string $dict, string $code): ?array - { - $dict = strtoupper($dict); - $code = (string)$code; - - if (isset(self::$labelsCache[$dict][$code])) { - return self::$labelsCache[$dict][$code]; - } - - $term = DictTerm::where('dict',$dict)->where('code',$code)->first(['labels']); - if (!$term) return null; - - $labels = $term->labels ?? null; - if (!is_array($labels)) return null; - - self::$labelsCache[$dict][$code] = $labels; - return $labels; - } - - /** 校验 code 是否存在于字典(用于必填维度) */ - public static function ensureExists(string $dict, ?string $code, string $fieldNameForError): void - { - if ($code === null || $code === '') { - throw new \InvalidArgumentException("缺少必填字段:{$fieldNameForError}"); - } - $ok = VehDictI18n::where('dict',$dict)->where('code',$code)->where('status', 1)->exists(); - if (!$ok) throw new \InvalidArgumentException("字典不存在或未启用:{$dict}.{$code}"); - } -} \ No newline at end of file diff --git a/app/common/service/VehDictMappingService.php b/app/common/service/VehDictMappingService.php deleted file mode 100644 index 67c5288..0000000 --- a/app/common/service/VehDictMappingService.php +++ /dev/null @@ -1,57 +0,0 @@ -validator; - } - - - public static function all(): array - { - $rows = VehDictMapping::where('status', 1)->orderBy('sort')->orderBy('id')->get()->toArray(); - $out = []; - foreach ($rows as $r) { - $out[$r['dict']] = [ - 'field' => $r['field'], - 'dict' => $r['dict'], - 'required' => (int)$r['required'] === 1, - ]; - } - return $out; - } - - public static function requiredDicts(): array - { - return array_keys(array_filter(self::all(), fn($x)=>$x['required']===true)); - } - - public static function enabled(string $dict): bool - { - $all = self::all(); - return isset($all[$dict]); - } -} \ No newline at end of file diff --git a/app/common/service/VehModificationService.php b/app/common/service/VehModificationService.php deleted file mode 100644 index 31c7119..0000000 --- a/app/common/service/VehModificationService.php +++ /dev/null @@ -1,28 +0,0 @@ -logic = (new VehModificationLogic()); - } - - /** - * 获取系统list - */ - public function getList() - { - return $this->logic->getList(); - } -} \ No newline at end of file diff --git a/app/common/service/VehMoneyValueService.php b/app/common/service/VehMoneyValueService.php deleted file mode 100644 index af45547..0000000 --- a/app/common/service/VehMoneyValueService.php +++ /dev/null @@ -1,77 +0,0 @@ -validator; - } - - - /** - * 复制金额记录 - * - * @param string $fromScene 源场景 - * @param int $fromId 源对象ID - * @param string $toScene 目标场景 - * @param int $toId 目标对象ID - * @return int 插入条数 - * @throws BusinessException - */ - public function copyMoneyValues(string $fromScene, int $fromId, string $toScene, int $toId): int - { - // 1. 查询源数据 - $rows = Db::table('veh_money_value') - ->where('object_scene', $fromScene) - ->where('object_id', $fromId) - ->get() - ->toArray(); - - if (empty($rows)) { - return 0; - } - - $now = time(); - $insertData = []; - - foreach ($rows as $row) { - $insertData[] = [ - 'object_scene' => $toScene, - 'object_id' => $toId, - 'field' => $row->field, - 'currency' => $row->currency, - 'amount' => $row->amount, - 'exchange_rate' => $row->exchange_rate, - 'remark' => $row->remark, - 'created_at' => $now, - 'updated_at' => $now, - ]; - } - - // 2. 插入新数据 - return Db::table('veh_money_value')->insert($insertData); - } -} \ No newline at end of file diff --git a/app/common/service/VehVehicleListingService.php b/app/common/service/VehVehicleListingService.php deleted file mode 100644 index 3aee146..0000000 --- a/app/common/service/VehVehicleListingService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file diff --git a/app/common/service/VehVehicleSkuService.php b/app/common/service/VehVehicleSkuService.php deleted file mode 100644 index a85ebcf..0000000 --- a/app/common/service/VehVehicleSkuService.php +++ /dev/null @@ -1,250 +0,0 @@ -logic = (new VehVehicleSkuLogic()); - } - - /** - * 获取验证器 - */ - public function getValidator() - { - return new $this->validator; - } - - - // // 枚举 - // private const MAPS = [ - // 'BODY' => [ - // 'SEDAN' => '三厢轿车', 'SUV'=>'SUV', 'HB'=>'两厢/掀背', 'MPV'=>'MPV', 'PICKUP'=>'皮卡' - // ], - // 'DRIVE' => [ - // 'FWD'=>'前驱', 'RWD'=>'后驱', 'AWD'=>'四驱(AWD)', '4WD'=>'四驱(4WD)' - // ], - // 'MOTOR_LAYOUT' => [ - // 'FWD'=>'前置单电机', 'RWD'=>'后置单电机', 'AWD'=>'双电机四驱', 'DM-I'=>'DM-i', 'DM-P'=>'DM-p' - // ], - // 'FUEL' => [ - // 'GAS'=>'汽油', 'HEV'=>'油电混动', 'PHEV'=>'插电混动', 'EV'=>'纯电', 'EREV'=>'增程' - // ], - // 'TRANS' => [ - // 'MT'=>'手动', 'AT'=>'自动', 'CVT'=>'无级', 'DCT'=>'双离合', '1SPEED'=>'单速' - // ], - // 'RANGE_STD' => [ - // 'CLTC'=>'CLTC', 'WLTP'=>'WLTP', 'EPA'=>'EPA', 'NEDC'=>'NEDC' - // ], - // 'EMISSION' => [ - // 'CHN6'=>'国六', 'EURO6'=>'欧6', 'EPA'=>'美国EPA' - // ], - // ]; - - // // *_code取中文 - // public function label(string $dict, ?string $code): ?string - // { - // if ($code === null || $code === '') return null; - // $dict = strtoupper($dict); - // $code = strtoupper($code); - // return self::MAPS[$dict][$code] ?? $code; - // } - - // // 静态映射把 *_code → 中文 - // private function backfill(array $d): array - // { - // $d['body_type'] = $this->label('BODY', $d['body_type_code']); - // $d['drive_type'] = $this->label('DRIVE', $d['drive_type_code']); - // $d['motor_layout'] = $this->label('MOTOR_LAYOUT', $d['motor_layout_code']); - // $d['fuel_type'] = $this->label('FUEL', $d['fuel_type_code']); - // $d['transmission'] = $this->label('TRANS', $d['transmission_code']); - // $d['range_std'] = $this->label('RANGE_STD', $d['range_std_code']); - // $d['emission_std'] = $this->label('EMISSION', $d['emission_std_code']); - // return $d; - // } - - protected function buildQueryConfig(Request $request, string $scene = 'default'): array - { - $p = $request->all(); - - $config = []; - $config['model'] = $this->modelClass; - switch ($scene) { - case 'default': - $config['where']['is_active'] = 1; - $config['order']['id'] = 'desc'; - - // 关键字筛选 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['model_name','series_name','brand_name',] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - break; - case 'index': - $config['where']['is_active'] = 1; - $config['order']['id'] = 'desc'; - - // 关键字筛选 - if (isset($p['keyword']) && $p['keyword']) { - $k = '%' . $p['keyword'] . '%'; - foreach (['model_name','series_name','brand_name',] as $col) { - $config['orWhere'][] = [$col, 'like', $k]; - } - } - - if(isset($p['brand_id']) && $p['brand_id']){ - $brand_code = Brand::where('id', $p['brand_id'])->value('brand_code'); - $config['where']['brand_code'] = $brand_code; - } - if(isset($p['series_id']) && $p['series_id']){ - $series_code = BrandSeries::where('id', $p['series_id'])->value('series_code'); - $config['where']['series_code'] = $series_code; - } - break; - case 'show': - $config['where']['id'] = $p['id']; - $config['where']['is_active'] = 1; - break; - case 'store': - break; - case 'update': - $config['where']['id'] = $p['id']; - break; - case 'destroy': - $config['where']['id'] = $p['id']; - break; - } - - return $config; - } - - public function beforeServiceStore($data, Request $request) - { - // $data = $this->backfill($data); - if (empty($data['model_code'])) { - $data['model_code'] = ModelNaming::buildModelCode($data); - } - if (empty($data['model_name'])) { - $data['model_name'] = ModelNaming::buildModelName($data); - } - if (empty($data['engine_disp_l'])) { - $data['engine_disp_l'] = 0; - } - if (empty($data['engine_turbo'])) { - $data['engine_turbo'] = 0; - } - if (empty($data['engine_power_kw'])) { - $data['engine_power_kw'] = 0; - } - if (empty($data['battery_kwh'])) { - $data['battery_kwh'] = 0; - } - if (empty($data['gears'])) { - $data['gears'] = 1; - } - if (empty($data['range_km'])) { //续航 - $data['range_km'] = 0; - } - if (empty($data['doors'])) { //车位数 - $data['doors'] = 0; - } - if (empty($data['seats'])) { //座位数 - $data['seats'] = 0; - } - if (empty($data['weight_kg'])) { //整车质量 - $data['weight_kg'] = 0; - } - $data['sku_code'] = SkuCodeBuilder::build($data); - $data['corp_id'] = 0; - $data['created_by'] = $request->user->uid; - $data['updated_by'] = $request->user->uid; - //指纹数组 - $fingerprintArr = [ - 'brand_name' => $data['brand_name'], - 'series_name' => $data['series_name'], - 'model_name' => $data['model_name'], - 'model_year' => $data['model_year'], - 'msrp' => $data['msrp'], - ]; - // 生成指纹 - $data['fingerprint'] = Fingerprint::makeFromArray($fingerprintArr); - return $data; - } - - protected function afterServiceStore($res) - { - - return $res; - } - - - public function beforeServiceUpdate($data, Request $request) - { - unset($data['created_at']); - unset($data['updated_at']); - // $data = $this->backfill($data); - if (empty($data['model_code'])) { - $data['model_code'] = ModelNaming::buildModelCode($data); - } - if (empty($data['model_name'])) { - $data['model_name'] = ModelNaming::buildModelName($data); - } - // 填充系统字段 - $data['updated_by'] = $request->user->uid; - //指纹数组 - $fingerprintArr = [ - 'brand_name' => $data['brand_name'], - 'series_name' => $data['series_name'], - 'model_name' => $data['model_name'], - 'model_year' => $data['model_year'], - 'msrp' => $data['msrp'], - ]; - // 生成指纹 - $data['fingerprint'] = Fingerprint::makeFromArray($fingerprintArr); - return $data; - } - - protected function afterServiceUpdate($res) - { - - return $res; - } - - /** - * 获取车型list - */ - public function getList($data) - { - return $this->logic->getList($data); - } -} \ No newline at end of file diff --git a/app/common/service/VehVehicleUnitService.php b/app/common/service/VehVehicleUnitService.php deleted file mode 100644 index 4af3ea4..0000000 --- a/app/common/service/VehVehicleUnitService.php +++ /dev/null @@ -1,31 +0,0 @@ -validator; - } -} \ No newline at end of file