CaiWuXiTong/app/Support/CourierBills/FreightConfirmation.php

290 lines
17 KiB
PHP

<?php
namespace App\Support\CourierBills;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use RuntimeException;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
/**
* 快递与代发共用的对方确认流程,财务结算台账仍由原业务负责。
*
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
* 状态、版本快照、逐单异议与处理记录分别存储,每次读写限定公司、合作方和账期。
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
*/
class FreightConfirmation
{
public const DATASET = 'courier-freight-confirm';
public const DISPUTES = 'courier-freight-dispute:';
public const OPEN = 'open';
public const CHECKED = 'checked';
public const SENDING = 'sending';
public const PUSHED = 'pushed';
public const FAILED = 'failed';
public const CONFIRMED = 'confirmed';
public const DISPUTED = 'disputed';
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待快递确认', self::FAILED => '推送失败', self::CONFIRMED => '快递已确认', self::DISPUTED => '快递有异议'];
public function __construct(private readonly SupplierPayableOverrideStore $store)
{
}
public static function key(string $month, int $factoryId): string
{
return $month . '|' . $factoryId;
}
public static function label(?array $state): string
{
return static::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? static::LABELS[self::OPEN];
}
public function state(string $month, int $factoryId, int $companyId): ?array
{
return $this->store->findRow(static::DATASET, self::key($month, $factoryId), $companyId);
}
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
public function states(string $month, int $companyId): array
{
$out = [];
foreach ($this->query(static::DATASET, $companyId)->where('record_key', 'like', $month . '|%')->get(['values'])->map(fn ($r) => json_decode($r->values, true)) as $row) {
if (($row['month'] ?? '') === $month) {
$out[(int) ($row['factory_id'] ?? 0)] = $row;
}
}
return $out;
}
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
return $this->locked($month, (int) $factory->id, $companyId, fn () => $this->checkLocked($month, $factory, $summary, $checked, $companyId, $userId, $by));
}
private function checkLocked(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
$status = (string) ($state['status'] ?? self::OPEN);
if ($checked && !in_array($status, [self::OPEN, self::CHECKED, self::FAILED], true)) {
throw new RuntimeException('账单已经推送,请通过重新推送更新版本。');
}
if (!$checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
}
$values = array_merge($this->base($state, $month, $factory), ['status' => $checked ? $status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status : self::OPEN, 'checked_at' => $checked ? now()->toDateTimeString() : null, 'checked_by' => $checked ? $by : null, 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff']]);
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
return $values;
}
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by, ?iterable $rows = null, array $fees = []): int
{
return $this->locked($month, (int) $factory->id, $companyId, function () use ($month, $factory, $summary, $attention, $companyId, $userId, $by, $rows, $fees) {
$version = $this->beginPush($month, $factory, $summary, $attention, $companyId, $userId, $by);
if ($rows !== null) {
$dataset = $this->snapshotDataset($month, (int) $factory->id, $version);
$batch = [];
$count = 0;
foreach ($rows as $row) {
if ($row['bill'] === null) {
continue;
}
$batch['line:' . str_pad((string) ++$count, 10, '0', STR_PAD_LEFT)] = array_intersect_key($row, array_flip(['waybill', 'ship_time', 'express', 'bill', 'final', 'status', 'label', 'note']));
if (count($batch) === 500) {
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
$batch = [];
}
}
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
$this->store->save($dataset, 'meta', ['summary' => $summary, 'fees' => $fees, 'rows' => $count], $companyId, $userId, 'freight_snapshot');
}
return $version;
});
}
private function beginPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
{
if ((int) ($summary['billed'] ?? 0) === 0) {
throw new RuntimeException('本期没有可推送的账单明细。');
}
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
if (($state['status'] ?? self::OPEN) === self::OPEN) {
throw new RuntimeException('先点「核对完成」再推送给厂家。');
}
if (($state['status'] ?? '') === self::SENDING) {
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
}
$version = (int) ($state['version'] ?? 0) + 1;
$values = array_merge($this->base($state, $month, $factory), ['status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(), 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'], 'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null, 'receipt_error' => null, 'receipt_status' => null, 'pushed_at' => null]);
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
return $version;
}
public function markPushed(string $month, int $factoryId, int $companyId): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
}
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
}
/**
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
*
* @param array<string,string> $disputes 快递单号 => 原因
* @return array<string,mixed> 提交后的状态
*/
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
return $this->locked($month, $factoryId, $companyId, fn () => $this->submitLocked($month, $factoryId, $version, $disputes, $companyId));
}
private function submitLocked(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
$state = $this->state($month, $factoryId, $companyId);
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
}
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
}
if (($state['status'] ?? '') !== self::PUSHED) {
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
}
if (count($disputes) > 500) {
throw new RuntimeException('一次最多提交 500 单异议。');
}
foreach ($disputes as $reason) {
if (trim((string) $reason) === '') {
throw new RuntimeException('请填写每单异议原因。');
}
}
if ($this->snapshot($month, $factoryId, $version, $companyId)) {
$query = $this->snapshotQuery($month, $factoryId, $version, $companyId);
$field = $query->getGrammar()->wrap('values->waybill');
$keys = array_map(fn ($w) => strtoupper((string)$w), array_keys($disputes));
$found = $keys === [] ? collect() : $query->whereRaw('UPPER('.$field.') IN ('.implode(',',array_fill(0,count($keys),'?')).')',$keys)
->get(['values'])->mapWithKeys(fn ($r) => [strtoupper((string)json_decode($r->values,true)['waybill']) => (string)json_decode($r->values,true)['waybill']]);
if ($found->count() !== count($disputes)) {
throw new RuntimeException('单号不在本次推送账单中。');
}
$canonical = [];
foreach ($disputes as $waybill => $reason) $canonical[$found[strtoupper((string)$waybill)]] = $reason;
$disputes = $canonical;
}
$now = now()->toDateTimeString();
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
foreach ($disputes as $waybill => $reason) {
$this->store->save(static::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill, ['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now], $companyId, null, 'manufacturer_link');
}
$this->merge($month, $factoryId, $companyId, ['status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED, 'confirmed_at' => $now, 'disputed_count' => count($disputes)], 'manufacturer_link');
});
return $this->state($month, $factoryId, $companyId) ?? [];
}
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
{
$q = $this->query(static::DISPUTES . self::key($month, $factoryId), $companyId);
if ($version !== null) {
$q->where('record_key', 'like', $version . '|%');
}
$rows = $q->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
if ($version !== null) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
}
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')] <=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
return $rows;
}
private function base(array $state, string $month, object $factory): array
{
$keep = array_diff_key($state, array_flip(['_action_key']));
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name, 'supplier' => (string) $factory->name, 'month' => $month]);
}
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
{
$state = $this->state($month, $factoryId, $companyId) ?? [];
unset($state['_action_key']);
$this->store->save(static::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
if (($state['version'] ?? 0) > 0) {
$this->store->save(static::DATASET . ':history:' . self::key($month, $factoryId), (string) $state['version'], array_merge($state, $values), $companyId, null, $source);
}
}
public function locked(string $month, int $owner, int $company, callable $action): mixed
{
return $this->store->transaction(function () use ($month, $owner, $company, $action) {
$this->query(static::DATASET, $company)->where('record_key', self::key($month, $owner))->lockForUpdate()->first();
return $action();
});
}
protected function query(string $dataset, int $company): Builder
{
return DB::connection(config('database.supplier_payable_maintenance_connection'))->table('supplier_payable_overrides')->where('company_id', $company)->where('dataset', $dataset);
}
private function snapshotDataset(string $month, int $owner, int $version): string
{
return static::DATASET . ':snapshot:' . self::key($month, $owner) . ':' . $version;
}
public function snapshot(string $month, int $owner, int $version, int $company): ?array
{
return $this->store->findRow($this->snapshotDataset($month, $owner, $version), 'meta', $company);
}
public function snapshotQuery(string $month, int $owner, int $version, int $company): Builder
{
return $this->query($this->snapshotDataset($month, $owner, $version), $company)->where('record_key', 'like', 'line:%');
}
public function history(string $month, int $owner, int $company): array
{
return $this->query(static::DATASET . ':history:' . self::key($month, $owner), $company)->orderByDesc('id')->limit(20)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
}
public function review(string $month, int $owner, int $version, string $waybill, string $decision, string $reply, ?float $amount, int $company, ?int $user, string $by): array
{
return $this->locked($month, $owner, $company, function () use ($month, $owner, $version, $waybill, $decision, $reply, $amount, $company, $user, $by) {
$state = $this->state($month, $owner, $company);
if ((int) ($state['version'] ?? 0) !== $version || ($state['status'] ?? '') !== self::DISPUTED) {
throw new RuntimeException('账单版本或状态已变化,请刷新后处理。');
}
$dataset = static::DISPUTES . self::key($month, $owner);
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
if (!$row) {
throw new RuntimeException('没有这条异议。');
}
if (isset($row['decision'])) {
throw new RuntimeException('这条异议已经处理,请勿重复提交。');
}
if (!in_array($decision, ['accept', 'reject'], true) || trim($reply) === '') {
throw new RuntimeException('请选择处理结果并填写核实依据。');
}
unset($row['_action_key']);
$row += ['decision' => $decision, 'reply' => trim($reply), 'reviewed_at' => now()->toDateTimeString(), 'reviewed_by' => $by, 'review_amount' => $amount, 'receipt_status' => 'pending'];
$this->store->save($dataset, $version . '|' . $waybill, $row, $company, $user, 'freight_review');
return $row;
});
}
public function markReceipt(string $month, int $owner, int $version, int $company, ?string $error, ?string $waybill = null): void
{
$this->locked($month, $owner, $company, function () use ($month, $owner, $version, $company, $error, $waybill) {
if ((int) ($this->state($month, $owner, $company)['version'] ?? 0) !== $version) {
return;
}
$values = ['receipt_status' => $error === null ? 'sent' : 'failed', 'receipt_error' => $error === null ? null : mb_substr($error, 0, 200)];
if ($waybill === null) {
$this->merge($month, $owner, $company, $values, 'freight_receipt');
return;
}
$dataset = static::DISPUTES . self::key($month, $owner);
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
if ($row) {
unset($row['_action_key']);
$this->store->save($dataset, $version . '|' . $waybill, array_merge($row, $values), $company, null, 'freight_receipt');
}
});
}
}