403 lines
16 KiB
PHP
403 lines
16 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace app\adminapi\lists\tcm;
|
||
|
||
use app\adminapi\lists\BaseAdminDataLists;
|
||
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\tcm\Prescription;
|
||
use app\common\model\tcm\PrescriptionOrder;
|
||
use app\common\model\tcm\PrescriptionOrderPayOrder;
|
||
use app\common\service\gancao\GancaoScmRecipelService;
|
||
use think\facade\Config;
|
||
use think\db\Query;
|
||
|
||
class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExtendInterface
|
||
{
|
||
public function setSearch(): array
|
||
{
|
||
return [
|
||
'=' => ['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<int, array{0: string, 1: string, 2: mixed}>
|
||
*/
|
||
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)) {
|
||
$diagIds = Diagnosis::where('assistant_id', $this->adminId)->whereNull('delete_time')->column('id');
|
||
$query->where(function ($q) use ($diagIds) {
|
||
$q->where('creator_id', $this->adminId);
|
||
if ($diagIds !== []) {
|
||
$q->whereOr('diagnosis_id', 'in', $diagIds);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 医助:仅「诊单医助=本人」的订单计业绩
|
||
*/
|
||
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)) {
|
||
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);
|
||
|
||
return $query;
|
||
}
|
||
if (!PrescriptionOrderLogic::canSeeAllPrescriptionOrders($this->adminInfo)) {
|
||
$diagIds = Diagnosis::where('assistant_id', $this->adminId)->whereNull('delete_time')->column('id');
|
||
$query->where(function ($q) use ($diagIds) {
|
||
$q->where('creator_id', $this->adminId);
|
||
if ($diagIds !== []) {
|
||
$q->whereOr('diagnosis_id', 'in', $diagIds);
|
||
}
|
||
});
|
||
}
|
||
|
||
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_linked_pay_amount' => $s['linked_pay_amount'],
|
||
'stats_time_start' => $s['label_start'],
|
||
'stats_time_end' => $s['label_end'],
|
||
/** 统计口径:all=支付审核白名单全量;assistant=医助仅诊单协助业绩;restricted=与列表同域 */
|
||
'stats_scope' => $s['scope'],
|
||
];
|
||
}
|
||
|
||
/**
|
||
* @return array{order_amount: float, linked_pay_amount: 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',
|
||
];
|
||
}
|
||
if ($t1 < $t0) {
|
||
$tmp = $t0;
|
||
$t0 = $t1;
|
||
$t1 = $tmp;
|
||
}
|
||
|
||
$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 {
|
||
return $id > 0;
|
||
}));
|
||
if ($ids === []) {
|
||
return $this->statsExtendPayload($orderAmount, 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);
|
||
|
||
return $this->statsExtendPayload($orderAmount, $sumPaid, $l0, $l1);
|
||
}
|
||
|
||
/**
|
||
* @return array{order_amount: float, linked_pay_amount: float, label_start: string, label_end: string, scope: string}
|
||
*/
|
||
private function statsExtendPayload(float $orderAmount, float $linked, 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' => $orderAmount,
|
||
'linked_pay_amount' => $linked,
|
||
'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}");
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按诊单患者姓名 / 手机号模糊检索(关联 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}')"
|
||
);
|
||
}
|
||
}
|