['prescription_id', 'fulfillment_status', 'prescription_audit_status', 'payment_slip_audit_status'], '%like%' => ['order_no'], 'between_time' => 'create_time', ]; } /** * 列表/统计条数:含全部搜索条件(含创建时间区间) */ private function buildFilteredQuery(): Query { $query = PrescriptionOrder::where($this->searchWhere)->whereNull('delete_time'); $this->applyPermissionAndExtraFilters($query); return $query; } /** * 今日汇总:与列表相同的「非时间」条件(医生/医助/患者/状态/单号等),不含创建时间区间,避免与「今日」语义重复 * * @return array */ private function searchWhereWithoutCreateTimeRange(): array { return array_values(array_filter( $this->searchWhere, static function ($w): bool { if (!\is_array($w) || \count($w) < 2) { return true; } if (($w[0] ?? '') === 'create_time' && ($w[1] ?? '') === 'between') { return false; } return true; } )); } private function applyPermissionAndExtraFilters($query): void { $this->applyDoctorAssistantFilters($query); $this->applyPatientKeywordFilter($query); if (!PrescriptionOrderLogic::canSeeAllPrescriptionOrders($this->adminInfo)) { $query->where('creator_id', $this->adminId); } $this->applyDataScopeForPrescriptionOrder($query); } /** * 数据隔离:创建者 ∈ 可见 admin,或 关联诊单医助 ∈ 可见 admin */ private function applyDataScopeForPrescriptionOrder($query): void { if (!$this->dataScopeShouldApply()) { return; } $ids = $this->getDataScopeVisibleAdminIds(); if ($ids === null) { return; } if ($ids === []) { $query->whereRaw('0 = 1'); return; } $poTbl = (new PrescriptionOrder())->getTable(); $diagTbl = (new Diagnosis())->getTable(); $inList = implode(',', $ids); $query->where(function ($q) use ($poTbl, $diagTbl, $inList) { $q->whereIn('creator_id', explode(',', $inList)); $q->whereOrRaw( "EXISTS (SELECT 1 FROM `{$diagTbl}` dg WHERE dg.`id` = `{$poTbl}`.`diagnosis_id` " . "AND dg.`delete_time` IS NULL AND dg.`assistant_id` IN ({$inList}))" ); }); } /** * 医助:仅「诊单医助=本人」的订单计业绩 */ private function applyAssistantDiagnosisOnlyFilter($query): void { $poTbl = (new PrescriptionOrder())->getTable(); $diagTbl = (new Diagnosis())->getTable(); $aid = (int) $this->adminId; $query->whereExists( "SELECT 1 FROM `{$diagTbl}` dg WHERE dg.`id` = `{$poTbl}`.`diagnosis_id` AND dg.`delete_time` IS NULL AND dg.`assistant_id` = {$aid}" ); } /** * 统计用查询骨架:不含 create_time 区间;其它筛选项 + 统计专用数据域(不重复 where) */ private function buildBaseQueryForStats(): Query { $query = PrescriptionOrder::where($this->searchWhereWithoutCreateTimeRange())->whereNull('delete_time'); $this->applyDoctorAssistantFilters($query); $this->applyPatientKeywordFilter($query); if (PrescriptionOrderLogic::canViewOrderListStatsAllScope($this->adminInfo)) { $this->applyDataScopeForPrescriptionOrder($query); return $query; } $assistantRid = (int) Config::get('project.prescription_order_stats_assistant_role_id', 2); $myRoles = array_map('intval', $this->adminInfo['role_id'] ?? []); if ($assistantRid > 0 && in_array($assistantRid, $myRoles, true)) { $this->applyAssistantDiagnosisOnlyFilter($query); $this->applyDataScopeForPrescriptionOrder($query); return $query; } if (!PrescriptionOrderLogic::canSeeAllPrescriptionOrders($this->adminInfo)) { $query->where('creator_id', $this->adminId); } $this->applyDataScopeForPrescriptionOrder($query); return $query; } /** * 统计所对应的时间:与入参 start_time / end_time 一致;未传则按自然日「今天」 * * @return array{0: int, 1: int, 2: string, 3: string} */ private function resolveStatsTimeWindow(): array { $st = trim((string) ($this->params['start_time'] ?? '')); $et = trim((string) ($this->params['end_time'] ?? '')); if ($st !== '' && $et !== '') { $t0 = strtotime($st); $t1 = strtotime($et); if ($t0 !== false && $t1 !== false) { return [(int) $t0, (int) $t1, $st, $et]; } } $t0 = strtotime(date('Y-m-d 00:00:00')); $t1 = strtotime(date('Y-m-d 23:59:59')); if ($t0 === false || $t1 === false) { return [0, 0, '', '']; } return [ (int) $t0, (int) $t1, date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59'), ]; } public function lists(): array { $query = $this->buildFilteredQuery(); $lists = $query ->order('id', 'desc') ->limit($this->limitOffset, $this->limitLength) ->select() ->toArray(); $poIds = array_values(array_filter(array_map('intval', array_column($lists, 'id')))); $paidSumByPo = []; if ($poIds !== []) { $links = PrescriptionOrderPayOrder::whereIn('prescription_order_id', $poIds) ->field(['prescription_order_id', 'pay_order_id']) ->select() ->toArray(); $byPo = []; foreach ($links as $l) { $poid = (int) ($l['prescription_order_id'] ?? 0); $oid = (int) ($l['pay_order_id'] ?? 0); if ($poid > 0 && $oid > 0) { $byPo[$poid][] = $oid; } } $allOids = []; foreach ($byPo as $oids) { $allOids = array_merge($allOids, $oids); } $allOids = array_values(array_unique($allOids)); $amountByOid = []; if ($allOids !== []) { $amountByOid = Order::whereIn('id', $allOids)->whereNull('delete_time')->column('amount', 'id'); } foreach ($poIds as $pid) { $s = 0.0; foreach ($byPo[$pid] ?? [] as $oid) { $s += (float) ($amountByOid[$oid] ?? 0); } $paidSumByPo[$pid] = round($s, 2); } } // 获取创建人姓名 $creatorIds = array_values(array_unique(array_filter(array_map('intval', array_column($lists, 'creator_id'))))); $creatorNames = []; if ($creatorIds !== []) { $creatorNames = \app\common\model\auth\Admin::whereIn('id', $creatorIds)->column('name', 'id'); } // 获取处方ID对应的开方人姓名 $prescriptionIds = array_values(array_unique(array_filter(array_map('intval', array_column($lists, 'prescription_id'))))); $prescriptionCreators = []; if ($prescriptionIds !== []) { $prescriptions = \app\common\model\tcm\Prescription::whereIn('id', $prescriptionIds) ->whereNull('delete_time') ->field(['id', 'creator_id', 'doctor_name']) ->select() ->toArray(); $doctorIds = []; foreach ($prescriptions as $rx) { $rxId = (int) ($rx['id'] ?? 0); $doctorId = (int) ($rx['creator_id'] ?? 0); $doctorName = (string) ($rx['doctor_name'] ?? ''); if ($rxId > 0) { $prescriptionCreators[$rxId] = [ 'doctor_id' => $doctorId, 'doctor_name' => $doctorName ]; if ($doctorId > 0) { $doctorIds[] = $doctorId; } } } // 如果 doctor_name 为空,从 Admin 表获取 $doctorIds = array_values(array_unique($doctorIds)); if ($doctorIds !== []) { $doctorNamesFromAdmin = \app\common\model\auth\Admin::whereIn('id', $doctorIds)->column('name', 'id'); foreach ($prescriptionCreators as &$pc) { if (empty($pc['doctor_name']) && $pc['doctor_id'] > 0) { $pc['doctor_name'] = $doctorNamesFromAdmin[$pc['doctor_id']] ?? ''; } } unset($pc); } } $depMin = PrescriptionOrderLogic::depositMinAmount(); $diagIdsForAssist = array_values(array_unique(array_filter(array_map('intval', array_column($lists, 'diagnosis_id'))))); $assistantByDiag = []; if ($diagIdsForAssist !== []) { $assistantByDiag = Diagnosis::whereIn('id', $diagIdsForAssist)->whereNull('delete_time')->column('assistant_id', 'id'); } foreach ($lists as &$item) { PrescriptionOrderLogic::maskInternalCostIfNeeded($item, $this->adminInfo); $pid = (int) ($item['id'] ?? 0); $item['linked_pay_order_count'] = (int) PrescriptionOrderPayOrder::where( 'prescription_order_id', $pid )->count(); $item['linked_pay_paid_total'] = $paidSumByPo[$pid] ?? 0.0; $item['deposit_min_amount'] = $depMin; $item['can_upload_gancao_reciperl'] = PrescriptionOrderLogic::canUploadGancaoRecipel( $item, $this->adminId, $this->adminInfo, $assistantByDiag ); // 添加创建人姓名 $creatorId = (int) ($item['creator_id'] ?? 0); $item['creator_name'] = $creatorId > 0 ? ($creatorNames[$creatorId] ?? '') : ''; // 添加开方人姓名 $rxId = (int) ($item['prescription_id'] ?? 0); $item['doctor_name'] = $rxId > 0 ? ($prescriptionCreators[$rxId]['doctor_name'] ?? '') : ''; } unset($item); return $lists; } public function extend(): array { $s = $this->computeListStatsForExtend(); return [ 'deposit_min_amount' => PrescriptionOrderLogic::depositMinAmount(), 'gancao_scm_enabled' => GancaoScmRecipelService::isConfigured(), 'stats_order_amount' => $s['order_amount'], 'stats_order_amount_not_cancelled' => $s['order_amount_not_cancelled'], 'stats_order_amount_cancelled' => $s['order_amount_cancelled'], /** 业绩:业务订单金额,剔除履约已取消(fulfillment_status=4),其余状态全部计入 */ 'stats_order_amount_performance' => $s['order_amount_not_cancelled'], 'stats_linked_pay_amount' => $s['linked_pay_amount'], 'stats_linked_pay_amount_not_cancelled' => $s['linked_pay_amount_not_cancelled'], 'stats_linked_pay_amount_cancelled' => $s['linked_pay_amount_cancelled'], /** 业绩-关联实付:剔除履约已取消订单的关联支付金额 */ 'stats_linked_pay_amount_performance' => $s['linked_pay_amount_not_cancelled'], 'stats_time_start' => $s['label_start'], 'stats_time_end' => $s['label_end'], /** 统计口径:all=支付审核白名单全量;assistant=医助仅诊单协助业绩;restricted=与列表同域 */ 'stats_scope' => $s['scope'], ]; } /** * 关联实付按业务订单 id 列表汇总 * * @param array $poIds */ private function sumLinkedPayForPrescriptionOrderIds(array $poIds): float { if ($poIds === []) { return 0.0; } $sum = (float) PrescriptionOrderPayOrder::alias('l') ->join('order o', 'l.pay_order_id = o.id') ->whereIn('l.prescription_order_id', $poIds) ->whereNull('o.delete_time') ->sum('o.amount'); return round($sum, 2); } /** * @return array{order_amount: float, order_amount_not_cancelled: float, order_amount_cancelled: float, linked_pay_amount: float, linked_pay_amount_not_cancelled: float, linked_pay_amount_cancelled: float, label_start: string, label_end: string, scope: string} */ private function computeListStatsForExtend(): array { [$t0, $t1, $l0, $l1] = $this->resolveStatsTimeWindow(); if ($t0 <= 0 || $t1 <= 0) { return $this->statsZeroPayload(); } if ($t1 < $t0) { $tmp = $t0; $t0 = $t1; $t1 = $tmp; } $q = $this->buildBaseQueryForStats()->whereBetween('create_time', [$t0, $t1]); $orderTotal = round((float) (clone $q)->sum('amount'), 2); $orderCancelled = round((float) (clone $q)->where('fulfillment_status', 4)->sum('amount'), 2); $orderNotCancelled = round($orderTotal - $orderCancelled, 2); $idsAll = (clone $q)->column('id'); $idsAll = array_values(array_filter(array_map('intval', $idsAll), static function (int $id): bool { return $id > 0; })); if ($idsAll === []) { return $this->statsExtendPayload( $orderTotal, $orderNotCancelled, $orderCancelled, 0.0, 0.0, 0.0, $l0, $l1 ); } $idsCancel = (clone $q)->where('fulfillment_status', 4)->column('id'); $idsCancel = array_values(array_filter(array_map('intval', $idsCancel), static function (int $id): bool { return $id > 0; })); $idsNotCancelled = array_values(array_diff($idsAll, $idsCancel)); $linkedTotal = $this->sumLinkedPayForPrescriptionOrderIds($idsAll); $linkedNotCancelled = $this->sumLinkedPayForPrescriptionOrderIds($idsNotCancelled); $linkedCancelled = $this->sumLinkedPayForPrescriptionOrderIds($idsCancel); return $this->statsExtendPayload( $orderTotal, $orderNotCancelled, $orderCancelled, $linkedTotal, $linkedNotCancelled, $linkedCancelled, $l0, $l1 ); } /** * @return array{order_amount: float, order_amount_not_cancelled: float, order_amount_cancelled: float, linked_pay_amount: float, linked_pay_amount_not_cancelled: float, linked_pay_amount_cancelled: float, label_start: string, label_end: string, scope: string} */ private function statsZeroPayload(): array { return $this->statsExtendPayload(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '', ''); } /** * @return array{order_amount: float, order_amount_not_cancelled: float, order_amount_cancelled: float, linked_pay_amount: float, linked_pay_amount_not_cancelled: float, linked_pay_amount_cancelled: float, label_start: string, label_end: string, scope: string} */ private function statsExtendPayload( float $orderTotal, float $orderNotCancelled, float $orderCancelled, float $linkedTotal, float $linkedNotCancelled, float $linkedCancelled, string $l0, string $l1 ): array { $scope = 'restricted'; if (PrescriptionOrderLogic::canViewOrderListStatsAllScope($this->adminInfo)) { $scope = 'all'; } else { $ar = (int) Config::get('project.prescription_order_stats_assistant_role_id', 2); if ($ar > 0 && in_array($ar, array_map('intval', $this->adminInfo['role_id'] ?? []), true)) { $scope = 'assistant'; } } return [ 'order_amount' => $orderTotal, 'order_amount_not_cancelled' => $orderNotCancelled, 'order_amount_cancelled' => $orderCancelled, 'linked_pay_amount' => $linkedTotal, 'linked_pay_amount_not_cancelled' => $linkedNotCancelled, 'linked_pay_amount_cancelled' => $linkedCancelled, 'label_start' => $l0, 'label_end' => $l1, 'scope' => $scope, ]; } public function count(): int { $query = $this->buildFilteredQuery(); return (int) $query->count(); } /** * 按开方医生(关联处方 creator_id)/ 诊单医助(关联诊单 assistant_id)筛选 */ private function applyDoctorAssistantFilters($query): void { $poTbl = (new PrescriptionOrder())->getTable(); if (isset($this->params['doctor_id']) && (int) $this->params['doctor_id'] > 0) { $doctorId = (int) $this->params['doctor_id']; $rxTbl = (new Prescription())->getTable(); $query->whereExists("SELECT 1 FROM {$rxTbl} rx WHERE rx.id = {$poTbl}.prescription_id AND rx.delete_time IS NULL AND rx.creator_id = {$doctorId}"); } if (isset($this->params['assistant_id']) && (int) $this->params['assistant_id'] > 0) { $assistantId = (int) $this->params['assistant_id']; $diagTbl = (new Diagnosis())->getTable(); $query->whereExists("SELECT 1 FROM {$diagTbl} dg WHERE dg.id = {$poTbl}.diagnosis_id AND dg.delete_time IS NULL AND dg.assistant_id = {$assistantId}"); } if (isset($this->params['assistant_dept_id']) && $this->params['assistant_dept_id'] !== '' && (int) $this->params['assistant_dept_id'] > 0) { $rootDeptId = (int) $this->params['assistant_dept_id']; $deptIds = DeptLogic::getSelfAndDescendantIds($rootDeptId); $deptIds = array_values(array_filter(array_map('intval', $deptIds), static function (int $id): bool { return $id > 0; })); if ($deptIds === []) { $query->whereRaw('0 = 1'); return; } $inList = implode(',', $deptIds); $diagTbl = (new Diagnosis())->getTable(); $adTbl = (new AdminDept())->getTable(); $query->whereExists( "SELECT 1 FROM `{$adTbl}` ad INNER JOIN `{$diagTbl}` dg ON ad.admin_id = dg.assistant_id AND dg.delete_time IS NULL " . "WHERE dg.id = `{$poTbl}`.`diagnosis_id` AND ad.dept_id IN ({$inList})" ); } } /** * 按诊单患者姓名 / 手机号模糊检索(关联 diagnosis_id) */ private function applyPatientKeywordFilter($query): void { $kw = trim((string) ($this->params['patient_keyword'] ?? '')); if ($kw === '') { return; } $poTbl = (new PrescriptionOrder())->getTable(); $diagTbl = (new Diagnosis())->getTable(); $likeInner = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $kw); $like = '%' . $likeInner . '%'; $likeSql = str_replace("'", "''", $like); $query->whereExists( "SELECT 1 FROM `{$diagTbl}` dg WHERE dg.`id` = `{$poTbl}`.`diagnosis_id` AND dg.`delete_time` IS NULL " . "AND (dg.`patient_name` LIKE '{$likeSql}' OR dg.`phone` LIKE '{$likeSql}')" ); } }