Merge branch 'master' into kpi-statis

This commit is contained in:
2026-04-24 12:19:04 +08:00
289 changed files with 1242 additions and 429 deletions
@@ -70,6 +70,8 @@ class DiagnosisController extends BaseAdminController
public function add()
{
$params = (new DiagnosisValidate())->post()->goCheck('add');
// 诊单创建人(需表 zyt_tcm_diagnosis 已增加 admin_id 列,见 sql 脚本)
$params['admin_id'] = (int) $this->adminId;
$result = DiagnosisLogic::add($params);
if ($result) {
return $this->success('添加成功', ['id' => $result], 1, 1);
@@ -165,8 +165,11 @@ class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
return;
}
// 主管角色ID列表(可根据实际调整)
$supervisorRoles = [0, 3];
// 可查看全部订单:project.order_list_view_all_roles;未配置时回退 order_edit_all_roles
$supervisorRoles = config('project.order_list_view_all_roles', null);
if (!\is_array($supervisorRoles) || $supervisorRoles === []) {
$supervisorRoles = config('project.order_edit_all_roles', [0, 3, 4, 9, 6]);
}
// 检查当前用户是否是主管
$roleIds = \app\common\model\auth\AdminRole::where('admin_id', $this->adminId)->column('role_id');
@@ -15,6 +15,7 @@
namespace app\adminapi\lists\tcm;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\dept\DeptLogic;
use app\common\model\tcm\Diagnosis;
use app\common\model\DiagnosisViewRecord;
use app\common\model\doctor\Appointment;
@@ -129,12 +130,21 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
$query->whereExists("SELECT 1 FROM {$rxTbl} rx WHERE rx.diagnosis_id = {$diagTbl}.id AND rx.delete_time IS NULL");
}
// 医助所属部门(随访等页面传 assistant_dept_id):只看待定部门下医助负责的诊单
// 医助所属部门(随访等页面传 assistant_dept_id):选父级时包含全部子级部门下医助
if (isset($this->params['assistant_dept_id']) && $this->params['assistant_dept_id'] !== '' && (int) $this->params['assistant_dept_id'] > 0) {
$deptId = (int) $this->params['assistant_dept_id'];
$adTbl = (new AdminDept())->getTable();
$diagTbl = (new Diagnosis())->getTable();
$query->whereExists("SELECT 1 FROM {$adTbl} ad WHERE ad.admin_id = {$diagTbl}.assistant_id AND ad.dept_id = {$deptId}");
$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');
} else {
$inList = implode(',', $deptIds);
$adTbl = (new AdminDept())->getTable();
$diagTbl = (new Diagnosis())->getTable();
$query->whereExists("SELECT 1 FROM {$adTbl} ad WHERE ad.admin_id = {$diagTbl}.assistant_id AND ad.dept_id IN ({$inList})");
}
}
// 按挂号状态优先级排序:已过号(4) > 已预约(1) > 已完成(3),然后按挂号日期+时间升序
@@ -153,11 +163,20 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
// 获取最早的挂号时间(用于同状态内排序)
$minAptExpr = '(SELECT MIN(CONCAT(apt.appointment_date, \' \', IFNULL(NULLIF(TRIM(apt.appointment_time), \'\'), \'00:00:00\'))) FROM ' . $aptTbl . ' apt WHERE apt.patient_id = ' . $diagTbl . '.id AND apt.status IN (1,3,4)' . $minAptDateCond . ')';
// 「已完成」Tab:按最近一条「已完成」(status=3) 挂号日期+时间降序,最新在最前;有 appointment_date 时仍只在该日内比
$isCompletedTab = isset($this->params['completed_appointment']) && (string) $this->params['completed_appointment'] === '1';
if ($isCompletedTab) {
$maxCompletedAptExpr = '(SELECT MAX(CONCAT(apt.appointment_date, \' \', IFNULL(NULLIF(TRIM(apt.appointment_time), \'\'), \'00:00:00\'))) FROM ' . $aptTbl . ' apt WHERE apt.patient_id = ' . $diagTbl . '.id AND apt.status = 3' . $minAptDateCond . ')';
$orderRaw = 'IFNULL(' . $maxCompletedAptExpr . ", '1970-01-01 00:00:00') DESC, {$diagTbl}.id DESC";
} else {
$orderRaw = 'CASE IFNULL(' . $minAptStatusExpr . ', 999) WHEN 4 THEN 1 WHEN 1 THEN 2 WHEN 3 THEN 3 ELSE 4 END ASC, IFNULL(' . $minAptExpr . ", '9999-12-31 23:59:59') ASC, {$diagTbl}.id DESC";
}
$lists = $query
->with(['DiagnosisViewRecord'])
->field(['id', 'patient_id', 'patient_name', 'id_card', 'phone', 'gender', 'age', 'diagnosis_date', 'diagnosis_type', 'syndrome_type', 'assistant_id', 'status', 'create_time', 'update_time'])
->append(['gender_desc', 'status_desc', 'diagnosis_date_text'])
->orderRaw('CASE IFNULL(' . $minAptStatusExpr . ', 999) WHEN 4 THEN 1 WHEN 1 THEN 2 WHEN 3 THEN 3 ELSE 4 END ASC, IFNULL(' . $minAptExpr . ", '9999-12-31 23:59:59') ASC, {$diagTbl}.id DESC")
->orderRaw($orderRaw)
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
@@ -5,11 +5,13 @@ declare(strict_types=1);
namespace app\adminapi\lists\tcm;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\dept\DeptLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\Order;
use app\common\model\tcm\Diagnosis;
use app\common\model\auth\AdminDept;
use app\common\model\tcm\Prescription;
use app\common\model\tcm\PrescriptionOrder;
use app\common\model\tcm\PrescriptionOrderPayOrder;
@@ -276,31 +278,48 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
$s = $this->computeListStatsForExtend();
return [
'deposit_min_amount' => PrescriptionOrderLogic::depositMinAmount(),
'gancao_scm_enabled' => GancaoScmRecipelService::isConfigured(),
'stats_order_amount' => $s['order_amount'],
'stats_linked_pay_amount' => $s['linked_pay_amount'],
'stats_time_start' => $s['label_start'],
'stats_time_end' => $s['label_end'],
'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'],
'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_time_start' => $s['label_start'],
'stats_time_end' => $s['label_end'],
/** 统计口径:all=支付审核白名单全量;assistant=医助仅诊单协助业绩;restricted=与列表同域 */
'stats_scope' => $s['scope'],
'stats_scope' => $s['scope'],
];
}
/**
* @return array{order_amount: float, linked_pay_amount: float, label_start: string, label_end: string, scope: string}
* 关联实付按业务订单 id 列表汇总
*
* @param array<int> $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 [
'order_amount' => 0.0,
'linked_pay_amount' => 0.0,
'label_start' => '',
'label_end' => '',
'scope' => 'restricted',
];
return $this->statsZeroPayload();
}
if ($t1 < $t0) {
$tmp = $t0;
@@ -309,29 +328,69 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
}
$q = $this->buildBaseQueryForStats()->whereBetween('create_time', [$t0, $t1]);
$orderAmount = round((float) (clone $q)->sum('amount'), 2);
$ids = (clone $q)->column('id');
$ids = array_values(array_filter(array_map('intval', $ids), static function (int $id): bool {
$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 ($ids === []) {
return $this->statsExtendPayload($orderAmount, 0.0, $l0, $l1);
if ($idsAll === []) {
return $this->statsExtendPayload(
$orderTotal,
$orderNotCancelled,
$orderCancelled,
0.0,
0.0,
0.0,
$l0,
$l1
);
}
$sumPaid = (float) PrescriptionOrderPayOrder::alias('l')
->join('order o', 'l.pay_order_id = o.id')
->whereIn('l.prescription_order_id', $ids)
->whereNull('o.delete_time')
->sum('o.amount');
$sumPaid = round($sumPaid, 2);
$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));
return $this->statsExtendPayload($orderAmount, $sumPaid, $l0, $l1);
$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, linked_pay_amount: float, label_start: string, label_end: string, scope: string}
* @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 $orderAmount, float $linked, string $l0, string $l1): array
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';
@@ -343,11 +402,15 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
}
return [
'order_amount' => $orderAmount,
'linked_pay_amount' => $linked,
'label_start' => $l0,
'label_end' => $l1,
'scope' => $scope,
'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,
];
}
@@ -376,6 +439,26 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
$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})"
);
}
}
/**
@@ -280,4 +280,61 @@ class DeptLogic extends BaseLogic
return self::getTree($data, $pid);
}
/**
* 指定部门及其全部下级部门 id(含自身)。筛选时选父级可匹配子级下成员(admin_dept.dept_id)。
*
* @return array<int>
*/
public static function getSelfAndDescendantIds(int $rootDeptId): array
{
if ($rootDeptId <= 0) {
return [];
}
$rows = Dept::field(['id', 'pid'])->select()->toArray();
if ($rows === []) {
return [$rootDeptId];
}
$validIds = [];
foreach ($rows as $r) {
$id = (int) ($r['id'] ?? 0);
if ($id > 0) {
$validIds[$id] = true;
}
}
if (!isset($validIds[$rootDeptId])) {
return [$rootDeptId];
}
$childrenByPid = [];
foreach ($rows as $r) {
$pid = (int) ($r['pid'] ?? 0);
$id = (int) ($r['id'] ?? 0);
if ($id <= 0) {
continue;
}
if (!isset($childrenByPid[$pid])) {
$childrenByPid[$pid] = [];
}
$childrenByPid[$pid][] = $id;
}
$out = [];
$queue = [$rootDeptId];
$seen = [];
while ($queue !== []) {
$id = array_shift($queue);
if (isset($seen[$id])) {
continue;
}
$seen[$id] = true;
$out[] = $id;
foreach ($childrenByPid[$id] ?? [] as $cid) {
$cid = (int) $cid;
if ($cid > 0 && !isset($seen[$cid])) {
$queue[] = $cid;
}
}
}
return $out;
}
}
@@ -92,7 +92,16 @@ class DiagnosisLogic extends BaseLogic
if (isset($params['diagnosis_date'])) {
$params['diagnosis_date'] = strtotime($params['diagnosis_date']);
}
// 表未增加 admin_id 列时勿写入,避免 SQL 报错(见 sql/1.9.20260421/add_tcm_diagnosis_admin_id.sql
// 注意:Model::getConnection() 在 think-orm 中返回连接名(string),须用 Db 查询对象取字段
if (array_key_exists('admin_id', $params)) {
$fieldNames = Db::name('tcm_diagnosis')->getTableFields();
if (! is_array($fieldNames) || ! in_array('admin_id', $fieldNames, true)) {
unset($params['admin_id']);
}
}
$model = Diagnosis::create($params);
// 自动为患者创建 TRTC 账号
@@ -13,6 +13,8 @@ use app\common\model\tcm\PrescriptionOrder;
use app\common\model\tcm\PrescriptionOrderLog;
use app\common\model\tcm\PrescriptionOrderPayOrder;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminDept;
use app\common\model\dept\Dept;
use app\common\service\ExpressTrackService;
use app\common\service\gancao\GancaoScmRecipelService;
use think\facade\Config;
@@ -32,6 +34,38 @@ class PrescriptionOrderLogic
return self::$error;
}
/**
* 部门自底向上链式名称,含父级(如:总部 / 华东 / 上海门诊)
*/
private static function buildDeptPath(int $deptId): string
{
if ($deptId <= 0) {
return '';
}
$names = [];
$id = $deptId;
for ($i = 0; $i < 50; $i++) {
$row = Dept::where('id', $id)->whereNull('delete_time')->field(['id', 'name', 'pid'])->find();
if ($row === null) {
break;
}
$data = $row->toArray();
array_unshift($names, (string) ($data['name'] ?? ''));
$pid = (int) ($data['pid'] ?? 0);
if ($pid <= 0) {
break;
}
$id = $pid;
}
if ($names === []) {
return '';
}
$names = array_filter($names, static fn (string $n): bool => $n !== '');
return implode(' / ', $names);
}
/**
* @param int[] $allowRoleIds
*/
@@ -607,6 +641,54 @@ class PrescriptionOrderLogic
unset($arr['prescription']['herbs']);
}
// 诊单医助 / 诊单创建人 及部门(多部门、含父级路径用「;」与「 / 」分隔);创建人为 tcm_diagnosis.admin_id
$arr['assistant_id'] = 0;
$arr['assistant_name'] = '';
$arr['assistant_dept_path'] = '';
$arr['diagnosis_creator_id'] = 0;
$arr['diagnosis_creator_name'] = '';
$arr['diagnosis_creator_dept_path'] = '';
$diagIdForMeta = (int) ($arr['diagnosis_id'] ?? 0);
if ($diagIdForMeta > 0) {
// 勿在 field 中写 admin_id:未执行建表补充列时会报 Unknown column
$dg = Diagnosis::where('id', $diagIdForMeta)->whereNull('delete_time')->find();
if ($dg !== null) {
$drow = $dg->toArray();
$astId = (int) ($drow['assistant_id'] ?? 0);
$arr['assistant_id'] = $astId;
if ($astId > 0) {
$an = Admin::where('id', $astId)->whereNull('delete_time')->value('name');
$arr['assistant_name'] = $an !== null && (string) $an !== '' ? (string) $an : '';
$deptIds = AdminDept::where('admin_id', $astId)->column('dept_id');
$pathSegments = [];
foreach ($deptIds as $did) {
$p = self::buildDeptPath((int) $did);
if ($p !== '') {
$pathSegments[] = $p;
}
}
$pathSegments = array_values(array_unique($pathSegments));
$arr['assistant_dept_path'] = $pathSegments === [] ? '' : implode('', $pathSegments);
}
$creId = (int) ($drow['admin_id'] ?? 0);
$arr['diagnosis_creator_id'] = $creId;
if ($creId > 0) {
$cn = Admin::where('id', $creId)->whereNull('delete_time')->value('name');
$arr['diagnosis_creator_name'] = $cn !== null && (string) $cn !== '' ? (string) $cn : '';
$deptIdsC = AdminDept::where('admin_id', $creId)->column('dept_id');
$pathSegmentsC = [];
foreach ($deptIdsC as $didC) {
$pc = self::buildDeptPath((int) $didC);
if ($pc !== '') {
$pathSegmentsC[] = $pc;
}
}
$pathSegmentsC = array_values(array_unique($pathSegmentsC));
$arr['diagnosis_creator_dept_path'] = $pathSegmentsC === [] ? '' : implode('', $pathSegmentsC);
}
}
}
return $arr;
}