更新
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\logic\doctor\AppointmentLogic;
|
||||
use app\adminapi\lists\tcm\DiagnosisLists;
|
||||
use app\adminapi\validate\doctor\AppointmentValidate;
|
||||
use app\common\enum\AppointmentTypeEnum;
|
||||
use app\common\model\doctor\Appointment;
|
||||
|
||||
$testApp = new think\App();
|
||||
$testLang = new think\Lang($testApp);
|
||||
think\Validate::maker(static fn (think\Validate $validator) => $validator->setLang($testLang));
|
||||
|
||||
function appointmentTypeExpect(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'id' => 1,
|
||||
'patient_id' => 101,
|
||||
'doctor_id' => 202,
|
||||
'appointment_date' => '2026-09-10',
|
||||
'appointment_time' => '09:30',
|
||||
'period' => 'morning',
|
||||
'channel_source' => 'test',
|
||||
'status' => 1,
|
||||
];
|
||||
|
||||
foreach (['video' => '视频问诊', 'text' => '图文问诊'] as $type => $label) {
|
||||
foreach (['create', 'adminEdit'] as $scene) {
|
||||
$validator = (new AppointmentValidate())->scene($scene);
|
||||
appointmentTypeExpect($validator->check($payload + ['appointment_type' => $type]), "$scene accepts $type");
|
||||
}
|
||||
appointmentTypeExpect(AppointmentTypeEnum::description($type) === $label, "$type label round trip");
|
||||
appointmentTypeExpect(AppointmentTypeEnum::withDefault(['appointment_type' => $type])['appointment_type'] === $type, 'default does not override an explicit choice');
|
||||
}
|
||||
|
||||
$invalidValues = ['', ' ', 'phone', 'Text', ' video ', 'unknown', 0, 1, true, false, null, [], ['text']];
|
||||
foreach ($invalidValues as $value) {
|
||||
foreach (['create', 'adminEdit'] as $scene) {
|
||||
appointmentTypeExpect(!(new AppointmentValidate())->scene($scene)->check($payload + ['appointment_type' => $value]), "$scene rejects " . json_encode($value));
|
||||
}
|
||||
// Invalid requests must be rejected before touching a database, even if called outside the controller.
|
||||
appointmentTypeExpect(AppointmentLogic::create(['appointment_type' => $value]) === false, 'create rejects invalid type before DB');
|
||||
appointmentTypeExpect(AppointmentLogic::adminEdit(['appointment_type' => $value], 0, []) === false, 'edit rejects invalid type before DB');
|
||||
}
|
||||
|
||||
appointmentTypeExpect((new AppointmentValidate())->scene('create')->check($payload), 'legacy create request may omit type');
|
||||
appointmentTypeExpect(AppointmentTypeEnum::withDefault([])['appointment_type'] === 'video', 'omitted create type persists as video');
|
||||
appointmentTypeExpect(!(new AppointmentValidate())->scene('adminEdit')->check($payload), 'edit cannot silently reset an existing text selection');
|
||||
appointmentTypeExpect(AppointmentLogic::adminEdit([], 0, []) === false, 'internal edit also requires explicit type');
|
||||
|
||||
$model = (new ReflectionClass(Appointment::class))->newInstanceWithoutConstructor();
|
||||
foreach ([null, '', ' '] as $legacyEmpty) {
|
||||
appointmentTypeExpect($model->getAppointmentTypeAttr($legacyEmpty) === 'video', 'legacy empty model value uses video');
|
||||
appointmentTypeExpect($model->getAppointmentTypeDescAttr(null, ['appointment_type' => $legacyEmpty]) === '视频问诊', 'legacy empty model label uses video');
|
||||
}
|
||||
appointmentTypeExpect(AppointmentTypeEnum::description('phone') === '电话问诊', 'historical phone records retain accurate labels');
|
||||
|
||||
$filter = (new ReflectionClass(AppointmentLogic::class))->getMethod('filterAppointmentRowByExistingColumns');
|
||||
appointmentTypeExpect($filter->invoke(null, ['appointment_type' => 'text'], ['appointment_type']) === ['appointment_type' => 'text'], 'text is retained in database write payload');
|
||||
try {
|
||||
$filter->invoke(null, ['appointment_type' => 'text'], ['id']);
|
||||
throw new RuntimeException('missing appointment_type column must not silently lose the selected type');
|
||||
} catch (RuntimeException $exception) {
|
||||
appointmentTypeExpect(str_contains($exception->getMessage(), '挂号表缺少 appointment_type'), 'missing schema yields an actionable error');
|
||||
}
|
||||
|
||||
$summary = (new ReflectionClass(DiagnosisLists::class))->getMethod('appendLatestAppointmentSummary');
|
||||
$lists = (new ReflectionClass(DiagnosisLists::class))->newInstanceWithoutConstructor();
|
||||
$row = [];
|
||||
$summary->invokeArgs($lists, [&$row, ['id' => 8, 'appointment_type' => 'text']]);
|
||||
appointmentTypeExpect($row['latest_appointment_id'] === 8 && $row['latest_appointment_type'] === 'text' && $row['latest_appointment_type_desc'] === '图文问诊', 'latest appointment summary keeps its own type');
|
||||
$summary->invokeArgs($lists, [&$row, ['id' => 9, 'appointment_type' => null]]);
|
||||
appointmentTypeExpect($row['latest_appointment_type'] === 'video', 'next legacy appointment does not inherit previous text type');
|
||||
|
||||
echo "Appointment type validation, defaults, legacy labels and summary: OK\n";
|
||||
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Real ORM/transaction tests. Requires an explicitly selected disposable local MySQL.
|
||||
* Run: ZYT_RX_ORDER_TEST_MYSQL_PORT=13379 php tests/PrescriptionOrderReleaseAndTimeTest.php
|
||||
* Never initializes the application or loads its business database configuration.
|
||||
*/
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\lists\tcm\PrescriptionLists;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\adminapi\validate\tcm\PrescriptionOrderValidate;
|
||||
use think\Container;
|
||||
use think\DbManager;
|
||||
use think\facade\Db;
|
||||
|
||||
$port = (int) getenv('ZYT_RX_ORDER_TEST_MYSQL_PORT');
|
||||
if ($port <= 0) {
|
||||
fwrite(STDERR, "Set ZYT_RX_ORDER_TEST_MYSQL_PORT to an isolated local MySQL instance.\n");
|
||||
exit(1);
|
||||
}
|
||||
$isWorker = ($argv[1] ?? '') === '--worker';
|
||||
$database = $isWorker ? (string) getenv('ZYT_RX_ORDER_TEST_DATABASE') : 'rx_order_test_' . bin2hex(random_bytes(6));
|
||||
if (!preg_match('/^rx_order_test_[a-f0-9]{12}$/', $database)) {
|
||||
throw new RuntimeException('Only this test\'s disposable databases are allowed');
|
||||
}
|
||||
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
if (!$isWorker) $pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
'connections' => ['mysql' => [
|
||||
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port,
|
||||
'database' => $database, 'username' => 'root', 'password' => '',
|
||||
'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]],
|
||||
]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
Container::getInstance()->instance('config', new think\Config());
|
||||
$testLang = new think\Lang($testApp);
|
||||
think\Validate::maker(static fn (think\Validate $validator) => $validator->setLang($testLang));
|
||||
$admin = ['root' => 1, 'admin_id' => 1, 'name' => '隔离测试管理员'];
|
||||
$checks = 0;
|
||||
$expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) throw new RuntimeException($message . ' | ' . PrescriptionOrderLogic::getError());
|
||||
$checks++;
|
||||
};
|
||||
$createParams = static fn (int $rxId): array => [
|
||||
'prescription_id' => $rxId, 'diagnosis_id' => 1, 'recipient_name' => '测试患者',
|
||||
'recipient_phone' => '13000000000', 'shipping_address' => '测试地址', 'fee_type' => 3, 'amount' => 100,
|
||||
];
|
||||
if ($isWorker) {
|
||||
echo "ready\n";
|
||||
flush();
|
||||
$out = PrescriptionOrderLogic::create($createParams((int) $argv[2]), 1, $admin);
|
||||
echo json_encode(['success' => is_array($out), 'error' => PrescriptionOrderLogic::getError()]) . "\n";
|
||||
exit(0);
|
||||
}
|
||||
|
||||
try {
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order
|
||||
ADD agency_collect_amount DECIMAL(10,2) NULL, ADD paid DECIMAL(10,2) DEFAULT 0,
|
||||
ADD refund_amount DECIMAL(10,2) DEFAULT 0, ADD express_company VARCHAR(20) DEFAULT "auto",
|
||||
ADD ship_mode VARCHAR(20) DEFAULT "gancao", ADD remark_assistant VARCHAR(500) DEFAULT "",
|
||||
ADD gancao_reciperl_order_no VARCHAR(100) DEFAULT ""');
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, diagnosis_id INT DEFAULT 1, gender INT DEFAULT 0,
|
||||
creator_id INT DEFAULT 1, assistant_id INT DEFAULT 0, is_shared INT DEFAULT 0,
|
||||
herbs TEXT, audit_status INT DEFAULT 1, void_status INT DEFAULT 0, visible_role_ids VARCHAR(100) DEFAULT "",
|
||||
audit_time INT NULL, audit_by INT NULL, audit_by_name VARCHAR(100) DEFAULT "", audit_remark VARCHAR(500) DEFAULT "",
|
||||
create_time INT DEFAULT 0, update_time INT DEFAULT 0, delete_time INT NULL
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec('CREATE TABLE zyt_order (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(50), patient_id INT DEFAULT 1,
|
||||
creator_id INT DEFAULT 1, order_type INT DEFAULT 3, amount DECIMAL(10,2), status INT,
|
||||
remark VARCHAR(200) DEFAULT "", is_exempt INT DEFAULT 0, payment_method VARCHAR(50) DEFAULT "",
|
||||
create_type VARCHAR(50) DEFAULT "", create_time INT DEFAULT 0, update_time INT DEFAULT 0, delete_time INT NULL
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_09_prescription_order_pay_links.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT,
|
||||
admin_name VARCHAR(64), action VARCHAR(32), summary VARCHAR(500), create_time INT
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_diagnosis (id INT PRIMARY KEY, assistant_id INT DEFAULT 0, delete_time INT NULL)');
|
||||
$pdo->exec('INSERT INTO zyt_tcm_diagnosis (id) VALUES (1)');
|
||||
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, source_revision INT, status VARCHAR(50)
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY, name VARCHAR(100), delete_time INT NULL)');
|
||||
$pdo->exec('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_system_role_menu (role_id INT, menu_id INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_system_menu (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, pid INT, type VARCHAR(5), name VARCHAR(100), icon VARCHAR(50),
|
||||
sort INT, perms VARCHAR(100), paths VARCHAR(100), component VARCHAR(100), selected VARCHAR(100),
|
||||
params VARCHAR(100), is_cache INT, is_show INT, is_disable INT DEFAULT 0, create_time INT, update_time INT
|
||||
)');
|
||||
|
||||
$newRx = static fn (array $fields = []): int => (int) Db::name('tcm_prescription')->insertGetId(array_merge(['herbs' => '[]'], $fields));
|
||||
$fixture = static fn (int $rx, array $fields = []): int => (int) Db::name('tcm_prescription_order')->insertGetId(array_merge([
|
||||
'prescription_id' => $rx, 'order_no' => 'OLD-' . bin2hex(random_bytes(4)), 'diagnosis_id' => 1,
|
||||
'creator_id' => 1, 'amount' => 100, 'paid' => 100, 'payment_slip_audit_status' => 1,
|
||||
'create_time' => 1724300000, 'fulfillment_status' => 5,
|
||||
], $fields));
|
||||
$row = static fn (int $id): array => Db::name('tcm_prescription_order')->where('id', $id)->find();
|
||||
$logRows = static fn (int $id): array => Db::name('tcm_prescription_order_log')->where('prescription_order_id', $id)->order('id')->select()->toArray();
|
||||
$detail = static fn (int $rx): array => PrescriptionLogic::detail($rx, 1, $admin);
|
||||
$listsClass = new ReflectionClass(PrescriptionLists::class);
|
||||
$lists = $listsClass->newInstanceWithoutConstructor();
|
||||
foreach (['adminInfo' => $admin, 'adminId' => 1, 'params' => [], 'searchWhere' => [], 'limitOffset' => 0, 'limitLength' => 1000] as $name => $value) {
|
||||
$listsClass->getProperty($name)->setValue($lists, $value);
|
||||
}
|
||||
$listRow = static function (int $rx) use ($lists): array {
|
||||
return array_values(array_filter($lists->lists(), static fn (array $r): bool => (int) $r['id'] === $rx))[0];
|
||||
};
|
||||
|
||||
// Existing refunded/cancelled/deleted history never blocks a new order or contaminates active audit flags.
|
||||
foreach ([['fulfillment_status' => 10], ['fulfillment_status' => 4], ['delete_time' => time()]] as $released) {
|
||||
$rx = $newRx();
|
||||
$oldId = $fixture($rx, array_merge($released, ['prescription_audit_status' => 2, 'prescription_audit_remark' => '旧驳回']));
|
||||
$before = $row($oldId);
|
||||
$expect($detail($rx)['has_prescription_order'] === 0 && $listRow($rx)['has_prescription_order'] === 0, 'Released history must be available in list and detail');
|
||||
$expect($detail($rx)['business_prescription_audit_rejected'] === 0 && $listRow($rx)['business_prescription_audit_rejected'] === 0, 'Released history must not carry rejection badges');
|
||||
$expect($listsClass->getMethod('collectRiskPrescriptionIds')->invoke($lists, [$rx]) === [], 'Released orders must not pin herb-risk rows');
|
||||
$out = PrescriptionOrderLogic::create($createParams($rx), 1, $admin);
|
||||
$expect(is_array($out), 'Approved prescription must support creating after released history');
|
||||
$expect($row($oldId) === $before, 'Creation must preserve all historical order fields');
|
||||
$expect($detail($rx)['has_prescription_order'] === 1 && $listRow($rx)['has_prescription_order'] === 1, 'New order must occupy the prescription in list and detail');
|
||||
$expect(PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'A second live order must be rejected');
|
||||
}
|
||||
foreach ([1, 2, 3, 5, 6, 7, 8, 9, 11, 12] as $status) {
|
||||
$rx = $newRx();
|
||||
$fixture($rx, ['fulfillment_status' => 10]);
|
||||
$fixture($rx, ['fulfillment_status' => $status]);
|
||||
$expect($detail($rx)['has_prescription_order'] === 1 && $listRow($rx)['has_prescription_order'] === 1, 'Every nonreleased live status must occupy prescription, even with refunded history');
|
||||
$expect(PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'Live status must prevent duplicate creation');
|
||||
}
|
||||
|
||||
// Exercise the actual refund endpoint logic and preserve payment/remote history and approved prescription.
|
||||
$rx = $newRx();
|
||||
$oldId = $fixture($rx, ['gancao_reciperl_order_no' => 'REMOTE-HISTORY']);
|
||||
$payId = Db::name('order')->insertGetId(['order_no' => 'PAID-HISTORY', 'status' => 2, 'amount' => 100]);
|
||||
Db::name('tcm_prescription_order_pay_order')->insert(['prescription_order_id' => $oldId, 'pay_order_id' => $payId, 'create_time' => time()]);
|
||||
Db::name('tcm_prescription_order')->where('id', $oldId)->update(['linked_pay_order_id' => $payId]);
|
||||
$out = PrescriptionOrderLogic::refund($oldId, '测试全退', 1, $admin);
|
||||
$expect(is_array($out) && (int) $out['fulfillment_status'] === 10, 'Full refund must transition to released status');
|
||||
$expect((int) Db::name('order')->where('id', $payId)->value('status') === 4, 'Original payment must stay linked and be marked refunded');
|
||||
$expect(Db::name('tcm_prescription_order_pay_order')->where('prescription_order_id', $oldId)->count() === 1, 'Refund must preserve payment association history');
|
||||
$expect($detail($rx)['has_prescription_order'] === 0 && (int) $detail($rx)['audit_status'] === 1, 'Refund must release an already approved prescription without resetting approval');
|
||||
$expect(is_array(PrescriptionOrderLogic::create($createParams($rx), 1, $admin)), 'Actual refund must permit a new business order');
|
||||
$expect($row($oldId)['gancao_reciperl_order_no'] === 'REMOTE-HISTORY' && (int) $row($oldId)['prescription_id'] === $rx, 'New order must preserve old remote and prescription associations');
|
||||
$rx = $newRx();
|
||||
$oldId = $fixture($rx);
|
||||
$out = PrescriptionOrderLogic::refund($oldId, '测试部分退款', 1, $admin, 20);
|
||||
$expect(is_array($out) && (int) $out['fulfillment_status'] === 5 && (float) $out['paid'] === 80.0, 'Partial refund must remain active while there is a balance');
|
||||
$expect($detail($rx)['has_prescription_order'] === 1 && PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'Partial refund must not release prescription');
|
||||
$out = PrescriptionOrderLogic::refund($oldId, '剩余全退', 1, $admin);
|
||||
$expect(is_array($out) && $detail($rx)['has_prescription_order'] === 0, 'Refunding remaining balance must release prescription');
|
||||
$rx = $newRx();
|
||||
$oldId = $fixture($rx, ['fulfillment_status' => 1]);
|
||||
$expect(is_array(PrescriptionOrderLogic::withdraw($oldId, 1, $admin)), 'Existing cancellation must still work');
|
||||
$expect(is_array(PrescriptionOrderLogic::create($createParams($rx), 1, $admin)), 'Withdrawn order must still release prescription');
|
||||
$rx = $newRx(['void_status' => 1]);
|
||||
$fixture($rx, ['fulfillment_status' => 10]);
|
||||
$expect(PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'Refund must never revive a voided prescription');
|
||||
$rx = $newRx(['delete_time' => time()]);
|
||||
$expect(PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'Deleted prescription must not be orderable');
|
||||
|
||||
// Audit-log failures roll back order creation and creation-time edits.
|
||||
$rx = $newRx();
|
||||
$oldId = $fixture($rx, ['fulfillment_status' => 10]);
|
||||
$before = $row($oldId);
|
||||
$pdo->exec("CREATE TRIGGER reject_order_log BEFORE INSERT ON zyt_tcm_prescription_order_log
|
||||
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced audit failure'");
|
||||
$expect(PrescriptionOrderLogic::create($createParams($rx), 1, $admin) === false, 'Create log failure must reject creation');
|
||||
$expect(Db::name('tcm_prescription_order')->where('prescription_id', $rx)->count() === 1, 'Create log failure must not leave a partial active order');
|
||||
$timeParams = ['id' => $oldId, 'create_time' => '2026-08-22 11:40:03'];
|
||||
$expect(PrescriptionOrderLogic::editTime($timeParams, 1, $admin) === false && $row($oldId) === $before, 'Time edit must roll back if audit logging fails');
|
||||
$pdo->exec('DROP TRIGGER reject_order_log');
|
||||
|
||||
// Dedicated permission is enforced before menu deployment, including owners and manager roles.
|
||||
foreach ([[], [3]] as $roles) {
|
||||
$out = PrescriptionOrderLogic::editTime($timeParams, 1, ['root' => 0, 'admin_id' => 1, 'role_id' => $roles]);
|
||||
$expect($out === false && $row($oldId) === $before, 'Ownership/general manager role must not imply time-edit permission');
|
||||
}
|
||||
foreach ([[], ['id' => 0, 'create_time' => '2026-08-22 11:40:03'], ['id' => 1, 'create_time' => ''],
|
||||
['id' => 1, 'create_time' => '2026-02-30 11:40:03'], ['id' => 1, 'create_time' => '2026-08-22'],
|
||||
['id' => 1, 'create_time' => ['2026-08-22 11:40:03']], ['id' => [1], 'create_time' => '2026-08-22 11:40:03']] as $invalid) {
|
||||
$expect(!(new PrescriptionOrderValidate())->scene('editTime')->check($invalid), 'Invalid time requests must be rejected');
|
||||
}
|
||||
$expect((new PrescriptionOrderValidate())->scene('editTime')->check($timeParams), 'Canonical creation datetime must validate');
|
||||
$out = PrescriptionOrderLogic::editTime($timeParams + ['paid' => 999, 'fulfillment_status' => 1], 1, $admin);
|
||||
$after = $row($oldId);
|
||||
$expect(is_array($out) && (int) $after['create_time'] === strtotime($timeParams['create_time']), 'Timestamp schema must retain Unix creation time');
|
||||
foreach ($before as $key => $value) {
|
||||
if (!in_array($key, ['create_time', 'update_time'], true)) $expect($after[$key] === $value, 'Time edit must preserve ' . $key);
|
||||
}
|
||||
$log = $logRows($oldId)[0];
|
||||
$expect($log['action'] === 'edit_time' && (int) $log['admin_id'] === 1
|
||||
&& str_contains($log['summary'], date('Y-m-d H:i:s', (int) $before['create_time']))
|
||||
&& str_contains($log['summary'], $timeParams['create_time']), 'Audit log must record operator, previous and new time');
|
||||
$expect(is_array(PrescriptionOrderLogic::editTime($timeParams, 1, $admin)) && count($logRows($oldId)) === 1, 'Repeated identical edit must not duplicate audit log');
|
||||
$deletedId = $fixture($newRx(), ['delete_time' => time()]);
|
||||
$expect(PrescriptionOrderLogic::editTime(['id' => $deletedId, 'create_time' => $timeParams['create_time']], 1, $admin) === false, 'Deleted order time must not be editable');
|
||||
$expect(PrescriptionOrderLogic::editTime(['id' => 999999, 'create_time' => $timeParams['create_time']], 1, $admin) === false, 'Missing order time must not be editable');
|
||||
|
||||
$pdo->exec("INSERT INTO zyt_system_menu (perms,is_disable) VALUES ('tcm.prescriptionOrder/lists',0)");
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/sql/1.9.20260909/add_prescription_order_edit_time_menu.sql');
|
||||
$pdo->exec($sql);
|
||||
$pdo->exec($sql);
|
||||
$expect(Db::name('system_menu')->where('perms', 'tcm.prescriptionOrder/editTime')->count() === 1, 'Time permission migration must be idempotent');
|
||||
$expect(Db::name('system_role_menu')->count() === 0, 'Migration must not grant privileges automatically');
|
||||
$menuId = Db::name('system_menu')->where('perms', 'tcm.prescriptionOrder/editTime')->value('id');
|
||||
Db::name('admin_role')->insert(['admin_id' => 2, 'role_id' => 2]);
|
||||
Db::name('system_role_menu')->insert(['role_id' => 2, 'menu_id' => $menuId]);
|
||||
$out = PrescriptionOrderLogic::editTime(['id' => $oldId, 'create_time' => '2026-08-23 11:40:03'], 2,
|
||||
['root' => 0, 'admin_id' => 2, 'role_id' => [2], 'name' => '获授权测试员']);
|
||||
$expect(is_array($out) && array_keys($out) === ['id', 'create_time'], 'Explicit time permission must work and return only safe fields');
|
||||
|
||||
// Two independent PHP connections race behind the prescription lock, including already-refunded history.
|
||||
foreach ([false, true] as $withHistory) {
|
||||
$rx = $newRx();
|
||||
if ($withHistory) $fixture($rx, ['fulfillment_status' => 10]);
|
||||
putenv('ZYT_RX_ORDER_TEST_DATABASE=' . $database);
|
||||
Db::startTrans();
|
||||
Db::name('tcm_prescription')->where('id', $rx)->lock(true)->find();
|
||||
$workers = [];
|
||||
try {
|
||||
foreach ([1, 2] as $_) {
|
||||
$process = proc_open([PHP_BINARY, __FILE__, '--worker', (string) $rx],
|
||||
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
if (!is_resource($process)) throw new RuntimeException('Cannot start concurrency worker');
|
||||
fclose($pipes[0]);
|
||||
$workers[] = [$process, $pipes];
|
||||
if (trim((string) fgets($pipes[1])) !== 'ready') throw new RuntimeException('Worker failed initialization');
|
||||
}
|
||||
} finally {
|
||||
Db::commit();
|
||||
}
|
||||
$results = [];
|
||||
foreach ($workers as [$process, $pipes]) {
|
||||
$output = stream_get_contents($pipes[1]);
|
||||
$errors = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
if (proc_close($process) !== 0) throw new RuntimeException('Worker failed: ' . $errors . $output);
|
||||
$results[] = json_decode(trim($output), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$expect(count(array_filter($results, static fn (array $r): bool => $r['success'])) === 1, 'Concurrent create must succeed exactly once');
|
||||
$expect(Db::name('tcm_prescription_order')->where('prescription_id', $rx)->whereNotIn('fulfillment_status', [4,10])->count() === 1, 'Concurrency must persist only one live order');
|
||||
}
|
||||
|
||||
// Compatibility with installations that store create_time as DATETIME.
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order ADD legacy_datetime DATETIME NULL');
|
||||
$pdo->exec('UPDATE zyt_tcm_prescription_order SET legacy_datetime=FROM_UNIXTIME(create_time)');
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order DROP create_time, CHANGE legacy_datetime create_time DATETIME NULL');
|
||||
$out = PrescriptionOrderLogic::editTime(['id' => $oldId, 'create_time' => '2026-08-24 11:40:03'], 1, $admin);
|
||||
$expect(is_array($out) && $row($oldId)['create_time'] === '2026-08-24 11:40:03', 'Datetime schema must preserve canonical datetime strings');
|
||||
echo "PrescriptionOrderReleaseAndTimeTest: {$checks} assertions passed\n";
|
||||
} finally {
|
||||
$manager->connect()->close();
|
||||
$pdo->exec("DROP DATABASE `{$database}`");
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Real MySQL/Think ORM regression tests; all enterprise WeChat requests are fake.
|
||||
* ZYT_WECOM_MEMBER_TEST_MYSQL_PORT must point at a disposable loopback MySQL server.
|
||||
* No application initialization, environment file, or business DB config is loaded.
|
||||
*/
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\logic\firstvisit\WecomPromotionLogic;
|
||||
use app\common\service\qywx\QywxCustomerAcquisitionApiService;
|
||||
use app\common\service\qywx\QywxPromotionMemberSchedulerService;
|
||||
use app\common\service\qywx\QywxPromotionRangeSyncService;
|
||||
use think\Container;
|
||||
use think\DbManager;
|
||||
use think\facade\Db;
|
||||
|
||||
final class MemberSyncFakeApi extends QywxCustomerAcquisitionApiService
|
||||
{
|
||||
public array $updates = [];
|
||||
public array $gets = [];
|
||||
public ?array $remoteUsers = null;
|
||||
public array $remoteDepartments = [];
|
||||
public string $failure = '';
|
||||
public ?Closure $onGet = null;
|
||||
|
||||
// Deliberately do not create the real HTTP client or token resolver.
|
||||
public function __construct() {}
|
||||
|
||||
public function updateLink(array $payload): array
|
||||
{
|
||||
$this->updates[] = $payload;
|
||||
if ($this->failure !== '') {
|
||||
throw new RuntimeException($this->failure);
|
||||
}
|
||||
return ['errcode' => 0, 'errmsg' => 'ok'];
|
||||
}
|
||||
|
||||
public function getLink(string $linkId): array
|
||||
{
|
||||
$this->gets[] = $linkId;
|
||||
$payload = $this->updates[count($this->updates) - 1] ?? [];
|
||||
$response = [
|
||||
'errcode' => 0,
|
||||
'link' => ['link_id' => $linkId, 'url' => 'https://work.weixin.qq.com/ca/isolated-test'],
|
||||
// Official GET shape: range is at the root, not under link.
|
||||
'range' => [
|
||||
'user_list' => $this->remoteUsers ?? ($payload['range']['user_list'] ?? []),
|
||||
'department_list' => $this->remoteDepartments,
|
||||
],
|
||||
];
|
||||
if ($this->onGet !== null) {
|
||||
($this->onGet)();
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
$port = (int) getenv('ZYT_WECOM_MEMBER_TEST_MYSQL_PORT');
|
||||
if ($port < 1024 || $port === 3306 || $port > 65535) {
|
||||
fwrite(STDERR, "Set ZYT_WECOM_MEMBER_TEST_MYSQL_PORT to an isolated local MySQL port (not 3306).\n");
|
||||
exit(1);
|
||||
}
|
||||
$database = 'wecom_member_test_' . bin2hex(random_bytes(6));
|
||||
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
'connections' => ['mysql' => [
|
||||
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port,
|
||||
'database' => $database, 'username' => 'root', 'password' => '',
|
||||
'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]],
|
||||
]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
Container::getInstance()->instance('config', new think\Config());
|
||||
$checks = 0;
|
||||
$passed = [];
|
||||
$failed = [];
|
||||
$expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
$checks++;
|
||||
};
|
||||
$run = static function (string $name, Closure $test) use (&$passed, &$failed): void {
|
||||
try {
|
||||
$test();
|
||||
$passed[] = $name;
|
||||
echo "PASS {$name}\n";
|
||||
} catch (Throwable $error) {
|
||||
$failed[$name] = $error->getMessage();
|
||||
echo "FAIL {$name}: {$error->getMessage()}\n";
|
||||
}
|
||||
};
|
||||
$admin = ['root' => 1, 'admin_id' => 1, 'name' => 'Isolated test administrator'];
|
||||
|
||||
try {
|
||||
// Use the deployed table definitions, without executing unrelated menu/cron mutations.
|
||||
$schemas = [
|
||||
'1.9.20260805/add_first_visit_wecom_promotion.sql' => ['qywx_promotion_pool', 'qywx_promotion_link'],
|
||||
'1.9.20260824/upgrade_qywx_promotion_member_dispatch.sql' => [
|
||||
'qywx_promotion_pool_member', 'qywx_promotion_dispatch_event', 'qywx_promotion_range_sync',
|
||||
],
|
||||
'1.9.20260828/add_wecom_promotion_pool_operators.sql' => ['qywx_promotion_pool_operator'],
|
||||
];
|
||||
foreach ($schemas as $file => $tables) {
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/sql/' . $file);
|
||||
foreach ($tables as $table) {
|
||||
if (!preg_match('/CREATE TABLE IF NOT EXISTS `zyt_' . preg_quote($table, '/') . '` \([\s\S]*?;/', $sql, $match)) {
|
||||
throw new RuntimeException('Missing fixture schema: ' . $table);
|
||||
}
|
||||
$pdo->exec($match[0]);
|
||||
}
|
||||
}
|
||||
$pdo->exec('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_system_role_menu (role_id INT, menu_id INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_system_menu (id INT PRIMARY KEY, perms VARCHAR(100), is_disable INT DEFAULT 0)');
|
||||
|
||||
$fixture = static function (array $syncFields = [], array $cachedUsers = ['XuKe', 'OldAssistant'], array $cachedDepartments = []): array {
|
||||
$poolId = (int) Db::name('qywx_promotion_pool')->insertGetId([
|
||||
'name' => '隔离范围同步测试', 'public_key' => bin2hex(random_bytes(16)), 'owner_admin_id' => 1,
|
||||
]);
|
||||
$linkId = (int) Db::name('qywx_promotion_link')->insertGetId([
|
||||
'pool_id' => $poolId, 'remote_link_id' => 'test-remote-' . $poolId,
|
||||
'wecom_url' => 'https://work.weixin.qq.com/ca/isolated-test', 'remote_status' => 1,
|
||||
'range_user_json' => json_encode($cachedUsers), 'range_department_json' => json_encode($cachedDepartments),
|
||||
]);
|
||||
foreach ([['XuKe', 1], ['OldAssistant', 0], ['AnotherOldAssistant', 0]] as $index => [$userId, $enabled]) {
|
||||
Db::name('qywx_promotion_pool_member')->insert([
|
||||
'pool_id' => $poolId, 'admin_id' => $index + 1, 'userid' => $userId,
|
||||
'enabled' => $enabled, 'today_date' => date('Y-m-d'),
|
||||
]);
|
||||
}
|
||||
Db::name('qywx_promotion_range_sync')->insert(array_replace([
|
||||
'pool_id' => $poolId, 'promotion_link_id' => $linkId, 'status' => 1,
|
||||
'desired_version' => 2, 'applied_version' => 1,
|
||||
], $syncFields));
|
||||
return [$poolId, $linkId, new MemberSyncFakeApi()];
|
||||
};
|
||||
$syncRow = static fn (int $poolId): array => Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->find();
|
||||
$linkRow = static fn (int $linkId): array => Db::name('qywx_promotion_link')->where('id', $linkId)->find();
|
||||
$retry = static fn (int $poolId, MemberSyncFakeApi $api): array => WecomPromotionLogic::syncMemberRange(
|
||||
$poolId, 1, $admin, new QywxPromotionRangeSyncService($api)
|
||||
);
|
||||
|
||||
$run('only XuKe is sent and both remote range dimensions are verified', static function () use ($fixture, $expect, $syncRow, $linkRow): void {
|
||||
[$poolId, $linkId, $api] = $fixture([], ['XuKe', 'OldAssistant'], ['42']);
|
||||
$result = (new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
$expect($result['status'] === 'synced', 'Exact confirmed range should sync');
|
||||
$expect(count($api->updates) === 1 && $api->gets === ['test-remote-' . $poolId], 'Must update then GET the same official link');
|
||||
$expect($api->updates[0]['range'] === ['user_list' => ['XuKe'], 'department_list' => []], 'Disabled members and departments must be removed from update');
|
||||
$link = $linkRow($linkId);
|
||||
$expect(json_decode($link['range_user_json'], true) === ['XuKe'] && json_decode($link['range_department_json'], true) === [], 'Save the GET-verified users and empty departments');
|
||||
$row = $syncRow($poolId);
|
||||
$expect((int) $row['status'] === 0 && (int) $row['applied_version'] === (int) $row['desired_version'] && $row['lock_token'] === '', 'Confirmed sync must finish its version and release the lease');
|
||||
});
|
||||
|
||||
foreach (['old user' => [['XuKe', 'OldAssistant'], []], 'department expansion' => [['XuKe'], ['42']]] as $name => [$users, $departments]) {
|
||||
$run('GET mismatch rejects ' . $name . ' and remains retryable', static function () use ($fixture, $expect, $syncRow, $linkRow, $users, $departments): void {
|
||||
[$poolId, $linkId, $api] = $fixture();
|
||||
$api->remoteUsers = $users;
|
||||
$api->remoteDepartments = $departments;
|
||||
$error = null;
|
||||
try {
|
||||
(new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
} catch (Throwable $caught) {
|
||||
$error = $caught;
|
||||
}
|
||||
$expect($error !== null, 'Mismatched confirmed range must reject sync');
|
||||
$row = $syncRow($poolId);
|
||||
$expect((int) $row['status'] === 3 && (int) $row['next_retry'] > time(), 'Mismatch must leave a scheduled retry');
|
||||
$expect((int) $row['applied_version'] === 1 && $row['last_error'] !== '' && $linkRow($linkId)['sync_error'] !== '', 'Failure must not advance confirmed version and must remain visible');
|
||||
$expect((int) Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->where('userid', 'OldAssistant')->value('enabled') === 0, 'Failure must preserve the saved offline switch');
|
||||
});
|
||||
}
|
||||
|
||||
$run('transport failure preserves last confirmed snapshot and retry', static function () use ($fixture, $expect, $syncRow, $linkRow): void {
|
||||
[$poolId, $linkId, $api] = $fixture();
|
||||
$before = $linkRow($linkId)['range_user_json'];
|
||||
$api->failure = 'fake upstream timeout';
|
||||
try {
|
||||
(new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
throw new LogicException('Expected fake transport error');
|
||||
} catch (RuntimeException $error) {
|
||||
$expect($error->getMessage() === $api->failure, 'Surface the transport error');
|
||||
}
|
||||
$row = $syncRow($poolId);
|
||||
$expect((int) $row['status'] === 3 && (int) $row['attempts'] === 1 && (int) $row['next_retry'] > time(), 'Transport failure must retain retry backoff');
|
||||
$expect($linkRow($linkId)['range_user_json'] === $before && $api->gets === [], 'Failed update cannot replace confirmed remote snapshot');
|
||||
});
|
||||
|
||||
$run('active sync lease cannot be reported as synced or stolen', static function () use ($fixture, $expect, $syncRow): void {
|
||||
$token = str_repeat('a', 32);
|
||||
[$poolId, , $api] = $fixture(['status' => 2, 'lock_token' => $token, 'lock_until' => time() + 90]);
|
||||
$result = (new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
$expect($result['status'] !== 'synced' && $api->updates === [] && $syncRow($poolId)['lock_token'] === $token, 'Existing worker keeps its active lease and caller stays pending');
|
||||
});
|
||||
|
||||
$run('version change during GET reports pending and resyncs', static function () use ($fixture, $expect, $syncRow): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
$api->onGet = static function () use ($poolId): void {
|
||||
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->inc('desired_version')->update();
|
||||
};
|
||||
$result = (new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
$row = $syncRow($poolId);
|
||||
$expect($result['status'] === 'pending' && (int) $row['status'] === 1, 'Stale confirmed version must report pending, never synced');
|
||||
$expect((int) $row['applied_version'] < (int) $row['desired_version'], 'Concurrent version must remain unconfirmed');
|
||||
$api->onGet = null;
|
||||
$expect((new QywxPromotionRangeSyncService($api))->syncPool($poolId)['status'] === 'synced', 'Next attempt should confirm the newer version');
|
||||
});
|
||||
|
||||
$run('lease expiry during GET cannot commit success', static function () use ($fixture, $expect, $syncRow): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
$api->onGet = static function () use ($poolId): void {
|
||||
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->update(['lock_until' => time() - 1]);
|
||||
};
|
||||
$result = (new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
$expect($result['status'] === 'pending' && (int) $syncRow($poolId)['status'] !== 0, 'Expired worker cannot acknowledge a completed sync');
|
||||
});
|
||||
|
||||
$run('superseded lease cannot overwrite newer worker snapshot', static function () use ($fixture, $expect, $syncRow, $linkRow): void {
|
||||
[$poolId, $linkId, $api] = $fixture();
|
||||
$newToken = str_repeat('b', 32);
|
||||
$api->onGet = static function () use ($poolId, $linkId, $newToken): void {
|
||||
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->update([
|
||||
'lock_token' => $newToken, 'lock_until' => time() + 90, 'desired_version' => 3,
|
||||
]);
|
||||
Db::name('qywx_promotion_link')->where('id', $linkId)->update(['range_user_json' => '["NewWorkerSnapshot"]']);
|
||||
};
|
||||
$result = (new QywxPromotionRangeSyncService($api))->syncPool($poolId);
|
||||
$expect($result['status'] === 'pending' && $syncRow($poolId)['lock_token'] === $newToken, 'Superseded worker must not release or acknowledge the new lease');
|
||||
$expect($linkRow($linkId)['range_user_json'] === '["NewWorkerSnapshot"]', 'Superseded worker must not overwrite a newer remote snapshot');
|
||||
});
|
||||
|
||||
foreach ([
|
||||
'expired running lease' => ['status' => 2, 'lock_token' => str_repeat('c', 32), 'lock_until' => time() - 1],
|
||||
'unconfirmed version' => ['status' => 0, 'desired_version' => 7, 'applied_version' => 6],
|
||||
] as $name => $fields) {
|
||||
$run('reconcile keeps ' . $name . ' pending despite matching cache', static function () use ($fixture, $expect, $syncRow, $fields): void {
|
||||
[$poolId] = $fixture($fields, ['XuKe']);
|
||||
$result = QywxPromotionMemberSchedulerService::reconcilePool($poolId);
|
||||
$expect($result['queued'] === true && (int) $syncRow($poolId)['status'] === 1, 'An unverified version or expired worker must be retried even when user cache matches');
|
||||
});
|
||||
}
|
||||
|
||||
$run('reconcile removes cached departments even when users match', static function () use ($fixture, $expect, $syncRow): void {
|
||||
[$poolId] = $fixture(['status' => 0, 'desired_version' => 2, 'applied_version' => 2], ['XuKe'], ['42']);
|
||||
$result = QywxPromotionMemberSchedulerService::reconcilePool($poolId);
|
||||
$expect($result['queued'] === true && (int) $syncRow($poolId)['status'] === 1, 'Residual department routes require a fresh update');
|
||||
});
|
||||
|
||||
foreach (['pending' => ['status' => 1], 'failed backoff' => ['status' => 3, 'next_retry' => time() + 300, 'last_error' => 'previous failure']] as $name => $fields) {
|
||||
$run('explicit retry repairs old ' . $name . ' without changing member switches', static function () use ($fixture, $expect, $syncRow, $retry, $fields): void {
|
||||
[$poolId, , $api] = $fixture($fields);
|
||||
$before = Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->column('enabled', 'userid');
|
||||
$result = $retry($poolId, $api);
|
||||
$expect($result['sync_status'] === 'synced' && $result['sync_error'] === '' && !$result['sync_queued'], 'Explicit retry must complete and return confirmed structured state');
|
||||
$expect($result['range_userids'] === ['XuKe'] && $result['range_department_ids'] === [] && count($api->updates) === 1, 'Retry must return the GET-confirmed member range');
|
||||
$expect($before === Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->column('enabled', 'userid') && (int) $syncRow($poolId)['status'] === 0, 'Retry must leave all switches unchanged');
|
||||
});
|
||||
}
|
||||
|
||||
$run('explicit retry active lease returns pending without false success', static function () use ($fixture, $expect, $retry, $syncRow): void {
|
||||
$token = str_repeat('d', 32);
|
||||
[$poolId, , $api] = $fixture(['status' => 2, 'lock_token' => $token, 'lock_until' => time() + 90]);
|
||||
$result = $retry($poolId, $api);
|
||||
$expect($result['sync_status'] === 'pending' && $result['sync_queued'] && $api->updates === [], 'In-flight retry must say pending');
|
||||
$expect($syncRow($poolId)['lock_token'] === $token && (int) $syncRow($poolId)['status'] === 2, 'Retry must preserve active worker ownership');
|
||||
});
|
||||
|
||||
$run('explicit retry API failure remains failed with saved local state', static function () use ($fixture, $expect, $retry, $syncRow): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
$api->failure = 'fake permission denied';
|
||||
$result = $retry($poolId, $api);
|
||||
$expect($result['sync_status'] === 'failed' && $result['sync_error'] !== '' && $result['sync_queued'], 'Failure should return a visible error and scheduled retry');
|
||||
$expect((int) $syncRow($poolId)['status'] === 3 && $result['range_userids'] === ['XuKe', 'OldAssistant'], 'Failure must expose the last confirmed range, including pending removal');
|
||||
});
|
||||
|
||||
$run('no eligible member is blocked and never sends empty official range', static function () use ($fixture, $expect, $retry, $syncRow): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->update(['enabled' => 0]);
|
||||
$result = $retry($poolId, $api);
|
||||
$expect($result['sync_status'] === 'blocked' && $result['sync_error'] !== '' && !$result['sync_queued'], 'Empty eligible range must clearly report blocked');
|
||||
$expect($api->updates === [] && (int) $syncRow($poolId)['status'] === 4, 'Blocked pool must not send an empty enterprise WeChat range');
|
||||
});
|
||||
|
||||
$run('explicit retry rejects pools outside operator scope', static function () use ($fixture, $expect): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
$error = null;
|
||||
try {
|
||||
WecomPromotionLogic::syncMemberRange($poolId, 99, ['root' => 0, 'admin_id' => 99], new QywxPromotionRangeSyncService($api));
|
||||
} catch (RuntimeException $caught) {
|
||||
$error = $caught;
|
||||
}
|
||||
$expect($error !== null && $api->updates === [], 'Unrelated account must not mutate remote member ranges');
|
||||
});
|
||||
|
||||
$run('batch repeated offline selection requeues the unsynced remote range', static function () use ($fixture, $expect, $syncRow, $admin): void {
|
||||
[$poolId, , $api] = $fixture(['status' => 0, 'desired_version' => 2, 'applied_version' => 2]);
|
||||
$result = WecomPromotionLogic::batchUpdatePools([
|
||||
'pool_ids' => [$poolId],
|
||||
'changes' => ['member_status' => ['member_admin_ids' => [2, 3], 'status' => 0]],
|
||||
], 1, $admin);
|
||||
$expect($result['failed'] === 0 && $result['member_matched'] === 2 && $result['member_updated'] === 0, 'An already-offline selection remains a valid repeat action');
|
||||
$expect($result['sync_queued_count'] === 1 && $result['results'][0]['sync_queued'] && (int) $syncRow($poolId)['status'] === 1, 'No-op local switches must still queue the stale official range');
|
||||
$expect((new QywxPromotionRangeSyncService($api))->syncPool($poolId)['status'] === 'synced' && $api->updates[0]['range']['user_list'] === ['XuKe'], 'The queued batch repair must leave only XuKe in the official link');
|
||||
});
|
||||
|
||||
$run('batch disables both old assistants and queue confirms XuKe only', static function () use ($fixture, $expect, $admin): void {
|
||||
[$poolId, , $api] = $fixture([], ['XuKe', 'OldAssistant', 'AnotherOldAssistant']);
|
||||
Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->update(['enabled' => 1]);
|
||||
$result = WecomPromotionLogic::batchUpdatePools([
|
||||
'pool_ids' => [$poolId],
|
||||
'changes' => ['member_status' => ['member_admin_ids' => [2, 3], 'status' => 0]],
|
||||
], 1, $admin);
|
||||
$expect($result['member_updated'] === 2 && $result['failed'] === 0 && $result['sync_queued_count'] === 1, 'Batch offline must save both switches and report queued remote work');
|
||||
$expect((new QywxPromotionRangeSyncService($api))->syncPool($poolId)['status'] === 'synced' && $api->updates[0]['range'] === ['user_list' => ['XuKe'], 'department_list' => []], 'Actual batch queue must update/get the final exact range');
|
||||
});
|
||||
|
||||
$run('single offline with active worker reports pending then retries successfully', static function () use ($fixture, $expect, $admin, $retry, $syncRow): void {
|
||||
$token = str_repeat('e', 32);
|
||||
[$poolId, , $api] = $fixture(['status' => 2, 'lock_token' => $token, 'lock_until' => time() + 90]);
|
||||
Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->where('userid', 'OldAssistant')->update(['enabled' => 1]);
|
||||
$memberId = (int) Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->where('userid', 'OldAssistant')->value('id');
|
||||
// Active lease prevents any real API request from the endpoint's default service.
|
||||
$result = WecomPromotionLogic::toggleMember($memberId, 0, 1, $admin);
|
||||
$expect($result['sync_status'] === 'pending' && $result['sync_queued'] && $syncRow($poolId)['lock_token'] === $token, 'Single toggle must not turn a service noop into success: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
|
||||
$expect((int) Db::name('qywx_promotion_pool_member')->where('id', $memberId)->value('enabled') === 0, 'Single toggle must persist offline locally while waiting for its worker');
|
||||
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->update(['lock_until' => time() - 1]);
|
||||
$expect($retry($poolId, $api)['sync_status'] === 'synced' && $api->updates[0]['range']['user_list'] === ['XuKe'], 'Explicit retry must clear the single-toggle pending removal');
|
||||
});
|
||||
|
||||
$run('single and batch preserve at least one eligible assistant', static function () use ($fixture, $expect, $admin): void {
|
||||
[$poolId] = $fixture();
|
||||
$memberId = (int) Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->where('userid', 'XuKe')->value('id');
|
||||
foreach (['single', 'batch'] as $method) {
|
||||
$error = null;
|
||||
try {
|
||||
if ($method === 'single') {
|
||||
WecomPromotionLogic::toggleMember($memberId, 0, 1, $admin);
|
||||
} else {
|
||||
WecomPromotionLogic::batchUpdatePools([
|
||||
'pool_ids' => [$poolId], 'changes' => ['member_status' => ['member_admin_ids' => [1], 'status' => 0]],
|
||||
], 1, $admin);
|
||||
}
|
||||
} catch (RuntimeException $caught) {
|
||||
$error = $caught;
|
||||
}
|
||||
$expect($error !== null && (int) Db::name('qywx_promotion_pool_member')->where('id', $memberId)->value('enabled') === 1, 'The final available member must remain online after rejected ' . $method . ' action');
|
||||
}
|
||||
});
|
||||
|
||||
$run('shared operator can retry its own assigned pool', static function () use ($fixture, $expect): void {
|
||||
[$poolId, , $api] = $fixture();
|
||||
Db::name('system_menu')->insert(['id' => 1, 'perms' => 'firstvisit.wecomPromotion/overview']);
|
||||
Db::name('qywx_promotion_pool_operator')->insert(['pool_id' => $poolId, 'admin_id' => 88]);
|
||||
$result = WecomPromotionLogic::syncMemberRange($poolId, 88, ['root' => 0, 'admin_id' => 88], new QywxPromotionRangeSyncService($api));
|
||||
$expect($result['sync_status'] === 'synced' && count($api->updates) === 1, 'Assigned operator should be allowed the targeted range retry');
|
||||
});
|
||||
|
||||
foreach ([
|
||||
'deleting' => ['status' => 5, 'lock_token' => str_repeat('f', 32), 'lock_until' => time() + 90],
|
||||
'delete failed' => ['status' => 4, 'last_error' => '企业微信官方获客链接删除失败: fake timeout'],
|
||||
] as $name => $fields) {
|
||||
$run('retry never revives ' . $name . ' pool', static function () use ($fixture, $expect, $retry, $syncRow, $fields): void {
|
||||
[$poolId, , $api] = $fixture($fields);
|
||||
$before = $syncRow($poolId);
|
||||
$result = $retry($poolId, $api);
|
||||
$expect($result['sync_status'] === 'blocked' && $api->updates === [] && $syncRow($poolId) === $before, 'Retry must preserve deletion ownership and leave remote API untouched');
|
||||
});
|
||||
}
|
||||
|
||||
echo json_encode(['passed' => count($passed), 'failed' => count($failed), 'checks' => $checks, 'failures' => $failed], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
|
||||
} finally {
|
||||
$pdo->exec("DROP DATABASE IF EXISTS `{$database}`");
|
||||
echo "Disposable test database dropped.\n";
|
||||
}
|
||||
exit($failed === [] ? 0 : 1);
|
||||
Reference in New Issue
Block a user