文件
yjyf/server/application/admin/controller/Service.php
MiAn 0370cb9bd6 feat: 新增师傅入驻审核与接单状态联动功能
- 新增师傅资质审核模块及权限
- 未审核通过的师傅默认禁用接单状态
- 新增售后退款申诉功能与相关界面
- 新增用户钱包管理及充值功能
- 更新服务定价矩阵相关数据库结构
- 修复微信支付证书验证问题
2026-11-17 10:28:01 +08:00

870 行
36 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
/**
* 商品管理(商品仅定义施工标的物与细分规格,服务价格统一配置在关联的主服务与增项服务上)
*
* @icon fa fa-cubes
*/
class Service extends Backend
{
/**
* Service模型对象
* @var \app\admin\model\Service
*/
protected $model = null;
protected $relationSearch = true;
protected $searchFields = 'id,name,desc,cat.name';
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Service;
$this->view->assign("statusList", $this->model->getStatusList());
// 获取统一服务字典表(fa_service_type,不绑定单一类目,主服务与增项服务同源)
$typesPool = Db::name('service_type')
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
$this->view->assign("typesPool", $typesPool);
}
public function index()
{
$this->request->filter(['strip_tags', 'trim']);
if (false === $this->request->isAjax()) {
$cats = Db::name('service_cat')
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
$this->view->assign('catList', $cats);
$catSearchList = [];
foreach ($cats as $c) {
$catSearchList[$c['id']] = $c['name'];
}
$this->view->assign('catSearchList', json_encode($catSearchList, JSON_UNESCAPED_UNICODE));
// 统计核心运营维度指标(明码标价体系,聚焦规格覆盖、增项覆盖与上下架状态)
$stats = [
'total' => (int)Db::name('service')->count(),
'normal' => (int)Db::name('service')->where('status', 'normal')->count(),
'has_spec' => (int)Db::name('service')->whereIn('id', function ($q) {
$q->name('service_spec')->where('status', 'normal')->field('service_id');
})->count(),
'has_addon' => (int)Db::name('service')->where('addons', '<>', '[]')->whereNotNull('addons')->where('addons', '<>', '')->count(),
'hidden' => (int)Db::name('service')->where('status', 'hidden')->count(),
];
$this->view->assign('stats', $stats);
return $this->view->fetch();
}
if ($this->request->request('keyField')) {
return $this->selectpage();
}
[$where, $sort, $order, $offset, $limit] = $this->buildparams();
$query = $this->model->with(['cat'])->where($where);
// 1. 扩展工项支持筛选(如 install/repair/remove 等)
$workCode = trim((string)$this->request->get('work_code', ''));
if ($workCode !== '') {
$query->where('service.service_types', 'like', '%"code":"' . addslashes($workCode) . '"%');
}
// 2. 计价模式筛选(fixed 一口价 / quote 师傅报价)
$priceType = trim((string)$this->request->get('price_type', ''));
if ($priceType !== '') {
$query->where('service.price_type', $priceType);
}
// 2. 细分规格配置状态筛选
$hasSpec = (string)$this->request->get('has_spec', '');
if ($hasSpec === '1') {
$query->whereIn('service.id', function ($q) {
$q->name('service_spec')->where('status', 'normal')->field('service_id');
});
} elseif ($hasSpec === '0') {
$query->whereNotIn('service.id', function ($q) {
$q->name('service_spec')->where('status', 'normal')->field('service_id');
});
}
// 3. 增值服务配置状态筛选
$hasAddon = (string)$this->request->get('has_addon', '');
if ($hasAddon === '1') {
$query->where('service.addons', '<>', '[]')->whereNotNull('service.addons')->where('service.addons', '<>', '');
} elseif ($hasAddon === '0') {
$query->where(function ($q) {
$q->whereNull('service.addons')->whereOr('service.addons', '[]')->whereOr('service.addons', '');
});
}
$list = $query->order($sort, $order)->paginate($limit);
$rows = $list->items();
if (!empty($rows)) {
$serviceIds = [];
foreach ($rows as $r) {
$serviceIds[] = (int)$r['id'];
}
// 一次性批量查询当前页商品的细分规格,避免 N+1 查询
$allSpecs = Db::name('service_spec')
->field('id,service_id,name,base_price,service_prices,description')
->where('service_id', 'in', $serviceIds)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
$specMap = [];
foreach ($allSpecs as $sp) {
$sid = (int)$sp['service_id'];
if (!isset($specMap[$sid])) {
$specMap[$sid] = [];
}
$pricesMap = !empty($sp['service_prices']) ? (json_decode($sp['service_prices'], true) ?: []) : [];
$spPrice = (float)$sp['base_price'];
if (!empty($pricesMap)) {
$priceTips = [];
foreach ($pricesMap as $pCode => $pVal) {
$priceTips[] = $pCode . ':¥' . round($pVal);
}
$specMap[$sid][] = $sp['name'] . ' (' . implode(',', $priceTips) . ')';
} elseif ($spPrice > 0) {
$specMap[$sid][] = $sp['name'] . '(¥' . round($spPrice) . ')';
} else {
$specMap[$sid][] = $sp['name'];
}
}
foreach ($rows as &$r) {
$sid = (int)$r['id'];
$r['specs_list'] = isset($specMap[$sid]) ? $specMap[$sid] : [];
// 直接在服务端解析为数组返回,防止前端 bootstrap-table escape:true 将 JSON 双引号转义为 &quot; 导致解析失败
$stArr = [];
if (!empty($r['service_types'])) {
$stArr = is_array($r['service_types']) ? $r['service_types'] : (json_decode($r['service_types'], true) ?: []);
}
$adArr = [];
if (!empty($r['addons'])) {
$adArr = is_array($r['addons']) ? $r['addons'] : (json_decode($r['addons'], true) ?: []);
}
$r['service_types_list'] = $stArr;
$r['addons_list'] = $adArr;
}
unset($r);
}
$result = ['total' => $list->total(), 'rows' => $rows];
return json($result);
}
/**
* 添加商品并配置关联服务定价
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$params = $this->formatServiceConfig($params);
$result = false;
Db::startTrans();
try {
$result = $this->model->allowField(true)->save($params);
$serviceId = $this->model->id;
// 处理商品规格列表
$this->syncSpecs($serviceId, $this->request->post('specs/a', []));
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 独立弹窗:配置主服务工项及基准价格与规格专属价格
*/
public function pricing_main($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if ($this->request->isPost()) {
$serviceTypesRaw = $this->request->post("service_types_raw");
$specPricesInput = $this->request->post("spec_prices/a", []);
$parsedTypes = [];
if ($serviceTypesRaw) {
$parsedTypes = is_string($serviceTypesRaw) ? (json_decode($serviceTypesRaw, true) ?: []) : $serviceTypesRaw;
}
if (empty($parsedTypes)) {
$this->error('请至少开启 1 项主服务工项');
}
$dictSupportMap = Db::name('service_type')->column('support_fixed', 'code');
$hasDefault = false;
foreach ($parsedTypes as &$pt) {
$code = isset($pt['code']) ? (string)$pt['code'] : '';
$supportFixed = isset($dictSupportMap[$code])
? (int)$dictSupportMap[$code]
: (isset($pt['support_fixed']) ? (int)$pt['support_fixed'] : 1);
$price = ($supportFixed === 1 && isset($pt['price'])) ? round((float)$pt['price'], 2) : 0.00;
$pt['price'] = $price;
$pt['support_fixed'] = $supportFixed;
if ($supportFixed === 1 && !empty($pt['is_default']) && !$hasDefault) {
$pt['is_default'] = 1;
$hasDefault = true;
} else {
$pt['is_default'] = 0;
}
}
unset($pt);
if (!$hasDefault && !empty($parsedTypes)) {
foreach ($parsedTypes as &$ptDef) {
if ((int)$ptDef['support_fixed'] === 1) {
$ptDef['is_default'] = 1;
$hasDefault = true;
break;
}
}
unset($ptDef);
if (!$hasDefault) {
$parsedTypes[0]['is_default'] = 1;
}
}
$defItem = $parsedTypes[0];
foreach ($parsedTypes as $pt) {
if (!empty($pt['is_default'])) {
$defItem = $pt;
break;
}
}
$supportFixed = isset($defItem['support_fixed']) ? (int)$defItem['support_fixed'] : 1;
$mainPrice = isset($defItem['price']) ? (float)$defItem['price'] : 0.00;
$priceType = ($supportFixed === 0 || $mainPrice <= 0) ? 'quote' : 'fixed';
Db::startTrans();
try {
// 更新商品主服务配置与基准价格
$row->save([
'service_types' => json_encode(array_values($parsedTypes), JSON_UNESCAPED_UNICODE),
'price_type' => $priceType,
'base_price' => $mainPrice,
'updatetime' => time(),
]);
// 更新各个细分规格的主服务专属定价字典
if (is_array($specPricesInput)) {
foreach ($specPricesInput as $specId => $pricesMap) {
$specId = (int)$specId;
if ($specId <= 0) continue;
$cleanPrices = [];
if (is_string($pricesMap)) {
$pricesMap = json_decode($pricesMap, true) ?: [];
}
if (is_array($pricesMap)) {
foreach ($pricesMap as $c => $v) {
$c = trim((string)$c);
$v = (float)$v;
if ($c !== '' && $v > 0) {
$cleanPrices[$c] = round($v, 2);
}
}
}
$servicePricesJson = !empty($cleanPrices) ? json_encode($cleanPrices, JSON_UNESCAPED_UNICODE) : null;
$specBasePrice = isset($cleanPrices[$defItem['code']]) ? $cleanPrices[$defItem['code']] : 0.00;
Db::name('service_spec')
->where('id', $specId)
->where('service_id', $row->id)
->update([
'service_prices' => $servicePricesJson,
'base_price' => $specBasePrice,
'updatetime' => time(),
]);
}
}
Db::commit();
$this->success('主服务定价配置保存成功');
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
}
$serviceTypes = [];
if (!empty($row->service_types)) {
$serviceTypes = is_array($row->service_types) ? $row->service_types : json_decode($row->service_types, true);
}
$specs = Db::name('service_spec')
->where('service_id', $row->id)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
foreach ($specs as &$sp) {
$sp['prices_map'] = !empty($sp['service_prices']) ? (json_decode($sp['service_prices'], true) ?: []) : [];
}
unset($sp);
$catName = Db::name('service_cat')->where('id', $row->cat_id)->value('name') ?: '未归类';
$this->view->assign([
'row' => $row,
'catName' => $catName,
'serviceTypes' => $serviceTypes ?: [],
'specs' => $specs ?: [],
]);
return $this->view->fetch();
}
/**
* 独立弹窗:配置增值服务工项及基准加价与规格专属加价
*/
public function pricing_addon($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if ($this->request->isPost()) {
$addonsRaw = $this->request->post("addons_raw");
$specAddonPricesInput = $this->request->post("spec_addon_prices/a", []);
$parsedAddons = [];
if ($addonsRaw) {
$parsedAddons = is_string($addonsRaw) ? (json_decode($addonsRaw, true) ?: []) : $addonsRaw;
}
$cleanAddons = [];
if (is_array($parsedAddons)) {
foreach ($parsedAddons as $idx => $ad) {
$adName = isset($ad['name']) ? trim((string)$ad['name']) : '';
$adPrice = isset($ad['price']) ? round((float)$ad['price'], 2) : 0.00;
if ($adName === '' || $adPrice <= 0) continue;
$cleanAddons[] = [
'id' => isset($ad['id']) ? (int)$ad['id'] : ($idx + 1),
'code' => isset($ad['code']) ? (string)$ad['code'] : ('addon_' . ($idx + 1)),
'name' => $adName,
'unit' => !empty($ad['unit']) ? (string)$ad['unit'] : '份',
'price' => $adPrice,
];
}
}
Db::startTrans();
try {
// 更新商品增值服务配置
$row->save([
'addons' => json_encode($cleanAddons, JSON_UNESCAPED_UNICODE),
'updatetime' => time(),
]);
// 更新各个细分规格的增值服务专属加价字典
if (is_array($specAddonPricesInput)) {
foreach ($specAddonPricesInput as $specId => $addonMap) {
$specId = (int)$specId;
if ($specId <= 0) continue;
$cleanAddonPrices = [];
if (is_string($addonMap)) {
$addonMap = json_decode($addonMap, true) ?: [];
}
if (is_array($addonMap)) {
foreach ($addonMap as $c => $v) {
$c = trim((string)$c);
$v = (float)$v;
if ($c !== '' && $v > 0) {
$cleanAddonPrices[$c] = round($v, 2);
}
}
}
$addonPricesJson = !empty($cleanAddonPrices) ? json_encode($cleanAddonPrices, JSON_UNESCAPED_UNICODE) : null;
Db::name('service_spec')
->where('id', $specId)
->where('service_id', $row->id)
->update([
'addon_prices' => $addonPricesJson,
'updatetime' => time(),
]);
}
}
Db::commit();
$this->success('增值服务加价配置保存成功');
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
}
$addons = [];
if (!empty($row->addons)) {
$addons = is_array($row->addons) ? $row->addons : json_decode($row->addons, true);
}
$specs = Db::name('service_spec')
->where('service_id', $row->id)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
foreach ($specs as &$sp) {
$sp['addon_prices_map'] = !empty($sp['addon_prices']) ? (json_decode($sp['addon_prices'], true) ?: []) : [];
}
unset($sp);
$catName = Db::name('service_cat')->where('id', $row->cat_id)->value('name') ?: '未归类';
$this->view->assign([
'row' => $row,
'catName' => $catName,
'assignedAddons' => $addons ?: [],
'specs' => $specs ?: [],
]);
return $this->view->fetch();
}
/**
* 编辑商品与关联服务定价
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params = $this->formatServiceConfig($params);
$result = false;
Db::startTrans();
try {
$result = $row->allowField(true)->save($params);
// 同步处理商品规格列表
$this->syncSpecs($row->id, $this->request->post('specs/a', []));
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
// 解析当前商品已关联的主服务与增项服务配置
$serviceTypes = [];
if (!empty($row->service_types)) {
$serviceTypes = is_array($row->service_types) ? $row->service_types : json_decode($row->service_types, true);
}
$addons = [];
if (!empty($row->addons)) {
$addons = is_array($row->addons) ? $row->addons : json_decode($row->addons, true);
}
// 获取已有商品规格并解析专属主服务与增值服务定价字典
$specs = Db::name('service_spec')
->where('service_id', $row->id)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
foreach ($specs as &$sp) {
$sp['prices_map'] = !empty($sp['service_prices']) ? (json_decode($sp['service_prices'], true) ?: []) : [];
$sp['addon_prices_map'] = !empty($sp['addon_prices']) ? (json_decode($sp['addon_prices'], true) ?: []) : [];
if (empty($sp['prices_map']) && (float)$sp['base_price'] > 0) {
$defCode = 'install';
foreach ($serviceTypes as $st) {
if (!empty($st['is_default']) && !empty($st['code'])) {
$defCode = (string)$st['code'];
break;
}
}
$sp['prices_map'][$defCode] = (float)$sp['base_price'];
}
}
unset($sp);
$catName = Db::name('service_cat')->where('id', $row->cat_id)->value('name') ?: '未归类';
$this->view->assign("row", $row);
$this->view->assign("catName", $catName);
$this->view->assign("serviceTypes", $serviceTypes ?: []);
$this->view->assign("assignedAddons", $addons ?: []);
$this->view->assign("specs", $specs ?: []);
return $this->view->fetch();
}
/**
* 商品档案与服务定价全景详情
*/
public function detail($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$catName = Db::name('service_cat')->where('id', $row->cat_id)->value('name') ?: '未归类';
$serviceTypes = !empty($row->service_types)
? (is_array($row->service_types) ? $row->service_types : (json_decode($row->service_types, true) ?: []))
: [];
$addons = !empty($row->addons)
? (is_array($row->addons) ? $row->addons : (json_decode($row->addons, true) ?: []))
: [];
$specs = Db::name('service_spec')
->where('service_id', $row->id)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
foreach ($specs as &$sp) {
$sp['prices_map'] = !empty($sp['service_prices']) ? (json_decode($sp['service_prices'], true) ?: []) : [];
$sp['addon_prices_map'] = !empty($sp['addon_prices']) ? (json_decode($sp['addon_prices'], true) ?: []) : [];
if (empty($sp['prices_map']) && (float)$sp['base_price'] > 0) {
$defCode = 'install';
foreach ($serviceTypes as $st) {
if (!empty($st['is_default']) && !empty($st['code'])) {
$defCode = (string)$st['code'];
break;
}
}
$sp['prices_map'][$defCode] = (float)$sp['base_price'];
}
}
unset($sp);
$orderAgg = Db::name('order')
->field('COUNT(*) AS total_cnt, SUM(CASE WHEN pay_status = 1 THEN pay_amount ELSE 0 END) AS total_gmv')
->where('service_id', $row->id)
->find();
$this->view->assign([
'row' => $row,
'catName' => $catName,
'serviceTypes' => $serviceTypes,
'addons' => $addons,
'specs' => $specs,
'orderCount' => (int)($orderAgg['total_cnt'] ?? 0),
'orderGmv' => number_format((float)($orderAgg['total_gmv'] ?? 0), 2, '.', ''),
]);
return $this->view->fetch();
}
/**
* 格式化商品关联的主服务与增项服务 JSON,并自动提取默认主服务价格用于底层索引兼容
*/
protected function formatServiceConfig($params)
{
$parsedTypes = [];
if (isset($params['service_types_raw'])) {
if (is_string($params['service_types_raw'])) {
$parsedTypes = json_decode($params['service_types_raw'], true) ?: [];
} else {
$parsedTypes = is_array($params['service_types_raw']) ? $params['service_types_raw'] : [];
}
unset($params['service_types_raw']);
if (empty($parsedTypes)) {
throw new ValidateException('请至少开启 1 项主服务');
}
$dictSupportMap = Db::name('service_type')->column('support_fixed', 'code');
$hasDefault = false;
foreach ($parsedTypes as &$pt) {
$code = isset($pt['code']) ? (string)$pt['code'] : '';
$supportFixed = isset($dictSupportMap[$code])
? (int)$dictSupportMap[$code]
: (isset($pt['support_fixed']) ? (int)$pt['support_fixed'] : 1);
$price = ($supportFixed === 1 && isset($pt['price'])) ? round((float)$pt['price'], 2) : 0.00;
$pt['price'] = $price;
$pt['support_fixed'] = $supportFixed;
if ($supportFixed === 1 && !empty($pt['is_default']) && !$hasDefault) {
$pt['is_default'] = 1;
$hasDefault = true;
} else {
$pt['is_default'] = 0;
}
}
unset($pt);
if (!$hasDefault && !empty($parsedTypes)) {
foreach ($parsedTypes as &$ptDef) {
if ((int)$ptDef['support_fixed'] === 1) {
$ptDef['is_default'] = 1;
$hasDefault = true;
break;
}
}
unset($ptDef);
if (!$hasDefault) {
$parsedTypes[0]['is_default'] = 1;
}
}
$params['service_types'] = json_encode(array_values($parsedTypes), JSON_UNESCAPED_UNICODE);
}
if (isset($params['addons_raw'])) {
$parsedAddons = is_string($params['addons_raw'])
? (json_decode($params['addons_raw'], true) ?: [])
: (is_array($params['addons_raw']) ? $params['addons_raw'] : []);
unset($params['addons_raw']);
$cleanAddons = [];
foreach ($parsedAddons as $idx => $ad) {
$adName = isset($ad['name']) ? trim((string)$ad['name']) : '';
$adPrice = isset($ad['price']) ? round((float)$ad['price'], 2) : 0.00;
if ($adName === '' || $adPrice <= 0) {
continue;
}
$cleanAddons[] = [
'id' => isset($ad['id']) ? (int)$ad['id'] : ($idx + 1),
'code' => isset($ad['code']) ? (string)$ad['code'] : ('addon_' . ($idx + 1)),
'name' => $adName,
'unit' => !empty($ad['unit']) ? (string)$ad['unit'] : '份',
'price' => $adPrice,
];
}
$params['addons'] = json_encode($cleanAddons, JSON_UNESCAPED_UNICODE);
}
// 自动从关联的主服务(优先默认首选主服务)同步底层 base_price 与 price_type
if (!empty($parsedTypes)) {
$defItem = $parsedTypes[0];
foreach ($parsedTypes as $pt) {
if (!empty($pt['is_default'])) {
$defItem = $pt;
break;
}
}
$supportFixed = isset($defItem['support_fixed']) ? (int)$defItem['support_fixed'] : 1;
$mainPrice = isset($defItem['price']) ? (float)$defItem['price'] : 0.00;
// 若该工项本身不支持一口价(需现场勘验)或价格为0,则自动切换为师傅报价模式;否则为标准一口价
if ($supportFixed === 0 || $mainPrice <= 0) {
$params['price_type'] = 'quote';
$params['base_price'] = 0.00;
} else {
$params['price_type'] = 'fixed';
$params['base_price'] = $mainPrice;
}
}
return $params;
}
/**
* 同步商品规格型号表(支持一个规格一套专属价格,未单独设价的工项自动沿用父级基准价,并联动系统图库)
*/
protected function syncSpecs($serviceId, $specsInput)
{
if (empty($serviceId)) return;
$now = time();
$svcRow = Db::name('service')->field('cat_id,service_types')->where('id', $serviceId)->find();
$catId = (int)($svcRow['cat_id'] ?? 0);
$svcTypes = !empty($svcRow['service_types']) ? (json_decode($svcRow['service_types'], true) ?: []) : [];
$defaultCode = 'install';
foreach ($svcTypes as $st) {
if (!empty($st['is_default']) && !empty($st['code'])) {
$defaultCode = (string)$st['code'];
break;
}
}
$keepIds = [];
if (!empty($specsInput) && is_array($specsInput)) {
$idx = 0;
foreach ($specsInput as $item) {
$name = trim(isset($item['name']) ? $item['name'] : '');
if ($name === '') continue;
$specDesc = isset($item['description']) ? trim($item['description']) : '';
$specImage = isset($item['image']) ? trim((string)$item['image']) : '';
// 解析当前规格的工项专属定价字典 (JSON / 关联数组)
$cleanPricesMap = [];
if (isset($item['service_prices'])) {
$rawPrices = is_array($item['service_prices'])
? $item['service_prices']
: (json_decode($item['service_prices'], true) ?: []);
foreach ($rawPrices as $pCode => $pVal) {
$pCode = trim((string)$pCode);
$pNum = (float)$pVal;
if ($pCode !== '' && $pNum > 0) {
$cleanPricesMap[$pCode] = round($pNum, 2);
}
}
}
// base_price 保持向下兼容:优先取默认首选主服务的专属价,未设则取传入的 base_price,均无则存 0.00
$specPrice = 0.00;
if (isset($cleanPricesMap[$defaultCode])) {
$specPrice = $cleanPricesMap[$defaultCode];
} elseif (isset($item['base_price']) && is_numeric($item['base_price']) && (float)$item['base_price'] > 0) {
$specPrice = round((float)$item['base_price'], 2);
if (!isset($cleanPricesMap[$defaultCode])) {
$cleanPricesMap[$defaultCode] = $specPrice;
}
} elseif (!empty($cleanPricesMap)) {
$specPrice = reset($cleanPricesMap);
}
$pricesJson = !empty($cleanPricesMap) ? json_encode($cleanPricesMap, JSON_UNESCAPED_UNICODE) : null;
$specId = isset($item['id']) ? (int)$item['id'] : 0;
$weigh = max(0, 100 - $idx * 5);
$idx++;
// 解析当前规格的增值服务专属加价字典 (JSON / 关联数组)
$cleanAddonPricesMap = [];
if (isset($item['addon_prices'])) {
$rawAddonPrices = is_array($item['addon_prices'])
? $item['addon_prices']
: (json_decode($item['addon_prices'], true) ?: []);
foreach ($rawAddonPrices as $aCode => $aVal) {
$aCode = trim((string)$aCode);
$aNum = (float)$aVal;
if ($aCode !== '' && $aNum > 0) {
$cleanAddonPricesMap[$aCode] = round($aNum, 2);
}
}
}
$addonPricesJson = !empty($cleanAddonPricesMap) ? json_encode($cleanAddonPricesMap, JSON_UNESCAPED_UNICODE) : null;
$saveData = [
'name' => $name,
'base_price' => $specPrice,
'service_prices' => $pricesJson,
'addon_prices' => $addonPricesJson,
'description' => $specDesc,
'weigh' => $weigh,
'updatetime' => $now,
];
if (array_key_exists('image', $item)) {
$saveData['image'] = $specImage;
}
if ($specId > 0) {
Db::name('service_spec')->where('id', $specId)->where('service_id', $serviceId)->update($saveData);
$keepIds[] = $specId;
} else {
$saveData['service_id'] = $serviceId;
$saveData['status'] = 'normal';
$saveData['createtime'] = $now;
$specId = (int)Db::name('service_spec')->insertGetId($saveData);
$keepIds[] = $specId;
}
// 若管理员为细分规格上传了参考图,自动同步更新或补充至 fa_system_gallery
if ($specImage !== '') {
$existingGal = Db::name('system_gallery')
->where('service_id', $serviceId)
->where('spec_id', $specId)
->find();
if ($existingGal) {
Db::name('system_gallery')->where('id', $existingGal['id'])->update([
'cat_id' => $catId,
'title' => $name,
'image' => $specImage,
'updatetime' => $now,
]);
} else {
Db::name('system_gallery')->insert([
'cat_id' => $catId,
'service_id' => $serviceId,
'spec_id' => $specId,
'title' => $name,
'image' => $specImage,
'weigh' => $weigh,
'status' => 'normal',
'createtime' => $now,
'updatetime' => $now,
]);
}
}
}
}
$delQuery = Db::name('service_spec')->where('service_id', $serviceId);
if (!empty($keepIds)) {
$delQuery->whereNotIn('id', $keepIds);
}
$delQuery->delete();
}
/**
* 删除保护:已产生历史业务订单的服务商品禁止物理删除,无关联订单删除时同步清理细分规格
*/
public function del($ids = null)
{
if (false === $this->request->isPost()) {
$this->error(__('Invalid parameters'));
}
$ids = $ids ?: $this->request->post('ids');
$idArr = array_values(array_filter(array_map('intval', explode(',', (string)$ids))));
if (!$idArr) {
$this->error(__('Parameter %s can not be empty', 'ids'));
}
$ordCnt = (int)Db::name('order')->where('service_id', 'in', $idArr)->count();
if ($ordCnt > 0) {
$this->error('所选商品已关联 ' . $ordCnt . ' 笔历史工单,禁止物理删除;如需下架请将状态设为隐藏');
}
Db::startTrans();
try {
Db::name('service_spec')->where('service_id', 'in', $idArr)->delete();
Db::name('system_gallery')->where('service_id', 'in', $idArr)->delete();
$deleted = Db::name('service')->where('id', 'in', $idArr)->delete();
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($deleted) {
$this->success();
}
$this->error(__('No rows were deleted'));
}
}