CaiWuXiTong/modules/EcommerceFinance/Services/CustomerServiceSurchargeSynchronizer.php

200 lines
13 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
/** 将查件工单中逐行审核通过的附加费同步为可复核的结算明细。 */
class CustomerServiceSurchargeSynchronizer
{
public const SOURCE = 'js_jst_work_order_info';
public const TABLE = 'courier_surcharge_settlement_rows';
public const STAGE = 'courier_surcharge_service_stage';
public const KIND = 'work_order_customer_service';
public const WORK_TYPE = '0FE39FBE88E448D396B2E8ED62775284';
public const FEE_TABLE = 'TABLEField1413856620250814155027';
public const FEE_TYPE = 'SELECTField1413856620250814155011';
public const FEE_AMOUNT = 'NUMBERField1413856620250814154738';
public const FEE_APPROVAL = 'SELECTField1413856620260611105055';
private ?int $highWaterId = null;
public static function dataset(int $company, string $courier): string
{
return 'derived.surcharge-service.' . $company . '.' . substr(hash('sha256', $courier), 0, 24);
}
public function sync(int $company, string $courier, ?string $from = null, ?string $to = null, ?callable $progress = null, int $batch = 300): array
{
$started = microtime(true);
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
$rules = DB::table('business_courier_surcharge_quotes')->where('company_id', $company)
->where('courier', $courier)->whereNull('deleted_at')->where('status', 'active')->where('mode', '聚工单客服核实')->orderBy('effective_at')->orderBy('id')->get()->all();
if ($rules === []) throw new RuntimeException('没有启用的聚工单客服核实报价。');
foreach ($rules as $rule) {
// 有重量等附加条件的报价需另外核实,不能忽略条件直接计费。
if (trim($rule->standard) !== '读取聚工单附加费明细'
|| ! in_array(trim($rule->condition), ['聚工单客服回复通过', '改地址客服回复通过'], true)
|| empty($rule->effective_at)) {
throw new RuntimeException('报价 #' . $rule->id . ' 含本次未接入的附加条件,请先核实。');
}
}
$from ??= min(array_map(fn ($r) => substr($r->effective_at, 0, 10), $rules));
$to ??= now('Asia/Shanghai')->toDateString();
$until = Carbon::parse($to)->addDay()->toDateString();
if ($from > $to) throw new RuntimeException('开始日期不能晚于结束日期。');
$sourceState = $db->table('business_mirror_table_states')->where('target_table', self::SOURCE)->first();
if (! $sourceState?->initial_completed_at || $sourceState->status === 'failed') {
throw new RuntimeException('聚工单共享镜像尚未就绪,保留上次结算结果。');
}
$key = self::dataset($company, $courier);
$state = $db->table('business_mirror_table_states')->where('dataset_key', $key)->first();
$cursor = json_decode($state->cursor ?? 'null', true);
$fingerprint = hash('sha256', json_encode($rules, JSON_THROW_ON_ERROR));
$resume = $state && in_array($state->status, ['running', 'failed'], true) && is_array($cursor)
&& ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to
&& ($cursor['rules'] ?? null) === $fingerprint;
$generation = $resume ? $state->generation : (string) Str::uuid();
$this->highWaterId = null;
$this->highWaterId = $resume ? (int) ($cursor['max_id'] ?? 0) : (int) $this->source($from, $until)->max('Id');
$lastDate = $resume ? $cursor['created'] : null;
$lastId = $resume ? $cursor['id'] : 0;
$scanned = $resume ? $cursor['scanned'] : 0;
$batch = min(max($batch, 1), 500);
$base = ['source_key' => 'operations_replica', 'source_object' => self::SOURCE,
'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation,
'last_attempted_at' => now(), 'updated_at' => now(), 'last_error_code' => null];
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => $key], $base + ($state ? [] : ['created_at' => now()]));
try {
if (! $resume) $db->table(self::STAGE)->where('dataset_key', $key)->delete();
$total = $this->source($from, $until)->count();
while (true) {
$records = $this->batch($from, $until, $lastDate, $lastId, $batch);
if ($records === []) break;
$rows = [];
foreach ($records as $record) {
foreach ($this->settlements((array) $record, $rules) as $row) {
$rows[] = $row + ['generation' => $generation, 'dataset_key' => $key];
}
$lastDate = $record->created;
$lastId = (int) $record->Id;
++$scanned;
}
$db->transaction(function () use ($db, $rows, $key, $from, $to, $fingerprint, $lastDate, $lastId, $scanned): void {
if ($rows !== []) $db->table(self::STAGE)->upsert($rows,
['dataset_key', 'rule_id', 'source_key', 'surcharge_type'],
['settlement_amount', 'evidence', 'generation', 'updated_at']);
$db->table('business_mirror_table_states')->where('dataset_key', $key)->update([
'cursor' => json_encode(['from' => $from, 'to' => $to, 'rules' => $fingerprint,
'created' => $lastDate, 'id' => $lastId, 'max_id' => $this->highWaterId, 'scanned' => $scanned], JSON_THROW_ON_ERROR), 'updated_at' => now()]);
});
if ($progress) $progress($scanned, $total);
}
if ($scanned !== $total || $this->source($from, $until)->count() !== $total) {
$db->table('business_mirror_table_states')->where('dataset_key', $key)->update(['cursor' => null]);
throw new RuntimeException('来源数量发生变化,本次不替换结算明细,请重新执行。');
}
$ruleIds = array_map(fn ($r) => $r->id, $rules);
$rows = $db->table(self::STAGE)->where('dataset_key', $key)->where('generation', $generation)->count();
$amount = $db->table(self::STAGE)->where('dataset_key', $key)->where('generation', $generation)->sum('settlement_amount');
$db->transaction(function () use ($db, $ruleIds, $from, $until, $key, $generation, $rows): void {
$db->table(self::TABLE)->where('source_kind', self::KIND)->whereIn('rule_id', $ruleIds)
->where('source_created_at', '>=', $from)->where('source_created_at', '<', $until)->delete();
$columns = array_values(array_diff($db->getSchemaBuilder()->getColumnListing(self::TABLE), ['id']));
$db->table(self::TABLE)->insertUsing($columns, $db->table(self::STAGE)->select($columns)
->where('dataset_key', $key)->where('generation', $generation));
$db->table('business_mirror_table_states')->where('dataset_key', $key)->update([
'status' => 'succeeded', 'cursor' => null, 'initial_completed_at' => now(), 'last_full_succeeded_at' => now(),
'last_succeeded_at' => now(), 'window_started_at' => $from, 'window_ends_at' => $until,
'last_upserted_rows' => $rows, 'mirror_row_count' => $rows, 'updated_at' => now()]);
$db->table(self::STAGE)->where('dataset_key', $key)->delete();
});
return ['scanned' => $scanned, 'rows' => $rows, 'amount' => number_format((float) $amount, 2, '.', ''),
'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2), 'peak_mb' => memory_get_peak_usage(true) / 1048576];
} catch (Throwable $e) {
$db->table('business_mirror_table_states')->where('dataset_key', $key)->update([
'status' => 'failed', 'last_error_code' => class_basename($e), 'updated_at' => now()]);
throw $e;
}
}
protected function source(string $from, string $until): Builder
{
return DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(self::SOURCE)
->where('woTypeId', self::WORK_TYPE)->where('created', '>=', $from)->where('created', '<', $until)
->when($this->highWaterId !== null, fn ($q) => $q->where('Id', '<=', $this->highWaterId));
}
protected function batch(string $from, string $until, ?string $lastDate, int $lastId, int $limit): array
{
return $this->source($from, $until)->when($lastDate, fn ($q) => $q->where(fn ($q) => $q
->where('created', '>', $lastDate)->orWhere(fn ($q) => $q->where('created', $lastDate)->where('Id', '>', $lastId))))
->orderBy('created')->orderBy('Id')->limit($limit)->get(['Id', 'woNo', 'created', 'status', 'businessFieldList'])->all();
}
/** 同一工单同一费用类型合并审核通过的行,不按商品数量重复计费。 */
public function settlements(array $record, array $rules): array
{
$fields = [];
foreach (json_decode($record['businessFieldList'], true, 512, JSON_THROW_ON_ERROR) ?? [] as $field) {
if (isset($field['fieldId'])) $fields[$field['fieldId']] = $field;
}
$value = fn ($key) => trim((string) ($fields[$key]['value'] ?? ''));
if (! in_array($value('logisticsField'), array_column($rules, 'courier'), true)) return [];
if (in_array($record['status'], ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)
|| $value('lIdField') === '' || empty($record['woNo'])) return [];
$amounts = [];
foreach ($fields[self::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$line = array_column($line, 'value', 'fieldId');
if (($line[self::FEE_APPROVAL] ?? '') !== '通过') continue;
$type = self::normalizeType(trim((string) ($line[self::FEE_TYPE] ?? '')));
$covered = array_filter($rules, fn ($rule) => in_array($type,
array_map([self::class, 'normalizeType'], json_decode($rule->types, true, 512, JSON_THROW_ON_ERROR)), true));
if ($covered === []) continue;
$text = trim((string) ($line[self::FEE_AMOUNT] ?? ''));
if ($type === '' || ! preg_match('/^\d{1,9}(?:\.\d{1,2})?$/D', $text)) {
throw new RuntimeException('工单 ' . $record['woNo'] . ' 已通过费用的类型或金额无效,请核实。');
}
$cents = (int) round((float) $text * 100);
if ($cents > 0) $amounts[$type] = ($amounts[$type] ?? 0) + $cents;
}
[$inspection, $reason] = array_pad(explode('/', $value('SELECT_CASCADEField1413856620250813172526'), 2), 2, '');
$items = $fields['itemInfo']['childFieldList'] ?? [];
$item = $items === [] ? [] : array_column($items[0], 'value', 'fieldId');
$rows = [];
$shippedAt = null;
if ($value('orderSendTime') !== '') {
try { $shippedAt = Carbon::parse($value('orderSendTime'))->toDateTimeString(); }
catch (Throwable) { throw new RuntimeException('工单 ' . $record['woNo'] . ' 的发货时间无效,请核实。'); }
}
foreach ($amounts as $type => $cents) {
$eligible = array_values(array_filter($rules, fn ($rule) => $rule->courier === $value('logisticsField')
&& substr($rule->effective_at, 0, 10) <= substr($record['created'], 0, 10)
&& in_array($type, array_map([self::class, 'normalizeType'], json_decode($rule->types, true, 512, JSON_THROW_ON_ERROR)), true)));
if ($eligible === []) continue;
// 同一快递同一类型存在历史报价时,采用生效时间最新的一条。
$rule = $eligible[array_key_last($eligible)];
$row = array_fill_keys(['outbound_io_id','platform_product_id','product_code','shop_name','online_order_no',
'length','width','height','volume','inspection_type','inspection_reason','return_waybill_no','settlement_weight'], null);
$rows[] = array_replace($row, ['rule_id' => $rule->id, 'courier_name' => $rule->courier,
'source_kind' => self::KIND, 'source_key' => $record['woNo'], 'source_created_at' => $record['created'],
'surcharge_type' => $type, 'waybill' => $value('lIdField'), 'platform_product_id' => $item['platformItemId'] ?? null,
'product_code' => $item['skuId'] ?? null, 'shop_name' => $fields['shopField']['valueLabel'] ?? null,
'online_order_no' => $value('orderField'), 'inspection_type' => $inspection, 'inspection_reason' => $reason,
'settlement_amount' => number_format($cents / 100, 2, '.', ''), 'settlement_status' => '已计算',
'evidence' => '聚工单 ' . $record['woNo'] . ';附加费明细逐行客服审核通过;' . $type . ' ' . number_format($cents / 100, 2, '.', '') . ' 元',
'shipped_at' => $shippedAt, 'pulled_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
}
return $rows;
}
public static function normalizeType(string $type): string
{
return match ($type) { '改地址费' => '改地址', default => $type };
}
}