feat(快递应付): 退回件明细与定时进仓同步 (#1717)
This commit is contained in:
parent
4722c93d57
commit
a75b0ee1ac
52
app/Console/Commands/SyncReturnedParcels.php
Normal file
52
app/Console/Commands/SyncReturnedParcels.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
|
||||
use Throwable;
|
||||
|
||||
class SyncReturnedParcels extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)}';
|
||||
protected $description = '同步聚水潭售后退货退款到快递应付退回件明细';
|
||||
|
||||
public function handle(ReturnedParcelSynchronizer $synchronizer): int
|
||||
{
|
||||
$from = (string) ($this->option('from') ?: ReturnedParcelSynchronizer::START);
|
||||
$to = (string) ($this->option('to') ?: now('Asia/Shanghai')->toDateString());
|
||||
foreach ([$from, $to] as $date) {
|
||||
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts)
|
||||
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
|
||||
$this->error('日期需要 YYYY-MM-DD。');
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
if ($from < ReturnedParcelSynchronizer::START || $from > $to) {
|
||||
$this->error('开始日期不得早于 2026-10-01,且不能晚于结束日期。');
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
|
||||
$this->error('请通过服务器 run-finance-batch.sh 执行同步。');
|
||||
return self::FAILURE;
|
||||
}
|
||||
$lock = Cache::lock('courier-returned-parcels-sync', 2100);
|
||||
if (! $lock->get()) {
|
||||
$this->warn('退回件同步正在运行,本次跳过。');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
try {
|
||||
$result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行"));
|
||||
$this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
|
||||
$from, $to, $result['rows'], $result['seconds'], $result['peak_mb']));
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。');
|
||||
return self::FAILURE;
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -71,6 +71,14 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 使用生产批处理入口,避免在网页容器运行全量退回件同步。
|
||||
$schedule->exec('sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels')
|
||||
->cron('0 10,16 * * *')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(60)
|
||||
->appendOutputTo(storage_path('logs/returned-parcels-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。
|
||||
$schedule->command('business-mirror:archive-store-information')
|
||||
->dailyAt('07:00')
|
||||
|
||||
@ -5972,6 +5972,7 @@ class Pages extends Controller
|
||||
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
||||
'shipping-data' => $this->contentForShippingData(),
|
||||
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
||||
'returned-parcels' => app(ReturnedParcelController::class)->page(request()),
|
||||
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
||||
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
||||
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
||||
|
||||
88
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
88
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer as Sync;
|
||||
use Throwable;
|
||||
|
||||
class ReturnedParcelController extends Controller
|
||||
{
|
||||
public const COLUMNS = [
|
||||
'received_at' => '进仓时间', 'after_sales_id' => '售后单号', 'online_after_sales_no' => '线上售后单号',
|
||||
'waybill' => '退回快递单号', 'courier' => '快递公司', 'shop' => '店铺', 'warehouse' => '收货仓库',
|
||||
'order_id' => '内部订单号', 'online_order_no' => '线上订单号', 'sku' => '商品编码', 'style_code' => '款式编码',
|
||||
'product_name' => '商品名称', 'properties' => '颜色规格', 'applied_qty' => '申请数量',
|
||||
'returned_qty' => '实退数量', 'price' => '商品单价', 'item_amount' => '明细金额',
|
||||
'status' => '售后状态', 'type' => '售后类型', 'goods_status' => '货物状态', 'reason' => '问题类型',
|
||||
'remark' => '备注', 'source_id' => '源明细编号',
|
||||
];
|
||||
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$filters = $this->filters($request);
|
||||
$data = ['view' => 'business.pages.courier-payables.returned-parcels', 'filters' => $filters,
|
||||
'columns' => self::COLUMNS, 'rows' => null, 'summary' => null, 'state' => null, 'error' => null];
|
||||
try {
|
||||
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
if (! Schema::connection($db->getName())->hasTable(Sync::TABLE)) {
|
||||
$data['error'] = '退回件明细尚未完成首次同步,请稍后刷新。';
|
||||
return $data;
|
||||
}
|
||||
$query = $this->query($filters);
|
||||
$data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COUNT(DISTINCT after_sales_id) AS orders_count, COALESCE(SUM(returned_qty),0) AS quantity')->first();
|
||||
$data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_id')->paginate(50)->withQueryString();
|
||||
$data['state'] = $db->table('business_mirror_table_states')->where('dataset_key', Sync::DATASET)->first();
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$data['error'] = '退回件明细暂时无法读取,请稍后重试。';
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function export(Request $request)
|
||||
{
|
||||
$query = $this->query($this->filters($request));
|
||||
$selected = array_values(array_intersect(explode(',', (string) $request->query('columns', '')), array_keys(self::COLUMNS)));
|
||||
$selected = $selected ?: array_keys(self::COLUMNS);
|
||||
return response()->streamDownload(function () use ($query, $selected): void {
|
||||
$file = fopen('php://output', 'w');
|
||||
fwrite($file, "\xEF\xBB\xBF");
|
||||
fputcsv($file, array_map(fn ($key) => self::COLUMNS[$key], $selected));
|
||||
foreach ($query->orderBy('source_id')->lazyById(1000, 'source_id') as $row) {
|
||||
fputcsv($file, array_map(function ($key) use ($row) {
|
||||
$value = (string) ($row->$key ?? '');
|
||||
if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value;
|
||||
return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value;
|
||||
}, $selected));
|
||||
}
|
||||
fclose($file);
|
||||
}, '退回件明细.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
return validator($request->query(), [
|
||||
'from' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:2026-10-01'],
|
||||
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
|
||||
'waybill' => ['nullable', 'string', 'max:255'], 'shop' => ['nullable', 'string', 'max:255'],
|
||||
'warehouse' => ['nullable', 'string', 'max:255'], 'sku' => ['nullable', 'string', 'max:255'],
|
||||
])->validate() + ['from' => Sync::START, 'to' => now('Asia/Shanghai')->toDateString(),
|
||||
'waybill' => '', 'shop' => '', 'warehouse' => '', 'sku' => ''];
|
||||
}
|
||||
|
||||
private function query(array $filters)
|
||||
{
|
||||
$query = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(Sync::TABLE)
|
||||
->where('received_at', '>=', $filters['from'] ?: Sync::START);
|
||||
if ($filters['to']) $query->where('received_at', '<', Carbon::parse($filters['to'])->addDay()->toDateString());
|
||||
foreach (['waybill', 'shop', 'warehouse', 'sku'] as $field) {
|
||||
if (filled($filters[$field])) $query->where($field, trim($filters[$field]));
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
@ -127,6 +127,10 @@ class SidebarPermissions
|
||||
$allowed[] = 'process-data/invoice-data';
|
||||
}
|
||||
|
||||
if (in_array('courier-payables/shipping-data', $allowed, true)) {
|
||||
$allowed[] = 'courier-payables/returned-parcels';
|
||||
}
|
||||
|
||||
return array_values(array_unique($allowed));
|
||||
}
|
||||
|
||||
|
||||
@ -10,6 +10,9 @@ return [
|
||||
| Entries are appended to an existing section in configuration order.
|
||||
|
|
||||
*/
|
||||
'courier-payables' => [
|
||||
['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'],
|
||||
],
|
||||
'module_sections' => [
|
||||
[
|
||||
'position_after' => 'inventory-management',
|
||||
|
||||
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! app()->environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') {
|
||||
return;
|
||||
}
|
||||
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) {
|
||||
if ($schema->hasTable($name)) continue;
|
||||
$schema->create($name, function (Blueprint $table): void {
|
||||
$table->unsignedBigInteger('source_id')->primary();
|
||||
$table->unsignedBigInteger('after_sales_id')->nullable()->index();
|
||||
$table->unsignedBigInteger('item_id')->nullable();
|
||||
$table->dateTime('received_at', 6)->index();
|
||||
$table->string('online_after_sales_no', 255)->nullable();
|
||||
$table->string('order_id', 64)->nullable();
|
||||
$table->string('online_order_no', 255)->nullable();
|
||||
$table->string('waybill', 255)->nullable()->index();
|
||||
$table->string('courier', 255)->nullable();
|
||||
$table->string('shop', 255)->nullable();
|
||||
$table->string('warehouse', 255)->nullable();
|
||||
$table->string('sku', 255)->nullable()->index();
|
||||
$table->string('style_code', 255)->nullable();
|
||||
$table->text('product_name')->nullable();
|
||||
$table->text('properties')->nullable();
|
||||
$table->decimal('applied_qty', 20, 4)->nullable();
|
||||
$table->decimal('returned_qty', 20, 4)->nullable();
|
||||
$table->decimal('price', 20, 4)->nullable();
|
||||
$table->decimal('item_amount', 20, 4)->nullable();
|
||||
$table->decimal('order_refund', 20, 4)->nullable();
|
||||
$table->string('status', 64)->nullable();
|
||||
$table->string('type', 64)->nullable();
|
||||
$table->string('goods_status', 64)->nullable();
|
||||
$table->text('reason')->nullable();
|
||||
$table->text('remark')->nullable();
|
||||
$table->dateTime('source_updated_at', 6)->nullable();
|
||||
$table->uuid('generation')->index();
|
||||
$table->dateTime('synced_at', 6);
|
||||
$table->index(['received_at', 'source_id'], 'returned_parcel_date_id_' . (str_ends_with($table->getTable(), '_stage') ? 'stage' : 'live'));
|
||||
$table->index(['shop', 'received_at']);
|
||||
$table->index(['warehouse', 'received_at']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$schema->dropIfExists('courier_returned_parcels_stage');
|
||||
$schema->dropIfExists('courier_returned_parcels');
|
||||
}
|
||||
};
|
||||
@ -248,6 +248,7 @@ CRON_TZ=Asia/Shanghai
|
||||
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
|
||||
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
|
||||
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
|
||||
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
|
||||
|
||||
@ -252,6 +252,7 @@ CRON_TZ=Asia/Shanghai
|
||||
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
|
||||
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
|
||||
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
|
||||
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
|
||||
|
||||
@ -11,7 +11,7 @@ case "${1:-}" in
|
||||
portal-freight:import-pending) is_import=1 ;;
|
||||
planting-reimbursement:auto-confirm) is_import=1 ;;
|
||||
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
|
||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
|
||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels) ;;
|
||||
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
|
||||
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
|
||||
esac
|
||||
@ -125,4 +125,15 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then
|
||||
--name "$container_name" batch "$@"
|
||||
exit $?
|
||||
fi
|
||||
if [ "$1" = 'business-mirror:sync-returned-parcels' ]; then
|
||||
container_name="caiwu_returned_parcels_$$"
|
||||
cleanup_returned_parcels() {
|
||||
docker rm --force "$container_name" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_returned_parcels EXIT INT TERM
|
||||
/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \
|
||||
--name "$container_name" batch "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@"
|
||||
|
||||
@ -20,6 +20,10 @@
|
||||
|
||||
## 当前迁移状态
|
||||
|
||||
“快递应付 → 退回件明细”按 `operations_replica/rpt.jst_returnAndRefundItem.receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 关联 `rpt.jst_returnAndRefundInfo` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,源明细 `Id` 为稳定键;分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存游标。完整核对来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。
|
||||
|
||||
生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每批最多 2,000 条商品,按所选商品关联售后主表。命令不会写聚水潭或其他财务台账。
|
||||
|
||||
| 状态 | 说明 |
|
||||
| --- | --- |
|
||||
| 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 |
|
||||
|
||||
137
modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php
Normal file
137
modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php
Normal file
@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** 按进仓时间同步商品级退回件;分页落暂存表,完整校验后才发布新快照。 */
|
||||
class ReturnedParcelSynchronizer
|
||||
{
|
||||
public const DATASET = 'derived.courier-returned-parcels';
|
||||
public const START = '2026-10-01';
|
||||
public const TABLE = 'courier_returned_parcels';
|
||||
public const STAGE = 'courier_returned_parcels_stage';
|
||||
|
||||
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
|
||||
|
||||
public function sync(string $from, string $to, ?callable $progress = null, int $batchSize = 2000): array
|
||||
{
|
||||
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$until = Carbon::parse($to, 'Asia/Shanghai')->addDay()->toDateString();
|
||||
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
|
||||
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
|
||||
$resume = $state && in_array($state->status, ['running', 'failed'], true)
|
||||
&& is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to;
|
||||
$generation = $resume ? $state->generation : (string) Str::uuid();
|
||||
$last = $resume ? (int) $cursor['last_id'] : 0;
|
||||
$batchSize = min(max($batchSize, 1), 2000);
|
||||
$started = microtime(true);
|
||||
$base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo + rpt.jst_returnAndRefundItem',
|
||||
'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation,
|
||||
'last_attempted_at' => now(), 'last_error_code' => null, 'updated_at' => now()];
|
||||
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => self::DATASET], $base +
|
||||
($state ? [] : ['created_at' => now()]));
|
||||
|
||||
try {
|
||||
if (! $resume) $db->table(self::STAGE)->delete();
|
||||
$expected = $this->sourceCount($from, $until);
|
||||
while (true) {
|
||||
$items = $this->items($from, $until, $last, $batchSize);
|
||||
if ($items === []) break;
|
||||
$headers = $this->headers(array_values(array_unique(array_column($items, 'as_id'))));
|
||||
$rows = [];
|
||||
foreach ($items as $item) {
|
||||
$header = $headers[(string) $item['as_id']] ?? null;
|
||||
if ($header === null) throw new RuntimeException('missing_after_sales_header');
|
||||
$rows[] = $this->row($item, $header, $generation);
|
||||
}
|
||||
$last = (int) end($items)['Id'];
|
||||
$db->transaction(function () use ($db, $rows, $last, $generation, $from, $to): void {
|
||||
foreach (array_chunk($rows, 400) as $part) {
|
||||
$db->table(self::STAGE)->upsert($part, ['source_id'], array_keys($part[0]));
|
||||
}
|
||||
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||
'cursor' => json_encode(['from' => $from, 'to' => $to, 'last_id' => $last]),
|
||||
'last_upserted_rows' => $db->table(self::STAGE)->where('generation', $generation)->count(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
});
|
||||
$progress && $progress($db->table(self::STAGE)->where('generation', $generation)->count(), $expected);
|
||||
if (count($items) < $batchSize) break;
|
||||
}
|
||||
$count = $db->table(self::STAGE)->where('generation', $generation)->count();
|
||||
if ($count !== $expected || $count !== $this->sourceCount($from, $until)) {
|
||||
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]);
|
||||
throw new RuntimeException('source_count_changed_retry_required');
|
||||
}
|
||||
// 同一事务替换范围,失败或中断不影响页面上一版;只操作派生镜像。
|
||||
$db->transaction(function () use ($db, $from, $until, $generation, $count): void {
|
||||
$db->table(self::TABLE)->where('received_at', '>=', $from)->where('received_at', '<', $until)->delete();
|
||||
$columns = $db->getSchemaBuilder()->getColumnListing(self::TABLE);
|
||||
$db->table(self::TABLE)->insertUsing($columns, $db->table(self::STAGE)->select($columns)->where('generation', $generation));
|
||||
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||
'status' => 'succeeded', 'cursor' => null, 'initial_completed_at' => now(),
|
||||
'last_succeeded_at' => now(), 'last_full_succeeded_at' => now(),
|
||||
'window_started_at' => $from, 'window_ends_at' => $until,
|
||||
'last_upserted_rows' => $count, 'mirror_row_count' => $db->table(self::TABLE)->count(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$db->table(self::STAGE)->where('generation', $generation)->delete();
|
||||
});
|
||||
return ['rows' => $count, 'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2),
|
||||
'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)];
|
||||
} catch (Throwable $exception) {
|
||||
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||
'status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now(),
|
||||
]);
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
protected function sourceCount(string $from, string $until): int
|
||||
{
|
||||
return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.jst_returnAndRefundItem WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]);
|
||||
}
|
||||
|
||||
protected function items(string $from, string $until, int $last, int $limit): array
|
||||
{
|
||||
return $this->upstream()->select('SELECT TOP (' . $limit . ') Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,'
|
||||
. 'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.jst_returnAndRefundItem'
|
||||
. ' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime) AND Id > ? ORDER BY Id', [$from, $until, $last]);
|
||||
}
|
||||
|
||||
protected function headers(array $ids): array
|
||||
{
|
||||
$rows = $this->upstream()->select('SELECT Id,as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,'
|
||||
. 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),updateTime,126) AS updateTime'
|
||||
. ' FROM rpt.jst_returnAndRefundInfo WHERE as_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')', $ids);
|
||||
$headers = [];
|
||||
foreach ($rows as $row) {
|
||||
$key = (string) $row['as_id'];
|
||||
if (! isset($headers[$key]) || (int) $row['Id'] > (int) $headers[$key]['Id']) $headers[$key] = $row;
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
private function upstream(): UpstreamReadOnlyQuery
|
||||
{
|
||||
return $this->queries->forSourceWithTimeout('operations_replica', 60);
|
||||
}
|
||||
|
||||
private function row(array $i, array $h, string $generation): array
|
||||
{
|
||||
return ['source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'],
|
||||
'received_at' => $i['receive_date'], 'online_after_sales_no' => $h['outer_as_id'],
|
||||
'order_id' => $h['o_id'], 'online_order_no' => $h['so_id'], 'waybill' => $h['l_id'],
|
||||
'courier' => $h['logistics_company'], 'shop' => $h['shop_name'], 'warehouse' => $h['warehouse'],
|
||||
'sku' => $i['sku_id'], 'style_code' => $i['i_id'], 'product_name' => $i['name'], 'properties' => $i['properties_value'],
|
||||
'applied_qty' => $i['qty'], 'returned_qty' => $i['r_qty'], 'price' => $i['price'], 'item_amount' => $i['amount'],
|
||||
'order_refund' => $h['refund'], 'status' => $h['status'], 'type' => $h['type'], 'goods_status' => $h['good_status'],
|
||||
'reason' => $h['question_type'], 'remark' => trim(($h['remark'] ?? '') . "\n" . ($i['remark'] ?? '')),
|
||||
'source_updated_at' => $h['updateTime'], 'generation' => $generation, 'synced_at' => now()];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,61 @@
|
||||
<section class="returned-parcels" data-returned-parcels data-finance-table-surface>
|
||||
<form method="get" class="returned-parcels-filters" data-returned-filter>
|
||||
@foreach (['from' => '进仓日期起', 'to' => '进仓日期止', 'waybill' => '退回快递单号', 'shop' => '店铺', 'warehouse' => '收货仓库', 'sku' => '商品编码'] as $key => $label)
|
||||
<label>{{ $label }}<input type="text" name="{{ $key }}" value="{{ $filters[$key] }}" @if(in_array($key, ['from','to'])) placeholder="YYYY-MM-DD" inputmode="numeric" @endif></label>
|
||||
@endforeach
|
||||
<button type="submit" class="returned-primary">查询</button>
|
||||
<a href="{{ route('business.pages.show', ['section' => 'courier-payables', 'page' => 'returned-parcels']) }}" data-returned-link>重置</a>
|
||||
<a href="{{ route('business.courier-payables.returned-parcels.export', $filters) }}">导出筛选结果</a>
|
||||
<button type="button" data-finance-server-export="visible">导出显示列</button>
|
||||
</form>
|
||||
<div class="returned-parcels-status" role="status">
|
||||
每天 10:00、16:00 自动同步 · 最近完成:{{ $state->last_succeeded_at ?? '尚未完成' }}
|
||||
@if(($state->status ?? '') === 'running')<span> · 正在同步,当前显示上次完整结果</span>@endif
|
||||
@if(($state->status ?? '') === 'failed')<span class="returned-warning"> · 最近同步失败,当前保留上次完整结果</span>@endif
|
||||
</div>
|
||||
@if($error)<p class="returned-warning" role="alert">{{ $error }}</p>@endif
|
||||
@if($summary)
|
||||
<p class="returned-parcels-summary">当前筛选:{{ number_format($summary->rows_count) }} 条商品明细 · {{ number_format($summary->orders_count) }} 个售后单 · 实退数量 {{ number_format($summary->quantity, 0) }}</p>
|
||||
@endif
|
||||
<div class="finance-table-controls" data-finance-controls></div>
|
||||
<div class="returned-parcels-scroll finance-table-scroll-owner">
|
||||
<table data-finance-table data-finance-table-name="returned-parcels" data-finance-table-key="{{ auth()->id() }}:{{ company_id() }}:courier-payables:returned-parcels" data-finance-export-base="{{ route('business.courier-payables.returned-parcels.export') }}" data-finance-export-query="{{ json_encode($filters) }}" aria-label="退回件明细">
|
||||
<thead><tr>@foreach($columns as $key => $label)<th scope="col" data-finance-column-key="{{ $key }}" data-export-field="{{ $key }}" @class(['returned-number' => in_array($key,['applied_qty','returned_qty','price','item_amount'])])>{{ $label }}</th>@endforeach</tr></thead>
|
||||
<tbody>
|
||||
@forelse($rows ?? [] as $row)
|
||||
<tr>@foreach($columns as $key => $label)
|
||||
<td @class(['returned-number' => in_array($key,['applied_qty','returned_qty','price','item_amount'])])>
|
||||
@if(in_array($key,['price','item_amount'])){{ $row->$key === null ? '—' : number_format($row->$key, 2) }}
|
||||
@elseif(in_array($key,['applied_qty','returned_qty'])){{ $row->$key === null ? '—' : rtrim(rtrim(number_format($row->$key, 4, '.', ''), '0'), '.') }}
|
||||
@else{{ $row->$key ?? '—' }}@endif
|
||||
</td>
|
||||
@endforeach</tr>
|
||||
@empty
|
||||
<tr><td colspan="{{ count($columns) }}" class="returned-empty">{{ $error ?: '当前进仓日期和筛选条件下没有退回件,请调整日期或清空筛选。' }}</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@if($rows)<div class="returned-parcels-footer" data-returned-pagination>每页 50 条 {{ $rows->links('business.partials.previous-next-pagination') }}</div>@endif
|
||||
<p class="returned-parcels-note">按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。</p>
|
||||
</section>
|
||||
<style>
|
||||
.returned-parcels{color:var(--vip-content-ink,#171717);font-size:13px}.returned-parcels-filters{display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;margin-bottom:14px}.returned-parcels-filters label{display:grid;gap:6px;font-size:12px}.returned-parcels-filters input{width:160px}.returned-parcels-filters input,.returned-parcels-filters button,.returned-parcels-filters a{height:34px;border:1px solid var(--vip-border,#D8D2C7);border-radius:8px;padding:0 10px;background:white;color:inherit}.returned-parcels-filters a{display:inline-flex;align-items:center;text-decoration:none}.returned-parcels-filters .returned-primary{background:var(--vip-content-accent-dark,#856632);color:white;border-color:var(--vip-content-accent-dark,#856632)}.returned-parcels-filters input:focus{outline:2px solid var(--vip-content-accent,#B9954F);outline-offset:2px}.returned-parcels-status,.returned-parcels-note{color:var(--vip-content-muted,#595959);font-size:12px;margin:10px 0}.returned-warning{color:var(--vip-warning,#935F07)}.returned-parcels-summary{margin:14px 0}.returned-parcels-scroll{overflow:auto;max-height:calc(100vh - 360px);min-height:220px;border:1px solid var(--vip-border,#D8D2C7);border-radius:8px;background:white}.returned-parcels table{border-collapse:collapse;width:100%;font-size:12.5px}.returned-parcels th,.returned-parcels td{padding:10px 12px;border-bottom:1px solid var(--vip-border,#D8D2C7);text-align:left;white-space:nowrap;max-width:320px;overflow:hidden;text-overflow:ellipsis}.returned-parcels th{position:sticky;top:0;background:var(--vip-content-accent-soft,#F7F0DE);z-index:1;font-size:12px}.returned-parcels td.returned-number,.returned-parcels th.returned-number{text-align:right;font-variant-numeric:tabular-nums}.returned-parcels tbody tr:hover{background:var(--vip-content-accent-soft,#F7F0DE)}.returned-parcels td.returned-empty{text-align:center;padding:40px;white-space:normal}.returned-parcels-footer{display:flex;justify-content:space-between;align-items:center;margin-top:12px}.returned-parcels-footer nav{margin:0}
|
||||
</style>
|
||||
@push('body_end')
|
||||
<script>
|
||||
(() => {
|
||||
if(window.returnedParcelsBound)return;window.returnedParcelsBound=true;
|
||||
async function load(url){
|
||||
const root=document.querySelector('[data-returned-parcels]');if(!root||root.getAttribute('aria-busy')==='true')return;
|
||||
root.setAttribute('aria-busy','true');
|
||||
try{const response=await fetch(url,{headers:{'X-Requested-With':'XMLHttpRequest'}});if(!response.ok)throw Error();
|
||||
const doc=new DOMParser().parseFromString(await response.text(),'text/html'),next=doc.querySelector('[data-returned-parcels]');if(!next)throw Error();
|
||||
root.replaceWith(next);history.replaceState({},'',url);document.dispatchEvent(new CustomEvent('business:content-updated'));
|
||||
}catch(_){root.removeAttribute('aria-busy');const message=document.createElement('p');message.className='returned-warning';message.setAttribute('role','alert');message.textContent='查询失败,请检查日期格式(YYYY-MM-DD)后重试。';root.prepend(message);}
|
||||
}
|
||||
document.addEventListener('submit',event=>{const form=event.target.closest('[data-returned-filter]');if(!form)return;event.preventDefault();const url=new URL(location.href);url.search=new URLSearchParams(new FormData(form)).toString();load(url.href);});
|
||||
document.addEventListener('click',event=>{const link=event.target.closest('[data-returned-pagination] a,[data-returned-link]');if(!link||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;event.preventDefault();load(link.href);});
|
||||
})();
|
||||
</script>
|
||||
@endpush
|
||||
@ -771,6 +771,10 @@ Route::get('workspace/courier-payables/shipping-data/suggest', 'Business\\Pages@
|
||||
->middleware('business.page:courier-payables,shipping-data')
|
||||
->name('business.courier-payables.shipping-data.suggest');
|
||||
|
||||
Route::get('workspace/courier-payables/returned-parcels/export', [\App\Http\Controllers\Business\ReturnedParcelController::class, 'export'])
|
||||
->middleware('business.page:courier-payables,returned-parcels')
|
||||
->name('business.courier-payables.returned-parcels.export');
|
||||
|
||||
foreach (['courier-payables', 'courier-payables-final'] as $unshippedSection) {
|
||||
Route::prefix('workspace/'.$unshippedSection.'/unshipped-waybills')
|
||||
->middleware('business.page:'.$unshippedSection.',unshipped-waybills')
|
||||
|
||||
186
tests/Feature/Business/ReturnedParcelsTest.php
Normal file
186
tests/Feature/Business/ReturnedParcelsTest.php
Normal file
@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Http\Controllers\Business\ReturnedParcelController;
|
||||
use App\Models\Auth\Permission;
|
||||
use App\Models\Auth\Role;
|
||||
use App\Utilities\BusinessNavigation;
|
||||
use App\Utilities\SidebarPermissions;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
|
||||
use RuntimeException;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class ReturnedParcelsTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$schema = Schema::connection('business_mirror');
|
||||
if (! $schema->hasTable('business_mirror_table_states')) {
|
||||
$schema->create('business_mirror_table_states', function (Blueprint $table): void {
|
||||
$table->string('dataset_key')->primary();
|
||||
foreach (['source_key','source_object','target_table','status','run_mode','generation','last_error_code'] as $key) $table->string($key)->nullable();
|
||||
$table->text('cursor')->nullable();
|
||||
foreach (['window_started_at','window_ends_at','initial_completed_at','last_full_succeeded_at','last_attempted_at','last_succeeded_at'] as $key) $table->dateTime($key)->nullable();
|
||||
$table->integer('last_upserted_rows')->default(0);
|
||||
$table->integer('mirror_row_count')->default(0);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
if (! $schema->hasTable(ReturnedParcelSynchronizer::TABLE)) {
|
||||
(require base_path('database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php'))->up();
|
||||
}
|
||||
}
|
||||
|
||||
private function synchronizer(array $items): ReturnedParcelFakeSynchronizer
|
||||
{
|
||||
return new ReturnedParcelFakeSynchronizer($items);
|
||||
}
|
||||
|
||||
private function item(int $id, string $received = '2026-11-02 12:00:00'): array
|
||||
{
|
||||
return ['Id'=>$id,'as_id'=>100,'asi_id'=>$id+1000,'receive_date'=>$received,'sku_id'=>'SKU-'.$id,
|
||||
'i_id'=>'STYLE','name'=>'测试商品','properties_value'=>'白色','qty'=>2,'r_qty'=>1,
|
||||
'price'=>'12.3400','amount'=>'24.6800','remark'=>'明细备注'];
|
||||
}
|
||||
|
||||
public function test_sync_preserves_item_grain_boundaries_and_is_idempotent(): void
|
||||
{
|
||||
$items = [$this->item(1, '2026-09-30 23:59:59'), $this->item(2, '2026-10-01 00:00:00'),
|
||||
$this->item(3, '2026-12-02 23:59:59'), $this->item(4, '2026-12-03 00:00:00')];
|
||||
$sync = $this->synchronizer($items);
|
||||
$this->assertSame(2, $sync->sync('2026-10-01','2026-12-02', null, 1)['rows']);
|
||||
$sync->sync('2026-10-01','2026-12-02', null, 1);
|
||||
$rows=DB::connection('business_mirror')->table(ReturnedParcelSynchronizer::TABLE)->orderBy('source_id')->get();
|
||||
$this->assertSame([2,3], $rows->pluck('source_id')->all());
|
||||
$this->assertSame([100,100], $rows->pluck('after_sales_id')->all());
|
||||
$this->assertEquals(1, $rows[0]->returned_qty);
|
||||
$this->assertEquals(12.34, $rows[0]->price);
|
||||
$this->assertSame('TEST-RETURN', $rows[0]->waybill);
|
||||
}
|
||||
|
||||
public function test_failed_sync_keeps_live_rows_and_resumes_from_committed_batch(): void
|
||||
{
|
||||
$sync=$this->synchronizer([$this->item(10)]);
|
||||
$sync->sync('2026-10-01','2026-12-02');
|
||||
$sync=$this->synchronizer([$this->item(20),$this->item(21),$this->item(22)]);
|
||||
$sync->failAfter=1;
|
||||
try {$sync->sync('2026-10-01','2026-12-02', null, 1); $this->fail('Expected upstream failure');}
|
||||
catch (RuntimeException $e) {$this->assertSame('upstream_failed', $e->getMessage());}
|
||||
$db=DB::connection('business_mirror');
|
||||
$this->assertSame([10], $db->table(ReturnedParcelSynchronizer::TABLE)->pluck('source_id')->all());
|
||||
$this->assertSame('failed', $db->table('business_mirror_table_states')->value('status'));
|
||||
$sync->failAfter=null;
|
||||
$sync->readCursors=[];
|
||||
$sync->sync('2026-10-01','2026-12-02', null, 1);
|
||||
$this->assertSame(20, $sync->readCursors[0]);
|
||||
$this->assertSame([20,21,22], $db->table(ReturnedParcelSynchronizer::TABLE)->orderBy('source_id')->pluck('source_id')->all());
|
||||
}
|
||||
|
||||
public function test_count_mismatch_keeps_previous_snapshot_and_resets_checkpoint(): void
|
||||
{
|
||||
$sync=$this->synchronizer([$this->item(1)]);
|
||||
$sync->sync('2026-10-01','2026-12-02');
|
||||
$sync=$this->synchronizer([$this->item(2)]);
|
||||
$sync->countOffset=1;
|
||||
try {$sync->sync('2026-10-01','2026-12-02'); $this->fail('Expected count mismatch');}
|
||||
catch (RuntimeException $e) {$this->assertSame('source_count_changed_retry_required', $e->getMessage());}
|
||||
$db=DB::connection('business_mirror');
|
||||
$this->assertSame([1], $db->table(ReturnedParcelSynchronizer::TABLE)->pluck('source_id')->all());
|
||||
$this->assertNull($db->table('business_mirror_table_states')->value('cursor'));
|
||||
}
|
||||
|
||||
public function test_page_reads_mirror_filters_received_date_and_paginates(): void
|
||||
{
|
||||
$items=[];
|
||||
for($id=1;$id<=55;$id++) $items[]=$this->item($id);
|
||||
$items[]=$this->item(90,'2026-12-03 12:00:00');
|
||||
$this->synchronizer($items)->sync('2026-10-01','2026-12-03');
|
||||
$controller=app(ReturnedParcelController::class);
|
||||
$request=Request::create('/?from=2026-11-01&to=2026-11-30');
|
||||
$data=$controller->page($request);
|
||||
$this->assertSame(55,$data['rows']->total());
|
||||
$this->assertCount(50,$data['rows']->items());
|
||||
$this->assertEquals(55,$data['summary']->quantity);
|
||||
$this->assertSame(1,(int)$data['summary']->orders_count);
|
||||
$filtered=$controller->page(Request::create('/?from=2026-11-01&to=2026-11-30&sku=SKU-2'));
|
||||
$this->assertSame(1,$filtered['rows']->total());
|
||||
$this->assertSame(2,$filtered['rows']->first()->source_id);
|
||||
$section=collect(BusinessNavigation::all())->firstWhere('slug','courier-payables');
|
||||
$this->assertSame('退回件明细',collect($section['pages'])->firstWhere('slug','returned-parcels')['title']);
|
||||
$this->user->attachPermission(Permission::where('name','read-admin-panel')->firstOrFail());
|
||||
$this->loginAs()->get(route('business.pages.show',['section'=>'courier-payables','page'=>'returned-parcels','from'=>'2026-11-01','to'=>'2026-11-30']))
|
||||
->assertOk()->assertSeeText('进仓时间')->assertSeeText('测试商品')->assertSeeText('55 条商品明细')->assertSeeText('10:00、16:00');
|
||||
}
|
||||
|
||||
public function test_schedule_uses_managed_batch_at_both_requested_times(): void
|
||||
{
|
||||
foreach (['activate-release.sh','activate-incremental-release.sh'] as $file) {
|
||||
$text=file_get_contents(base_path('deploy/'.$file));
|
||||
$this->assertStringContainsString('0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels', $text);
|
||||
}
|
||||
$this->assertStringContainsString('/usr/bin/timeout 1800', file_get_contents(base_path('deploy/run-finance-batch.sh')));
|
||||
}
|
||||
|
||||
public function test_returned_page_inherits_existing_shipping_visibility_only(): void
|
||||
{
|
||||
$this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
|
||||
$subject = 'user_' . $this->user->id;
|
||||
setting()->set('system.sidebar_permissions', ['configured' => [$subject], 'subjects' => [$subject => ['courier-payables/shipping-data']]]);
|
||||
setting()->save();
|
||||
$this->assertContains('courier-payables/returned-parcels', SidebarPermissions::effectiveAllowedKeys($this->user));
|
||||
$this->assertNotContains('courier-payables/courier-information', SidebarPermissions::effectiveAllowedKeys($this->user));
|
||||
}
|
||||
|
||||
public function test_export_contains_every_filtered_row_and_preserves_long_identifiers(): void
|
||||
{
|
||||
$items=[];
|
||||
for($id=1;$id<=55;$id++)$items[]=$this->item($id);
|
||||
$this->synchronizer($items)->sync('2026-10-01','2026-12-02');
|
||||
$this->user->attachPermission(Permission::where('name','read-admin-panel')->firstOrFail());
|
||||
$response=$this->loginAs()->get(route('business.courier-payables.returned-parcels.export',[
|
||||
'from'=>'2026-11-01','to'=>'2026-11-30','columns'=>'online_order_no,sku',
|
||||
]))->assertOk();
|
||||
$csv=$response->streamedContent();
|
||||
$this->assertSame(56, count(array_filter(explode("\n",$csv))));
|
||||
$this->assertStringContainsString("'00001234567890123456", $csv);
|
||||
$this->assertStringContainsString("'SKU-55", $csv);
|
||||
$this->assertStringNotContainsString('明细金额', $csv);
|
||||
}
|
||||
|
||||
public function test_command_rejects_invalid_dates_before_querying_source(): void
|
||||
{
|
||||
$this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-02-30','--to'=>'2026-12-02'])->assertFailed();
|
||||
$this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-11-01','--to'=>'2026-10-01'])->assertFailed();
|
||||
}
|
||||
}
|
||||
|
||||
class ReturnedParcelFakeSynchronizer extends ReturnedParcelSynchronizer
|
||||
{
|
||||
public ?int $failAfter=null;
|
||||
public int $countOffset=0;
|
||||
public array $readCursors=[];
|
||||
public function __construct(public array $source) {}
|
||||
protected function sourceCount(string $from,string $until): int
|
||||
{
|
||||
return count(array_filter($this->source,fn($row)=>$row['receive_date'] >= $from && $row['receive_date'] < $until))+$this->countOffset;
|
||||
}
|
||||
protected function items(string $from,string $until,int $last,int $limit): array
|
||||
{
|
||||
$this->readCursors[]=$last;
|
||||
if($this->failAfter!==null && count($this->readCursors)>$this->failAfter)throw new RuntimeException('upstream_failed');
|
||||
return array_slice(array_values(array_filter($this->source,fn($row)=>$row['Id']>$last && $row['receive_date'] >= $from && $row['receive_date'] < $until)),0,$limit);
|
||||
}
|
||||
protected function headers(array $ids): array
|
||||
{
|
||||
$h=['Id'=>10,'as_id'=>100,'outer_as_id'=>'ONLINE-AS','o_id'=>99,'so_id'=>'00001234567890123456','l_id'=>'TEST-RETURN',
|
||||
'logistics_company'=>'测试快递','shop_name'=>'测试店铺','warehouse'=>'测试仓库','status'=>'Confirmed','type'=>'退货退款',
|
||||
'good_status'=>'已收货','question_type'=>'测试原因','refund'=>'24.6800','remark'=>'售后备注','updateTime'=>'2026-12-03 10:00:00'];
|
||||
return [100=>$h];
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user