model = new \app\admin\model\Service; $this->view->assign("statusList", $this->model->getStatusList()); if (in_array($this->request->action(), ['index', 'detail', 'pricing_main', 'add', 'edit'], true) && !$this->request->isPost()) { $site = $this->view->config['site']; $site['version'] .= '.service-floor-fees-zero'; $this->assignconfig('site', $site); } // 获取统一服务字典表(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) { $specMap[$sp['service_id']][] = $sp; } $dictionary = ProductPricing::dictionary(); foreach ($rows as &$r) { $sid = (int)$r['id']; $config = ProductPricing::read($r->getData()); $r['specs_list'] = array_map(function ($spec) use ($config) { $name = $spec['name']; if ($config) { if (isset($config['spec_configs'][$spec['id']])) { return $name . '(独立配置)'; } return isset($config['specs'][$spec['id']]) ? $name . '(已单独设价)' : $name; } $prices = json_decode($spec['service_prices'] ?? '', true) ?: []; if ($prices) { $tips = []; foreach ($prices as $code => $price) { $tips[] = $code . ':¥' . round($price); } return $name . ' (' . implode(',', $tips) . ')'; } return $spec['base_price'] > 0 ? $name . '(¥' . round($spec['base_price']) . ')' : $name; }, $specMap[$sid] ?? []); // 直接在服务端解析为数组返回,防止前端 bootstrap-table escape:true 将 JSON 双引号转义为 " 导致解析失败 $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) ?: []); } if ($config) { $names = []; foreach ($stArr as $type) { $names[$type['code']] = $type['name']; } $addonNames = array_column($adArr, 'name', 'code'); $adArr = []; foreach ($config['services'] as $code => $type) { foreach ($type['addons'] as $addon => $cents) { $adArr[] = ['name' => ($names[$code] ?? $code) . '加购' . ($addonNames[$addon] ?? $addon), 'price' => $cents / 100, 'unit' => $dictionary[$addon]['unit'] ?? '']; } } $r->hidden(['pricing_config']); } $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 = array_diff_key($params, array_flip(['pricing_config', 'service_types', 'addons', 'base_price', 'price_type'])); $params['status'] = 'hidden'; $result = false; Db::startTrans(); try { $params = $this->normalizeFloorFees($params); $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', '')); } $this->view->assign(['floorFee' => '10.00', 'freeFloor' => 2]); return $this->view->fetch(); } private function normalizeFloorFees(array $params) { $mode = $this->request->post('floor_fee_mode', ''); if ($mode !== 'free' && $mode !== 'paid') { return $params; } $fee = $mode === 'free' ? 0.0 : filter_var($params['floor_fee'] ?? null, FILTER_VALIDATE_FLOAT); if ($fee === false || $fee < 0 || $fee > 99999999.99 || round($fee, 2) !== $fee) { throw new ValidateException('每层费用须为 0 元或正数,且最多保留两位小数'); } if ($fee === 0.0) { return array_replace($params, ['floor_fee' => 0, 'free_floor' => 0]); } $freeFloors = filter_var($params['free_floor'] ?? null, FILTER_VALIDATE_INT, [ 'options' => ['min_range' => 0, 'max_range' => 2147483647], ]); if ($freeFloors === false) { throw new ValidateException('免费楼层数须为非负整数'); } return array_replace($params, ['floor_fee' => $fee, 'free_floor' => $freeFloors]); } /** * 商品服务与价格使用同一份配置,整体保存。 */ 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->auth->check('service/pricing_addon')) { $this->error('配置服务价格需要主服务和增值服务两项权限'); } $dictionary = ProductPricing::dictionary(); $specQuery = function () use ($row) { return Db::name('service_spec')->where('service_id', $row->id)->where('status', 'normal'); }; if ($this->request->isPost()) { $this->token(); Db::startTrans(); try { $current = Db::name('service')->where('id', $row->id)->lock(true)->find(); if (!$current) { throw new \InvalidArgumentException('商品已删除'); } $previous = ProductPricing::read($current); $input = json_decode((string)$this->request->post('pricing_payload', '', null), true); if (!is_array($input) || !array_key_exists('spec_configs', $input) || (int)($input['revision'] ?? -1) !== (int)($previous['revision'] ?? 0)) { throw new \InvalidArgumentException('配置已变更或格式无效,请重新打开后再保存'); } if (!$previous && !empty(json_decode($current['addons'] ?? '', true)) && empty($input['reviewed'])) { throw new \InvalidArgumentException('请先核对旧增值服务的归属'); } $specNames = $specQuery()->column('name', 'id'); $config = ProductPricing::validate($input, $dictionary, array_map('intval', array_keys($specNames)), $specNames); $config['revision'] = (int)($previous['revision'] ?? 0) + 1; $config['legacy'] = $previous['legacy'] ?? array_intersect_key($current, array_flip([ 'service_types', 'addons', 'base_price', 'price_type', ])); $options = ProductPricing::options($config, $dictionary, 0); $default = $options['services'][$config['default']]; $serviceTypes = ProductPricing::publicServices($options); $addons = []; foreach ($serviceTypes as &$service) { foreach ($service['addons'] as $addon) { $addons[$addon['code']] = ['code' => $addon['code'], 'name' => $addon['name']]; } unset($service['addons']); } unset($service); Db::name('service')->where('id', $row->id)->update([ 'pricing_config' => json_encode($config, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'service_types' => json_encode($serviceTypes, JSON_UNESCAPED_UNICODE), 'addons' => json_encode(array_values($addons), JSON_UNESCAPED_UNICODE), 'base_price' => ($default['cents'] ?? 0) / 100, 'price_type' => $default['mode'], 'updatetime' => time(), ]); Db::commit(); } catch (\InvalidArgumentException $e) { Db::rollback(); $this->error($e->getMessage(), '', ['__token__' => $this->request->token()]); } catch (\Throwable $e) { Db::rollback(); \think\Log::error('[ProductPricing] ' . $e->getMessage()); $this->error('服务价格保存失败,请重试', '', ['__token__' => $this->request->token()]); } $this->success('全部配置已保存'); } $specs = $specQuery()->order('weigh desc,id asc')->select(); $data = $row->getData(); $config = ProductPricing::read($data); $legacy = $config ? [] : (json_decode($data['addons'] ?? '', true) ?: []); $draft = $config ?? ProductPricing::legacyDraft($data, $dictionary, $specs); $previousSpecPrices = !empty($draft['specs']); $draft['spec_configs'] = array_intersect_key( ProductPricing::expandLegacySpecs($draft), array_flip(array_column($specs, 'id')) ); unset($draft['legacy'], $draft['specs']); $this->view->assign([ 'row' => $row, 'pricingData' => json_encode([ 'draft' => $draft, 'dictionary' => $dictionary, 'selectedSpecId' => (int)$this->request->get('spec_id', 0), 'legacyAddons' => $legacy, 'previousSpecPrices' => $previousSpecPrices && !empty($draft['spec_configs']), 'legacySpecAddons' => $config ? [] : array_column(array_map(function ($spec) { return ['id' => $spec['id'], 'prices' => json_decode($spec['addon_prices'] ?? '', true) ?: []]; }, $specs), 'prices', 'id'), 'specs' => array_map(function ($spec) { return ['id' => (int)$spec['id'], 'name' => $spec['name']]; }, $specs), ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ]); return $this->view->fetch('pricing_workspace'); } public function pricing_addon($ids = null) { if ($this->request->isPost()) { $this->error('请在商品的「服务与价格配置」中统一保存'); } $this->redirect('service/pricing_main', ['ids' => $ids, 'dialog' => 1]); } /** * 编辑商品与关联服务定价 */ 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 = array_diff_key($params, array_flip(['pricing_config', 'service_types', 'addons', 'base_price', 'price_type'])); $result = false; Db::startTrans(); try { $params = $this->normalizeFloorFees($params); $current = Db::name('service')->where('id', $row->id)->lock(true)->find(); if (($params['status'] ?? '') === 'normal' && empty($current['pricing_config']) && empty(json_decode($current['service_types'] ?? '', true))) { throw new ValidateException('请先完成服务与价格配置,再上架商品'); } $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', '')); } $specs = Db::name('service_spec') ->where('service_id', $row->id) ->where('status', 'normal') ->order('weigh desc, id asc') ->select(); $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("specs", $specs ?: []); $this->view->assign(['floorFee' => $row->floor_fee, 'freeFloor' => $row->free_floor]); return $this->view->fetch(); } /** * 商品档案与服务定价全景详情 */ public function detail($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')); } $product = $row->getData(); $dictionary = ProductPricing::dictionary(); $specs = Db::name('service_spec') ->where('service_id', $row->id) ->where('status', 'normal') ->order('weigh desc, id asc') ->select(); $saved = ProductPricing::read($product); $config = $saved ?? ProductPricing::legacyDraft($product, $dictionary, $specs); if (!$saved && $product['price_type'] === 'quote') { foreach ($config['services'] as &$service) { $service['mode'] = 'quote'; } unset($service); } $legacyAddons = $saved ? [] : (json_decode($product['addons'] ?? '', true) ?: []); $parent = [ 'id' => 0, 'name' => '商品通用配置', 'services' => ProductPricing::publicServices(ProductPricing::options($config, $dictionary, 0)), 'legacyAddons' => $this->detailLegacyAddons($legacyAddons, [], $dictionary), ]; $scopes = [$parent]; foreach ($specs as $spec) { $specId = (int)$spec['id']; $addonPrices = $saved ? [] : (json_decode($spec['addon_prices'] ?? '', true) ?: []); $status = isset($config['spec_configs'][$specId]) ? '独立配置' : (!empty($config['specs'][$specId]) || $addonPrices ? '历史规格定价' : '沿用通用'); $scopes[] = [ 'id' => $specId, 'name' => $spec['name'], 'status' => $status, 'description' => $spec['description'], 'image' => $this->detailImage($spec['image'] ?? ''), 'services' => $status === '沿用通用' ? $parent['services'] : ProductPricing::publicServices(ProductPricing::options($config, $dictionary, $specId)), 'legacyAddons' => $this->detailLegacyAddons($legacyAddons, $addonPrices, $dictionary), ]; } $this->view->assign([ 'row' => $row, 'catName' => Db::name('service_cat')->where('id', $row->cat_id)->value('name'), 'cover' => $this->detailImage($product['image'] ?? ''), 'description' => $product['description'] ?? $product['desc'] ?? '', 'canEditPricing' => $this->auth->check('service/pricing_main') && $this->auth->check('service/pricing_addon'), 'detailData' => json_encode([ 'scopes' => $scopes, 'selectedSpecId' => (int)$this->request->get('spec_id', 0), ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ]); return $this->view->fetch(); } private function detailLegacyAddons(array $addons, array $specPrices, array $dictionary) { $names = array_column($dictionary, null, 'name'); $result = []; foreach ($addons as $addon) { $code = $addon['code'] ?? ''; $name = $addon['name'] ?? ''; $type = $dictionary[$code] ?? $names[$name] ?? null; if (!$type) { continue; } $price = (float)($specPrices[$name] ?? $specPrices[$code] ?? 0); if ($price <= 0) { $price = (float)($addon['price'] ?? 0); } if ($price > 0) { $result[] = ['name' => $type['name'], 'price' => $price, 'unit' => $addon['unit'] ?? $type['unit']]; } } return $result; } private function detailImage($path) { if (!$path) { return ''; } if (strpos($path, '/assets/') === 0 || strpos($path, '/icon/') === 0) { return $path; } $url = cdnurl($path, true); return preg_match('~^(?:https?:)?//~i', $url) ? $url : ''; } /** * 同步商品规格型号表(支持一个规格一套专属价格,未单独设价的工项自动沿用父级基准价,并联动系统图库) */ protected function syncSpecs($serviceId, $specsInput) { if (empty($serviceId)) return; $now = time(); $catId = (int)Db::name('service')->where('id', $serviceId)->value('cat_id'); $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']) : ''; $specId = (int)($item['id'] ?? 0); $weigh = max(0, 100 - $idx * 5); $idx++; $saveData = [ 'name' => $name, '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')); } }