更新
This commit is contained in:
@@ -17,6 +17,7 @@ use app\common\service\prescriptionai\PrescriptionAiStore as Store;
|
||||
use app\common\service\prescriptionai\PrescriptionAiVisibility as Visibility;
|
||||
use DomainException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Log;
|
||||
|
||||
final class PrescriptionAiLogic
|
||||
{
|
||||
@@ -169,23 +170,30 @@ final class PrescriptionAiLogic
|
||||
if (!$task) {
|
||||
throw new DomainException('资料尚未准备完成,请查看分析状态');
|
||||
}
|
||||
if ($task['status'] === 'success' || in_array($task['status'], Policy::ACTIVE_TASKS, true)) {
|
||||
return ['batch_id' => $batchId, 'status' => $task['status']];
|
||||
}
|
||||
if ($task['status'] !== 'failed') {
|
||||
$now = time();
|
||||
$newRetry = $task['status'] === 'failed';
|
||||
if ($newRetry) {
|
||||
if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) {
|
||||
throw new DomainException('该模型已达手动重试上限,请检查失败原因');
|
||||
}
|
||||
$changes = [
|
||||
'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => $now,
|
||||
'manual_retries' => (int) $task['manual_retries'] + 1,
|
||||
'lock_token' => '', 'lock_until' => 0, 'error_code' => '', 'updated_at' => $now,
|
||||
];
|
||||
$task = array_replace($task, $changes);
|
||||
} elseif ($task['status'] !== 'success' && !in_array($task['status'], Policy::ACTIVE_TASKS, true)) {
|
||||
throw new DomainException('该任务不能重试');
|
||||
}
|
||||
if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) {
|
||||
throw new DomainException('该模型已达手动重试上限,请检查失败原因');
|
||||
$state = self::taskStates([$task], $now)[0];
|
||||
if ($newRetry) {
|
||||
// Keep audit history and the encrypted resume checkpoint across retry rounds.
|
||||
$changes['next_run_at'] = $state['progress']['next_run_at'];
|
||||
$changes['error_code'] = $state['error_code'];
|
||||
Db::name('prescription_ai_task')->where('id', $task['id'])->update($changes);
|
||||
Store::refreshBatch($batchId);
|
||||
}
|
||||
// Attempt history and lifetime counter remain immutable across retry rounds.
|
||||
Db::name('prescription_ai_task')->where('id', $task['id'])->update([
|
||||
'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => time(), 'lock_token' => '',
|
||||
'manual_retries' => (int) $task['manual_retries'] + 1,
|
||||
'lock_until' => 0, 'error_code' => '', 'updated_at' => time(),
|
||||
]);
|
||||
Store::refreshBatch($batchId);
|
||||
return ['batch_id' => $batchId, 'status' => 'retry_wait'];
|
||||
return ['batch_id' => $batchId, 'model_key' => $model] + $state;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -280,12 +288,54 @@ final class PrescriptionAiLogic
|
||||
'metric_label' => '药味与剂量一致度(不代表临床准确率)'];
|
||||
}
|
||||
|
||||
/** Project the retry response and polled model states from the same task, ledger and attempt history. */
|
||||
private static function taskStates(array $tasks, int $now): array
|
||||
{
|
||||
$budgetModels = [];
|
||||
$attemptTaskIds = [];
|
||||
foreach ($tasks as $task) {
|
||||
if ($task['status'] !== 'retry_wait') { continue; }
|
||||
if ($task['error_code'] !== 'BUDGET_PAUSED' || (int) $task['next_run_at'] <= $now) {
|
||||
$budgetModels[] = $task['model_key'];
|
||||
}
|
||||
if ((int) $task['total_attempts'] > 0) {
|
||||
$attemptTaskIds[] = $task['id'];
|
||||
}
|
||||
}
|
||||
$exhausted = Store::exhaustedModels($budgetModels, $now);
|
||||
$lastErrors = $attemptTaskIds ? Db::name('prescription_ai_attempt')->alias('a')
|
||||
->join('prescription_ai_task t', 't.id = a.task_id AND t.total_attempts = a.attempt_no')
|
||||
->whereIn('a.task_id', $attemptTaskIds)->whereIn('a.status', ['failed', 'expired'])
|
||||
->column('a.error_code', 'task_id') : [];
|
||||
$maxRetries = (int) config('prescription_analysis.max_manual_retries', 2);
|
||||
$states = [];
|
||||
foreach ($tasks as $task) {
|
||||
$code = $task['error_code'];
|
||||
$lastError = $task['status'] === 'failed' ? $code : ($lastErrors[$task['id']] ?? '');
|
||||
if ($task['status'] === 'retry_wait') {
|
||||
if (in_array($task['model_key'], $exhausted, true)) {
|
||||
$code = 'BUDGET_PAUSED';
|
||||
$task['next_run_at'] = max((int) $task['next_run_at'], strtotime('tomorrow', $now));
|
||||
} elseif ($code === 'BUDGET_PAUSED' && (int) $task['next_run_at'] <= $now) {
|
||||
$code = ''; // Yesterday's pause has expired; eligibility still awaits a real claim.
|
||||
}
|
||||
}
|
||||
$task['error_code'] = $code;
|
||||
$states[] = ['status' => $task['status'], 'error_code' => $code,
|
||||
'error_message' => $code !== '' ? Policy::errorMessage($code) : '',
|
||||
'last_error_code' => $lastError, 'last_error_message' => $lastError !== '' ? Policy::errorMessage($lastError) : '',
|
||||
'manual_retries' => (int) $task['manual_retries'], 'max_manual_retries' => $maxRetries,
|
||||
'progress' => Progress::task($task, $now)];
|
||||
}
|
||||
return $states;
|
||||
}
|
||||
|
||||
private static function models(array $batchIds, bool $full, bool $agreementVisible = true): array
|
||||
{
|
||||
if ($batchIds === []) {
|
||||
return [];
|
||||
}
|
||||
$taskFields = ['batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'result_id',
|
||||
$taskFields = ['id', 'batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'manual_retries', 'result_id',
|
||||
'started_at', 'finished_at', 'updated_at', 'next_run_at'];
|
||||
if (Store::supportsProgress()) {
|
||||
$taskFields[] = 'progress_json';
|
||||
@@ -298,14 +348,11 @@ final class PrescriptionAiLogic
|
||||
}
|
||||
$results = Db::name('prescription_ai_result')->whereIn('batch_id', $batchIds)->field($fields)->select()->toArray();
|
||||
$map = [];
|
||||
foreach ($tasks as $task) {
|
||||
$map[(int) $task['batch_id']][$task['model_key']] = [
|
||||
'status' => $task['status'], 'score' => null, 'herb_score' => null,
|
||||
'error_code' => $task['error_code'], 'error_message' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '',
|
||||
'reason' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '',
|
||||
'report_id' => (int) $task['result_id'],
|
||||
'progress' => Progress::task($task),
|
||||
];
|
||||
$taskStates = self::taskStates($tasks, time());
|
||||
foreach ($tasks as $index => $task) {
|
||||
$state = $taskStates[$index];
|
||||
$map[(int) $task['batch_id']][$task['model_key']] = $state + ['score' => null, 'herb_score' => null,
|
||||
'reason' => $state['error_message'], 'report_id' => (int) $task['result_id']];
|
||||
}
|
||||
foreach ($results as $result) {
|
||||
$body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : [];
|
||||
@@ -387,7 +434,17 @@ final class PrescriptionAiLogic
|
||||
if (!Access::sourceIds($ids, $actor, $info) || empty($batch['access_cipher'])) {
|
||||
return false;
|
||||
}
|
||||
$access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']);
|
||||
try {
|
||||
$access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']);
|
||||
} catch (\RuntimeException $e) {
|
||||
if ($e->getMessage() !== Cipher::INVALID_PAYLOAD) {
|
||||
throw $e;
|
||||
}
|
||||
// An unreadable authorization snapshot cannot establish access to this batch.
|
||||
Log::warning('Unreadable prescription AI access snapshot: {code} (batch_id={batch_id})',
|
||||
['code' => Cipher::INVALID_PAYLOAD, 'batch_id' => (int) $batch['id']]);
|
||||
return false;
|
||||
}
|
||||
return \app\common\service\prescriptionai\PrescriptionAiContext::assertSnapshotAccess($access, $actor, $info);
|
||||
}
|
||||
|
||||
|
||||
@@ -3015,7 +3015,8 @@ class PrescriptionOrderLogic
|
||||
|
||||
$logSummary = $summary;
|
||||
if ($changeParts !== []) {
|
||||
$logSummary .= '(' . implode(';', $changeParts) . ')';
|
||||
$changeSummary = '(' . implode(';', $changeParts) . ')';
|
||||
$logSummary = mb_substr($summary, 0, 500 - mb_strlen($changeSummary)) . $changeSummary;
|
||||
}
|
||||
self::writeLog($id, $adminId, $adminInfo, 'manual_log', $logSummary);
|
||||
|
||||
@@ -4482,26 +4483,30 @@ class PrescriptionOrderLogic
|
||||
}
|
||||
}
|
||||
|
||||
$paymentAuditActions = ['audit_pay_approve', 'audit_pay_reject'];
|
||||
$paymentAuditResetActions = [
|
||||
'revoke_pay_audit', 'audit_rx_reject', 'revoke_rx_audit', 'add_pay_order', 'link_pay_order', 'completion_request',
|
||||
];
|
||||
$logRows = PrescriptionOrderLog::whereIn('prescription_order_id', $poIds)
|
||||
->whereIn('action', ['audit_rx_approve', 'audit_rx_reject', 'revoke_rx_audit'])
|
||||
->field(['prescription_order_id', 'id', 'action', 'admin_name', 'create_time'])
|
||||
->whereIn('action', [...$paymentAuditActions, ...$paymentAuditResetActions, 'manual_log'])
|
||||
->field(['prescription_order_id', 'action', 'admin_name', 'create_time', 'summary'])
|
||||
->order('id', 'asc')
|
||||
->select()
|
||||
->toArray();
|
||||
$auditEffectiveByPo = [];
|
||||
$paymentAuditByPo = [];
|
||||
foreach ($logRows as $lg) {
|
||||
$pid = (int) ($lg['prescription_order_id'] ?? 0);
|
||||
if ($pid <= 0) {
|
||||
$pid = (int) $lg['prescription_order_id'];
|
||||
$action = $lg['action'];
|
||||
if (in_array($action, $paymentAuditActions, true)) {
|
||||
$paymentAuditByPo[$pid] = $lg;
|
||||
continue;
|
||||
}
|
||||
$act = (string) ($lg['action'] ?? '');
|
||||
if ($act === 'revoke_rx_audit') {
|
||||
$auditEffectiveByPo[$pid] = null;
|
||||
// 手工调整支付审核状态会追加固定格式的变更说明,普通备注不影响已有审核记录。
|
||||
if ($action === 'manual_log'
|
||||
&& !preg_match('/[(;]支付单审核:(待审核|已通过|已驳回) → (待审核|已通过|已驳回))$/u', (string) $lg['summary'])) {
|
||||
continue;
|
||||
}
|
||||
if ($act === 'audit_rx_approve' || $act === 'audit_rx_reject') {
|
||||
$auditEffectiveByPo[$pid] = $lg;
|
||||
}
|
||||
unset($paymentAuditByPo[$pid]);
|
||||
}
|
||||
|
||||
// 服务套餐字典:与前端 formatServicePackage 同口径(dict_data type_value=server_order;只取启用项做兜底取原值)
|
||||
@@ -4703,16 +4708,18 @@ class PrescriptionOrderLogic
|
||||
$item['export_center_label'] = '一中心';
|
||||
}
|
||||
|
||||
$paSt = (int) ($item['prescription_audit_status'] ?? 0);
|
||||
$aud = $auditEffectiveByPo[$poId] ?? null;
|
||||
if (($paSt === 1 || $paSt === 2) && \is_array($aud)) {
|
||||
$at = (int) ($aud['create_time'] ?? 0);
|
||||
$item['export_rx_audit_time'] = $at > 0 ? date('Y-m-d H:i:s', $at) : '';
|
||||
$item['export_rx_auditor'] = (string) ($aud['admin_name'] ?? '');
|
||||
} else {
|
||||
$item['export_rx_audit_time'] = '';
|
||||
$item['export_rx_auditor'] = '';
|
||||
$paymentAudit = $paymentAuditByPo[$poId] ?? [];
|
||||
$expectedAction = match ((int) ($item['payment_slip_audit_status'] ?? 0)) {
|
||||
1 => 'audit_pay_approve',
|
||||
2 => 'audit_pay_reject',
|
||||
default => null,
|
||||
};
|
||||
if ($expectedAction === null || ($paymentAudit['action'] ?? null) !== $expectedAction) {
|
||||
$paymentAudit = [];
|
||||
}
|
||||
$auditTime = (int) ($paymentAudit['create_time'] ?? 0);
|
||||
$item['export_payment_audit_time'] = $auditTime > 0 ? date('Y-m-d H:i:s', $auditTime) : '';
|
||||
$item['export_payment_auditor'] = (string) ($paymentAudit['admin_name'] ?? '');
|
||||
}
|
||||
unset($item);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user