Merge branch 'develop'

This commit is contained in:
mzl
2025-09-16 10:53:57 +08:00
parent b399f85707
commit 62c32d25ff
210 changed files with 15388 additions and 95 deletions
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace app\common\service;
use app\admin\validate\BrandSeriesValidate;
use app\common\logic\BrandSeriesLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\BrandSeries;
use support\exception\BusinessException;
use support\Request;
class BrandSeriesService
{
protected $logic;
public function __construct()
{
$this->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);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace app\common\service;
use app\common\logic\BrandLogic;
class BrandService
{
protected $logic;
public function __construct()
{
$this->logic = (new BrandLogic());
}
/**
* 获取系统list
*/
public function getList()
{
return $this->logic->getList();
}
}
@@ -273,4 +273,14 @@ class MessageNotificationsService
{
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();
}
}
+20
View File
@@ -56,4 +56,24 @@ class OssService
// 生成 OSS 私有 URL(有效期为 3600 秒)
return $this->ossClient->signUrl($this->bucket, $objectKey, $expireTime);
}
/**
* 删除 OSS 上的文件
* @param string $objectKey OSS上存储的对象名称
* @return bool 删除是否成功
*/
public function deleteFile($objectKey)
{
try {
// 删除 OSS 上的文件
$this->ossClient->deleteObject($this->bucket, $objectKey);
return true;
} catch (OssException $e) {
// 错误处理
throw new \RuntimeException('OSS Delete Error: ' . $e->getMessage());
} catch (\Throwable $th) {
// 错误处理
throw new BusinessException('Delete Error: ' . $th->getMessage());
}
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\StockOrderAccountsValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrderAccounts;
class StockOrderAccountsService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrderAccounts::class;
/**
* 验证器
*/
protected $validator = StockOrderAccountsValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\StockOrderItemOptionsValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrderItemOptions;
class StockOrderItemOptionsService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrderItemOptions::class;
/**
* 验证器
*/
protected $validator = StockOrderItemOptionsValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\StockOrderItemsValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrderItems;
class StockOrderItemsService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrderItems::class;
/**
* 验证器
*/
protected $validator = StockOrderItemsValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
+742
View File
@@ -0,0 +1,742 @@
<?php
namespace app\common\service;
use app\common\model\StockOrderAccounts;
use app\common\model\StockOrderItemOptions;
use app\common\model\StockOrderItems;
use app\common\validate\StockOrdersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrders;
use app\common\model\SysCurrency;
use support\Request;
use app\common\model\User;
use support\Db;
use support\Model;
use app\admin\model\ApprovalInstances;
use app\admin\model\ApprovalRecords;
class StockOrdersService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrders::class;
/**
* 验证器
*/
protected $validator = StockOrdersValidate::class;
/**
* 获取验证器
*/
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':
// ====== ====== 筛选 ====== ======
// 业务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'];
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';
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;
$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;
// if ($data['is_final'] == 1) {
$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;
}
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();
$appro->start('stock_orders', 'stock_orders', $item->id, $item->toArray(), $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->pdfData($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 pdfData($item)
{
$vehList = [];
$index = 0;
$totalProfit = 0; // 总利润
// $priceFields = [
// 'official_price', // '官方指导价',
// 'discount_price', // '优惠',
// 'listing_price', // '二手挂牌价价',
// 'reduction_price', // '优惠',
// 'handling_fee', // '手续费',
// 'retrofit_fee', // '改装费',
// 'fob_transport_fee', // 'FOB运输费',
// 'port_misc_fee', // '港杂',
// 'ocean_freight', // '海运费',
// 'unit_price', // '单价',
// 'total_price', // '总价',
// // 'profit', // '利润'
// ];
foreach ($item->items as $k => $v) {
$currencyInfo = SysCurrency::where('currency_code', $item->settlement_currency)->first(['currency_symbol', 'currency_name'])->toArray();
// 存在则数量加1
if (count($vehList) > 0 && isset($vehList[$v->unique_id])) {
$vehList[$v->unique_id]['num'] += 1;
$vehList[$v->unique_id]['total_price']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['total_price']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
$vehList[$v->unique_id]['profit']['currency_info'] = $currencyInfo['currency_symbol'].number_format($vehList[$v->unique_id]['profit']['amount']*$vehList[$v->unique_id]['num'], 2, '.', ',');
continue;
}
$index += 1;
// 处理金额 (每次循环重新初始化)
$mv = [];
foreach ($v->moneyValues as $money) {
$mv[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $money->currency)->value('currency_symbol').number_format($money->amount, 2, '.', ',')
];
}
// 处理改装 (每次循环重新初始化)
$mfy = '';
foreach ($v->options as $my) {
$mfy .= $my->option_name_snapshot.' ';
}
// 计算单项利润并累加到总利润
$itemProfit = $this->calculateProfit($mv, $item);
$totalProfit += $itemProfit;
// 处理结果集
$vehListItem = [
'index' => $index,
'model_snapshot' => $v->model_snapshot,
'color_interior_snapshot' => $v->color_interior_snapshot,
'color_exterior_snapshot' => $v->color_exterior_snapshot,
'num' => 1,
'modify' => $mfy,
'mileage' => $v->mileage
];
$vehList[$v->unique_id] = $vehListItem + $mv;
}
$mvs = [];
foreach ($item->moneyValues as $moneys) {
$mvs[$moneys->field] = [
'currency' => $moneys->currency,
'amount' => $moneys->amount,
'rate' => $moneys->exchange_rate,
'currency_info' => SysCurrency::where('currency_code', $moneys->currency)->value('currency_symbol').number_format($moneys->amount, 2, '.', ','),
];
}
$accList = [];
foreach ($item->accounts as $k => $v) {
$accList[] = [
'index' => '收款'.($k + 1),
'remit_country_name_snapshot' => $v->remit_country_name_snapshot,
'remit_date' => date('Y-m-d', $v->remit_date),
'currency_name_snapshot' => $v->currency_name_snapshot,
'account_name_snapshot' => $v->account_name_snapshot,
'remitter_name' => $v->remitter_name,
'amount' => $v->amount,
];
}
$veh = [
'order_no' => $item->order_no,
'salesperson_snapshot' => $item->salesperson_snapshot,
'sign_img_url' => (!empty($item->salesperson->sign_img)) ?
(new \app\common\service\OssService)->generatePrivateUrl($item->salesperson->sign_img) : '',
'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($vehList), // 重新索引数组
'contract_exchange_rate' => $item->contract_exchange_rate,
'cif_total_amount' => $mvs['cif_total_amount'],
'profit_total' => $mvs['profit_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' => $accList,
'acc_index' => count($accList)+1,
'currency_symbol' => $item->settlement_currency,
'sign_imgs' => $this->queryAppro($item->id),
'contract_url' => (!empty($item->contract)) ? (new \app\common\service\OssService)->generatePrivateUrl($item->contract) : ''
];
return $veh;
}
public function queryAppro($bizId)
{
$instances = ApprovalInstances::where('biz_id', $bizId)->where('biz_type', 'stock_orders')->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);
$pdfData = $this->pdfData($item);
return $this->postProcess('Detail', $pdfData);
}
/**
* 审批
*/
public function serviceApproval(Request $request)
{
$config = $this->buildQueryConfig($request, 'approval');
$this->logicUpdateBy($config, [
'approval_status' => 1
]);
$item = $this->logicShow($config);
$this->startApproval($item);
return $this->postProcess('Approval', $item);
}
/**
* 创建
*
* @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);
// 处理车辆和账户信息
$this->processOrderItems($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;
// 1) 优先使用 fillable
$keys = $m->getFillable();
// 2) 若没配置 fillable(常见:用 guarded),回退到完整表字段,避免误伤
if (empty($keys)) {
$keys = $m->getConnection()
->getSchemaBuilder()
->getColumnListing($m->getTable());
}
// 3) 允许额外白名单(如虚拟字段、JSON映射字段)
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)
{
$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);
// 更新主表
$updated = $this->logicUpdateBy($config, $dbData);
// 获取更新后的数据
$order = $this->logicShow($config);
// 处理车辆和账户信息
$this->processOrderItems($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 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
{
$cifTotalAmount = 0.00;
// $cifTotalAmountRate = 0;
// $cifTotalAmountCurrency = 'CNY';
$profitTotalAmount = 0.00;
foreach ($vehList as $veh) {
$veh['order_id'] = $order->id;
$veh['unique_id'] = $this->generateVehicleUniqueId($veh);
$item = StockOrderItems::create($veh);
// 处理金额信息
$this->processVehiclePrices($item, $veh);
// 计算利润
$profit = $this->calculateProfit($veh, $order);
$item->addMoney('profit', $order->settlement_currency, $profit, $order->contract_exchange_rate, '利润');
// 累计到岸价
$cifTotalAmount += $veh['total_price']['amount'] ?? 0;
$profitTotalAmount += $profit;
// if (isset($veh['retrofit_fee']['rate'])) {
// $cifTotalAmountRate = $veh['retrofit_fee']['rate'];
// }
// if (isset($veh['retrofit_fee']['currency'])) {
// $cifTotalAmountCurrency = $veh['retrofit_fee']['currency'];
// }
// 处理改装项
$this->processModificationItems($item->id, $veh['modify_list'] ?? []);
}
// 保存合计到岸价
$order->addMoney('cif_total_amount', $order->settlement_currency, $cifTotalAmount, $order->contract_exchange_rate, '合计到岸价');
// 利润
$order->addMoney('profit_total', $order->settlement_currency, $profitTotalAmount, $order->contract_exchange_rate, '总利润');
}
/**
* 生成车辆唯一标识
*/
private function generateVehicleUniqueId(array $veh): string
{
$uniqueIdStr = "";
$uniqueIdStr .= $veh['sku_id'] ?? '';
$uniqueIdStr .= $veh['model_snapshot'] ?? '';
$uniqueIdStr .= $veh['color_interior_code'] ?? '';
$uniqueIdStr .= $veh['color_exterior_code'] ?? '';
$uniqueIdStr .= $veh['mileage'] ?? '';
$uniqueIdStr .= json_encode($veh['modify_list'] ?? []);
return md5($uniqueIdStr);
}
/**
* 处理车辆价格信息
*/
private function processVehiclePrices($item, array $veh): void
{
// 基础费用
$priceFields = [
'unit_price' => '单价',
'total_price' => '总价',
'handling_fee' => '手续费',
'fob_transport_fee' => 'FOB运输费',
'port_misc_fee' => '港杂',
'retrofit_fee' => '改装费',
'ocean_freight' => '海运费'
];
foreach ($priceFields as $field => $description) {
if (!empty($veh[$field]['amount'])) {
$item->addMoney(
$field,
$veh[$field]['currency'],
$veh[$field]['amount'],
$veh[$field]['rate'],
$description
);
}
}
// 根据里程处理新车或二手车价格
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
if (!empty($veh['listing_price']['amount'])) {
$item->addMoney(
'listing_price',
$veh['listing_price']['currency'],
$veh['listing_price']['amount'],
$veh['listing_price']['rate'],
'二手挂牌价'
);
}
if (!empty($veh['reduction_price']['amount'])) {
$item->addMoney(
'reduction_price',
$veh['reduction_price']['currency'],
$veh['reduction_price']['amount'],
$veh['reduction_price']['rate'],
'二手减价'
);
}
} else {
// 新车
if (!empty($veh['official_price']['amount'])) {
$item->addMoney(
'official_price',
$veh['official_price']['currency'],
$veh['official_price']['amount'],
$veh['official_price']['rate'],
'官方指导价'
);
}
if (!empty($veh['discount_price']['amount'])) {
$item->addMoney(
'discount_price',
$veh['discount_price']['currency'],
$veh['discount_price']['amount'],
$veh['discount_price']['rate'],
'优惠价'
);
}
}
}
/**
* 计算利润
*/
private function calculateProfit(array $veh, $order): float
{
$unitPrice = (float)($veh['unit_price']['amount'] ?? 0);
if (!empty($veh['mileage']) && $veh['mileage'] > 0) {
// 二手车
$ttPrice = ($veh['listing_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['reduction_price']['amount'] ?? 0;
} else {
// 新车
$ttPrice = ($veh['official_price']['amount'] ?? 0) / ($order->contract_exchange_rate ?: 1);
$ddPrice = $veh['discount_price']['amount'] ?? 0;
}
$handlingFee = (float)($veh['handling_fee']['amount'] ?? 0);
$fobTransportFee = (float)($veh['fob_transport_fee']['amount'] ?? 0);
$portMiscFee = (float)($veh['port_misc_fee']['amount'] ?? 0);
$retrofitFee = (float)($veh['retrofit_fee']['amount'] ?? 0);
$oceanFreight = (float)($veh['ocean_freight']['amount'] ?? 0);
return $unitPrice - $ttPrice - $ddPrice - $handlingFee - $fobTransportFee - $portMiscFee - $retrofitFee - $oceanFreight;
}
/**
* 处理改装项
*/
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);
}
}
}
@@ -0,0 +1,435 @@
<?php
namespace app\common\service;
use app\common\model\StockOrderAccounts;
use app\common\model\StockOrderItemOptions;
use app\common\model\StockOrderItems;
use app\common\validate\StockOrdersValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\StockOrders;
use app\common\model\SysCurrency;
use support\Request;
use app\common\model\User;
use support\Db;
class StockOrdersService_bak
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = StockOrders::class;
/**
* 验证器
*/
protected $validator = StockOrdersValidate::class;
/**
* 获取验证器
*/
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':
// ====== ====== 筛选 ====== ======
// 业务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['dataLimit']['type'] = 'relation';
// $config['dataLimit']['userId'] = $request->user->uid;
// $config['dataLimit']['userField'] = 'salesperson_id';
break;
case 'print':
$config['where']['id'] = $p['id'];
break;
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';
break;
case 'store':
break;
case 'update':
$config['where']['id'] = $p['id'];
break;
case 'destroy':
$config['where']['id'] = $p['id'];
break;
}
return $config;
}
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); // 表1
// 车辆
$cifTotalAmount = 0;
$cifTotalAmountRate = 0;
$cifTotalAmountCurrency = 'CNY';
// $profit = 0;
foreach ($data['veh_list'] as $veh) {
$veh['order_id'] = $created->id;
// 唯一标识
$uniqueIdStr = "";
$uniqueIdStr .= $veh['sku_id'];
$uniqueIdStr .= $veh['model_snapshot'];
$uniqueIdStr .= $veh['color_interior_code'];
$uniqueIdStr .= $veh['color_exterior_code'];
$uniqueIdStr .= $veh['mileage'];
$uniqueIdStr .= json($veh['modify_list']);
$veh['unique_id'] = md5($uniqueIdStr);
$item = StockOrderItems::create($veh); // 表2
// 金额 // 表3
// $item->addMoney('official_price', $veh['official_price']['currency'], $veh['official_price']['amount'], $veh['official_price']['rate'], '官方指导价');
// $item->addMoney('discount_price', $veh['discount_price']['currency'], $veh['discount_price']['amount'], $veh['discount_price']['rate'], '优惠价');
if ($veh['unit_price']['amount']) {
$item->addMoney('unit_price', $veh['unit_price']['currency'], $veh['unit_price']['amount'], $veh['unit_price']['rate'], '单价');
}
if ($veh['total_price']['amount']) {
$item->addMoney('total_price', $veh['total_price']['currency'], $veh['total_price']['amount'], $veh['total_price']['rate'], '总价');
}
if ($veh['handling_fee']['amount']) {
$item->addMoney('handling_fee', $veh['handling_fee']['currency'], $veh['handling_fee']['amount'], $veh['handling_fee']['rate'], '手续费');
}
if ($veh['fob_transport_fee']['amount']) {
$item->addMoney('fob_transport_fee', $veh['fob_transport_fee']['currency'], $veh['fob_transport_fee']['amount'], $veh['fob_transport_fee']['rate'], 'FOB运输费');
}
if ($veh['port_misc_fee']['amount']) {
$item->addMoney('port_misc_fee', $veh['port_misc_fee']['currency'], $veh['port_misc_fee']['amount'], $veh['port_misc_fee']['rate'], '港杂');
}
if ($veh['retrofit_fee']['amount']) {
$item->addMoney('retrofit_fee', $veh['retrofit_fee']['currency'], $veh['retrofit_fee']['amount'], $veh['retrofit_fee']['rate'], '改装费');
}
// 二手车 or 新车
if ($veh['mileage'] > 0) {
if ($veh['listing_price']['amount']) {
$item->addMoney('listing_price', $veh['listing_price']['currency'], $veh['listing_price']['amount'], $veh['listing_price']['rate'], '二手挂牌价');
}
if ($veh['reduction_price']['amount']) {
$item->addMoney('reduction_price', $veh['reduction_price']['currency'], $veh['reduction_price']['amount'], $veh['reduction_price']['rate'], '二手减价');
}
$ttPrice = ($veh['listing_price']['amount'] / $created->contract_exchange_rate);
$ddPrice = $veh['reduction_price']['amount'];
} else {
if ($veh['official_price']['amount']) {
$item->addMoney('official_price', $veh['official_price']['currency'], $veh['official_price']['amount'], $veh['official_price']['rate'], '官方指导价');
}
if ($veh['discount_price']['amount'] ) {
$item->addMoney('discount_price', $veh['discount_price']['currency'], $veh['discount_price']['amount'], $veh['discount_price']['rate'], '优惠价');
}
$ttPrice = ($veh['official_price']['amount'] / $created->contract_exchange_rate);
$ddPrice = $veh['discount_price']['amount'];
}
// 利润
$profit = (float)$veh['unit_price']['amount'] - (float)$ttPrice - (float)$ddPrice - (float)$veh['handling_fee']['amount'] - (float)$veh['fob_transport_fee']['amount'] - (float)$veh['port_misc_fee']['amount'] - (float)$veh['retrofit_fee']['amount'];
$item->addMoney('profit', $veh['unit_price']['currency'], $profit, $veh['unit_price']['rate'], '利润');
// cif_total_amount
$cifTotalAmount += $veh['total_price']['amount'];
$cifTotalAmountRate = $veh['retrofit_fee']['rate'];
$cifTotalAmountCurrency = $veh['retrofit_fee']['currency'];
// 改装
if (count($veh['modify_list']) > 0) {
foreach ($veh['modify_list'] as $modify) {
$modify['order_item_id'] = $item->id;
StockOrderItemOptions::create($modify); // 表4
}
}
}
// 计算&&插入 表1
$created->addMoney('cif_total_amount', $cifTotalAmountCurrency, $cifTotalAmount, $cifTotalAmountRate, '合计到岸价');
// 账户
if (count($data['account_list']) > 0) {
foreach ($data['account_list'] as $account) {
$account['order_id'] = $created->id;
$account['remit_date'] = strtotime($account['remit_date']);
StockOrderAccounts::create($account); // 表5
}
}
return $this->postProcess('Store', $created);
});
}
public function beforeServiceStore($data, Request $request)
{
$userId = $request->user->uid;
$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') ?? '';
return $data;
}
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.'】创建终版成功,但更新原单失败');
}
}
// 启动审批
$appro = new \app\common\utils\approval\service\ApprovalFlowService();
$result = $appro->start('stock_orders', 'stock_orders', $res->id, $res->toArray(), $res->salesperson_id);
var_dump($result);
// 异步生成pdf文件
\Webman\RedisQueue\Redis::send('stock-order-pdf', ['id'=>$res->id]);
return $res;
}
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->pdfData($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
);
// // 在线预览
// return new \support\Response(200, [
// 'Content-Type' => 'application/pdf',
// 'Content-Disposition' => 'inline; filename="stock-order.pdf"',
// ], $pdfBin);
// $url = [
// 'file_name' => $fileName,
// 'file_url' => getenv('MAIN_DOMAIN').'/pdf/'.$fileName
// ];
// 上传云端
$param = [
'path' => $dir . $fileName,
'scene' => 'stock_orders',
'category' => 'pdf',
'original_name' => $fileName
];
$up = new UploadService();
$res = $up->uploadLocalFile($param);
@unlink($dir . $fileName);
// 更新文件地址
$item->file_url = $res['file_name'];
$item->save();
return $res;
}
public function servicePrint(Request $request)
{
$config = $this->buildQueryConfig($request, 'show');
$item = $this->logicShow($config);
return $this->postProcess('Print', $item);
}
public function pdfData($item)
{
$vehList = [];
$index = 0;
foreach ($item->items as $k => $v) {
// 存在则数量加1
if (count($vehList) > 0 && isset($vehList[$v->unique_id])) {
$vehList[$v->unique_id]['num'] += 1;
$vehList[$v->unique_id]['total_price'] += $vehList[$v->unique_id]['unit_price'];
$vehList[$v->unique_id]['total_price_text'] = $vehList[$v->unique_id]['total_price_symbol'].number_format($vehList[$v->unique_id]['total_price'], 2, '.', ',');
continue;
}
$index += 1;
// 处理金额
$mv = [];
foreach ($v->moneyValues as $money) {
$mv[$money->field] = [
'currency' => $money->currency,
'amount' => $money->amount,
'rate' => $money->exchange_rate,
'currency_symbol' => SysCurrency::where('currency_code', $money->currency)->value('currency_symbol'),
];
}
// 处理改装
$mfy = '';
foreach ($v->options as $my) {
$mfy .= $my->option_name_snapshot.' ';
}
// 处理结果集
$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,
'modify' => $mfy,
'mileage' => $v->mileage,
'unit_price' => $mv['unit_price']['amount'],
'total_price' => $mv['total_price']['amount'],
'unit_price_symbol' => $mv['unit_price']['currency_symbol'],
'total_price_symbol' => $mv['total_price']['currency_symbol'],
'unit_price_text' => $mv['unit_price']['currency_symbol'].number_format($mv['unit_price']['amount'], 2, '.', ','),
'total_price_text' => $mv['total_price']['currency_symbol'].number_format($mv['total_price']['amount'], 2, '.', ',')
];
// 根据里程处理 新车or二手车
if ($v->mileage > 0) {
if (isset($mv['reduction_price'])) {
$vehList[$v->unique_id]['reduction_price'] = $mv['reduction_price']['amount'];
$vehList[$v->unique_id]['reduction_price_symbol'] = $mv['reduction_price']['currency_symbol'];
$vehList[$v->unique_id]['reduction_price_text'] = $mv['reduction_price']['currency_symbol'].number_format($mv['reduction_price']['amount'], 2, '.', ',');
}
$vehList[$v->unique_id]['listing_price'] = $mv['listing_price']['amount'];
$vehList[$v->unique_id]['listing_price_symbol'] = $mv['listing_price']['currency_symbol'];
$vehList[$v->unique_id]['listing_price_text'] = $mv['listing_price']['currency_symbol'].number_format($mv['listing_price']['amount'], 2, '.', ',');
} else {
if (isset($mv['discount_price'])) {
$vehList[$v->unique_id]['discount_price'] = $mv['discount_price']['amount'];
$vehList[$v->unique_id]['discount_price_symbol'] = $mv['discount_price']['currency_symbol'];
$vehList[$v->unique_id]['discount_price_text'] = $mv['discount_price']['currency_symbol'].number_format($mv['discount_price']['amount'], 2, '.', ',');
}
$vehList[$v->unique_id]['official_price'] = $mv['official_price']['amount'];
$vehList[$v->unique_id]['official_price_symbol'] = $mv['official_price']['currency_symbol'];
$vehList[$v->unique_id]['official_price_text'] = $mv['official_price']['currency_symbol'].number_format($mv['official_price']['amount'], 2, '.', ',');
}
}
$accList = [];
$accIndex = 1;
foreach ($item->accounts as $k => $v) {
$accList[] = [
'index' => '收款'.$k + 1,
'remit_country_name_snapshot' => $v->remit_country_name_snapshot,
'remit_date' => date('Y-m-d', $v->remit_date),
'currency_name_snapshot' => $v->currency_name_snapshot,
'account_name_snapshot' => $v->account_name_snapshot,
'remitter_name' => $v->remitter_name,
'amount' => $v->amount,
];
$accIndex += 1;
}
$cifTotalAmount = 0.00;
if ($item->moneyValues) {
$cifTotalAmountSysboml = SysCurrency::where('currency_code', $item->moneyValues->currency)->value('currency_symbol');
$cifTotalAmount = $cifTotalAmountSysboml.sprintf("%.2f", $item->moneyValues->amount, $item->moneyValues->exchange_rate);
}
$veh = [
'order_no' => $item->order_no,
'salesperson_snapshot' => $item->salesperson_snapshot,
// 'sign_img' => $item->salesperson->sign_img,
'sign_img_url' => (!empty($item->salesperson->sign_img))?(new \app\common\service\OssService)->generatePrivateUrl($item->salesperson->sign_img):'',
'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' => $vehList,
'contract_exchange_rate' => $item->contract_exchange_rate,
'cif_total_amount' => $item->cif_total_amount,
'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),
// 账户
'account_list' => $accList,
'acc_index' => $accIndex,
'cif_total_amount' => $cifTotalAmount
];
return $veh;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace app\common\service;
use app\admin\validate\SysAccountValidate;
use app\common\logic\SysAccountLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\SysAccount;
use support\Request;
class SysAccountService
{
protected $logic;
public function __construct()
{
$this->logic = (new SysAccountLogic());
}
/**
* 获取系统list
*/
public function getList()
{
return $this->logic->getList();
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace app\common\service;
use app\common\logic\SysCurrencyLogic;
use app\common\logic\SystemsLogic;
class SysCurrencyService
{
protected $logic;
public function __construct()
{
$this->logic = (new SysCurrencyLogic());
}
/**
* 获取系统list
*/
public function getList()
{
return $this->logic->getList();
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace app\common\service;
use app\admin\validate\SysDictItemValidate;
use app\common\logic\SysDictItemLogic;
use app\common\logic\SysDictLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\SysDictItem;
use support\exception\BusinessException;
use support\Request;
class SysDictItemService
{
protected $logic;
public function __construct()
{
$this->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);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace app\common\service;
use app\admin\validate\SysDictValidate;
use app\common\logic\SysDictLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\SysDict;
use support\Request;
class SysDictService
{
protected $logic;
public function __construct()
{
$this->logic = (new SysDictLogic());
}
/**
* 获取系统list
*/
public function getList()
{
return $this->logic->getList();
}
public static function pluckValuesByCode(string $dictCode): \Illuminate\Support\Collection
{
return SysDict::where('dict_code', $dictCode)
->where('status', 1)
->first()?->items()
->where('status', 1)
->orderBy('sort')
->pluck('item_value') ?? collect();
}
public static function pluckKeyValueByCode(string $dictCode): \Illuminate\Support\Collection
{
return SysDict::where('dict_code', $dictCode)
->where('status', 1)
->first()?->items()
->where('status', 1)
->orderBy('sort')
->pluck('item_value', 'item_label') ?? collect();
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace app\common\service;
use app\admin\validate\SysPortValidate;
use app\common\logic\SysPortLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\SysPort;
use support\Request;
class SysPortService
{
protected $logic;
public function __construct()
{
$this->logic = (new SysPortLogic());
}
/**
* 获取系统list
*/
public function getList($params)
{
$where = [];
if(isset($params['scene']) && $params['scene']) {
if($params['scene'] == 'domestic'){
$where['country_id'] = 45;
}else{
$where['country_id'] = ['<>', 45];
}
}
return $this->logic->getList($where);
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
namespace app\common\service;
use support\exception\BusinessException;
use support\Log;
use support\Request;
class UploadService
{
/**
* 从服务器本地路径上传文件到 OSS
*
* @param Request $request
* - path: 本地文件绝对路径
* - scene: 业务分区/场景
* - category: 文件分类(可选)
* - original_name: 原始文件名(可选)
*/
public function uploadLocalFile($param)
{
try {
$filePath = $param['path'];
$scene = $param['scene'];
$category = $param['category']??'general';
$providedOriginalName = $param['original_name']??'';
if (empty($filePath)) {
Log::error('本地文件路径不能为空',$param);
throw new BusinessException('本地文件路径不能为空');
}
if (!file_exists($filePath) || !is_readable($filePath)) {
Log::error('本地文件不存在或不可读',$param);
throw new BusinessException('本地文件不存在或不可读');
}
if (empty($scene)) {
Log::error('上传场景不能为空',$param);
throw new BusinessException('上传场景不能为空');
}
$basename = basename($filePath);
$originalName = $providedOriginalName ?: $basename;
$extensionFromName = pathinfo($originalName, PATHINFO_EXTENSION);
$extensionFromPath = pathinfo($basename, PATHINFO_EXTENSION);
$extension = $extensionFromName ?: $extensionFromPath;
$mime = mime_content_type($filePath) ?: 'application/octet-stream';
$size = filesize($filePath) ?: 0;
$sceneUrl = $scene ? ($scene . '/') : '';
$dir = 'x_server/' . $sceneUrl . date('Ymd') . '/';
// 使用传入的 original_name 命名(缺少扩展名时补上推断的扩展名),并做简单安全处理
$safeBaseName = preg_replace('/[\\\\\/]+/', '_', $originalName);
if ($extension && strtolower(pathinfo($safeBaseName, PATHINFO_EXTENSION)) !== strtolower($extension)) {
// 若提供的名称没有扩展名或扩展名不一致,则以推断扩展名为准
$safeBaseName = pathinfo($safeBaseName, PATHINFO_FILENAME) . '.' . $extension;
} elseif (!$extension && !pathinfo($safeBaseName, PATHINFO_EXTENSION)) {
// 实在没有扩展名信息时,保持原名
}
// 重名检测:同一目录、同名且同类型则在文件名后追加序号
$uploadedFilesService = new UploadedFilesService();
$candidateName = $safeBaseName;
$nameBody = pathinfo($safeBaseName, PATHINFO_FILENAME);
$nameExt = pathinfo($safeBaseName, PATHINFO_EXTENSION);
$counter = 1;
while (true) {
$candidatePath = $dir . $candidateName;
$existing = $uploadedFilesService->findFile(['file_path' => $candidatePath]);
if (!$existing) {
break;
}
// 若存在同路径同名,且类型也相同,则追加序号
if (isset($existing->file_type) && strtolower($existing->file_type) === strtolower($mime)) {
$suffix = ' (' . $counter . ')';
$candidateName = $nameBody . $suffix . ($nameExt !== '' ? ('.' . $nameExt) : '');
$counter++;
continue;
}
// 类型不同则允许同名,结束循环
break;
}
$objectKey = $dir . $candidateName;
$ossService = new OssService();
$ossService->uploadImage($filePath, $objectKey);
$privateUrl = $ossService->generatePrivateUrl($objectKey);
// 记录文件信息到数据库
$uploadedFilesService = new UploadedFilesService();
$fileInfo = [
'file_name' => basename($objectKey),
'file_path' => $objectKey,
'file_size' => $size,
'file_type' => $mime,
'original_name' => $originalName,
];
$recordResult = $uploadedFilesService->recordFileInfo($fileInfo, null, $scene, $category);
$data = [
'original_name' => $originalName,
'file_name' => $objectKey,
'file_url' => $privateUrl,
'file_id' => $recordResult['id'] ?? null,
'partition' => $scene,
'category' => $category,
];
return $data;
} catch (\Throwable $e) {
Log::error($e->getMessage(),$param);
throw new BusinessException($e->getMessage());
}
}
/**
* 删除 OSS 上的文件
*
* @param array $param
* - object_key: OSS 对象键名-oss路径(必需)
* - file_id: 数据库文件记录ID(可选,用于删除数据库记录)
* @return bool 删除是否成功
*
* 示例
* $uploadService = new UploadService();
*
* 只删除 OSS 文件
* $uploadService->deleteOssFile([
* 'object_key' => 'vehicle_album/documents/20241201/abc123.pdf'
* ]);
*
* 同时删除 OSS 文件和数据库记录
* $uploadService->deleteOssFile([
* 'object_key' => 'vehicle_album/images/20241201/abc123.jpg',
* 'file_id' => 123
* ]);
*/
public function deleteOssFile($objectKey,$fileId = null)
{
try {
if (empty($objectKey)) {
Log::error('OSS对象键名不能为空', $objectKey);
throw new BusinessException('OSS对象键名不能为空');
}
$uploadedFilesService = new UploadedFilesService();
// 如果提供了文件ID,同时删除数据库记录
if ($fileId) {
$uploadedFilesService->deleteFile($fileId);
}else{
$uploadedFilesService = new UploadedFilesService();
if (empty($fileId)) {
$where = ['file_path' => $objectKey];
$file = $uploadedFilesService->getFile($where);
$fileId = $file->id;
}
if(!empty($fileId)){
$uploadedFilesService->deleteFile($fileId);
}
}
// 删除 OSS 上的文件
$ossService = new OssService();
$ossService->deleteFile($objectKey);
Log::info('OSS文件删除成功', ['object_key' => $objectKey, 'file_id' => $fileId]);
return true;
} catch (\Throwable $e) {
Log::error('删除OSS文件失败: ' . $e->getMessage());
throw new BusinessException('删除OSS文件失败: ' . $e->getMessage());
}
}
}
+238
View File
@@ -0,0 +1,238 @@
<?php
namespace app\common\service;
use app\common\validate\UploadedFilesValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\UploadedFiles;
use support\Request;
use support\exception\BusinessException;
class UploadedFilesService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = UploadedFiles::class;
/**
* 文件上传分区配置
*/
protected array $uploadPartitions = [
'image' => [
'path' => 'images',
'max_size' => 5 * 1024 * 1024, // 5MB
'allowed_types' => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
'extensions' => ['jpg', 'jpeg', 'png', 'gif', 'webp']
],
'document' => [
'path' => 'documents',
'max_size' => 10 * 1024 * 1024, // 10MB
'allowed_types' => ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
'extensions' => ['pdf', 'doc', 'docx']
],
'audio' => [
'path' => 'audios',
'max_size' => 20 * 1024 * 1024, // 20MB
'allowed_types' => ['audio/mp3', 'audio/wav', 'audio/ogg'],
'extensions' => ['mp3', 'wav', 'ogg']
],
'other' => [
'path' => 'others',
'max_size' => 5 * 1024 * 1024, // 5MB
'allowed_types' => [],
'extensions' => []
]
];
/**
* 记录文件信息到数据库
*
* @param array $fileInfo 文件信息
* @param Request|null $request 请求对象(可选)
* @param string $partition 分区名称
* @param string $category 文件分类
* @return array
* @throws BusinessException
*/
public function recordFileInfo(array $fileInfo, ?Request $request = null, string $partition = 'other', string $category = 'general'): array
{
// 验证必需的文件信息
$requiredFields = ['file_name', 'file_path', 'file_size', 'file_type'];
foreach ($requiredFields as $field) {
if (!isset($fileInfo[$field])) {
throw new BusinessException("缺少必需的文件信息字段: {$field}");
}
}
// 获取文件扩展名
$fileExtension = pathinfo($fileInfo['file_name'], PATHINFO_EXTENSION);
// 记录到数据库
$uploadIp = $request ? $request->getRealIp() : '0.0.0.0';
$userAgent = $request ? $request->header('User-Agent', '') : '';
$fileData = [
'file_name' => $fileInfo['file_name'],
'file_path' => $fileInfo['file_path'],
'file_size' => $fileInfo['file_size'],
'file_type' => $fileInfo['file_type'],
'category' => $category,
'original_name' => $fileInfo['original_name'] ?? '',
'extension' => $fileExtension,
'partition' => $partition,
'upload_ip' => $uploadIp,
'user_agent' => $userAgent,
];
$uploadedFile = $this->logicCreate($fileData);
return [
'id' => $uploadedFile->id,
'file_name' => $fileInfo['file_name'],
'file_path' => $fileInfo['file_path'],
'file_url' => getenv('MAIN_DOMAIN') . $fileInfo['file_path'],
'file_size' => $fileInfo['file_size'],
'file_type' => $fileInfo['file_type'],
'category' => $category,
'partition' => $partition,
'original_name' => $fileInfo['original_name'] ?? '',
'extension' => $fileExtension,
];
}
/**
* 获取文件信息
*
* @param int $fileId
* @return array|null
*/
public function getFileInfo(int $fileId): ?array
{
$file = $this->logicShow(['where' => ['id' => $fileId]]);
if (!$file) {
return null;
}
return [
'id' => $file->id,
'file_name' => $file->file_name,
'file_path' => $file->file_path,
'file_url' => getenv('MAIN_DOMAIN') . $file->file_path,
'file_size' => $file->file_size,
'file_type' => $file->file_type,
'category' => $file->category,
'partition' => $file->partition ?? 'other',
'original_name' => $file->original_name ?? '',
'extension' => $file->extension ?? '',
'created_at' => $file->created_at,
];
}
/**
* 获取文件
*
* @param string $path
* @return bool|\Illuminate\Database\Eloquent\Model
*/
public function getFile(array $where)
{
$config['model'] = $this->modelClass;
$config['where'] = $where;
$file = $this->logicShow($config);
if (!$file) {
return false;
}
return $file;
}
/**
* 获取文件
*
* @param string $path
* @return bool|\Illuminate\Database\Eloquent\Model
*/
public function findFile(array $where)
{
$file = UploadedFiles::where(['file_path' => $where['file_path']]);
if (!$file) {
return false;
}
return $file;
}
/**
* 删除文件
*
* @param int $fileId
* @return bool
*/
public function deleteFile(int $fileId): bool
{
$config['model'] = $this->modelClass;
$config['where'] = ['id' => $fileId];
$file = $this->logicShow($config);
if (!$file) {
return false;
}
// 删除数据库记录
$config =[
'model' => $this->modelClass,
'where' => ['id' => $fileId],
];
return $this->logicDeleteBy($config);
}
/**
* 获取分区配置
*
* @return array
*/
public function getPartitionConfig(): array
{
return $this->uploadPartitions;
}
/**
* 生成文件名
*
* @param $file
* @return string
*/
protected function generateFileName($file): string
{
$extension = $file->getUploadExtension();
$timestamp = time();
$random = substr(md5(uniqid()), 0, 8);
return $timestamp . '_' . $random . '.' . $extension;
}
/**
* 格式化文件大小
*
* @param int $bytes
* @return string
*/
protected function formatFileSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
}
+6 -1
View File
@@ -52,6 +52,9 @@ class UserService
'sn' => $user->sn,
'corp_id' => $user->corp_id,
'corp_name' => $corp_name,
'report_to' => $user->report_to,
'sign_img' => $user->sign_img,
'sign_img_url' => (!empty($user->sign_img))?(new \app\common\service\OssService)->generatePrivateUrl($user->sign_img):'',
],
// 'menu' => $menuTree,
// 'permissions' => $permissionCodes
@@ -84,7 +87,9 @@ class UserService
'email' => $user->email,
'sex' => $user->sex,
'status' => $user->status,
'roles' => $user->roles->pluck('name')
'roles' => $user->roles->pluck('name'),
'sign_img' => $user->sign_img,
'sign_img_url' => (!empty($user->sign_img))?$ossservice->generatePrivateUrl($user->sign_img):'',
];
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace app\common\service;
use app\admin\validate\VehColorValidate;
use app\common\logic\VehColorLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehColor;
use support\exception\BusinessException;
class VehColorService
{
protected $logic;
public function __construct()
{
$this->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);
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace app\common\service;
use app\common\validate\VehDictI18nValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehDictI18n;
class VehDictI18nService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehDictI18n::class;
/**
* 验证器
*/
protected $validator = VehDictI18nValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->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}");
}
}
@@ -0,0 +1,57 @@
<?php
namespace app\common\service;
use app\common\validate\VehDictMappingValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehDictMapping;
class VehDictMappingService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehDictMapping::class;
/**
* 验证器
*/
protected $validator = VehDictMappingValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->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]);
}
}
@@ -0,0 +1,28 @@
<?php
namespace app\common\service;
use app\admin\validate\VehModificationValidate;
use app\common\logic\VehModificationLogic;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehModification;
use support\Request;
class VehModificationService
{
protected $logic;
public function __construct()
{
$this->logic = (new VehModificationLogic());
}
/**
* 获取系统list
*/
public function getList()
{
return $this->logic->getList();
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\VehMoneyValueValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehMoneyValue;
class VehMoneyValueService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehMoneyValue::class;
/**
* 验证器
*/
protected $validator = VehMoneyValueValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\VehVehicleListingValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehVehicleListing;
class VehVehicleListingService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehVehicleListing::class;
/**
* 验证器
*/
protected $validator = VehVehicleListingValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}
+164
View File
@@ -0,0 +1,164 @@
<?php
namespace app\common\service;
use app\common\logic\Fingerprint;
use app\common\logic\ModelNaming;
use app\common\logic\SkuCodeBuilder;
use app\common\validate\VehVehicleSkuValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehVehicleSku;
use support\Request;
class VehVehicleSkuService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehVehicleSku::class;
/**
* 验证器
*/
protected $validator = VehVehicleSkuValidate::class;
/**
* 获取验证器
*/
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';
break;
case 'index':
$config['where']['is_active'] = 1;
$config['order']['id'] = 'desc';
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);
}
$data['sku_code'] = SkuCodeBuilder::build($data);
$data['corp_id'] = 0;
$data['created_by'] = $request->user->uid;
$data['updated_by'] = $request->user->uid;
// 指纹
$data['fingerprint'] = Fingerprint::makeFromArray($data);
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;
// 指纹
$data['fingerprint'] = Fingerprint::makeFromArray($data);
return $data;
}
protected function afterServiceUpdate($res)
{
return $res;
}
}
@@ -0,0 +1,31 @@
<?php
namespace app\common\service;
use app\common\validate\VehVehicleUnitValidate;
use app\common\traits\crud\CrudServiceTrait;
use app\common\model\VehVehicleUnit;
class VehVehicleUnitService
{
use CrudServiceTrait;
/**
* 指定当前要操作的模型
*/
protected string $modelClass = VehVehicleUnit::class;
/**
* 验证器
*/
protected $validator = VehVehicleUnitValidate::class;
/**
* 获取验证器
*/
public function getValidator()
{
return new $this->validator;
}
}