first commit

This commit is contained in:
Your Name
2026-09-08 11:40:15 +08:00
commit a5353f7eb5
9568 changed files with 1646214 additions and 0 deletions
@@ -0,0 +1,372 @@
<?php
declare(strict_types=1);
namespace app\adminapi\lists\firstvisit;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\firstvisit\MyPatientLogic;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\DiagnosisViewRecord;
use app\common\model\auth\Admin;
use app\common\model\doctor\Appointment;
use app\common\model\tcm\Diagnosis;
use think\db\Query;
use think\facade\Db;
class MyPatientLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExtendInterface
{
private const EFFECTIVE_APPOINTMENT_STATUSES = [1, 3, 4];
public function setSearch(): array
{
return [];
}
public function lists(): array
{
$query = $this->buildQuery(true, true);
$appointmentTable = (new Appointment())->getTable();
$today = date('Y-m-d');
$upcomingSql = "SELECT MIN(CONCAT(sort_apt.appointment_date, ' ', IFNULL(NULLIF(TRIM(sort_apt.appointment_time), ''), '00:00:00')))"
. " FROM {$appointmentTable} sort_apt"
. ' WHERE sort_apt.patient_id = d.id'
. ' AND sort_apt.status IN (1,4)'
. " AND sort_apt.appointment_date >= '{$today}'";
$rows = $query
->field([
'd.id', 'd.patient_id', 'd.patient_name', 'd.phone', 'd.id_card', 'd.gender', 'd.age',
'd.diagnosis_date', 'd.diagnosis_type', 'd.syndrome_type', 'd.assistant_id',
'd.assign_read_at', 'd.create_time',
])
->orderRaw("CASE WHEN ({$upcomingSql}) IS NULL THEN 1 ELSE 0 END ASC")
->orderRaw("IFNULL(({$upcomingSql}), '9999-12-31 23:59:59') ASC")
->order('d.id', 'desc')
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
return $this->appendRelations($rows);
}
public function count(): int
{
return (int) $this->buildQuery(true, true)->count('d.id');
}
public function extend(): array
{
$today = date('Y-m-d');
$tomorrow = date('Y-m-d', strtotime('+1 day'));
$dayAfter = date('Y-m-d', strtotime('+2 days'));
return [
'summary' => [
'today' => $this->countByAppointmentDate($today),
'tomorrow' => $this->countByAppointmentDate($tomorrow),
'day_after' => $this->countByAppointmentDate($dayAfter),
],
'scope' => MyPatientLogic::scopeMeta($this->adminId, $this->adminInfo),
'dates' => [
'today' => $today,
'tomorrow' => $tomorrow,
'day_after' => $dayAfter,
],
];
}
private function buildQuery(bool $applyStatusFilter, bool $applyDateFilter): Query
{
$diagnosisTable = (new Diagnosis())->getTable();
$query = Db::table($diagnosisTable)
->alias('d')
->whereNull('d.delete_time')
->where('d.status', 1);
MyPatientLogic::applyScope($query, $this->adminId, $this->adminInfo);
$this->applyKeyword($query);
$statusFilter = $applyStatusFilter ? trim((string) ($this->params['status_filter'] ?? '')) : '';
$appointmentTable = (new Appointment())->getTable();
if ($statusFilter === 'unbooked') {
$query->whereNotExists(
"SELECT 1 FROM {$appointmentTable} unbooked_apt"
. ' WHERE unbooked_apt.patient_id = d.id'
. ' AND unbooked_apt.status IN (' . implode(',', self::EFFECTIVE_APPOINTMENT_STATUSES) . ')'
);
}
$appointmentStatuses = self::EFFECTIVE_APPOINTMENT_STATUSES;
if (in_array($statusFilter, ['pending_interview', 'booked'], true)) {
$appointmentStatuses = [1];
} elseif ($statusFilter === 'completed') {
$appointmentStatuses = [3];
} elseif ($statusFilter === 'missed') {
$appointmentStatuses = [4];
}
$needsAppointmentFilter = in_array(
$statusFilter,
['pending_interview', 'booked', 'completed', 'missed'],
true
);
[$startDate, $endDate] = $applyDateFilter ? $this->dateRange() : ['', ''];
if ($startDate !== '' || $endDate !== '') {
$needsAppointmentFilter = true;
}
if ($needsAppointmentFilter) {
$conditions = [
'filter_apt.patient_id = d.id',
'filter_apt.status IN (' . implode(',', $appointmentStatuses) . ')',
];
if ($startDate !== '') {
$conditions[] = "filter_apt.appointment_date >= '{$startDate}'";
}
if ($endDate !== '') {
$conditions[] = "filter_apt.appointment_date <= '{$endDate}'";
}
$query->whereExists(
"SELECT 1 FROM {$appointmentTable} filter_apt WHERE " . implode(' AND ', $conditions)
);
}
return $query;
}
private function applyKeyword(Query $query): void
{
$keyword = trim((string) ($this->params['keyword'] ?? ''));
if ($keyword === '') {
return;
}
$needle = addslashes($keyword);
$adminTable = (new Admin())->getTable();
$appointmentTable = (new Appointment())->getTable();
$query->whereRaw(
"(d.patient_name LIKE '%{$needle}%'"
. " OR d.phone LIKE '%{$needle}%'"
. " OR EXISTS (SELECT 1 FROM {$adminTable} assistant_admin"
. ' WHERE assistant_admin.id = CAST(d.assistant_id AS UNSIGNED)'
. ' AND assistant_admin.delete_time IS NULL'
. " AND assistant_admin.name LIKE '%{$needle}%')"
. " OR EXISTS (SELECT 1 FROM {$appointmentTable} keyword_apt"
. " INNER JOIN {$adminTable} doctor_admin ON doctor_admin.id = keyword_apt.doctor_id"
. ' AND doctor_admin.delete_time IS NULL'
. ' WHERE keyword_apt.patient_id = d.id'
. ' AND keyword_apt.status IN (1,3,4)'
. " AND doctor_admin.name LIKE '%{$needle}%'))"
);
}
/** @return array{0:string,1:string} */
private function dateRange(): array
{
$startDate = $this->normalizeDate($this->params['start_date'] ?? '');
$endDate = $this->normalizeDate($this->params['end_date'] ?? '');
if ($startDate === '' && $endDate !== '') {
$startDate = $endDate;
}
if ($endDate === '' && $startDate !== '') {
$endDate = $startDate;
}
if ($startDate !== '' && $endDate !== '' && $startDate > $endDate) {
[$startDate, $endDate] = [$endDate, $startDate];
}
return [$startDate, $endDate];
}
private function normalizeDate($value): string
{
$value = trim((string) $value);
return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) ? $value : '';
}
private function countByAppointmentDate(string $date): int
{
$query = $this->buildQuery(false, false);
$appointmentTable = (new Appointment())->getTable();
$query->whereExists(
"SELECT 1 FROM {$appointmentTable} summary_apt"
. ' WHERE summary_apt.patient_id = d.id'
. " AND summary_apt.appointment_date = '{$date}'"
. ' AND summary_apt.status IN (1,3,4)'
);
return (int) $query->count('d.id');
}
/**
* @param array<int, array<string, mixed>> $rows
* @return array<int, array<string, mixed>>
*/
private function appendRelations(array $rows): array
{
if ($rows === []) {
return [];
}
$diagnosisIds = array_values(array_unique(array_map('intval', array_column($rows, 'id'))));
$assistantIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'assistant_id')))));
$appointmentTable = (new Appointment())->getTable();
$appointments = Db::table($appointmentTable)
->whereIn('patient_id', $diagnosisIds)
->whereIn('status', self::EFFECTIVE_APPOINTMENT_STATUSES)
->field(['id', 'patient_id', 'doctor_id', 'appointment_date', 'appointment_time', 'status'])
->order('appointment_date', 'asc')
->order('appointment_time', 'asc')
->order('id', 'asc')
->select()
->toArray();
$doctorIds = array_values(array_unique(array_filter(array_map('intval', array_column($appointments, 'doctor_id')))));
$adminIds = array_values(array_unique(array_merge($assistantIds, $doctorIds)));
$adminNames = $adminIds === [] ? [] : Admin::whereIn('id', $adminIds)->whereNull('delete_time')->column('name', 'id');
$appointmentMap = [];
foreach ($appointments as $appointment) {
$diagnosisId = (int) ($appointment['patient_id'] ?? 0);
if ($diagnosisId > 0) {
$appointmentMap[$diagnosisId][] = $appointment;
}
}
$viewTable = (new DiagnosisViewRecord())->getTable();
$confirmedIds = Db::table($viewTable)
->whereIn('diagnosis_id', $diagnosisIds)
->where('is_confirmed', 1)
->whereNull('delete_time')
->column('diagnosis_id');
$confirmedSet = array_fill_keys(array_map('intval', $confirmedIds), true);
[$rangeStart, $rangeEnd] = $this->dateRange();
$today = date('Y-m-d');
$statusFilter = trim((string) ($this->params['status_filter'] ?? ''));
$preferredStatuses = [
'pending_interview' => [1],
'booked' => [1],
'completed' => [3],
'missed' => [4],
][$statusFilter] ?? [];
foreach ($rows as &$row) {
$diagnosisId = (int) $row['id'];
$rowAppointments = $appointmentMap[$diagnosisId] ?? [];
$primary = $this->pickPrimaryAppointment(
$rowAppointments,
$rangeStart,
$rangeEnd,
$today,
$preferredStatuses
);
$completedCount = count(array_filter($rowAppointments, static function (array $appointment): bool {
return (int) ($appointment['status'] ?? 0) === 3;
}));
$assistantId = (int) ($row['assistant_id'] ?? 0);
$row['diagnosis_id'] = $diagnosisId;
$row['source_patient_id'] = (int) ($row['patient_id'] ?? 0);
$row['phone_masked'] = $this->maskPhone((string) ($row['phone'] ?? ''));
unset($row['phone']);
$row['has_id_card'] = trim((string) ($row['id_card'] ?? '')) !== '' ? 1 : 0;
unset($row['id_card']);
$row['gender_desc'] = (int) ($row['gender'] ?? 0) === 1 ? '男' : '女';
$row['diagnosis_date_text'] = $this->formatDiagnosisDate($row['diagnosis_date'] ?? '');
$row['assistant_name'] = (string) ($adminNames[$assistantId] ?? '未分配');
$row['confirmed'] = isset($confirmedSet[$diagnosisId]) ? 1 : 0;
$row['confirmation_text'] = $row['confirmed'] ? '已确认' : '待确认';
$row['visit_count'] = $completedCount;
$row['revisit_count'] = max(0, $completedCount - 1);
$row['appointment_id'] = $primary ? (int) $primary['id'] : 0;
$row['appointment_status'] = $primary ? (int) $primary['status'] : 0;
$row['appointment_status_text'] = $this->appointmentStatusText((int) ($primary['status'] ?? 0));
$row['appointment_doctor_id'] = $primary ? (int) $primary['doctor_id'] : 0;
$row['appointment_doctor_name'] = $primary
? (string) ($adminNames[(int) $primary['doctor_id']] ?? '未知医生')
: '未预约';
$row['appointment_time_text'] = $primary ? $this->appointmentTimeText($primary) : '';
$row['has_appointment'] = $primary !== null ? 1 : 0;
}
unset($row);
return $rows;
}
/**
* @param array<int, array<string, mixed>> $appointments
* @return array<string, mixed>|null
*/
private function pickPrimaryAppointment(
array $appointments,
string $rangeStart,
string $rangeEnd,
string $today,
array $preferredStatuses = []
): ?array
{
if ($appointments === []) {
return null;
}
$candidates = $appointments;
if ($preferredStatuses !== []) {
$candidates = array_values(array_filter($candidates, static function (array $appointment) use ($preferredStatuses): bool {
return in_array((int) ($appointment['status'] ?? 0), $preferredStatuses, true);
}));
}
if ($rangeStart !== '' || $rangeEnd !== '') {
$candidates = array_values(array_filter($candidates, static function (array $appointment) use ($rangeStart, $rangeEnd): bool {
$date = (string) ($appointment['appointment_date'] ?? '');
return ($rangeStart === '' || $date >= $rangeStart) && ($rangeEnd === '' || $date <= $rangeEnd);
}));
}
if ($candidates === []) {
$candidates = $appointments;
}
foreach ($candidates as $appointment) {
$status = (int) ($appointment['status'] ?? 0);
$date = (string) ($appointment['appointment_date'] ?? '');
if (in_array($status, [1, 4], true) && $date >= $today) {
return $appointment;
}
}
return $candidates[count($candidates) - 1] ?? null;
}
private function maskPhone(string $phone): string
{
return preg_replace('/^(\d{3})\d{4}(\d{4})$/', '$1****$2', $phone) ?: $phone;
}
private function formatDiagnosisDate($value): string
{
if (is_numeric($value)) {
return (int) $value > 0 ? date('Y-m-d', (int) $value) : '';
}
$text = trim((string) $value);
return $text === '' ? '' : substr($text, 0, 10);
}
private function appointmentTimeText(array $appointment): string
{
$time = trim((string) ($appointment['appointment_time'] ?? ''));
if (strlen($time) > 5) {
$time = substr($time, 0, 5);
}
return trim((string) ($appointment['appointment_date'] ?? '') . ' ' . $time);
}
private function appointmentStatusText(int $status): string
{
return [1 => '待面诊', 3 => '已完成', 4 => '已过号'][$status] ?? '未预约';
}
}
@@ -0,0 +1,362 @@
<?php
declare(strict_types=1);
namespace app\adminapi\lists\firstvisit;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\firstvisit\MyPatientLogic;
use app\adminapi\logic\stats\YejiStatsLogic;
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\auth\Admin;
use app\common\model\tcm\Prescription;
use app\common\model\tcm\PrescriptionOrder;
use app\common\model\tcm\PrescriptionOrderPayOrder;
use think\db\Query;
use think\facade\Db;
/**
* “我的患者”内嵌订单列表。
*
* 订单可见性始终锚定 diagnosis 别名 d,并复用 MyPatientLogic;订单创建人仅用于展示,
* 不能作为患者归属或数据范围条件。
*/
class MyPatientOrderLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExtendInterface
{
public function setSearch(): array
{
return [];
}
public function lists(): array
{
$rows = $this->buildQuery()
->field([
'po.id', 'po.order_no', 'po.prescription_id', 'po.diagnosis_id', 'po.creator_id',
'po.recipient_name', 'po.recipient_phone', 'po.fee_type', 'po.amount',
'po.prescription_audit_status', 'po.payment_slip_audit_status',
'po.fulfillment_status', 'po.express_company', 'po.tracking_number', 'po.ship_mode',
'po.gancao_reciperl_order_no', 'po.ej_pharmacy_order_no',
'po.gancao_submit_time', 'po.ej_pharmacy_submit_time',
'po.ej_pharmacy_status', 'po.ej_pharmacy_review_status', 'po.refund_amount',
'po.create_time',
'd.patient_name', 'd.phone AS patient_phone', 'd.assistant_id',
])
->order('po.id', 'desc')
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
return $this->appendRelations($rows);
}
public function count(): int
{
return (int) $this->buildQuery()->count('po.id');
}
public function extend(): array
{
$query = $this->buildQuery();
$pendingQuery = clone $query;
$effectiveAmountQuery = clone $query;
YejiStatsLogic::applyPrescriptionOrderEffectiveAmountQuery($effectiveAmountQuery, 'po');
// 拒收指标保留关键词、审核和日期条件,但不受当前履约状态按钮影响,
// 避免点击“拒收订单”后分母被收窄为拒收状态而固定显示 100%。
$rejectionScopeQuery = $this->buildQuery(true);
$rejectionScopeOrderCount = (int) (clone $rejectionScopeQuery)->count('po.id');
$rejectedCount = (int) (clone $rejectionScopeQuery)
->where('po.fulfillment_status', 9)
->count('po.id');
$orderCount = (int) (clone $query)->count('po.id');
return [
'summary' => [
'orders' => $orderCount,
'amount' => round((float) $effectiveAmountQuery->sum('po.amount'), 2),
'pending' => (int) $pendingQuery
->where(function ($q) {
$q->where('po.prescription_audit_status', 0)
->whereOr('po.payment_slip_audit_status', 0);
})
->count('po.id'),
'completed' => (int) (clone $query)->whereIn('po.fulfillment_status', [3, 6])->count('po.id'),
'rejected' => $rejectedCount,
'rejection_rate' => $rejectionScopeOrderCount > 0
? round($rejectedCount / $rejectionScopeOrderCount * 100, 2)
: 0.0,
],
'scope' => MyPatientLogic::scopeMeta($this->adminId, $this->adminInfo),
];
}
private function buildQuery(bool $ignoreFulfillmentStatus = false): Query
{
$query = PrescriptionOrder::alias('po')
->join('tcm_diagnosis d', 'po.diagnosis_id = d.id')
->whereNull('po.delete_time')
->whereNull('d.delete_time')
->where('d.status', 1);
MyPatientLogic::applyScope($query, $this->adminId, $this->adminInfo);
$this->applyKeyword($query);
$this->applyStatusFilters($query, $ignoreFulfillmentStatus);
$this->applyDateFilter($query);
return $query;
}
private function applyKeyword(Query $query): void
{
$keyword = trim((string) ($this->params['keyword'] ?? ''));
if ($keyword === '') {
return;
}
$query->where(function ($q) use ($keyword) {
$like = '%' . $keyword . '%';
$q->whereLike('po.order_no', $like)
->whereOr('d.patient_name', 'like', $like)
->whereOr('d.phone', 'like', $like)
->whereOr('po.recipient_name', 'like', $like)
->whereOr('po.recipient_phone', 'like', $like);
if (preg_match('/^\d+$/', $keyword)) {
$id = (int) $keyword;
if ($id > 0) {
$q->whereOr('po.id', $id)
->whereOr('po.prescription_id', $id)
->whereOr('po.diagnosis_id', $id);
}
}
});
}
private function applyStatusFilters(Query $query, bool $ignoreFulfillmentStatus = false): void
{
foreach (['prescription_audit_status', 'payment_slip_audit_status', 'fulfillment_status'] as $field) {
if ($ignoreFulfillmentStatus && $field === 'fulfillment_status') {
continue;
}
$raw = $this->params[$field] ?? '';
if ($raw === '' || $raw === null) {
continue;
}
$query->where('po.' . $field, (int) $raw);
}
}
private function applyDateFilter(Query $query): void
{
[$startDate, $endDate] = $this->dateRange();
if ($startDate !== '') {
$query->where('po.create_time', '>=', strtotime($startDate . ' 00:00:00'));
}
if ($endDate !== '') {
$query->where('po.create_time', '<=', strtotime($endDate . ' 23:59:59'));
}
}
/** @return array{0:string,1:string} */
private function dateRange(): array
{
$startDate = $this->normalizeDate($this->params['start_date'] ?? '');
$endDate = $this->normalizeDate($this->params['end_date'] ?? '');
if ($startDate === '' && $endDate !== '') {
$startDate = $endDate;
}
if ($endDate === '' && $startDate !== '') {
$endDate = $startDate;
}
if ($startDate !== '' && $endDate !== '' && $startDate > $endDate) {
[$startDate, $endDate] = [$endDate, $startDate];
}
return [$startDate, $endDate];
}
private function normalizeDate($value): string
{
$value = trim((string) $value);
return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) ? $value : '';
}
/**
* @param array<int, array<string, mixed>> $rows
* @return array<int, array<string, mixed>>
*/
private function appendRelations(array $rows): array
{
if ($rows === []) {
return [];
}
$orderIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'id')))));
$prescriptionIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'prescription_id')))));
$creatorIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'creator_id')))));
$assistantIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'assistant_id')))));
$prescriptionMap = [];
$doctorIds = [];
if ($prescriptionIds !== []) {
$prescriptions = Prescription::whereIn('id', $prescriptionIds)
->whereNull('delete_time')
->field(['id', 'creator_id', 'doctor_name'])
->select()
->toArray();
foreach ($prescriptions as $prescription) {
$prescriptionId = (int) ($prescription['id'] ?? 0);
$doctorId = (int) ($prescription['creator_id'] ?? 0);
if ($prescriptionId > 0) {
$prescriptionMap[$prescriptionId] = $prescription;
}
if ($doctorId > 0) {
$doctorIds[] = $doctorId;
}
}
}
$adminIds = array_values(array_unique(array_merge($creatorIds, $assistantIds, $doctorIds)));
$adminNames = $adminIds === []
? []
: Admin::whereIn('id', $adminIds)->whereNull('delete_time')->column('name', 'id');
$linkCounts = [];
$paidTotals = [];
if ($orderIds !== []) {
$linkRows = PrescriptionOrderPayOrder::whereIn('prescription_order_id', $orderIds)
->field(['prescription_order_id', 'pay_order_id'])
->select()
->toArray();
$payOrderIds = array_values(array_unique(array_filter(array_map('intval', array_column($linkRows, 'pay_order_id')))));
$payOrders = $payOrderIds === []
? []
: Order::whereIn('id', $payOrderIds)
->whereNull('delete_time')
->field(['id', 'amount', 'status'])
->select()
->toArray();
$payOrderMap = [];
foreach ($payOrders as $payOrder) {
$payOrderMap[(int) ($payOrder['id'] ?? 0)] = $payOrder;
}
foreach ($linkRows as $linkRow) {
$orderId = (int) ($linkRow['prescription_order_id'] ?? 0);
if ($orderId > 0) {
$linkCounts[$orderId] = ($linkCounts[$orderId] ?? 0) + 1;
}
$payOrder = $payOrderMap[(int) ($linkRow['pay_order_id'] ?? 0)] ?? [];
if ($orderId > 0 && in_array((int) ($payOrder['status'] ?? 0), [2, 5], true)) {
$paidTotals[$orderId] = round(
(float) ($paidTotals[$orderId] ?? 0) + (float) ($payOrder['amount'] ?? 0),
2
);
}
}
}
$assistantByDiagnosis = [];
foreach ($rows as $row) {
$diagnosisId = (int) ($row['diagnosis_id'] ?? 0);
if ($diagnosisId > 0) {
$assistantByDiagnosis[$diagnosisId] = (int) ($row['assistant_id'] ?? 0);
}
}
$claimByOrder = [];
if ($orderIds !== []) {
$claimRows = Db::name('pharmacy_submission_claim')
->whereIn('prescription_order_id', $orderIds)
->field(['prescription_order_id', 'target', 'status', 'lease_expires_at'])
->order('source_revision', 'desc')
->select()
->toArray();
foreach ($claimRows as $claimRow) {
$orderId = (int) ($claimRow['prescription_order_id'] ?? 0);
if ($orderId > 0 && !isset($claimByOrder[$orderId])) {
$claimByOrder[$orderId] = $claimRow;
}
}
}
foreach ($rows as &$row) {
$prescription = $prescriptionMap[(int) ($row['prescription_id'] ?? 0)] ?? [];
$doctorId = (int) ($prescription['creator_id'] ?? 0);
$doctorName = trim((string) ($prescription['doctor_name'] ?? ''));
$creatorId = (int) ($row['creator_id'] ?? 0);
$assistantId = (int) ($row['assistant_id'] ?? 0);
$row['patient_phone_masked'] = $this->maskPhone((string) ($row['patient_phone'] ?? ''));
$row['recipient_phone_masked'] = $this->maskPhone((string) ($row['recipient_phone'] ?? ''));
unset($row['patient_phone'], $row['recipient_phone']);
$row['creator_name'] = (string) ($adminNames[$creatorId] ?? '—');
$row['assistant_name'] = (string) ($adminNames[$assistantId] ?? '未分配');
$row['doctor_name'] = $doctorName !== '' ? $doctorName : (string) ($adminNames[$doctorId] ?? '—');
$row['linked_pay_order_count'] = (int) ($linkCounts[(int) $row['id']] ?? 0);
$row['linked_pay_paid_total'] = (float) ($paidTotals[(int) $row['id']] ?? 0);
$claim = $claimByOrder[(int) $row['id']] ?? [];
$row['pharmacy_claim_target'] = (string) ($claim['target'] ?? '');
$row['pharmacy_claim_status'] = (string) ($claim['status'] ?? '');
$row['pharmacy_claim_lease_expires_at'] = (int) ($claim['lease_expires_at'] ?? 0);
$row['can_upload_pharmacy'] = PrescriptionOrderLogic::canUploadToPharmacy(
$row,
$this->adminId,
$this->adminInfo,
$assistantByDiagnosis
);
$row['create_time_text'] = $this->formatTimestamp($row['create_time'] ?? 0);
$row['fee_type_text'] = $this->feeTypeText((int) ($row['fee_type'] ?? 0));
$row['prescription_audit_text'] = $this->auditStatusText((int) ($row['prescription_audit_status'] ?? 0));
$row['payment_slip_audit_text'] = $this->auditStatusText((int) ($row['payment_slip_audit_status'] ?? 0));
$row['fulfillment_text'] = $this->fulfillmentStatusText((int) ($row['fulfillment_status'] ?? 0));
$fulfillmentStatus = (int) ($row['fulfillment_status'] ?? 0);
$refundAmount = round((float) ($row['refund_amount'] ?? 0), 2);
$amountIncluded = !in_array(
$fulfillmentStatus,
YejiStatsLogic::PRESCRIPTION_ORDER_FULFILLMENT_EXCLUDED_FROM_PERFORMANCE,
true
) && $refundAmount <= 0;
$row['amount_included'] = $amountIncluded;
$row['effective_amount'] = $amountIncluded ? round((float) ($row['amount'] ?? 0), 2) : 0.0;
$row['amount_exclusion_text'] = $amountIncluded
? ''
: ($refundAmount > 0 || $fulfillmentStatus === 10 ? '退款不计入' : $row['fulfillment_text'] . '不计入');
}
unset($row);
return $rows;
}
private function maskPhone(string $phone): string
{
return preg_replace('/^(\d{3})\d{4}(\d{4})$/', '$1****$2', $phone) ?: $phone;
}
private function formatTimestamp($value): string
{
return is_numeric($value) && (int) $value > 0 ? date('Y-m-d H:i', (int) $value) : '';
}
private function auditStatusText(int $status): string
{
return [0 => '待审核', 1 => '已通过', 2 => '已驳回'][$status] ?? '未知';
}
private function feeTypeText(int $type): string
{
return [1 => '挂号', 2 => '问诊', 3 => '药品', 4 => '首付', 5 => '尾款', 6 => '其他', 7 => '全部'][$type] ?? '其他';
}
private function fulfillmentStatusText(int $status): string
{
return [
1 => '待双审通过', 2 => '待发货', 3 => '已完成', 4 => '已取消',
5 => '已发货', 6 => '已签收', 7 => '进行中', 8 => '暂不制药',
9 => '拒收', 10 => '退款', 11 => '保留药方', 12 => '制药缓发',
][$status] ?? '未知';
}
}
@@ -0,0 +1,702 @@
<?php
declare(strict_types=1);
namespace app\adminapi\lists\firstvisit;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\firstvisit\MyPatientLogic;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\DiagnosisViewRecord;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\doctor\Appointment;
use app\common\model\doctor\Roster;
use app\common\model\tcm\Prescription;
use app\common\service\doctor\RosterSegmentService;
use think\db\Query;
use think\facade\Db;
/**
* “我的患者”内嵌面诊进度。
*
* 一条挂号一行;只返回脱敏患者信息,并严格复用 MyPatientLogic 的患者级范围。
*/
class MyPatientProgressLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExtendInterface
{
private const EFFECTIVE_STATUSES = [1, 3, 4];
private const AVG_MINUTES_PER_VISIT = 15;
public function setSearch(): array
{
return [];
}
public function lists(): array
{
$rows = $this->buildQuery(true)
->field([
'a.id', 'a.patient_id AS diagnosis_id', 'a.doctor_id', 'a.appointment_date',
'a.appointment_time', 'a.appointment_type', 'a.status', 'a.create_time',
'd.patient_id AS source_patient_id', 'd.patient_name', 'd.phone', 'd.gender', 'd.age',
'd.assistant_id', 'doctor_admin.name AS doctor_name', 'assistant_admin.name AS assistant_name',
])
->order('a.appointment_date', 'asc')
->order('a.appointment_time', 'asc')
->order('a.id', 'asc')
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
return $this->appendProgress($rows);
}
public function count(): int
{
return (int) $this->buildQuery(true)->count('a.id');
}
public function extend(): array
{
$query = $this->buildQuery(false);
[$startDate, $endDate] = $this->dateRange();
$summary = [
'total' => (int) (clone $query)->count('a.id'),
'booked' => (int) (clone $query)->where('a.status', 1)->count('a.id'),
'completed' => (int) (clone $query)->where('a.status', 3)->count('a.id'),
'missed' => (int) (clone $query)->where('a.status', 4)->count('a.id'),
];
$scheduleMode = $this->usesOwnershipSchedule() ? 'ownership' : 'roster';
$weekSchedule = $scheduleMode === 'ownership' ? $this->ownershipWeekSchedule() : $this->weekSchedule();
$todaySchedule = $weekSchedule[0] ?? $this->emptyScheduleDay(date('Y-m-d'));
$todayOverview = $scheduleMode === 'ownership'
? [
'total_visits' => (int) ($todaySchedule['total_appointments'] ?? 0),
'booked' => (int) ($todaySchedule['waiting_appointments'] ?? 0),
'completed' => (int) ($todaySchedule['completed_appointments'] ?? 0),
'missed' => (int) ($todaySchedule['missed_appointments'] ?? 0),
'empty_slots' => 0,
'passed_slots' => 0,
'remaining_slots' => 0,
'doctor_count' => (int) ($todaySchedule['doctor_count'] ?? 0),
]
: [
'total_visits' => (int) ($todaySchedule['total_slots'] ?? 0),
'booked' => (int) ($todaySchedule['booked_slots'] ?? 0),
'completed' => 0,
'missed' => 0,
// 空号口径:剩余可预约号源(未过时刻且未被有效挂号占用),过号单独给出
'empty_slots' => (int) ($todaySchedule['remaining_slots'] ?? 0),
'passed_slots' => (int) ($todaySchedule['passed_slots'] ?? 0),
'remaining_slots' => (int) ($todaySchedule['remaining_slots'] ?? 0),
'doctor_count' => (int) ($todaySchedule['doctor_count'] ?? 0),
];
return [
'summary' => $summary,
'schedule_mode' => $scheduleMode,
'today_overview' => $todayOverview,
'week_schedule' => $weekSchedule,
'scope' => MyPatientLogic::scopeMeta($this->adminId, $this->adminInfo),
'dates' => ['start' => $startDate, 'end' => $endDate],
];
}
private function buildQuery(bool $applyStatus): Query
{
$query = Appointment::alias('a')
->join('tcm_diagnosis d', 'a.patient_id = d.id')
->leftJoin('admin doctor_admin', 'a.doctor_id = doctor_admin.id')
->leftJoin('admin assistant_admin', 'CAST(d.assistant_id AS UNSIGNED) = assistant_admin.id')
->whereNull('d.delete_time')
->where('d.status', 1);
MyPatientLogic::applyScope($query, $this->adminId, $this->adminInfo);
$this->applyKeyword($query);
$this->applyDateFilter($query);
if ($applyStatus) {
$status = $this->params['status'] ?? '';
if ($status !== '' && $status !== null && in_array((int) $status, self::EFFECTIVE_STATUSES, true)) {
$query->where('a.status', (int) $status);
} else {
$query->whereIn('a.status', self::EFFECTIVE_STATUSES);
}
} else {
$query->whereIn('a.status', self::EFFECTIVE_STATUSES);
}
return $query;
}
private function applyKeyword(Query $query): void
{
$keyword = trim((string) ($this->params['keyword'] ?? ''));
if ($keyword === '') {
return;
}
$query->where(function ($q) use ($keyword) {
$like = '%' . $keyword . '%';
$q->whereLike('d.patient_name', $like)
->whereOr('d.phone', 'like', $like)
->whereOr('doctor_admin.name', 'like', $like)
->whereOr('assistant_admin.name', 'like', $like);
if (preg_match('/^\d+$/', $keyword)) {
$id = (int) $keyword;
if ($id > 0) {
$q->whereOr('a.id', $id)->whereOr('d.id', $id);
}
}
});
}
private function applyDateFilter(Query $query): void
{
[$startDate, $endDate] = $this->dateRange();
$query->whereBetween('a.appointment_date', [$startDate, $endDate]);
}
/** @return array{0:string,1:string} */
private function dateRange(): array
{
$today = date('Y-m-d');
$startDate = $this->normalizeDate($this->params['start_date'] ?? '') ?: $today;
$endDate = $this->normalizeDate($this->params['end_date'] ?? '') ?: $startDate;
if ($startDate > $endDate) {
[$startDate, $endDate] = [$endDate, $startDate];
}
$startTs = strtotime($startDate);
$endTs = strtotime($endDate);
if ($startTs !== false && $endTs !== false && $endTs - $startTs > 31 * 86400) {
$endDate = date('Y-m-d', $startTs + 31 * 86400);
}
return [$startDate, $endDate];
}
private function normalizeDate($value): string
{
$value = trim((string) $value);
return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) ? $value : '';
}
/**
* @param array<int, array<string, mixed>> $rows
* @return array<int, array<string, mixed>>
*/
private function appendProgress(array $rows): array
{
if ($rows === []) {
return [];
}
$diagnosisIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'diagnosis_id')))));
$appointmentIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'id')))));
$queuePositionMap = $this->queuePositionMap($rows);
$confirmedSet = [];
if ($diagnosisIds !== []) {
$viewTable = (new DiagnosisViewRecord())->getTable();
$confirmedIds = Db::table($viewTable)
->whereIn('diagnosis_id', $diagnosisIds)
->where('is_confirmed', 1)
->whereNull('delete_time')
->column('diagnosis_id');
$confirmedSet = array_fill_keys(array_map('intval', $confirmedIds), true);
}
$prescriptionMap = [];
if ($appointmentIds !== []) {
$prescriptions = Prescription::whereIn('appointment_id', $appointmentIds)
->whereNull('delete_time')
->where('void_status', 0)
->field(['id', 'appointment_id', 'audit_status', 'is_system_auto'])
->order('id', 'desc')
->select()
->toArray();
foreach ($prescriptions as $prescription) {
$appointmentId = (int) ($prescription['appointment_id'] ?? 0);
if ($appointmentId > 0 && !isset($prescriptionMap[$appointmentId])) {
$prescriptionMap[$appointmentId] = $prescription;
}
}
}
foreach ($rows as &$row) {
$appointmentId = (int) ($row['id'] ?? 0);
$diagnosisId = (int) ($row['diagnosis_id'] ?? 0);
$status = (int) ($row['status'] ?? 0);
$prescription = $prescriptionMap[$appointmentId] ?? [];
$confirmed = isset($confirmedSet[$diagnosisId]);
$prescribed = $prescription !== [];
$aheadCount = $status === 1 ? (int) ($queuePositionMap[$appointmentId] ?? 0) : 0;
$row['phone_masked'] = $this->maskPhone((string) ($row['phone'] ?? ''));
unset($row['phone']);
$row['gender_desc'] = (int) ($row['gender'] ?? 0) === 1 ? '男' : '女';
$row['assistant_name'] = trim((string) ($row['assistant_name'] ?? '')) ?: '未分配';
$row['doctor_name'] = trim((string) ($row['doctor_name'] ?? '')) ?: '未知医生';
$row['appointment_time_text'] = $this->appointmentTimeText($row);
$row['status_text'] = $this->appointmentStatusText($status);
$row['appointment_type_text'] = $this->appointmentTypeText((string) ($row['appointment_type'] ?? ''));
$row['registered'] = 1;
$row['diagnosis_confirmed'] = $confirmed ? 1 : 0;
$row['visit_completed'] = $status === 3 ? 1 : 0;
$row['has_prescription'] = $prescribed ? 1 : 0;
$row['prescription_id'] = (int) ($prescription['id'] ?? 0);
$row['prescription_audit_status'] = $prescribed ? (int) ($prescription['audit_status'] ?? 0) : -1;
$row['progress_text'] = $this->progressText($confirmed, $status === 3, $prescribed, $status);
$row['queue_no'] = $status === 1 ? $aheadCount + 1 : 0;
$row['ahead_count'] = $aheadCount;
$row['estimated_wait_minutes'] = $aheadCount * self::AVG_MINUTES_PER_VISIT;
$row['queue_status'] = $this->queueStatus($status, $confirmed, $aheadCount);
$row['queue_status_text'] = $this->queueStatusText((string) $row['queue_status']);
$row['is_self_patient'] = (
(int) ($row['assistant_id'] ?? 0) === $this->adminId
|| (int) ($row['doctor_id'] ?? 0) === $this->adminId
) ? 1 : 0;
}
unset($row);
return $rows;
}
/**
* 候诊位次按 progress.vue 的真实规则计算:同医生、同日、待就诊,按预约时刻和挂号 ID 升序。
* 队列计算读取完整医生队列,只向当前范围列表返回人数,不暴露范围外患者身份。
*
* @param array<int,array<string,mixed>> $rows
* @return array<int,int>
*/
private function queuePositionMap(array $rows): array
{
$doctorIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'doctor_id')))));
$dates = array_values(array_unique(array_filter(array_map('strval', array_column($rows, 'appointment_date')))));
if ($doctorIds === [] || $dates === []) {
return [];
}
$queueRows = Appointment::whereIn('doctor_id', $doctorIds)
->whereIn('appointment_date', $dates)
->where('status', 1)
->field(['id', 'doctor_id', 'appointment_date', 'appointment_time'])
->order('doctor_id', 'asc')
->order('appointment_date', 'asc')
->order('appointment_time', 'asc')
->order('id', 'asc')
->select()
->toArray();
$groupCounts = [];
$positions = [];
foreach ($queueRows as $queueRow) {
$group = (int) ($queueRow['doctor_id'] ?? 0) . '|' . (string) ($queueRow['appointment_date'] ?? '');
$positions[(int) ($queueRow['id'] ?? 0)] = (int) ($groupCounts[$group] ?? 0);
$groupCounts[$group] = (int) ($groupCounts[$group] ?? 0) + 1;
}
return $positions;
}
/**
* 未来七天号源:完全复用 paiban/availableSlots 的生成口径,按医生+日期+时刻去重。
*
* @return array<int,array<string,mixed>>
*/
private function weekSchedule(): array
{
$startDate = date('Y-m-d');
$endDate = date('Y-m-d', strtotime($startDate . ' +6 days'));
$days = [];
for ($offset = 0; $offset < 7; $offset++) {
$date = date('Y-m-d', strtotime($startDate . " +{$offset} days"));
$days[$date] = $this->emptyScheduleDay($date);
}
$doctorIds = $this->visibleDoctorIds($startDate, $endDate);
if ($doctorIds === []) {
return array_values($days);
}
$rosters = Roster::whereIn('doctor_id', $doctorIds)
->whereBetween('date', [$startDate, $endDate])
->where('status', 1)
->whereNull('delete_time')
->field(['doctor_id', 'date', 'period', 'start_time', 'end_time', 'slot_minutes', 'quota'])
->select()
->toArray();
$doctorNames = Admin::whereIn('id', $doctorIds)->column('name', 'id');
$doctorSlotSets = [];
$doctorWindowSets = [];
foreach ($rosters as $roster) {
$date = (string) ($roster['date'] ?? '');
$doctorId = (int) ($roster['doctor_id'] ?? 0);
$window = RosterSegmentService::resolveWindow($roster);
if (!isset($days[$date]) || $doctorId <= 0 || $window === null) {
continue;
}
[$startTime, $endTime] = $window;
$times = RosterSegmentService::generateSlotTimes(
$startTime,
$endTime,
RosterSegmentService::normalizeSlotMinutes($roster['slot_minutes'] ?? 15)
);
$times = RosterSegmentService::applyQuotaCap($times, (int) ($roster['quota'] ?? 0));
foreach ($times as $time) {
$doctorSlotSets[$date][$doctorId][$time] = true;
}
$doctorWindowSets[$date][$doctorId][$startTime . '-' . $endTime] = true;
}
$appointments = Appointment::whereIn('doctor_id', $doctorIds)
->whereBetween('appointment_date', [$startDate, $endDate])
->where('status', 1)
->field(['doctor_id', 'appointment_date', 'appointment_time'])
->select()
->toArray();
$doctorBookedSets = [];
foreach ($appointments as $appointment) {
$date = (string) ($appointment['appointment_date'] ?? '');
$doctorId = (int) ($appointment['doctor_id'] ?? 0);
$time = substr((string) ($appointment['appointment_time'] ?? ''), 0, 5);
if (isset($doctorSlotSets[$date][$doctorId][$time])) {
$doctorBookedSets[$date][$doctorId][$time] = true;
}
}
$today = date('Y-m-d');
$nowHm = date('H:i');
foreach ($days as $date => &$day) {
$doctorDetails = [];
$total = 0;
$booked = 0;
$passed = 0;
$remaining = 0;
foreach ($doctorSlotSets[$date] ?? [] as $doctorId => $slotSet) {
$doctorTotal = count($slotSet);
$bookedSet = $doctorBookedSets[$date][$doctorId] ?? [];
$doctorBooked = count($bookedSet);
$doctorPassed = 0;
$doctorRemaining = 0;
foreach ($slotSet as $time => $_) {
if (isset($bookedSet[$time])) {
continue;
}
// 与挂号选号一致:今日已过(含当前分钟)的未约号源计为过号,其余为剩余可约
$isPassed = $date < $today || ($date === $today && strcmp((string) $time, $nowHm) <= 0);
if ($isPassed) {
$doctorPassed++;
} else {
$doctorRemaining++;
}
}
$total += $doctorTotal;
$booked += $doctorBooked;
$passed += $doctorPassed;
$remaining += $doctorRemaining;
$scheduleWindows = array_values(array_keys($doctorWindowSets[$date][$doctorId] ?? []));
sort($scheduleWindows, SORT_STRING);
$doctorDetails[] = [
'doctor_id' => (int) $doctorId,
'doctor_name' => trim((string) ($doctorNames[$doctorId] ?? '')) ?: '未知医生',
'schedule_windows' => $scheduleWindows,
'total_slots' => $doctorTotal,
'booked_slots' => $doctorBooked,
'passed_slots' => $doctorPassed,
'remaining_slots' => $doctorRemaining,
// 空号对外展示剩余可约;过号/未挂号细分见 passed/remaining
'empty_slots' => $doctorRemaining,
];
}
usort($doctorDetails, static function (array $left, array $right): int {
return $right['remaining_slots'] <=> $left['remaining_slots']
?: $right['booked_slots'] <=> $left['booked_slots']
?: $right['total_slots'] <=> $left['total_slots']
?: strcmp((string) $left['doctor_name'], (string) $right['doctor_name']);
});
$day['total_slots'] = $total;
$day['booked_slots'] = $booked;
$day['passed_slots'] = $passed;
$day['remaining_slots'] = $remaining;
$day['empty_slots'] = $remaining;
$day['doctor_count'] = count($doctorDetails);
$day['doctors'] = $doctorDetails;
}
unset($day);
return array_values($days);
}
/**
* 医助“本人归属”只统计其患者的真实挂号,不再把历史接诊医生的整周号源算到本人名下。
*
* @return array<int,array<string,mixed>>
*/
private function ownershipWeekSchedule(): array
{
$startDate = date('Y-m-d');
$endDate = date('Y-m-d', strtotime($startDate . ' +6 days'));
$days = [];
for ($offset = 0; $offset < 7; $offset++) {
$date = date('Y-m-d', strtotime($startDate . " +{$offset} days"));
$days[$date] = $this->emptyScheduleDay($date);
}
$query = Appointment::alias('ownership_a')
->join('tcm_diagnosis d', 'ownership_a.patient_id = d.id')
->leftJoin('admin ownership_doctor', 'ownership_a.doctor_id = ownership_doctor.id')
->whereNull('d.delete_time')
->where('d.status', 1)
->whereBetween('ownership_a.appointment_date', [$startDate, $endDate])
->whereIn('ownership_a.status', self::EFFECTIVE_STATUSES);
MyPatientLogic::applyScope($query, $this->adminId, $this->adminInfo);
$appointments = $query
->field([
'ownership_a.id', 'ownership_a.doctor_id', 'ownership_a.appointment_date',
'ownership_a.appointment_time', 'ownership_a.status',
'ownership_doctor.name AS doctor_name',
])
->order('ownership_a.appointment_date', 'asc')
->order('ownership_a.appointment_time', 'asc')
->order('ownership_a.id', 'asc')
->select()
->toArray();
$doctorDetails = [];
foreach ($appointments as $appointment) {
$date = (string) ($appointment['appointment_date'] ?? '');
$doctorId = (int) ($appointment['doctor_id'] ?? 0);
if (!isset($days[$date]) || $doctorId <= 0) {
continue;
}
if (!isset($doctorDetails[$date][$doctorId])) {
$doctorDetails[$date][$doctorId] = [
'doctor_id' => $doctorId,
'doctor_name' => trim((string) ($appointment['doctor_name'] ?? '')) ?: '未知医生',
'appointment_time_set' => [],
'total_appointments' => 0,
'waiting_appointments' => 0,
'completed_appointments' => 0,
'missed_appointments' => 0,
];
}
$time = substr((string) ($appointment['appointment_time'] ?? ''), 0, 5);
if ($time !== '') {
$doctorDetails[$date][$doctorId]['appointment_time_set'][$time] = true;
}
$status = (int) ($appointment['status'] ?? 0);
$doctorDetails[$date][$doctorId]['total_appointments']++;
if ($status === 1) {
$doctorDetails[$date][$doctorId]['waiting_appointments']++;
} elseif ($status === 3) {
$doctorDetails[$date][$doctorId]['completed_appointments']++;
} elseif ($status === 4) {
$doctorDetails[$date][$doctorId]['missed_appointments']++;
}
}
foreach ($days as $date => &$day) {
$rows = [];
foreach ($doctorDetails[$date] ?? [] as $doctor) {
$times = array_values(array_keys($doctor['appointment_time_set'] ?? []));
sort($times, SORT_STRING);
unset($doctor['appointment_time_set']);
$doctor['appointment_times'] = $times;
$rows[] = $doctor;
}
usort($rows, static function (array $left, array $right): int {
return $right['waiting_appointments'] <=> $left['waiting_appointments']
?: $right['total_appointments'] <=> $left['total_appointments']
?: strcmp((string) $left['doctor_name'], (string) $right['doctor_name']);
});
$day['total_appointments'] = array_sum(array_column($rows, 'total_appointments'));
$day['waiting_appointments'] = array_sum(array_column($rows, 'waiting_appointments'));
$day['completed_appointments'] = array_sum(array_column($rows, 'completed_appointments'));
$day['missed_appointments'] = array_sum(array_column($rows, 'missed_appointments'));
$day['doctor_count'] = count($rows);
$day['doctors'] = $rows;
}
unset($day);
return array_values($days);
}
private function usesOwnershipSchedule(): bool
{
if ((int) ($this->adminInfo['root'] ?? 0) === 1) {
return false;
}
$roleIds = $this->currentRoleIds();
return in_array(2, $roleIds, true) && array_intersect($roleIds, [3, 7, 8]) === [];
}
/** @return int[] */
private function visibleDoctorIds(string $startDate, string $endDate): array
{
if ((int) ($this->adminInfo['root'] ?? 0) === 1) {
$doctorIds = array_values(array_unique(array_map('intval', Roster::whereBetween('date', [$startDate, $endDate])
->where('status', 1)
->whereNull('delete_time')
->column('doctor_id'))));
return $this->activeDoctorIds($doctorIds);
}
$roleIds = $this->currentRoleIds();
$isTeamRole = array_intersect($roleIds, [3, 7, 8]) !== [];
$isDoctor = in_array(1, $roleIds, true);
$isAssistant = in_array(2, $roleIds, true);
// 纯医生账号的概览只统计本人排班,避免同一患者曾由其他医生接诊时放大到其他医生。
if (!$isTeamRole && $isDoctor && !$isAssistant) {
return $this->activeDoctorIds([$this->adminId]);
}
$query = Appointment::alias('scope_a')
->join('tcm_diagnosis d', 'scope_a.patient_id = d.id')
->whereNull('d.delete_time')
->where('d.status', 1)
->whereIn('scope_a.status', self::EFFECTIVE_STATUSES)
->where('scope_a.doctor_id', '>', 0);
MyPatientLogic::applyScope($query, $this->adminId, $this->adminInfo);
$doctorIds = array_values(array_unique(array_filter(array_map('intval', $query->distinct(true)->column('scope_a.doctor_id')))));
if (!$isTeamRole && $isDoctor) {
$doctorIds[] = $this->adminId;
}
return $this->activeDoctorIds(array_values(array_unique($doctorIds)));
}
/** @return int[] */
private function currentRoleIds(): array
{
return array_values(array_unique(array_filter(array_map('intval', AdminRole::where('admin_id', $this->adminId)->column('role_id')))));
}
/** @param int[] $doctorIds @return int[] */
private function activeDoctorIds(array $doctorIds): array
{
$doctorIds = array_values(array_unique(array_filter(array_map('intval', $doctorIds))));
if ($doctorIds === []) {
return [];
}
$roleDoctorIds = array_values(array_unique(array_map('intval', AdminRole::whereIn('admin_id', $doctorIds)
->where('role_id', 1)
->column('admin_id'))));
if ($roleDoctorIds === []) {
return [];
}
$activeSet = array_fill_keys(array_map('intval', Admin::whereIn('id', $roleDoctorIds)
->where('disable', 0)
->column('id')), true);
return array_values(array_filter($doctorIds, static function (int $doctorId) use ($activeSet): bool {
return isset($activeSet[$doctorId]);
}));
}
/** @return array<string,mixed> */
private function emptyScheduleDay(string $date): array
{
$weekdayLabels = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
$timestamp = strtotime($date) ?: time();
return [
'date' => $date,
'date_text' => date('m-d', $timestamp),
'weekday' => $weekdayLabels[(int) date('w', $timestamp)],
'total_slots' => 0,
'booked_slots' => 0,
'passed_slots' => 0,
'remaining_slots' => 0,
'empty_slots' => 0,
'doctor_count' => 0,
'doctors' => [],
'total_appointments' => 0,
'waiting_appointments' => 0,
'completed_appointments' => 0,
'missed_appointments' => 0,
];
}
private function queueStatus(int $status, bool $confirmed, int $aheadCount): string
{
if ($status === 3) {
return 'completed';
}
if ($status === 4) {
return 'missed';
}
if ($confirmed) {
return 'consulting';
}
return $aheadCount === 0 ? 'next' : 'waiting';
}
private function queueStatusText(string $status): string
{
return [
'completed' => '已完成',
'missed' => '已过号',
'consulting' => '就诊中',
'next' => '待确认',
'waiting' => '等待中',
][$status] ?? '等待中';
}
private function maskPhone(string $phone): string
{
return preg_replace('/^(\d{3})\d{4}(\d{4})$/', '$1****$2', $phone) ?: $phone;
}
private function appointmentTimeText(array $row): string
{
$time = trim((string) ($row['appointment_time'] ?? ''));
if (strlen($time) > 5) {
$time = substr($time, 0, 5);
}
return trim((string) ($row['appointment_date'] ?? '') . ' ' . $time);
}
private function appointmentStatusText(int $status): string
{
return [1 => '已挂号', 3 => '已完成', 4 => '已过号'][$status] ?? '未知';
}
private function appointmentTypeText(string $type): string
{
return ['video' => '视频问诊', 'text' => '图文问诊', 'phone' => '电话问诊'][$type] ?? '面诊';
}
private function progressText(bool $confirmed, bool $completed, bool $prescribed, int $status): string
{
if ($status === 4) {
return '已过号';
}
if (!$confirmed) {
return '待确认诊单';
}
if (!$completed) {
return '待完诊';
}
return $prescribed ? '已开方' : '待开方';
}
}