Compare commits
2 Commits
main
...
fix/limeng
| Author | SHA1 | Date | |
|---|---|---|---|
| 25ec37482c | |||
|
|
db4ea26b0e |
@ -49,7 +49,10 @@ class ImportPayablesFinal extends Command
|
||||
}
|
||||
|
||||
$fields = $registry->fields($section, $dataset);
|
||||
$storeDataset = $registry->storeDataset($section, $dataset);
|
||||
$storeDataset = 'final:'
|
||||
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
|
||||
. ':'
|
||||
. $dataset;
|
||||
$totalCreated = 0;
|
||||
$totalUpdated = 0;
|
||||
$totalRows = 0;
|
||||
|
||||
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||
use App\Support\DropshipFreight\DropshipConfirmation;
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Throwable;
|
||||
|
||||
class MatchBillSurcharges extends Command
|
||||
{
|
||||
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
|
||||
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
|
||||
|
||||
public function handle(SurchargeSettlementMatcher $matcher): int
|
||||
{
|
||||
$month=(string)($this->option('month')?:now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m'));
|
||||
if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D',$month)){$this->error('请填写有效账单月份 YYYY-MM');return self::FAILURE;}
|
||||
if(!$this->option('all')&&$this->option('statement')===[]&&$this->option('factory')===[]){$this->error('请选择对账单、厂家或 --all');return self::FAILURE;}
|
||||
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
|
||||
$lock=Cache::lock('bill-surcharge-matching',3900);if(!$lock->get()){$this->error('附加费匹配正在运行');return self::FAILURE;}
|
||||
try{
|
||||
$db=DB::connection('business_mirror');$statements=[];$factories=[];
|
||||
if($this->option('all')||$this->option('statement')!==[]){
|
||||
$statements=$db->table('courier_bill_statements')->where('bill_month',$month)->where('status','<>','confirmed')
|
||||
->when($this->option('existing-only'),fn($q)=>$q->whereIn('id',$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('bill_month',$month)->select('owner_id')))
|
||||
->when(!$this->option('all'),fn($q)=>$q->whereIn('id',array_map('intval',$this->option('statement'))))->orderBy('id')->pluck('id')->all();
|
||||
foreach($statements as $id){app(CourierBillMatcher::class)->refreshSurchargeSummary((int)$id);$this->line('快递对账单 #'.$id.' 附加费已匹配');}
|
||||
}
|
||||
if($this->option('all')||$this->option('factory')!==[]){
|
||||
$store=app(DropshipFreightStore::class);
|
||||
$factories=$db->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')->whereNotNull('factory_id')
|
||||
->when($this->option('existing-only'),fn($q)=>$q->whereIn('factory_id',$db->table('dropship_bill_surcharges')->where('bill_month',$month)->select('factory_id')))
|
||||
->when(!$this->option('all'),fn($q)=>$q->whereIn('factory_id',array_map('intval',$this->option('factory'))))->distinct()->pluck('factory_id')->all();
|
||||
foreach($factories as $id){
|
||||
$state=app(DropshipConfirmation::class)->state($month,(int)$id,(int)$this->option('company'));
|
||||
if(($state['status']??'')==='confirmed'){$this->line('厂家 #'.$id.' 已确认,跳过');continue;}
|
||||
$db->transaction(function()use($db,$store,$id,$month){foreach($db->table('dropship_bill_files')->where('factory_id',$id)->where('bill_month',$month)->where('status','parsed')->get() as $file)$store->storeSurchargeRows($file,(int)$id);});
|
||||
$matcher->dropship((int)$id,$month);$this->line('代发厂家 #'.$id.' 附加费已匹配');
|
||||
}
|
||||
}
|
||||
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');return self::SUCCESS;
|
||||
}catch(Throwable $e){report($e);$this->error('附加费匹配失败:'.$e->getMessage());return self::FAILURE;}
|
||||
finally{$lock->release();}
|
||||
}
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer;
|
||||
use Throwable;
|
||||
|
||||
class PullCustomerServiceSurcharges extends Command
|
||||
{
|
||||
protected $signature = 'courier-surcharge:pull-customer-service {--courier= : 报价中的完整快递名称} {--company=1} {--from= : 工单创建日期起(含),默认报价生效日} {--to= : 工单创建日期止(含),默认今天}';
|
||||
protected $description = '同步聚工单客服逐行审核通过的附加费,完整校验后替换指定快递的派生结算明细';
|
||||
|
||||
public function handle(CustomerServiceSurchargeSynchronizer $sync): int
|
||||
{
|
||||
$courier = trim((string) $this->option('courier'));
|
||||
if ($courier === '' || (int) $this->option('company') < 1) { $this->error('请指定快递完整名称及有效公司。'); return self::FAILURE; }
|
||||
foreach (['from','to'] as $option) {
|
||||
$date = $this->option($option);
|
||||
if ($date && (! 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 (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
|
||||
$this->error('请使用服务器 run-finance-batch.sh 执行。'); return self::FAILURE;
|
||||
}
|
||||
$lock = Cache::lock(CustomerServiceSurchargeSynchronizer::dataset((int) $this->option('company'), $courier), 2100);
|
||||
if (! $lock->get()) { $this->error('该快递附加费同步正在执行。'); return self::FAILURE; }
|
||||
try {
|
||||
$result = $sync->sync((int) $this->option('company'), $courier, $this->option('from'), $this->option('to'),
|
||||
fn ($done, $total) => $this->line("已扫描 {$done} / {$total} 张查件工单"));
|
||||
$this->info(sprintf('%s 附加费同步完成:%s 至 %s,%d 条,金额 %s 元,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
|
||||
$courier, $result['from'], $result['to'], $result['rows'], $result['amount'], $result['seconds'], $result['peak_mb']));
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $e) {
|
||||
report($e); $this->error('附加费同步失败,保留上次完整结果:' . $e->getMessage()); return self::FAILURE;
|
||||
} finally { $lock->release(); }
|
||||
}
|
||||
}
|
||||
@ -1,110 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||
|
||||
class PushSupplierZeroDifferenceConfirmations extends Command
|
||||
{
|
||||
protected $signature = 'supplier-reconciliation:push-zero-difference-confirmations
|
||||
{--month= : 账期 YYYY-MM,默认上月}
|
||||
{--company=1 : 公司 ID}
|
||||
{--supplier=* : 只处理指定厂家,可重复传入}
|
||||
{--dry-run : 只检查,不发送}
|
||||
{--force : 已有待确认或已确认记录时仍重新推送}';
|
||||
|
||||
protected $description = '扫描厂家上传的账单,双方完全一致时自动推送货款确认';
|
||||
|
||||
public function handle(
|
||||
SupplierStatementStore $statements,
|
||||
SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||
): int {
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$month = trim((string) $this->option('month'));
|
||||
if ($month === '') {
|
||||
$month = now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m');
|
||||
}
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
|
||||
$this->error('账期格式必须为 YYYY-MM。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
Company::findOrFail($companyId)->makeCurrent();
|
||||
|
||||
$suppliers = array_values(array_filter(array_map(
|
||||
static fn (mixed $supplier): string => trim((string) $supplier),
|
||||
(array) $this->option('supplier'),
|
||||
)));
|
||||
if ($suppliers === []) {
|
||||
$suppliers = $statements->uploadedSuppliers($companyId);
|
||||
}
|
||||
$suppliers = array_values(array_unique($suppliers));
|
||||
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
if ($suppliers === []) {
|
||||
$this->info('没有找到已上传对账单的厂家。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$force = (bool) $this->option('force');
|
||||
$rows = [];
|
||||
$pushed = 0;
|
||||
$failed = 0;
|
||||
$skipped = 0;
|
||||
|
||||
foreach ($suppliers as $supplier) {
|
||||
if ($dryRun) {
|
||||
$assessment = $zeroDifferenceConfirmations->assess($supplier, $companyId, $month);
|
||||
$status = $assessment['eligible'] ? '可推送' : '不推送';
|
||||
$reason = $assessment['reason'];
|
||||
$qty = $assessment['qty'];
|
||||
$amount = $assessment['amount'];
|
||||
} else {
|
||||
$result = $zeroDifferenceConfirmations->pushMonth(
|
||||
$supplier,
|
||||
$companyId,
|
||||
$month,
|
||||
null,
|
||||
! $force,
|
||||
);
|
||||
$status = match ($result['status']) {
|
||||
'pushed' => '已推送',
|
||||
'failed' => '失败',
|
||||
default => '跳过',
|
||||
};
|
||||
$reason = $result['reason'];
|
||||
$qty = $result['qty'];
|
||||
$amount = $result['amount'];
|
||||
if ($result['status'] === 'pushed') {
|
||||
$pushed++;
|
||||
} elseif ($result['status'] === 'failed') {
|
||||
$failed++;
|
||||
} else {
|
||||
$skipped++;
|
||||
}
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
$supplier,
|
||||
$status,
|
||||
rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.'),
|
||||
rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.'),
|
||||
$reason,
|
||||
];
|
||||
}
|
||||
|
||||
$this->table(['厂家', '状态', '件数', '货款金额', '说明'], $rows);
|
||||
if ($dryRun) {
|
||||
$this->info("{$month} 检查完成,共 " . count($suppliers) . ' 家;未发送任何消息。');
|
||||
} else {
|
||||
$this->info("{$month} 处理完成:已推送 {$pushed} 家,跳过 {$skipped} 家,失败 {$failed} 家。");
|
||||
}
|
||||
|
||||
return $failed > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -7,14 +7,13 @@ use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。
|
||||
* 后台重建某月账单项目覆盖快照,供科目映射页即时读取。
|
||||
*/
|
||||
class RefreshAccountMappingCoverage extends Command
|
||||
{
|
||||
protected $signature = 'account-mapping:refresh-coverage
|
||||
{month? : all 或账单月份 YYYY-MM}
|
||||
{--pending : 处理页面登记的下一个刷新请求}
|
||||
{--monthly : 本月尚未成功刷新时执行跨月刷新}';
|
||||
{month? : 账单月份,格式 YYYY-MM}
|
||||
{--pending : 处理页面登记的下一个刷新请求}';
|
||||
|
||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||
|
||||
@ -22,12 +21,6 @@ class RefreshAccountMappingCoverage extends Command
|
||||
{
|
||||
$runningPath = null;
|
||||
$month = trim((string) $this->argument('month')) ?: null;
|
||||
$monthly = (bool) $this->option('monthly');
|
||||
if ($monthly && $this->option('pending')) {
|
||||
$this->error('--monthly 与 --pending 不能同时使用。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($this->option('pending')) {
|
||||
$request = $coverage->claimPendingRefresh();
|
||||
if ($request === null) {
|
||||
@ -38,20 +31,9 @@ class RefreshAccountMappingCoverage extends Command
|
||||
$month = $request['month'];
|
||||
$runningPath = $request['path'];
|
||||
}
|
||||
if ($monthly) {
|
||||
if (! $coverage->monthlyRefreshDue()) {
|
||||
$this->line('本月未映射清单已生成,无需重复刷新。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$month = 'all';
|
||||
}
|
||||
|
||||
try {
|
||||
$isAll = $month === 'all';
|
||||
$raw = $isAll
|
||||
? $coverage->refreshAllMonths()
|
||||
: $coverage->refreshForMonth($month);
|
||||
$raw = $coverage->refreshForMonth($month);
|
||||
if (($raw['status'] ?? '') === 'refreshing') {
|
||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||
if ($runningPath !== null) {
|
||||
@ -61,12 +43,10 @@ class RefreshAccountMappingCoverage extends Command
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$summary = $isAll
|
||||
? $coverage->missingAcrossMonths()
|
||||
: $coverage->missingForMonth($month);
|
||||
$summary = $coverage->missingForMonth($month);
|
||||
$this->info(sprintf(
|
||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
||||
$isAll ? '跨月全部账单' : (string) $summary['month'],
|
||||
(string) $summary['month'],
|
||||
(int) $summary['missing_item_count'],
|
||||
(int) $summary['missing_row_count'],
|
||||
(int) $summary['source_rows'],
|
||||
|
||||
@ -1,192 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
|
||||
use Throwable;
|
||||
|
||||
class SummarizeBillRange extends Command
|
||||
{
|
||||
private const ALLOWED_TABS = [
|
||||
'taobao-alipay',
|
||||
'taobao-wechat',
|
||||
'pinduoduo',
|
||||
'jd-wallet',
|
||||
'jd-transactions',
|
||||
'jingxi',
|
||||
'douyin',
|
||||
'dewu',
|
||||
'dewu-alipay',
|
||||
'xiaohongshu',
|
||||
];
|
||||
|
||||
protected $signature = 'bill-sync:summarize-range
|
||||
{--tabs= : 逗号分隔的账单页签}
|
||||
{--from= : 开始日期 YYYY-MM-DD}
|
||||
{--to= : 截止日期 YYYY-MM-DD}
|
||||
{--company-id=1 : 公司 ID}
|
||||
{--json : 输出 JSON}';
|
||||
|
||||
protected $description = '按指定日期范围和页签汇总财务系统账单笔数、收入与支出';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$tabs = array_values(array_unique(array_filter(array_map(
|
||||
static fn (string $tab): string => trim($tab),
|
||||
explode(',', (string) $this->option('tabs')),
|
||||
))));
|
||||
$unknownTabs = array_values(array_diff($tabs, self::ALLOWED_TABS));
|
||||
if ($tabs === [] || $unknownTabs !== []) {
|
||||
$this->error('账单页签无效:' . ($unknownTabs ? implode(',', $unknownTabs) : '不能为空'));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$from = $this->date((string) $this->option('from'));
|
||||
$to = $this->date((string) $this->option('to'));
|
||||
if ($from === null || $to === null || $from->gt($to)) {
|
||||
$this->error('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$companyId = max(1, (int) $this->option('company-id'));
|
||||
$fromText = $from->toDateString();
|
||||
$toText = $to->toDateString();
|
||||
$platforms = [];
|
||||
$rowCount = 0;
|
||||
$incomeCents = 0;
|
||||
$expenseCents = 0;
|
||||
|
||||
foreach ($tabs as $tab) {
|
||||
try {
|
||||
$summary = $this->summary($tab, $fromText, $toText, $companyId);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error("账单页签 {$tab} 汇总失败。");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$platforms[$tab] = $summary;
|
||||
$rowCount += $summary['row_count'];
|
||||
$incomeCents += $summary['income_cents'];
|
||||
$expenseCents += $summary['expense_cents'];
|
||||
}
|
||||
|
||||
$result = [
|
||||
'from' => $fromText,
|
||||
'to' => $toText,
|
||||
'company_id' => $companyId,
|
||||
'row_count' => $rowCount,
|
||||
'income_cents' => $incomeCents,
|
||||
'expense_cents' => $expenseCents,
|
||||
'platforms' => $platforms,
|
||||
];
|
||||
|
||||
if ((bool) $this->option('json')) {
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
} else {
|
||||
$this->table(
|
||||
['页签', '笔数', '收入', '支出'],
|
||||
array_map(
|
||||
static fn (string $tab, array $summary): array => [
|
||||
$tab,
|
||||
number_format($summary['row_count']),
|
||||
number_format($summary['income_cents'] / 100, 2),
|
||||
number_format($summary['expense_cents'] / 100, 2),
|
||||
],
|
||||
array_keys($platforms),
|
||||
array_values($platforms),
|
||||
),
|
||||
);
|
||||
$this->line(sprintf(
|
||||
'合计:%d 笔,收入 %.2f,支出 %.2f',
|
||||
$rowCount,
|
||||
$incomeCents / 100,
|
||||
$expenseCents / 100,
|
||||
));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
|
||||
private function summary(string $tab, string $from, string $to, int $companyId): array
|
||||
{
|
||||
if ($tab === 'xiaohongshu') {
|
||||
$summary = DB::table('ec_account_bills')
|
||||
->where('company_id', $companyId)
|
||||
->where('bill_type', 'xiaohongshu')
|
||||
->where('occurred_at', '>=', $from . ' 00:00:00')
|
||||
->where('occurred_at', '<', Carbon::parse($to)->addDay()->toDateString() . ' 00:00:00')
|
||||
->selectRaw(
|
||||
'COUNT(*) AS row_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
|
||||
)
|
||||
->first();
|
||||
|
||||
return $this->normalize($summary->row_count, $summary->income, $summary->expense);
|
||||
}
|
||||
|
||||
$filters = ['start' => $from, 'end' => $to];
|
||||
$result = match ($tab) {
|
||||
'taobao-alipay' => app(StoreReceivingAlipayBillMirrorRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)
|
||||
->paginateAccountBills($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'jd-wallet' => app(StoreReceivingJdWalletBillRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'jd-transactions' => app(JdDailyBillRepository::class)
|
||||
->forPlatform('jd')
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'jingxi' => app(JdDailyBillRepository::class)
|
||||
->forPlatform('jingxi')
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'douyin' => app(StoreReceivingDouyinBillMirrorRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'dewu' => app(StoreReceivingDewuBillMirrorRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)
|
||||
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||
};
|
||||
|
||||
return $this->normalize(
|
||||
$result['total'] ?? ($result['summary']['count'] ?? 0),
|
||||
$result['summary']['income'] ?? 0,
|
||||
$result['summary']['expense'] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
|
||||
private function normalize(mixed $rows, mixed $income, mixed $expense): array
|
||||
{
|
||||
return [
|
||||
'row_count' => (int) $rows,
|
||||
'income_cents' => (int) round((float) $income * 100),
|
||||
'expense_cents' => (int) round((float) $expense * 100),
|
||||
];
|
||||
}
|
||||
|
||||
private function date(string $value): ?Carbon
|
||||
{
|
||||
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
|
||||
|
||||
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
|
||||
}
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
<?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,14 +71,6 @@ 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')
|
||||
|
||||
@ -12,7 +12,6 @@ use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingSuggestion;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
||||
use RuntimeException;
|
||||
@ -75,7 +74,6 @@ class AccountMappingActions extends Controller
|
||||
private readonly AccountMappingCoa $coa,
|
||||
private readonly AccountMappingWorkbookImporter $importer,
|
||||
private readonly AccountMappingCoverage $coverage,
|
||||
private readonly AccountMappingSuggestion $suggestion,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
@ -98,13 +96,11 @@ class AccountMappingActions extends Controller
|
||||
]);
|
||||
|
||||
try {
|
||||
$month = trim((string) ($data['month'] ?? ''));
|
||||
$refresh = (bool) ($data['refresh'] ?? false);
|
||||
$payload = $month === ''
|
||||
? $this->coverage->missingAcrossMonths($refresh, false)
|
||||
: $this->coverage->missingForMonth($month, $refresh, false);
|
||||
|
||||
return response()->json($payload);
|
||||
return response()->json($this->coverage->missingForMonth(
|
||||
trim((string) ($data['month'] ?? '')) ?: null,
|
||||
(bool) ($data['refresh'] ?? false),
|
||||
false,
|
||||
));
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
||||
} catch (Throwable $exception) {
|
||||
@ -116,20 +112,6 @@ class AccountMappingActions extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
/** 补映射时按同名账单项目查找可带入的既有规则。 */
|
||||
public function suggest(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'platform' => ['required', 'string', 'max:120'],
|
||||
'item' => ['required', 'string', 'max:500'],
|
||||
]);
|
||||
|
||||
return response()->json($this->suggestion->suggest(
|
||||
(string) $data['platform'],
|
||||
(string) $data['item'],
|
||||
));
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$values = $this->payloadValues($request);
|
||||
|
||||
@ -7,7 +7,6 @@ use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\StatementExporter;
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\CourierBills\Rebooks;
|
||||
use App\Support\CourierBills\Waybill;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
@ -121,7 +120,6 @@ final class CourierBillController extends Controller
|
||||
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
||||
}
|
||||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
||||
$items=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->summaryItems((int)$statement->id,$items);
|
||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
||||
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||||
$shippingSync = null;
|
||||
@ -137,26 +135,7 @@ final class CourierBillController extends Controller
|
||||
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
||||
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
||||
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
|
||||
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id), 'cbRebook' => $this->rebookSummary((int) $statement->id),
|
||||
'cbSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
|
||||
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('courier',(int)$statement->id)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null];
|
||||
}
|
||||
|
||||
/** 单家对账单上的补记账说明:补几个月、本期补几单多少、还有几单待复核。 @return array<string,mixed>|null */
|
||||
private function rebookSummary(int $statementId): ?array
|
||||
{
|
||||
try {
|
||||
$plan = app(Rebooks::class)->forStatement($statementId);
|
||||
} catch (\Throwable $error) {
|
||||
report($error);
|
||||
|
||||
return null;
|
||||
}
|
||||
$rows = collect($plan['rows']);
|
||||
|
||||
return ['months' => $plan['months'], 'source' => $plan['source'], 'window' => $plan['window'],
|
||||
'count' => $rows->where('amount', '>', 0)->count(), 'amount' => round((float) $rows->sum('amount'), 2),
|
||||
'pending' => $rows->where('status', '待复核')->count(), 'done' => $rows->filter(fn ($r) => str_starts_with($r['status'], '已补'))->count()];
|
||||
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id)];
|
||||
}
|
||||
|
||||
private function detailsData(Request $request, string $month): array
|
||||
@ -212,28 +191,10 @@ final class CourierBillController extends Controller
|
||||
|
||||
private function uploadData(string $month): array
|
||||
{
|
||||
$jointUploads = [];
|
||||
foreach (\App\Support\CourierBills\CourierJointUploads::SETS as $key => $set) {
|
||||
try {
|
||||
app(\App\Support\CourierBills\CourierJointUploads::class)->resolve($key);
|
||||
$jointUploads[$key] = $set;
|
||||
} catch (RuntimeException) { /* 分组未配置的环境不显示入口。 */ }
|
||||
}
|
||||
|
||||
return ['cbJointUploads' => $jointUploads, 'cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
||||
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
||||
}
|
||||
|
||||
public function jointUploadLink(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'],
|
||||
'joint' => ['required', Rule::in(array_keys(\App\Support\CourierBills\CourierJointUploads::SETS))]]);
|
||||
$url = $this->guard(fn () => app(\App\Support\CourierBills\CourierUploadLink::class)
|
||||
->jointPageUrl((int) (company_id() ?: 1), $data['joint'], $data['month']));
|
||||
|
||||
return redirect()->away($url);
|
||||
}
|
||||
|
||||
private function ledgerData(Request $request): array
|
||||
{
|
||||
$db = $this->store->db();
|
||||
@ -247,16 +208,6 @@ final class CourierBillController extends Controller
|
||||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||||
'cbSearch' => $search,
|
||||
'cbRebookStats' => $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
|
||||
->groupBy('r.refund_month', 'r.deduct_month', 'g.name', 'r.source')
|
||||
->selectRaw(sprintf('%s as refund_month, %s as deduct_month, %s as group_name, %s as source, COUNT(*) as n, SUM(%s) as amount',
|
||||
...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['r.refund_month', 'r.deduct_month', 'g.name', 'r.source', 'r.amount'])))
|
||||
->orderByDesc('r.refund_month')->orderBy('r.deduct_month')->orderBy('g.name')->limit(500)->get(),
|
||||
'cbRebookReviews' => $db->table('courier_bill_rebook_reviews')->groupBy('deduct_month')
|
||||
->selectRaw('deduct_month, COUNT(*) as n, MAX(updated_at) as at')->orderByDesc('deduct_month')->limit(24)->get(),
|
||||
'cbRebookHits' => $search === null ? collect() : $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
|
||||
->where('r.waybill_no', $search)->orderBy('r.deduct_month')->get(['r.*', 'g.name as group_name']),
|
||||
'cbRebookReviewHits' => $search === null ? collect() : $db->table('courier_bill_rebook_reviews')->where('waybill_no', $search)->orderBy('deduct_month')->get(),
|
||||
];
|
||||
}
|
||||
|
||||
@ -458,17 +409,14 @@ final class CourierBillController extends Controller
|
||||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
||||
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
||||
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||||
'rebook_months' => ['nullable', 'in:0,1,2'],
|
||||
], [], ['name' => '分组名称', 'express_names' => '快递名称1', 'rebook_months' => '补记账']);
|
||||
$data['rebook_months'] ??= null;
|
||||
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
|
||||
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
||||
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||||
if ($exists) {
|
||||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||||
}
|
||||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||||
$id = $this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||||
$this->refreshOpenStatements($id);
|
||||
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
||||
}
|
||||
@ -489,49 +437,6 @@ final class CourierBillController extends Controller
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
}
|
||||
|
||||
/** 导入已经补过的记账(系统上线前手工补的),补过的单以后不再补。 */
|
||||
public function importRebooks(Request $request)
|
||||
{
|
||||
return $this->importRebookFile($request, 'rebooks', '已补记录', function (string $path, string $extension): string {
|
||||
$r = app(Rebooks::class)->importRefunds($path, $extension);
|
||||
|
||||
return '读到 ' . $r['rows'] . ' 行,新增 ' . $r['inserted'] . ' 条已补记录' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||
});
|
||||
}
|
||||
|
||||
/** 导入复核记账:这单现在应扣多少,本期补款 = 当时扣的 − 现在应扣。 */
|
||||
public function importRebookReviews(Request $request)
|
||||
{
|
||||
return $this->importRebookFile($request, 'reviews', '复核记账', function (string $path, string $extension, string $name): string {
|
||||
$r = app(Rebooks::class)->importReviews($path, $extension, $name);
|
||||
|
||||
return '读到 ' . $r['rows'] . ' 行,导入 ' . $r['inserted'] . ' 条复核记账' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||
});
|
||||
}
|
||||
|
||||
/** 补记账规则改了、复核导了之后,重排还没确认的对账单小汇总。 */
|
||||
private function importRebookFile(Request $request, string $field, string $label, callable $import)
|
||||
{
|
||||
$file = $request->validate([$field => ['required', 'file', 'max:51200']], [], [$field => $label . '文件'])[$field];
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages([$field => '只支持 xlsx、xls、csv。']);
|
||||
}
|
||||
$message = $this->guard(fn () => $import($file->getRealPath(), $extension, $file->getClientOriginalName()));
|
||||
$this->refreshOpenStatements();
|
||||
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
}
|
||||
|
||||
private function refreshOpenStatements(?int $groupId = null): void
|
||||
{
|
||||
$matcher = app(\App\Support\CourierBills\CourierBillMatcher::class);
|
||||
$this->store->db()->table('courier_bill_statements')->where('status', 'open')
|
||||
->when($groupId !== null, fn ($q) => $q->where('group_id', $groupId))
|
||||
->where('bill_month', '>=', now()->subMonthsNoOverflow(2)->format('Y-m'))->pluck('id')
|
||||
->each(fn ($id) => $matcher->refreshSummary((int) $id));
|
||||
}
|
||||
|
||||
public function exportStatement(Request $request, int $statement)
|
||||
{
|
||||
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\CourierJointUploads;
|
||||
use App\Support\CourierBills\CourierUploadLink;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\PortalFreightBillImports;
|
||||
@ -31,20 +30,17 @@ final class CourierUploadShare extends Controller
|
||||
{
|
||||
$t = $this->target($request, $token);
|
||||
$expires = $this->expiresAt($request);
|
||||
$query = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']);
|
||||
if ($t['joint'] !== null) $query->where('extra_group_ids', json_encode(['joint_upload' => $t['payload']['joint']]));
|
||||
else $query->where(fn ($q) => $q->whereNull('extra_group_ids')->orWhere('extra_group_ids', 'not like', '%"joint_upload"%'));
|
||||
$files = $query->orderByDesc('id')->limit(20)->get();
|
||||
$files = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month'])
|
||||
->orderByDesc('id')->limit(20)->get();
|
||||
$pending = array_map(static fn (array $file): object => (object) [
|
||||
'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'],
|
||||
'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'],
|
||||
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'], $t['joint']['key'] ?? null));
|
||||
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month']));
|
||||
$files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values();
|
||||
|
||||
return response()->view('business.pages.courier-payables.courier-bills.upload-share', [
|
||||
'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files,
|
||||
'expiresAt' => $expires, 'confirmed' => $t['confirmed'],
|
||||
'joint' => $t['joint'], 'uploadLabel' => $t['joint']['label'] ?? $t['group']->name,
|
||||
'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires),
|
||||
'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $token, $t['companyId'], $expires),
|
||||
])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive',
|
||||
@ -55,7 +51,7 @@ final class CourierUploadShare extends Controller
|
||||
{
|
||||
$t = $this->target($request, $token);
|
||||
|
||||
return $this->template->download(($t['joint']['label'] ?? $t['group']->name) . '_' . $t['month'] . '_账单上传模板.xlsx');
|
||||
return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx');
|
||||
}
|
||||
|
||||
public function upload(Request $request, string $token): RedirectResponse
|
||||
@ -75,14 +71,13 @@ final class CourierUploadShare extends Controller
|
||||
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
|
||||
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
|
||||
'source' => 'courier_upload_link',
|
||||
'joint' => $t['payload']['joint'],
|
||||
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
|
||||
]);
|
||||
|
||||
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
|
||||
}
|
||||
|
||||
/** @return array{companyId:int,group:object,month:string,confirmed:bool,joint:?array,payload:array} */
|
||||
/** @return array{companyId:int,group:object,month:string,confirmed:bool} */
|
||||
private function target(Request $request, string $token): array
|
||||
{
|
||||
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
|
||||
@ -90,15 +85,10 @@ final class CourierUploadShare extends Controller
|
||||
abort_if($payload === null, 404, '链接无效或已过期。');
|
||||
$group = collect($this->store->groups())->firstWhere('id', $payload['group_id']);
|
||||
abort_if($group === null, 404, '链接无效或已过期。');
|
||||
$joint = null;
|
||||
if ($payload['joint'] !== null) {
|
||||
try { $joint = app(CourierJointUploads::class)->verify($payload['joint']); }
|
||||
catch (\RuntimeException $e) { abort(410, $e->getMessage()); }
|
||||
}
|
||||
$confirmed = $this->store->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$group->id])
|
||||
$confirmed = $this->store->db()->table('courier_bill_statements')->where('group_id', $group->id)
|
||||
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
|
||||
|
||||
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed, 'joint' => $joint, 'payload' => $payload];
|
||||
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed];
|
||||
}
|
||||
|
||||
private function expiresAt(Request $request): CarbonImmutable
|
||||
|
||||
@ -108,12 +108,7 @@ final class DropshipFreightController extends Controller
|
||||
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
|
||||
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()),
|
||||
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()),
|
||||
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name),
|
||||
'dfSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
|
||||
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null,
|
||||
'dfSurchargeSummary' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
|
||||
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)
|
||||
->selectRaw('item,SUM(bill_amount) AS bill,SUM(self_amount) AS self')->groupBy('item')->get() : collect()];
|
||||
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)];
|
||||
}
|
||||
|
||||
private function uploadData(string $month): array
|
||||
|
||||
@ -5038,14 +5038,17 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 按表维护的页面数据:终版页签及快递记账明细使用各自的独立数据集。
|
||||
* 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。
|
||||
*
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
protected function payablesFinalData(array $section, ?array $page): ?array
|
||||
{
|
||||
$sectionSlug = (string) ($section['slug'] ?? '');
|
||||
if (empty($page)) {
|
||||
if (empty($page) || ! in_array($sectionSlug, [
|
||||
PayablesFinalRegistry::SECTION_SUPPLIER,
|
||||
PayablesFinalRegistry::SECTION_COURIER,
|
||||
], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -5064,7 +5067,9 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
$keyword = trim((string) request('keyword', ''));
|
||||
$storeDataset = $registry->storeDataset($sectionSlug, $dataset);
|
||||
$storeDataset = PayablesFinalActions::DATASET_PREFIX
|
||||
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
|
||||
. $dataset;
|
||||
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
||||
$requestedMonth = trim((string) request('month', ''));
|
||||
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
||||
@ -5972,7 +5977,6 @@ 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(),
|
||||
@ -6002,7 +6006,6 @@ class Pages extends Controller
|
||||
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
||||
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
||||
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
|
||||
'raw-statements' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->rawStatementsData(),
|
||||
'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
|
||||
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
||||
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
||||
@ -8808,7 +8811,6 @@ class Pages extends Controller
|
||||
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
||||
$pagePaymentAmount = '0.00';
|
||||
$filteredPaymentAmount = '0.00';
|
||||
$storePaymentSummary = [];
|
||||
$shopNames = [];
|
||||
$paymentReasons = [];
|
||||
$error = null;
|
||||
@ -8853,9 +8855,6 @@ class Pages extends Controller
|
||||
);
|
||||
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
||||
$filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00');
|
||||
$storePaymentSummary = is_array($result['store_summary'] ?? null)
|
||||
? $result['store_summary']
|
||||
: [];
|
||||
}
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
@ -8870,7 +8869,6 @@ class Pages extends Controller
|
||||
'smallPaymentSyncStatus' => $syncStatus,
|
||||
'smallPaymentPageAmount' => $pagePaymentAmount,
|
||||
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
||||
'smallPaymentStoreSummary' => $storePaymentSummary,
|
||||
'smallPaymentShops' => $shopNames,
|
||||
'smallPaymentReasons' => $paymentReasons,
|
||||
'smallPaymentStatuses' => [
|
||||
|
||||
@ -16,7 +16,8 @@ use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 终版页签和快递记账明细的导入、导出及编辑,各入口使用独立数据集。
|
||||
* 「终版」目录的按表数据:界面与基础页面一致,数据独立存放
|
||||
* (数据集键 final:<目录>:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。
|
||||
*/
|
||||
class PayablesFinalActions extends Controller
|
||||
{
|
||||
@ -170,7 +171,9 @@ class PayablesFinalActions extends Controller
|
||||
|
||||
private function storeDataset(Request $request): string
|
||||
{
|
||||
return $this->registry->storeDataset($this->section($request), $this->dataset($request));
|
||||
$section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier';
|
||||
|
||||
return self::DATASET_PREFIX . $section . ':' . $this->dataset($request);
|
||||
}
|
||||
|
||||
private function csvText(mixed $value): string
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@ -15,9 +15,7 @@ use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementWorkbookExporter;
|
||||
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
@ -38,8 +36,6 @@ class SupplierReconciliation extends Controller
|
||||
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
||||
private readonly SupplierPortalAccess $supplierPortalAccess,
|
||||
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
||||
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||
private readonly SupplierStatementWorkbookExporter $statementWorkbookExporter,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
@ -73,8 +69,7 @@ class SupplierReconciliation extends Controller
|
||||
);
|
||||
|
||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||
$notices = [];
|
||||
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||
$receiptNotice = '';
|
||||
if ($supplierPortalUpload) {
|
||||
try {
|
||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||
@ -83,30 +78,14 @@ class SupplierReconciliation extends Controller
|
||||
$records,
|
||||
);
|
||||
if ($receiptSent) {
|
||||
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||
}
|
||||
|
||||
try {
|
||||
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
|
||||
$supplier,
|
||||
(int) (company_id() ?: 1),
|
||||
$records,
|
||||
user_id() ? (int) user_id() : null,
|
||||
);
|
||||
$autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush);
|
||||
if ($autoPushNotice !== '') {
|
||||
$notices[] = $autoPushNotice;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$notices[] = '零差异对账确认自动推送失败,对账单已正常保存';
|
||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
||||
}
|
||||
}
|
||||
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
|
||||
$message .= $receiptNotice !== '' ? $receiptNotice : '。';
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json(['message' => $message, 'rows' => $rows])
|
||||
@ -166,23 +145,6 @@ class SupplierReconciliation extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function exportRawStatement(Request $request): StreamedResponse
|
||||
{
|
||||
[$supplier, $companyId] = $this->returnTarget($request);
|
||||
$latestUpload = $this->statements->uploads($supplier, $companyId, 1)[0] ?? null;
|
||||
if ($latestUpload === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'raw_statement_export' => '该厂家还没有上传对账单,暂无原始账单可导出。',
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->statementWorkbookExporter->download(
|
||||
$this->statements->streamRows($supplier, $companyId),
|
||||
$supplier,
|
||||
(string) ($latestUpload['uploaded_at'] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
public function saveDingTalkRobot(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
|
||||
@ -13,7 +13,6 @@ use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
@ -31,7 +30,6 @@ class SupplierReconciliation extends Controller
|
||||
private readonly SupplierReconciliationPageData $pageData,
|
||||
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
||||
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
||||
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||
) {
|
||||
}
|
||||
|
||||
@ -76,7 +74,7 @@ class SupplierReconciliation extends Controller
|
||||
user_id() ? (int) user_id() : null,
|
||||
);
|
||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||
$notices = [];
|
||||
$receiptNotice = '';
|
||||
try {
|
||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||
$supplier,
|
||||
@ -84,30 +82,13 @@ class SupplierReconciliation extends Controller
|
||||
$records,
|
||||
);
|
||||
if ($receiptSent) {
|
||||
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
||||
}
|
||||
|
||||
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||
try {
|
||||
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
|
||||
$supplier,
|
||||
$companyId,
|
||||
$records,
|
||||
user_id() ? (int) user_id() : null,
|
||||
);
|
||||
$autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush);
|
||||
if ($autoPushNotice !== '') {
|
||||
$notices[] = $autoPushNotice;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$notices[] = '零差异对账确认自动推送失败,对账单已正常保存';
|
||||
}
|
||||
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
|
||||
$message .= $receiptNotice !== '' ? $receiptNotice : '。';
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json(['message' => $message, 'rows' => $rows])
|
||||
|
||||
@ -169,7 +169,7 @@ final class BillParser
|
||||
}
|
||||
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
||||
$skip[$sheet] = ['附加费表:按单号和费用类型匹配结算', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
||||
$freight[] = $sheet;
|
||||
} else {
|
||||
|
||||
@ -1,121 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees;
|
||||
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
|
||||
|
||||
/** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */
|
||||
final class BillSurchargeQuoteCalculator
|
||||
{
|
||||
public function calculate(array $input, string $scope, string $month, array $allowedCouriers): array
|
||||
{
|
||||
if ($input === [] || $allowedCouriers === []) return ['rows' => [], 'notes' => [], 'metadata' => []];
|
||||
$rules = DB::table('business_courier_surcharge_quotes')->where('company_id', (int) (company_id() ?: 1))
|
||||
->where('status', 'active')->whereNull('deleted_at')->whereIn('courier', $allowedCouriers)
|
||||
->where('scope', $scope === 'dropship' ? '代发仓' : '自有快递')
|
||||
->orderByDesc('effective_at')->orderByDesc('id')->get();
|
||||
$waybills = array_values(array_unique(array_column($input, 'waybill_no')));
|
||||
$shipping = app(ShippingLookup::class);
|
||||
$ships = $shipping->details($waybills);
|
||||
$freights = $shipping->summaries($waybills);
|
||||
$needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实');
|
||||
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
|
||||
$rows = $notes = $metadata = [];
|
||||
foreach ($input as $fee) {
|
||||
$wb = strtoupper($fee['waybill_no']); $type = SurchargeSettlementMatcher::type($fee['item']);
|
||||
$ship = $ships[$wb] ?? []; $courier = $ship['express_name1'] ?? '';
|
||||
$date = substr((string) ($ship['ship_time'] ?? ''), 0, 10);
|
||||
$metadata[$wb] = ['courier_name' => $courier ?: null, 'platform_product_id' => $ship['item_id'] ?? null,
|
||||
'product_code' => $ship['barcode'] ?? null, 'shop_name' => $ship['shop_name'] ?? null,
|
||||
'online_order_no' => $ship['trade_no'] ?? null];
|
||||
if($date !== '' && $date >= date('Y-m-d', strtotime($month . '-01 +1 month'))){
|
||||
$notes[$wb][$type]='发货日期晚于账单月份,未计入本月';
|
||||
continue;
|
||||
}
|
||||
$candidates = $rules->filter(fn ($r) => $r->courier === $courier
|
||||
&& in_array($type, array_map([SurchargeSettlementMatcher::class, 'type'], json_decode($r->types, true) ?: []), true));
|
||||
$rule = $candidates->first(fn ($r) => $date !== '' && substr($r->effective_at, 0, 10)
|
||||
<= ($r->mode === '聚工单客服核实' ? $month . '-31' : $date));
|
||||
if ($rule === null) {
|
||||
$notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录';
|
||||
continue;
|
||||
}
|
||||
$base = ['rule_id' => $rule->id, 'courier_name' => $courier, 'waybill' => $wb, 'surcharge_type' => $type,
|
||||
'shipped_at' => $ship['ship_time'] ?? null, 'source_created_at' => null,
|
||||
'platform_product_id' => $ship['item_id'] ?? null, 'product_code' => $ship['barcode'] ?? null,
|
||||
'shop_name' => $ship['shop_name'] ?? null, 'online_order_no' => $ship['trade_no'] ?? null,
|
||||
'source_kind' => 'bill_quote', 'source_key' => $wb . '|' . $type, 'outbound_io_id' => null];
|
||||
$result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? []);
|
||||
if (is_string($result)) { $notes[$wb][$type] = '报价 #' . $rule->id . ':' . $result; continue; }
|
||||
foreach ($result as $price) $rows[$wb][$type][] = (object) array_replace($base, $price,
|
||||
['settlement_status' => '已计算', 'evidence' => '报价 #' . $rule->id . ';' . $price['evidence']]);
|
||||
}
|
||||
return compact('rows', 'notes', 'metadata');
|
||||
}
|
||||
|
||||
private function price(object $rule, string $type, array $ship, array $freight, array $orders): array|string
|
||||
{
|
||||
if ($rule->mode === '取发出运费') {
|
||||
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费'], true)) return '计费条件尚未支持自动核验';
|
||||
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
|
||||
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
|
||||
$amount = round($freight['calc_freight'], 2);
|
||||
return [['settlement_amount' => $amount, 'evidence' => '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
|
||||
}
|
||||
if ($rule->mode === '按尺寸/最长边') {
|
||||
if (! preg_match('/^(?:单边超|最长边超过?)\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米)$/iu', trim($rule->condition), $threshold)
|
||||
|| ! preg_match('/^(\d+(?:\.\d+)?)\s*元?\s*\/\s*单$/u', trim($rule->standard), $price)) return '尺寸计费条件或单价尚未支持自动核验';
|
||||
$sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)];
|
||||
if (min($sides) <= 0) return '发货商品缺少完整尺寸';
|
||||
$max = max($sides); $amount = $max > (float) $threshold[1] ? (float) $price[1] : 0;
|
||||
return [['settlement_amount' => $amount, 'evidence' => '最长边 ' . $max . 'cm,报价阈值 ' . $threshold[1] . 'cm,按票计费']];
|
||||
}
|
||||
if ($rule->mode !== '聚工单客服核实') return '计费方式“' . $rule->mode . '”尚未接入账单自动核价';
|
||||
if (trim($rule->standard) !== '读取聚工单附加费明细') return '客服计价标准尚未支持自动核验';
|
||||
$condition = trim($rule->condition);
|
||||
if (preg_match('/^重量\s*(\d+(?:\.\d+)?)\s*(?:kg|公斤|千克)以上[,,、]?上楼费聚工单客服回复通过$/iu', $condition, $weight)) {
|
||||
if (($freight['charge_weight'] ?? null) === null) return '缺少已核算计费重量,无法检查上楼费门槛';
|
||||
if ((float) $freight['charge_weight'] < (float) $weight[1]) return [['settlement_amount' => 0,
|
||||
'evidence' => '本票计费重量 ' . $freight['charge_weight'] . 'kg,未达到 ' . $weight[1] . 'kg 门槛,不计费']];
|
||||
} elseif (! in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) return '客服附加条件尚未支持自动核验';
|
||||
$result = []; $found = false;
|
||||
foreach ($orders as $order) {
|
||||
$fields = [];
|
||||
foreach (json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [] as $f) if (isset($f['fieldId'])) $fields[$f['fieldId']] = $f;
|
||||
if (($fields['logisticsField']['value'] ?? '') !== $rule->courier
|
||||
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|
||||
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
|
||||
$cents = 0;
|
||||
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
|
||||
$v = array_column($line, 'value', 'fieldId');
|
||||
$actualType = match (trim((string) ($v[ServiceFees::FEE_TYPE] ?? ''))) {
|
||||
'拦截退回运费' => '退回费', default => SurchargeSettlementMatcher::type((string) ($v[ServiceFees::FEE_TYPE] ?? '')),
|
||||
};
|
||||
if ($actualType !== $type) continue;
|
||||
$found = true;
|
||||
if (($v[ServiceFees::FEE_APPROVAL] ?? '') !== '通过') continue;
|
||||
$amount = trim((string) ($v[ServiceFees::FEE_AMOUNT] ?? ''));
|
||||
if (! preg_match('/^\d{1,9}(?:\.\d{1,2})?$/D', $amount)) return '客服已通过的费用金额无效';
|
||||
$cents += (int) round((float) $amount * 100);
|
||||
}
|
||||
if ($cents > 0) $result[] = ['settlement_amount' => $cents / 100,
|
||||
'source_kind' => ServiceFees::KIND, 'source_key' => $order->woNo, 'source_created_at' => $order->created,
|
||||
'evidence' => '聚工单 ' . $order->woNo . ' 附加费明细逐项审核通过'];
|
||||
}
|
||||
return $result ?: ($found ? '对应工单附加费未审核通过' : '未找到对应单号、费用类型和快递的客服费用明细');
|
||||
}
|
||||
|
||||
private function workOrders(array $waybills, string $month): array
|
||||
{
|
||||
if (! app(WorkOrderWaybillLookup::class)->ready()) return [];
|
||||
$rows = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))
|
||||
->table(WorkOrderWaybillLookup::TABLE . ' as l')->join(WorkOrderWaybillLookup::SOURCE . ' as w', 'w._mirror_key', '=', 'l.mirror_key')
|
||||
->whereIn('l.waybill', $waybills)->where('w.created', '<', date('Y-m-d', strtotime($month . '-01 +1 month')))
|
||||
->orderBy('w.Id')->get(['l.waybill', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
|
||||
$result = [];
|
||||
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@ -254,17 +254,13 @@ final class CourierBillMatcher
|
||||
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
||||
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
||||
$kinds['配件补发扣款'] = 'accessory';
|
||||
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
|
||||
$surchargeMatcher->courier($statementId);
|
||||
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
|
||||
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
|
||||
$fees = $this->surchargeItems($statementId);
|
||||
$template = $this->templateFor($statementId);
|
||||
$this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
|
||||
$sort = 8000;
|
||||
foreach ($fees as $item => $sum) {
|
||||
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
||||
$items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
|
||||
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填
|
||||
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
|
||||
$kinds[$item] = 'fee';
|
||||
}
|
||||
}
|
||||
@ -306,34 +302,6 @@ final class CourierBillMatcher
|
||||
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 历史账单补接附加费时只更新费用行,保留原运费与手工小汇总。 */
|
||||
public function refreshSurchargeSummary(int $statementId): void
|
||||
{
|
||||
$db=self::db();
|
||||
$db->transaction(function()use($db,$statementId):void{
|
||||
$statement=$db->table('courier_bill_statements')->where('id',$statementId)->lockForUpdate()->first();
|
||||
if(!$statement||$statement->status==='confirmed')return;
|
||||
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($statementId);
|
||||
if(!$matcher->ready())return;
|
||||
$sums=$matcher->query('courier',$statementId)->selectRaw('summary_label,SUM(bill_amount) AS bill,SUM(self_amount) AS self')
|
||||
->groupBy('summary_label')->get();
|
||||
$auto=[];foreach($sums as $sum)$auto[$sum->summary_label]=['bill'=>(float)$sum->bill,'self'=>(float)$sum->self,'kind'=>'fee'];
|
||||
$template=$this->templateFor($statementId);
|
||||
$rows=$template===null?array_map(fn($label,$v)=>['label'=>$label]+$v,array_keys($auto),array_values($auto))
|
||||
:array_values(array_filter(SummaryTemplate::apply($template,$auto,(int)substr($statement->bill_month,5,2)),fn($r)=>$r['fee']));
|
||||
foreach($rows as $row){
|
||||
$existing=$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->where('label',$row['label'])->orderBy('id')->first();
|
||||
if($existing){
|
||||
if(!$existing->manual)$db->table('courier_bill_summary_items')->where('id',$existing->id)->update(['self_amount'=>round((float)$row['self'],2)]);
|
||||
}else{
|
||||
$sort=(int)$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->max('sort')+1;
|
||||
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$statementId,'label'=>$row['label'],
|
||||
'bill_amount'=>$row['bill'],'self_amount'=>round((float)$row['self'],2),'manual'=>false,'sort'=>$sort]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
||||
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
||||
@ -361,36 +329,6 @@ final class CourierBillMatcher
|
||||
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 补记账:按扣款月份各一行「补X月记账」(快递金额空、自算为补款金额),照模板落到「补9月记账」「2026.8-9月记账补款」「补记账」这类行。
|
||||
* 已经手工加了补记账行时不再自动加,免得补两次;记账明细、复核还没导时不加。
|
||||
*
|
||||
* @param list<string>|null $template
|
||||
* @param \Illuminate\Support\Collection<string,int> $manualLabels
|
||||
* @param array<string,array{bill:?float,self:float,sort:int}> $items
|
||||
* @param array<string,string> $kinds
|
||||
*/
|
||||
private function addRebooks(int $statementId, ?array $template, $manualLabels, array &$items, array &$kinds): void
|
||||
{
|
||||
foreach ($manualLabels->keys() as $label) {
|
||||
if (Rebooks::isRebookLabel((string) $label)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
$plan = app(Rebooks::class)->forStatement($statementId, $template);
|
||||
} catch (\Throwable $error) {
|
||||
report($error);
|
||||
|
||||
return;
|
||||
}
|
||||
foreach (Rebooks::totals($plan['rows']) as $deductMonth => $amount) {
|
||||
$label = Rebooks::label($deductMonth);
|
||||
$items[$label] = ['bill' => null, 'self' => $amount, 'sort' => 9100 + (int) substr($deductMonth, 5, 2)];
|
||||
$kinds[$label] = 'rebook:' . (int) substr($deductMonth, 5, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */
|
||||
public function feeLabels(int $statementId): array
|
||||
{
|
||||
@ -442,7 +380,7 @@ final class CourierBillMatcher
|
||||
|
||||
/**
|
||||
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
|
||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。
|
||||
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
||||
*
|
||||
* @return array<string,float>
|
||||
@ -457,11 +395,9 @@ final class CourierBillMatcher
|
||||
return [];
|
||||
}
|
||||
$result = [];
|
||||
$files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
|
||||
foreach ($files as $file) {
|
||||
$fileId = (int) $file->id;
|
||||
$primary = (int) $file->statement_id;
|
||||
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
|
||||
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
|
||||
foreach ($primaryIds as $fileId => $primaryId) {
|
||||
$primary = (int) $primaryId;
|
||||
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
||||
if (! (clone $rows)->exists()) {
|
||||
continue;
|
||||
@ -479,14 +415,11 @@ final class CourierBillMatcher
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
|
||||
$assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId)
|
||||
->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : [];
|
||||
$shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void {
|
||||
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
||||
foreach ($chunk as $row) {
|
||||
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
||||
$owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary);
|
||||
if ($owner !== $statementId) {
|
||||
if (($names[$express] ?? $primary) !== $statementId) {
|
||||
continue;
|
||||
}
|
||||
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;
|
||||
|
||||
@ -54,10 +54,6 @@ final class CourierBillStore
|
||||
'weight_header' => self::blank($data['weight_header'] ?? null),
|
||||
'updated_at' => now(),
|
||||
];
|
||||
if (array_key_exists('rebook_months', $data)) {
|
||||
// 补记账补几个月:空 = 按小汇总识别
|
||||
$values['rebook_months'] = in_array($data['rebook_months'], [null, ''], true) ? null : min(max((int) $data['rebook_months'], 0), Rebooks::MAX_MONTHS);
|
||||
}
|
||||
if ($id === null) {
|
||||
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
||||
}
|
||||
@ -366,31 +362,6 @@ final class CourierBillStore
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function uploadJoint(UploadedFile $file, string $month, array $scope, string $user): int
|
||||
{
|
||||
return $this->db()->transaction(function () use ($file, $month, $scope, $user): int {
|
||||
$set = app(CourierJointUploads::class)->verify($scope);
|
||||
$this->lockJointTargets($set['group_ids'], $month);
|
||||
$id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month,
|
||||
$set['group_ids'], $set['groups'], $user, true, $scope);
|
||||
if ($this->db()->table('courier_bill_files')->where('id', $id)->value('status') === 'parsed') {
|
||||
foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId);
|
||||
}
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
private function lockJointTargets(array $ids, string $month): void
|
||||
{
|
||||
$db = $this->db();
|
||||
$db->table('courier_bill_groups')->whereIn('id', $ids)->orderBy('id')->lockForUpdate()->get();
|
||||
if ($db->table('courier_bill_statements')->whereIn('group_id', $ids)->where('bill_month', $month)
|
||||
->orderBy('id')->lockForUpdate()->get()->contains('status', 'confirmed')) {
|
||||
throw new RuntimeException('联合上传范围中有分组本月已确认结算,请联系财务。');
|
||||
}
|
||||
}
|
||||
|
||||
/** 给待选分组的文件指定分组,读入并对账。 */
|
||||
public function assign(int $fileId, int $groupId): void
|
||||
{
|
||||
@ -423,7 +394,6 @@ final class CourierBillStore
|
||||
$db->transaction(function () use ($db, $file): void {
|
||||
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
|
||||
if(app(SurchargeSettlementMatcher::class)->ready())$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('file_id',$file->id)->delete();
|
||||
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
||||
});
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
@ -453,7 +423,7 @@ final class CourierBillStore
|
||||
* @param list<int> $groupIds
|
||||
* @param list<object> $groups
|
||||
*/
|
||||
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false, ?array $joint = null): int
|
||||
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int
|
||||
{
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||
@ -466,7 +436,7 @@ final class CourierBillStore
|
||||
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
|
||||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
|
||||
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
||||
'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
|
||||
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
|
||||
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
||||
]);
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
@ -486,12 +456,6 @@ final class CourierBillStore
|
||||
{
|
||||
$db = $this->db();
|
||||
$file = $db->table('courier_bill_files')->find($fileId);
|
||||
$joint = json_decode((string) $file->extra_group_ids, true)['joint_upload'] ?? null;
|
||||
if ($joint !== null) {
|
||||
$set = app(CourierJointUploads::class)->verify($joint);
|
||||
$this->lockJointTargets($set['group_ids'], (string) $file->bill_month);
|
||||
$portal = true;
|
||||
}
|
||||
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
|
||||
if ($statement !== null && $statement->status === 'confirmed') {
|
||||
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
||||
@ -517,7 +481,7 @@ final class CourierBillStore
|
||||
$feeCount = 0;
|
||||
$overlap = null;
|
||||
try {
|
||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, $joint, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
|
||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
|
||||
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
||||
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
||||
}
|
||||
@ -598,7 +562,7 @@ final class CourierBillStore
|
||||
$db->table('courier_bill_surcharges')->insert($fees);
|
||||
}
|
||||
|
||||
return $portal && $joint === null ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
|
||||
return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
|
||||
});
|
||||
} catch (Throwable $error) {
|
||||
if ($reread) {
|
||||
@ -629,7 +593,7 @@ final class CourierBillStore
|
||||
$notes[] = '没有找到含单号和运费列的工作表';
|
||||
}
|
||||
if ($feeCount > 0) {
|
||||
$notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
|
||||
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
|
||||
}
|
||||
$unread = [];
|
||||
foreach ($sheets as $sheet) {
|
||||
@ -677,8 +641,6 @@ final class CourierBillStore
|
||||
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
||||
{
|
||||
$db = $this->db();
|
||||
$metadata = json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true);
|
||||
if (isset($metadata['joint_upload'])) return $this->splitJoint($fileId, $month, $metadata['joint_upload']);
|
||||
$groups = collect($this->groups());
|
||||
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
|
||||
$bundle = trim((string) ($primary->bundle ?? ''));
|
||||
@ -759,56 +721,6 @@ final class CourierBillStore
|
||||
return implode(';', $parts);
|
||||
}
|
||||
|
||||
/** 只在签名授权范围内逐批归组;任何无法归属的行整份退回,避免留在错误的主分组。 */
|
||||
private function splitJoint(int $fileId, string $month, array $scope): string
|
||||
{
|
||||
$db = $this->db();
|
||||
$set = app(CourierJointUploads::class)->verify($scope);
|
||||
$this->lockJointTargets($set['group_ids'], $month);
|
||||
$owners = [];
|
||||
$statements = [];
|
||||
foreach ($set['groups'] as $g) {
|
||||
foreach (array_intersect(array_unique([$g->name, ...$g->express_names]), $set['names']) as $name) {
|
||||
if (isset($owners[$name]) && $owners[$name] !== (int) $g->id) throw new RuntimeException('联合上传快递名称重复,请联系财务。');
|
||||
$owners[$name] = (int) $g->id;
|
||||
}
|
||||
$statement = $db->table('courier_bill_statements')->where('group_id', $g->id)->where('bill_month', $month)->first();
|
||||
if ($statement !== null) $statements[(int) $g->id] = (int) $statement->id;
|
||||
}
|
||||
$counts = [];
|
||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void {
|
||||
$shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all());
|
||||
$moves = [];
|
||||
foreach ($lines as $line) {
|
||||
$raw = json_decode((string) $line->raw, true);
|
||||
$declared = trim((string) ($raw[4] ?? ''));
|
||||
if ($declared !== '' && ! isset($owners[$declared])) throw new RuntimeException('第 ' . $line->row_no . ' 行快递名称不在本链接范围内。整份文件未读入。');
|
||||
$name = trim((string) ($shipping[strtoupper($line->waybill_no)]['express_name'] ?? ''));
|
||||
if ($name === '') $name = $declared;
|
||||
$groupId = $owners[$name] ?? null;
|
||||
if ($groupId === null) throw new RuntimeException('第 ' . $line->row_no . ' 行单号 ' . $line->waybill_no . ' 无法归到本链接范围;系统查不到时请填写范围内的快递名称。整份文件未读入。');
|
||||
$statements[$groupId] ??= (int) $db->table('courier_bill_statements')->insertGetId([
|
||||
'group_id' => $groupId, 'bill_month' => $month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
$moves[$statements[$groupId]][] = (int) $line->id;
|
||||
$counts[$groupId] = ($counts[$groupId] ?? 0) + 1;
|
||||
}
|
||||
foreach ($moves as $statementId => $ids) $db->table('courier_bill_lines')->whereIn('id', $ids)->update(['statement_id' => $statementId]);
|
||||
});
|
||||
// 附加费沿用同单号的运费归属,不把找不到归属的费用默认塞给主分组。
|
||||
$missingFee = $db->table('courier_bill_surcharges as fee')->where('fee.file_id', $fileId)
|
||||
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('courier_bill_lines as line')
|
||||
->whereColumn('line.file_id', 'fee.file_id')->whereColumn('line.waybill_no', 'fee.waybill_no'))->first();
|
||||
if ($missingFee !== null) throw new RuntimeException('附加费单号 ' . $missingFee->waybill_no . ' 缺少对应运费明细,无法确定分组。整份文件未读入。');
|
||||
$ambiguous = $db->table('courier_bill_lines')->where('file_id', $fileId)->groupBy('waybill_no')
|
||||
->havingRaw('COUNT(DISTINCT statement_id) > 1')->first(['waybill_no']);
|
||||
if ($ambiguous !== null) throw new RuntimeException('单号 ' . $ambiguous->waybill_no . ' 填写了不同快递名称,请核对。整份文件未读入。');
|
||||
$notes = [];
|
||||
foreach ($set['groups'] as $g) if (isset($counts[$g->id])) $notes[] = $g->name . ' ' . $counts[$g->id] . ' 行';
|
||||
|
||||
return '联合上传已归组:' . implode('、', $notes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
||||
* 涉及的对账单有已确认结算的就不动。
|
||||
@ -1014,7 +926,7 @@ final class CourierBillStore
|
||||
return $files;
|
||||
}
|
||||
|
||||
/** 确认结算:锁定对账单,结算台账记下这批单号;这期补记账补的单记进补记账台账(补过的不再补)。 */
|
||||
/** 确认结算:锁定对账单,结算台账记下这批单号。 */
|
||||
public function confirm(int $statementId, string $user): void
|
||||
{
|
||||
$db = $this->db();
|
||||
@ -1047,9 +959,6 @@ final class CourierBillStore
|
||||
if ($buffer !== []) {
|
||||
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
|
||||
}
|
||||
$rebooks = app(Rebooks::class);
|
||||
$rebooks->forget((int) $statement->id);
|
||||
$rebooks->record((int) $statement->id);
|
||||
$db->table('courier_bill_statements')->where('id', $statement->id)->update([
|
||||
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
|
||||
]);
|
||||
@ -1061,7 +970,6 @@ final class CourierBillStore
|
||||
$db = $this->db();
|
||||
$db->transaction(function () use ($db, $statementId): void {
|
||||
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
||||
app(Rebooks::class)->forget($statementId);
|
||||
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
||||
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** 明确授权的联合上传范围,不从机器人、文件名或合并账单配置推断。 */
|
||||
final class CourierJointUploads
|
||||
{
|
||||
public const SETS = [
|
||||
'qiaoshe' => ['label' => '樵舍联合上传', 'names' => ['江西新建中通', '江西中通快运', '樵舍中通', '樵舍中通-上楼', '山东中通快运', '西安圆通', '西安中通快运']],
|
||||
'yuantong' => ['label' => '圆通联合上传', 'names' => ['常州圆通其他', '常州圆通-上楼', '小件宿迁圆通', '睢宁宿迁圆通', '苏北宿迁圆通']],
|
||||
'hebei' => ['label' => '河北中通与霸州百世联合上传', 'names' => ['河北中通-江三', '河北中通小件-江三', '霸州百世快运-雅柏']],
|
||||
'debang-shunfeng' => ['label' => '德邦与顺丰干配联合上传', 'names' => ['睢宁德邦', '崔桥顺丰干配', '山东顺丰干配', '山东顺丰大件', '苏北顺丰干配大件', '苏北顺丰干配小件']],
|
||||
];
|
||||
|
||||
public function resolve(string $key): array
|
||||
{
|
||||
$set = self::SETS[$key] ?? throw new RuntimeException('联合上传范围不存在。');
|
||||
$groups = app(CourierBillStore::class)->groups();
|
||||
$selected = [];
|
||||
foreach ($set['names'] as $name) {
|
||||
$matches = array_values(array_filter($groups, static fn ($g) => $g->name === $name || in_array($name, $g->express_names, true)));
|
||||
if (count($matches) !== 1) throw new RuntimeException('联合上传分组「' . $name . '」未配置或存在重名,请联系财务。');
|
||||
$g = $matches[0];
|
||||
// 可通过别名定位既有分组;上传时仍只允许本集合列出的名称。
|
||||
$selected[(int) $g->id] = $g;
|
||||
}
|
||||
ksort($selected);
|
||||
$fingerprint = [];
|
||||
foreach ($selected as $id => $group) {
|
||||
$names = $group->express_names;
|
||||
sort($names);
|
||||
$fingerprint[] = [$id, $group->name, $names];
|
||||
}
|
||||
|
||||
return $set + ['key' => $key, 'groups' => array_values($selected), 'group_ids' => array_keys($selected),
|
||||
'fingerprint' => hash('sha256', json_encode($fingerprint, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
public function snapshot(string $key): array
|
||||
{
|
||||
$set = $this->resolve($key);
|
||||
|
||||
return array_intersect_key($set, array_flip(['key', 'group_ids', 'fingerprint']));
|
||||
}
|
||||
|
||||
public function verify(array $snapshot): array
|
||||
{
|
||||
$set = $this->resolve((string) ($snapshot['key'] ?? ''));
|
||||
if ($set['group_ids'] !== ($snapshot['group_ids'] ?? null) || $set['fingerprint'] !== ($snapshot['fingerprint'] ?? null)) {
|
||||
throw new RuntimeException('联合上传分组设置已变化,请联系财务重新生成链接。');
|
||||
}
|
||||
|
||||
return $set;
|
||||
}
|
||||
}
|
||||
@ -19,21 +19,12 @@ final class CourierUploadLink
|
||||
return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId);
|
||||
}
|
||||
|
||||
public function jointPageUrl(int $companyId, string $key, string $month): string
|
||||
{
|
||||
$joint = app(CourierJointUploads::class)->snapshot($key);
|
||||
$payload = ['company_id' => $companyId, 'group_id' => $joint['group_ids'][0], 'month' => $month, 'joint' => $joint];
|
||||
$token = rtrim(strtr(base64_encode(Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR))), '+/', '-_'), '=');
|
||||
|
||||
return $this->signedRoute('signed.courier-bill-upload.show', $token, $companyId);
|
||||
}
|
||||
|
||||
public function signedRoute(string $routeName, string $token, int $companyId, ?\DateTimeInterface $expires = null): string
|
||||
{
|
||||
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
|
||||
}
|
||||
|
||||
/** @return array{group_id:int,month:string,joint:?array}|null */
|
||||
/** @return array{group_id:int,month:string}|null */
|
||||
public function resolveToken(string $token, int $companyId): ?array
|
||||
{
|
||||
try {
|
||||
@ -51,7 +42,7 @@ final class CourierUploadLink
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month'], 'joint' => $payload['joint'] ?? null];
|
||||
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']];
|
||||
}
|
||||
|
||||
private function token(int $companyId, int $groupId, string $month): string
|
||||
|
||||
@ -112,27 +112,6 @@ final class FreightBillTemplate
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** 逐行保留单号与类型,不能只汇总账单金额后丢失匹配依据。 */
|
||||
public function surchargeRows(string $path,string $extension): \Generator
|
||||
{
|
||||
foreach($this->reader->sheets($path,$extension) as $name=>$rows){
|
||||
if(!str_contains(trim((string)$name),self::SURCHARGE_SHEET))continue;
|
||||
$header=false;
|
||||
foreach($rows as $number=>$row){
|
||||
$cells=array_slice(array_map(static fn($v):string=>trim((string)$v),$row),0,3);
|
||||
if(implode('',$cells)==='')continue;
|
||||
if(!$header){
|
||||
if(array_values(self::trimTail($cells))!==self::SURCHARGE_HEADERS)throw new RuntimeException('附加费表头不符合模板,无法逐单核对。');
|
||||
$header=true;continue;
|
||||
}
|
||||
if(in_array($cells[0]??'',self::TOTAL_WORDS,true))continue;
|
||||
$waybill=Waybill::normalize($cells[0]??'');$amount=BillParser::number($cells[1]??null);$type=$cells[2]??'';
|
||||
if($waybill===null||$amount===null||$type==='')throw new RuntimeException('附加费第 '.$number.' 行缺少完整单号、金额或类型。');
|
||||
yield ['sheet'=>(string)$name,'row_no'=>(int)$number,'waybill_no'=>$waybill,'item'=>$type,'amount'=>$amount];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{rows:int,waybills:int,amount:float} */
|
||||
private function validateBill(?iterable $rows): array
|
||||
{
|
||||
|
||||
@ -32,7 +32,7 @@ final class PortalFreightBillImports
|
||||
touch($queue . '/' . $token);
|
||||
}
|
||||
|
||||
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null, ?string $jointKey = null): array
|
||||
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array
|
||||
{
|
||||
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
|
||||
rsort($files);
|
||||
@ -42,7 +42,6 @@ final class PortalFreightBillImports
|
||||
if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue;
|
||||
if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue;
|
||||
if ($month !== null && $task['month'] !== $month) continue;
|
||||
if (($task['joint']['key'] ?? null) !== $jointKey) continue;
|
||||
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
|
||||
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
|
||||
'message' => $task['message'], 'at' => $task['created_at']];
|
||||
@ -90,8 +89,7 @@ final class PortalFreightBillImports
|
||||
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
|
||||
if (($task['source'] ?? null) === 'courier_upload_link') {
|
||||
if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。');
|
||||
$joint = isset($task['joint']) ? app(CourierJointUploads::class)->verify($task['joint']) : null;
|
||||
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$task['target_id']])
|
||||
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->where('group_id', $task['target_id'])
|
||||
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
|
||||
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
|
||||
}
|
||||
@ -112,9 +110,7 @@ final class PortalFreightBillImports
|
||||
} else {
|
||||
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
|
||||
$store = app(CourierBillStore::class);
|
||||
$file = new UploadedFile($path, $task['original_name'], null, null, true);
|
||||
$id = isset($joint) ? $store->uploadJoint($file, $task['month'], $task['joint'], $task['uploader'])
|
||||
: $store->uploadFor($file, $task['month'], $task['target_id'], $task['uploader']);
|
||||
$id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']);
|
||||
$row = $store->db()->table('courier_bill_files')->find($id);
|
||||
}
|
||||
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));
|
||||
|
||||
@ -1,478 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Generator;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* 补记账:记账扣过的单,快递后来退回了,在后面的账期把多扣的补回去。
|
||||
*
|
||||
* - 补哪几个月:对账分组里设(不补 / 补上月 / 补前两个月),没设就按上月小汇总里的补记账类目识别
|
||||
* (「补9月记账」「补8月记账」→ 补前两个月;「2026.8-9月记账补款」→ 补前两个月;「补记账」「9月记账补款」→ 补上月)。最多补两个月,超期不补。
|
||||
* - 当时扣的:记账明细里那个扣款月份这单的「结算记账」合计。
|
||||
* - 现在应扣:复核记账(财务每月导入;逻辑定下来后换成系统算)。没复核的单先不补。
|
||||
* - 本期补款 = 当时扣的 − 现在应扣;补记账台账里补过的单不再补。
|
||||
* - 对账单确认时,这期补的单记进补记账台账;取消确认就撤掉。
|
||||
*/
|
||||
final class Rebooks
|
||||
{
|
||||
/** 记账明细的数据集(快递应付 → 记账明细)。 */
|
||||
public const BOOKKEEPING_DATASET = 'courier:bookkeeping-details';
|
||||
public const MAX_MONTHS = 2;
|
||||
public const RULES = [0 => '不补', 1 => '补上月', 2 => '补前两个月'];
|
||||
|
||||
private ?bool $hasMonthIndex = null;
|
||||
|
||||
public static function db(): ConnectionInterface
|
||||
{
|
||||
return CourierBillMatcher::db();
|
||||
}
|
||||
|
||||
/**
|
||||
* 小汇总里补记账类目(已顺延到本月)要补几个月:类目里提到的扣款月份离本月最远的那个;没写月份的算补上月。0 = 小汇总里没有补记账。
|
||||
*
|
||||
* @param list<string>|null $labels
|
||||
*/
|
||||
public static function monthsFromLabels(?array $labels, string $month): int
|
||||
{
|
||||
$current = (int) substr($month, 5, 2);
|
||||
$result = 0;
|
||||
foreach ($labels ?? [] as $label) {
|
||||
$label = SummaryTemplate::normalize((string) $label);
|
||||
if (! self::isRebookLabel($label)) {
|
||||
continue;
|
||||
}
|
||||
$mentioned = self::monthsIn($label);
|
||||
if ($mentioned === []) {
|
||||
$result = max($result, 1);
|
||||
continue;
|
||||
}
|
||||
foreach ($mentioned as $m) {
|
||||
$lag = ($current - $m + 12) % 12;
|
||||
if ($lag >= 1) {
|
||||
$result = max($result, min($lag, self::MAX_MONTHS));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** 是不是补记账类目:「补9月记账」「2026.8-9月记账补款」「补记账」「9月记账补款」。 */
|
||||
public static function isRebookLabel(string $label): bool
|
||||
{
|
||||
$label = SummaryTemplate::normalize($label);
|
||||
|
||||
return str_contains($label, '记账') && (str_starts_with($label, '补') || str_contains($label, '记账补'));
|
||||
}
|
||||
|
||||
/** 类目里写到的月份(「2026.8-9月」→ 8、9)。 @return list<int> */
|
||||
public static function monthsIn(string $label): array
|
||||
{
|
||||
$months = [];
|
||||
preg_match_all('/(?:\d{4}[.年])?(\d{1,2})(?:-(?:\d{4}[.年])?(\d{1,2}))?月/u', $label, $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $m) {
|
||||
$a = (int) $m[1];
|
||||
$b = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : $a;
|
||||
if ($a < 1 || $a > 12 || $b < 1 || $b > 12) {
|
||||
continue;
|
||||
}
|
||||
for ($i = $a, $n = 0; $n < 12; $i = $i % 12 + 1, $n++) {
|
||||
$months[] = $i;
|
||||
if ($i === $b) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($months));
|
||||
}
|
||||
|
||||
/** 小汇总类目是不是这个扣款月份的补记账行:写了这个月、或范围里含这个月、或没写月份。 */
|
||||
public static function labelCovers(string $label, int $deductMonth): bool
|
||||
{
|
||||
if (! self::isRebookLabel($label)) {
|
||||
return false;
|
||||
}
|
||||
$months = self::monthsIn(SummaryTemplate::normalize($label));
|
||||
|
||||
return $months === [] || in_array($deductMonth, $months, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 这家这个月补几个月。
|
||||
*
|
||||
* @param list<string>|null $template 上月小汇总类目(已顺延)
|
||||
* @return array{months:int,source:string}
|
||||
*/
|
||||
public static function rule(object $group, string $month, ?array $template): array
|
||||
{
|
||||
if (isset($group->rebook_months) && $group->rebook_months !== null && $group->rebook_months !== '') {
|
||||
return ['months' => min(max((int) $group->rebook_months, 0), self::MAX_MONTHS), 'source' => 'group'];
|
||||
}
|
||||
|
||||
return ['months' => self::monthsFromLabels($template, $month), 'source' => 'summary'];
|
||||
}
|
||||
|
||||
/** 要补的扣款月份:本月往前 1..n 个月。 @return list<string> */
|
||||
public static function window(string $month, int $months): array
|
||||
{
|
||||
$base = CarbonImmutable::createFromFormat('Y-m-d', $month . '-01');
|
||||
$result = [];
|
||||
for ($i = min($months, self::MAX_MONTHS); $i >= 1; $i--) {
|
||||
$result[] = $base->subMonthsNoOverflow($i)->format('Y-m');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一张对账单的补记账明细(含还没复核、已经补过的,金额为 0 的不补)。
|
||||
*
|
||||
* @return array{months:int,source:string,window:list<string>,rows:list<array<string,mixed>>}
|
||||
*/
|
||||
public function forStatement(int $statementId, ?array $template = null): array
|
||||
{
|
||||
$db = self::db();
|
||||
$statement = $db->table('courier_bill_statements')->find($statementId);
|
||||
if ($statement === null) {
|
||||
throw new RuntimeException('对账单不存在。');
|
||||
}
|
||||
if ($statement->status === 'confirmed') {
|
||||
return $this->confirmedPlan($statement);
|
||||
}
|
||||
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||||
$template ??= app(CourierBillMatcher::class)->templateFor($statementId);
|
||||
$rule = self::rule($group, (string) $statement->bill_month, $template);
|
||||
$window = self::window((string) $statement->bill_month, $rule['months']);
|
||||
$names = array_values(array_filter(array_map('trim', (array) json_decode((string) $group->express_names, true))));
|
||||
|
||||
return $rule + ['window' => $window, 'rows' => $window === [] || $names === []
|
||||
? [] : $this->rows($names, $window, (string) $statement->bill_month, $statementId)];
|
||||
}
|
||||
|
||||
/** 已确认账单只读确认时记录,不随复核、分组或原记账明细变化。 */
|
||||
private function confirmedPlan(object $statement): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach (self::db()->table('courier_bill_rebooks')->where('statement_id', $statement->id)
|
||||
->orderBy('deduct_month')->orderBy('waybill_no')->cursor() as $record) {
|
||||
$info = json_decode((string) $record->details, true) ?: [];
|
||||
$rows[] = ['deduct_month' => $record->deduct_month, 'waybill' => $record->waybill_no,
|
||||
'carrier' => $info['carrier'] ?? '', 'deducted' => (float) $record->deducted,
|
||||
'refunded' => null, 'current' => (float) $record->current, 'amount' => (float) $record->amount,
|
||||
'status' => '本期补款', 'info' => $info];
|
||||
}
|
||||
$window = array_values(array_unique(array_column($rows, 'deduct_month')));
|
||||
$months = $window === [] ? 0 : min(self::MAX_MONTHS, (int) CarbonImmutable::parse($window[0] . '-01')
|
||||
->diffInMonths(CarbonImmutable::parse($statement->bill_month . '-01')));
|
||||
|
||||
return ['months' => $months, 'source' => 'confirmed', 'window' => $window, 'rows' => $rows];
|
||||
}
|
||||
|
||||
/**
|
||||
* 这家的扣款单:按单号 + 扣款月份合计「结算记账」,带上已补、复核和本期补款。
|
||||
*
|
||||
* @param list<string> $names 快递名称1
|
||||
* @param list<string> $window 扣款月份
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function rows(array $names, array $window, string $month, ?int $statementId = null): array
|
||||
{
|
||||
$names = array_flip($names);
|
||||
$deductions = [];
|
||||
foreach ($this->bookkeeping($window) as $row) {
|
||||
$carrier = trim((string) ($row['carrier'] ?? ''));
|
||||
if (! isset($names[$carrier])) {
|
||||
continue;
|
||||
}
|
||||
$waybill = Waybill::normalize((string) (($row['tracking_no_clean'] ?? '') ?: ($row['tracking_no'] ?? '')));
|
||||
if ($waybill === null) {
|
||||
continue;
|
||||
}
|
||||
$key = $waybill . '|' . $row['summary_month'];
|
||||
$deductions[$key] ??= ['deduct_month' => (string) $row['summary_month'], 'waybill' => $waybill, 'carrier' => $carrier,
|
||||
'deducted' => '0', 'info' => $row];
|
||||
$deductions[$key]['deducted'] = bcadd($deductions[$key]['deducted'], (string) (($row['settle_bookkeeping'] ?? '') ?: '0'), 4);
|
||||
}
|
||||
if ($deductions === []) {
|
||||
return [];
|
||||
}
|
||||
$waybills = array_values(array_unique(array_column($deductions, 'waybill')));
|
||||
$refunded = [];
|
||||
$reviews = [];
|
||||
foreach (array_chunk($waybills, 1000) as $chunk) {
|
||||
foreach (self::db()->table('courier_bill_rebooks')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
|
||||
->when($statementId !== null, fn ($q) => $q->where(fn ($q) => $q->whereNull('statement_id')->orWhere('statement_id', '<>', $statementId)))
|
||||
->get(['waybill_no', 'deduct_month', 'refund_month', 'amount']) as $r) {
|
||||
$k = strtoupper($r->waybill_no) . '|' . $r->deduct_month;
|
||||
$refunded[$k] = ['amount' => (float) ($refunded[$k]['amount'] ?? 0) + (float) $r->amount,
|
||||
'month' => min($refunded[$k]['month'] ?? $r->refund_month, $r->refund_month)];
|
||||
}
|
||||
foreach (self::db()->table('courier_bill_rebook_reviews')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
|
||||
->get(['waybill_no', 'deduct_month', 'current_amount']) as $r) {
|
||||
$reviews[strtoupper($r->waybill_no) . '|' . $r->deduct_month] = (float) $r->current_amount;
|
||||
}
|
||||
}
|
||||
$rows = [];
|
||||
foreach ($deductions as $key => $d) {
|
||||
$k = strtoupper($d['waybill']) . '|' . $d['deduct_month'];
|
||||
$deducted = round((float) $d['deducted'], 2);
|
||||
$current = $reviews[$k] ?? null;
|
||||
$done = $refunded[$k] ?? null;
|
||||
[$status, $amount] = match (true) {
|
||||
$done !== null => ['已补(' . $done['month'] . ')', 0.0],
|
||||
$deducted <= 0 => ['没扣', 0.0],
|
||||
$current === null => ['待复核', 0.0],
|
||||
$current >= $deducted => ['仍应扣,不补', 0.0],
|
||||
default => ['本期补款', round($deducted - $current, 2)],
|
||||
};
|
||||
$rows[] = ['deduct_month' => $d['deduct_month'], 'waybill' => $d['waybill'], 'carrier' => $d['carrier'],
|
||||
'deducted' => $deducted, 'refunded' => $done === null ? null : round($done['amount'], 2), 'current' => $current,
|
||||
'amount' => $amount, 'status' => $status, 'info' => $d['info']];
|
||||
}
|
||||
usort($rows, static fn (array $a, array $b): int => [$a['deduct_month'], $a['waybill']] <=> [$b['deduct_month'], $b['waybill']]);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** 各扣款月份本期补款合计(只算要补的)。 @param list<array<string,mixed>> $rows @return array<string,float> */
|
||||
public static function totals(array $rows): array
|
||||
{
|
||||
$totals = [];
|
||||
foreach ($rows as $row) {
|
||||
if ($row['amount'] > 0) {
|
||||
$totals[$row['deduct_month']] = round(($totals[$row['deduct_month']] ?? 0) + $row['amount'], 2);
|
||||
}
|
||||
}
|
||||
ksort($totals);
|
||||
|
||||
return $totals;
|
||||
}
|
||||
|
||||
/** 小汇总里补记账那一行的名字:「补9月记账」。 */
|
||||
public static function label(string $deductMonth): string
|
||||
{
|
||||
return '补' . (int) substr($deductMonth, 5, 2) . '月记账';
|
||||
}
|
||||
|
||||
/** 导出子表名:一个月「补9月记账」,两个月「2026.9-10月记账补款」。 @param list<string> $window */
|
||||
public static function sheetName(array $window): string
|
||||
{
|
||||
if (count($window) <= 1) {
|
||||
return self::label($window[0] ?? '');
|
||||
}
|
||||
$first = $window[0];
|
||||
$last = $window[count($window) - 1];
|
||||
|
||||
return substr($first, 0, 4) . '.' . (int) substr($first, 5, 2) . '-' . (substr($last, 0, 4) !== substr($first, 0, 4) ? substr($last, 0, 4) . '.' : '')
|
||||
. (int) substr($last, 5, 2) . '月记账补款';
|
||||
}
|
||||
|
||||
/** 对账单确认:这期补的单记进补记账台账。 */
|
||||
public function record(int $statementId): int
|
||||
{
|
||||
$statement = self::db()->table('courier_bill_statements')->find($statementId);
|
||||
$plan = $this->forStatement($statementId);
|
||||
$this->assertSummaryMatches($statementId, $plan['rows']);
|
||||
$now = now();
|
||||
$buffer = [];
|
||||
foreach ($plan['rows'] as $row) {
|
||||
if ($row['amount'] <= 0) {
|
||||
continue;
|
||||
}
|
||||
$buffer[] = ['group_id' => $statement->group_id, 'waybill_no' => $row['waybill'], 'deduct_month' => $row['deduct_month'],
|
||||
'refund_month' => $statement->bill_month, 'deducted' => $row['deducted'], 'current' => $row['current'],
|
||||
'amount' => $row['amount'], 'statement_id' => $statementId, 'source' => 'statement',
|
||||
'details' => json_encode($row['info'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'created_at' => $now];
|
||||
}
|
||||
$inserted = 0;
|
||||
foreach (array_chunk($buffer, 500) as $chunk) {
|
||||
$count = self::db()->table('courier_bill_rebooks')->insertOrIgnore($chunk);
|
||||
if ($count !== count($chunk)) {
|
||||
throw new RuntimeException('补记账状态已变化,存在已经补过的单号,请重新匹配核对后确认。');
|
||||
}
|
||||
$inserted += $count;
|
||||
}
|
||||
|
||||
return $inserted;
|
||||
}
|
||||
|
||||
/** 手工回填或复核变化不能让小汇总金额与逐单补款记录不一致。 */
|
||||
private function assertSummaryMatches(int $statementId, array $rows): void
|
||||
{
|
||||
$actual = [];
|
||||
foreach (self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)
|
||||
->orderBy('sort')->get(['label', 'self_amount']) as $item) {
|
||||
$label = SummaryTemplate::normalize($item->label);
|
||||
if (self::isRebookLabel($label)) {
|
||||
$actual[$label] = round(($actual[$label] ?? 0) + (float) $item->self_amount, 2);
|
||||
}
|
||||
}
|
||||
$expected = [];
|
||||
foreach (self::totals($rows) as $month => $amount) {
|
||||
$label = self::label($month);
|
||||
if (! array_key_exists($label, $actual)) {
|
||||
foreach (array_keys($actual) as $candidate) {
|
||||
if (self::labelCovers($candidate, (int) substr($month, 5, 2))) {
|
||||
$label = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
$expected[$label] = round(($expected[$label] ?? 0) + $amount, 2);
|
||||
}
|
||||
foreach (array_unique([...array_keys($actual), ...array_keys($expected)]) as $label) {
|
||||
if (bccomp((string) ($actual[$label] ?? 0), (string) ($expected[$label] ?? 0), 2) !== 0) {
|
||||
throw new RuntimeException('补记账小汇总与逐单复核金额不一致,请更新复核记账并重新匹配核对后确认。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function forget(int $statementId): void
|
||||
{
|
||||
self::db()->table('courier_bill_rebooks')->where('statement_id', $statementId)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入已经补过的记录(系统上线前手工补的):单号、扣款月份、补款账期、补款金额,可带「对账分组」。
|
||||
*
|
||||
* @return array{rows:int,inserted:int,rejected:int}
|
||||
*/
|
||||
public function importRefunds(string $path, string $extension): array
|
||||
{
|
||||
$groups = collect(app(CourierBillStore::class)->groups())->keyBy(static fn ($g): string => (string) $g->name);
|
||||
|
||||
return $this->importSheet($path, $extension, [
|
||||
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
|
||||
'refund' => ['补款账期', '补款月份'], 'amount' => ['补款金额', '需补款', '补款'], 'group' => ['对账分组', '快递名称', '账单快递名称'],
|
||||
], ['waybill', 'deduct', 'refund', 'amount'], function (array $v) use ($groups): ?array {
|
||||
$amount = BillParser::number($v['amount'] ?? null);
|
||||
if ($amount === null || ($refund = CourierBillStore::month((string) ($v['refund'] ?? ''))) === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['table' => 'courier_bill_rebooks', 'row' => ['group_id' => $groups->get(trim((string) ($v['group'] ?? '')))?->id,
|
||||
'refund_month' => $refund, 'amount' => round($amount, 2), 'deducted' => null, 'current' => null,
|
||||
'statement_id' => null, 'source' => 'import', 'created_at' => now()]];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入复核记账(这单现在应扣多少):单号、扣款月份、现应扣。同一单号同一扣款月份再导就覆盖。
|
||||
*
|
||||
* @return array{rows:int,inserted:int,rejected:int}
|
||||
*/
|
||||
public function importReviews(string $path, string $extension, string $sourceName): array
|
||||
{
|
||||
return $this->importSheet($path, $extension, [
|
||||
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
|
||||
'current' => ['现应扣', '现在应扣', '复核记账', '应扣金额'],
|
||||
], ['waybill', 'deduct', 'current'], function (array $v) use ($sourceName): ?array {
|
||||
$current = BillParser::number($v['current'] ?? null);
|
||||
if ($current === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['table' => 'courier_bill_rebook_reviews', 'upsert' => ['current_amount', 'source_name', 'updated_at'],
|
||||
'row' => ['current_amount' => round($current, 2), 'source_name' => mb_substr($sourceName, 0, 255), 'updated_at' => now()]];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,list<string>> $columns
|
||||
* @param list<string> $required
|
||||
* @param callable(array<string,mixed>):?array{table:string,row:array<string,mixed>,upsert?:list<string>} $build
|
||||
* @return array{rows:int,inserted:int,rejected:int}
|
||||
*/
|
||||
private function importSheet(string $path, string $extension, array $columns, array $required, callable $build): array
|
||||
{
|
||||
$reader = new BillWorkbookReader();
|
||||
$rows = $inserted = $rejected = 0;
|
||||
$buffers = [];
|
||||
$flush = function () use (&$buffers, &$inserted): void {
|
||||
foreach ($buffers as $table => [$upsert, $records]) {
|
||||
foreach (array_chunk(array_values($records), 500) as $chunk) {
|
||||
$inserted += $upsert === null ? self::db()->table($table)->insertOrIgnore($chunk)
|
||||
: self::db()->table($table)->upsert($chunk, ['waybill_no', 'deduct_month'], $upsert);
|
||||
}
|
||||
}
|
||||
$buffers = [];
|
||||
};
|
||||
foreach ($reader->sheets($path, $extension) as $sheetRows) {
|
||||
$index = null;
|
||||
foreach ($sheetRows as $row) {
|
||||
if ($index === null) {
|
||||
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
|
||||
$found = [];
|
||||
foreach ($columns as $field => $names) {
|
||||
foreach ($names as $name) {
|
||||
if (($i = array_search($name, $header, true)) !== false) {
|
||||
$found[$field] = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (array_diff($required, array_keys($found)) !== []) {
|
||||
throw new RuntimeException('表头须含' . implode('', array_map(static fn (string $f): string => '「' . $columns[$f][0] . '」', $required)) . '。');
|
||||
}
|
||||
$index = $found;
|
||||
continue;
|
||||
}
|
||||
$values = [];
|
||||
foreach ($index as $field => $i) {
|
||||
$values[$field] = $row[$i] ?? null;
|
||||
}
|
||||
if (trim((string) ($values['waybill'] ?? '')) === '' && trim((string) ($values['deduct'] ?? '')) === '') {
|
||||
continue;
|
||||
}
|
||||
$rows++;
|
||||
$waybill = Waybill::normalize((string) ($values['waybill'] ?? ''));
|
||||
$deduct = CourierBillStore::month((string) ($values['deduct'] ?? ''));
|
||||
$built = $waybill === null || $deduct === null ? null : $build($values);
|
||||
if ($built === null) {
|
||||
$rejected++;
|
||||
continue;
|
||||
}
|
||||
$record = ['waybill_no' => strtoupper($waybill), 'deduct_month' => $deduct] + $built['row'];
|
||||
$key = $record['waybill_no'] . '|' . $deduct . '|' . ($record['refund_month'] ?? '');
|
||||
$buffers[$built['table']] ??= [$built['upsert'] ?? null, []];
|
||||
$buffers[$built['table']][1][$key] = $record; // 同一文件里重复的后一行为准
|
||||
if (count($buffers[$built['table']][1]) >= 500) {
|
||||
$flush();
|
||||
}
|
||||
}
|
||||
break; // 只读第一张表
|
||||
}
|
||||
$flush();
|
||||
|
||||
return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected];
|
||||
}
|
||||
|
||||
/**
|
||||
* 记账明细里这几个扣款月份的行。
|
||||
*
|
||||
* @param list<string> $months
|
||||
* @return Generator<int,array<string,mixed>>
|
||||
*/
|
||||
private function bookkeeping(array $months): Generator
|
||||
{
|
||||
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
|
||||
$this->hasMonthIndex ??= Schema::connection($connection->getName())->hasColumn('supplier_payable_overrides', 'summary_month_key');
|
||||
$query = $connection->table('supplier_payable_overrides')->select(['id', 'values'])
|
||||
->where('company_id', (int) (company_id() ?: 1))->where('dataset', self::BOOKKEEPING_DATASET)
|
||||
->whereIn($this->hasMonthIndex ? 'summary_month_key' : 'values->summary_month', $months);
|
||||
// 保留 rows() 的 trim 后精确匹配,避免 SQL 原值筛选漏掉带首尾空白的快递名称。
|
||||
foreach ($query->lazyById(500) as $record) {
|
||||
$values = json_decode((string) $record->values, true);
|
||||
if (is_array($values)) {
|
||||
yield $values;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -91,7 +91,7 @@ final class StatementExporter
|
||||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||||
$bill = 0.0;
|
||||
$self = 0.0;
|
||||
foreach (app(SurchargeSettlementMatcher::class)->summaryItems($id,$db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get()) as $item) {
|
||||
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
|
||||
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
||||
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
||||
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
||||
@ -175,53 +175,10 @@ final class StatementExporter
|
||||
}
|
||||
});
|
||||
|
||||
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
|
||||
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
|
||||
$this->writeNotes($book, $ids, $originals);
|
||||
$book->writeTo($output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 补记账子表:本期要补的单(当时扣的 − 现在应扣),表名照手工版「补9月记账」「2026.8-9月记账补款」。
|
||||
*
|
||||
* @param list<int> $ids
|
||||
* @param list<string> $tail
|
||||
* @param array<int,string> $groupNames
|
||||
*/
|
||||
private function writeRebooks(StreamingWorkbook $book, array $ids, array $tail, array $groupNames, bool $multi): void
|
||||
{
|
||||
$info = ['线上订单号' => 'online_order_no', '记账原因' => 'bookkeeping_reason', '商品编码' => 'product_code', '商品名称' => 'product_name',
|
||||
'发起时间' => 'started_at', '店铺名称' => 'shop_name', '订单发货仓库' => 'shipping_warehouse', '退回单号' => 'return_no', '记账分析' => 'analysis'];
|
||||
$plans = [];
|
||||
$window = [];
|
||||
foreach ($ids as $id) {
|
||||
try {
|
||||
$plan = app(Rebooks::class)->forStatement($id);
|
||||
} catch (\Throwable $error) {
|
||||
report($error);
|
||||
continue;
|
||||
}
|
||||
$rows = array_values(array_filter($plan['rows'], static fn (array $r): bool => $r['amount'] > 0));
|
||||
if ($rows !== []) {
|
||||
$plans[$id] = $rows;
|
||||
$window = array_values(array_unique([...$window, ...array_column($rows, 'deduct_month')]));
|
||||
}
|
||||
}
|
||||
if ($plans === []) {
|
||||
return;
|
||||
}
|
||||
sort($window);
|
||||
$name = Rebooks::sheetName($window);
|
||||
$book->row($name, ['扣款月份', '物流单号', '物流公司', ...array_keys($info), '当时扣(结算记账)', '现在应扣', '本期补款', ...$tail], true);
|
||||
foreach ($plans as $id => $rows) {
|
||||
foreach ($rows as $r) {
|
||||
$book->row($name, [$r['deduct_month'], $r['waybill'], $r['carrier'],
|
||||
...array_map(static fn (string $f): ?string => ($r['info'][$f] ?? '') === '' ? null : (string) $r['info'][$f], array_values($info)),
|
||||
$r['deducted'], $r['current'], $r['amount'], ...($multi ? [$groupNames[$id] ?? ''] : [])]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
||||
*
|
||||
|
||||
@ -187,7 +187,6 @@ final class SummaryTemplate
|
||||
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
|
||||
$kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
|
||||
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
|
||||
str_starts_with($kind, 'rebook:') => $find(static fn (string $n): bool => Rebooks::labelCovers($n, (int) substr($kind, 7))),
|
||||
$kind === 'fee' => self::feeSlot($key, $find),
|
||||
default => null,
|
||||
};
|
||||
|
||||
@ -1,230 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/** 按账单月份归集,逐票/费用类型匹配结算表;不改来源报价和费用。 */
|
||||
class SurchargeSettlementMatcher
|
||||
{
|
||||
public const TABLE = 'bill_surcharge_matches';
|
||||
public const HEADERS = ['账单月份','来源工作表','原始行号','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'];
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
return DB::connection('business_mirror')->getSchemaBuilder()->hasTable(self::TABLE);
|
||||
}
|
||||
|
||||
public static function type(string $type): string
|
||||
{
|
||||
$type = preg_replace('/\s+/u', '', $type) ?? '';
|
||||
return match ($type) {
|
||||
'改地址费','改址费','改址' => '改地址',
|
||||
'上楼','直客上楼费' => '上楼费', '超长' => '超长费',
|
||||
'退件费','退货费','退回运费' => '退回费', '拦截','拦截退回' => '拦截费',
|
||||
'派送费','派件费','直客派送费' => '送货费', '保价费' => '保费',
|
||||
'入仓费' => '进仓费', '直客超区费' => '超区费', default => $type,
|
||||
};
|
||||
}
|
||||
|
||||
/** 不刷新已确认账单;只更新附加费派生匹配记录。 */
|
||||
public function courier(int $id): void
|
||||
{
|
||||
if (! $this->ready()) return;
|
||||
$db = DB::connection('business_mirror');
|
||||
$s = $db->table('courier_bill_statements')->find($id);
|
||||
if (! $s || $s->status === 'confirmed') return;
|
||||
$group = $db->table('courier_bill_groups')->find($s->group_id);
|
||||
$names = (array) json_decode($group->express_names, true);
|
||||
$files = $db->table('courier_bill_lines')->where('statement_id', $id)->distinct()->pluck('file_id')
|
||||
->merge($db->table('courier_bill_files')->where('statement_id', $id)->pluck('id'))->unique()->all();
|
||||
$seen = [];
|
||||
$db->transaction(function () use ($db, $s, $id, $names, $files, &$seen): void {
|
||||
if($db->table('courier_bill_statements')->where('id',$id)->lockForUpdate()->value('status')==='confirmed')return;
|
||||
$db->table(self::TABLE)->where('scope','courier')->where('owner_id',$id)->delete();
|
||||
foreach ($files as $fileId) {
|
||||
$file = $db->table('courier_bill_files')->find($fileId);
|
||||
if (! $file || $file->status !== 'parsed') continue;
|
||||
$shared = $db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('statement_id')
|
||||
->push($file->statement_id)->filter()->unique()->values()->all();
|
||||
$ownership = [];
|
||||
if (count($shared)>1) {
|
||||
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g','g.id','=','s.group_id')
|
||||
->whereIn('s.id',$shared)->orderBy('s.id')->get(['s.id','g.express_names']) as $owner) {
|
||||
foreach ((array) json_decode($owner->express_names,true) as $name) $ownership[trim($name)] ??= (int)$owner->id;
|
||||
}
|
||||
}
|
||||
$joint = isset(json_decode($file->extra_group_ids ?? '[]',true)['joint_upload']);
|
||||
$freightSheets=$db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('sheet')->flip()->all();
|
||||
$db->table('courier_bill_surcharges')->where('file_id',$fileId)->orderBy('id')->chunkById(300,
|
||||
function ($fees) use ($db,$s,$id,$names,$file,$joint,$ownership,$freightSheets,&$seen): void {
|
||||
$ships=$ownership!==[]&&!$joint?$this->ships($fees->pluck('waybill_no')->all()):[];
|
||||
$assigned=$joint?$db->table('courier_bill_lines')->where('file_id',$file->id)->whereIn('waybill_no',$fees->pluck('waybill_no'))
|
||||
->pluck('statement_id','waybill_no')->all():[];
|
||||
$input=[];
|
||||
foreach($fees as $f){
|
||||
$ship=$ships[strtoupper($f->waybill_no)]??[];
|
||||
$owner=$joint?($assigned[$f->waybill_no]??0):($ownership[$ship['express']??'']??$file->statement_id);
|
||||
if((int)$owner!==$id)continue;
|
||||
$label=isset($freightSheets[$f->sheet])||trim($f->sheet)===''?$f->item:$f->sheet;
|
||||
$input[]=['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
|
||||
'item'=>$f->item,'amount'=>$f->amount,'label'=>preg_replace('/\s+/u','',$label)];
|
||||
}
|
||||
$this->storeMatches('courier',$id,$s->bill_month,$input,$names,null,$seen);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 页面只叠加附加费自算值;已确认对账单继续读取确认时保存的金额。 */
|
||||
public function summaryItems(int $id,iterable $items): \Illuminate\Support\Collection
|
||||
{
|
||||
$items=collect($items);$db=DB::connection('business_mirror');
|
||||
if(!$this->ready()||$db->table('courier_bill_statements')->where('id',$id)->value('status')==='confirmed')return $items;
|
||||
$sums=$this->query('courier',$id)->selectRaw('summary_label,SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all();
|
||||
if($sums===[])return $items;
|
||||
$month=(int)substr((string)$db->table('courier_bill_statements')->where('id',$id)->value('bill_month'),5,2);
|
||||
$labels=$items->pluck('label')->all();$auto=[];
|
||||
foreach($sums as $label=>$amount)$auto[$label]=['bill'=>null,'self'=>$amount===null?null:(float)$amount,'kind'=>'fee'];
|
||||
$mapped=SummaryTemplate::apply($labels,$auto,$month);$byLabel=[];
|
||||
foreach($mapped as $row)if($row['fee'])$byLabel[$row['label']]=$row['self'];
|
||||
return $items->map(function($item)use($byLabel){
|
||||
$copy=clone $item;if(!$copy->manual&&array_key_exists($copy->label,$byLabel))$copy->self_amount=$byLabel[$copy->label];return $copy;
|
||||
});
|
||||
}
|
||||
|
||||
public function dropship(int $factoryId, string $month): void
|
||||
{
|
||||
if (! $this->ready()) return;
|
||||
$db=DB::connection('business_mirror');$factory=$db->table('dropship_factories')->find($factoryId);
|
||||
if(!$factory)throw new RuntimeException('厂家不存在');
|
||||
$state=app(\App\Support\DropshipFreight\DropshipConfirmation::class)->state($month,$factoryId,(int)(company_id()?:1));
|
||||
if(($state['status']??'')==='confirmed')return;
|
||||
$seen=[];
|
||||
$db->transaction(function () use($db,$factory,$factoryId,$month,&$seen): void {
|
||||
$db->table(self::TABLE)->where('scope','dropship')->where('owner_id',$factoryId)->where('bill_month',$month)->delete();
|
||||
$db->table('dropship_bill_surcharges as f')->join('dropship_bill_files as b','b.id','=','f.file_id')->where('b.status','parsed')
|
||||
->where('f.factory_id',$factoryId)->where('f.bill_month',$month)->select('f.*')->orderBy('f.id')
|
||||
->chunkById(300,function($fees)use($factory,$factoryId,$month,&$seen):void{
|
||||
$input=array_map(fn($f)=>['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
|
||||
'item'=>$f->item,'amount'=>$f->amount,'label'=>$f->item],$fees->all());
|
||||
$this->storeMatches('dropship',$factoryId,$month,$input,[],$factory,$seen);
|
||||
},'f.id','id');
|
||||
});
|
||||
}
|
||||
|
||||
private function ships(array $waybills): array
|
||||
{
|
||||
$db=DB::connection(config('jushuitan.connection','business_mirror'));
|
||||
if(!$db->getSchemaBuilder()->hasTable('jst_oms_shipping'))return [];
|
||||
$result=[];
|
||||
foreach($db->table('jst_oms_shipping')->whereIn('express_no',array_unique($waybills))->orderBy('id')
|
||||
->get(['express_no','express_name1','warehouse_name']) as $r){
|
||||
$key=strtoupper($r->express_no);
|
||||
$result[$key]['express']=$r->express_name1;
|
||||
$result[$key]['pairs'][$r->warehouse_name][$r->express_name1]=true;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function storeMatches(string $scope,int $owner,string $month,array $input,array $names,?object $factory,array &$seen): void
|
||||
{
|
||||
if($input===[])return;
|
||||
$db=DB::connection('business_mirror');$waybills=array_values(array_unique(array_column($input,'waybill_no')));
|
||||
$source=[];
|
||||
if($db->getSchemaBuilder()->hasTable('courier_surcharge_settlement_rows')){
|
||||
$sourceQuery=$db->table('courier_surcharge_settlement_rows')->whereIn('waybill',$waybills)->where('settlement_status','已计算');
|
||||
$end=date('Y-m-d',strtotime($month.'-01 +1 month'));
|
||||
if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){
|
||||
$sourceQuery->where(fn($q)=>$q->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end])->orWhere(fn($q)=>$q->whereNull('source_created_at')->whereNull('shipped_at')));
|
||||
}else{$sourceQuery->where(fn($q)=>$q->whereNull('shipped_at')->orWhere('shipped_at','<',$end));}
|
||||
foreach($sourceQuery
|
||||
->orderBy('id')->get() as $r)$source[strtoupper($r->waybill)][self::type($r->surcharge_type)][]=$r;
|
||||
}
|
||||
$prior=[];
|
||||
foreach($db->table(self::TABLE)->whereIn('waybill_no',$waybills)
|
||||
->where(fn($q)=>$q->where('scope','<>',$scope)->orWhere('owner_id','<>',$owner)->orWhere('bill_month','<>',$month))
|
||||
->where('match_status','已匹配')->get(['settlement_ids','bill_month']) as $r)
|
||||
foreach(json_decode($r->settlement_ids??'[]',true)?:[] as $sid)$prior[$sid]=$r->bill_month;
|
||||
$ships=$factory?$this->ships($waybills):[];
|
||||
$own=$factory?array_fill_keys(app(DropshipFreightStore::class)->ownExpressNames(),true):[];
|
||||
$allowedCouriers=$names;
|
||||
if($factory){
|
||||
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
|
||||
foreach($ships as $ship)foreach(array_keys($ship['pairs'][$factory->warehouse]??[]) as $express)
|
||||
if(!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[])$allowedCouriers[]=$express;
|
||||
}
|
||||
$unresolved=array_values(array_filter($input,fn($f)=>array_filter($source[strtoupper($f['waybill_no'])][self::type($f['item'])]??[],
|
||||
fn($r)=>in_array($r->courier_name,$allowedCouriers,true))===[]));
|
||||
$calculated=app(BillSurchargeQuoteCalculator::class)->calculate($unresolved,$scope,$month,array_values(array_unique($allowedCouriers)));
|
||||
$output=[];
|
||||
foreach($input as $f){
|
||||
$type=self::type($f['item']);$wb=strtoupper($f['waybill_no']);$rows=$source[$wb][$type]??[];
|
||||
$row=['scope'=>$scope,'owner_id'=>$owner,'file_id'=>$f['file_id'],'sheet'=>$f['sheet'],'row_no'=>$f['row_no'],
|
||||
'bill_month'=>$month,'waybill_no'=>$wb,'item'=>$type,'summary_label'=>$f['label'],'bill_amount'=>$f['amount'],'self_amount'=>null,
|
||||
'courier_name'=>null,'platform_product_id'=>null,'product_code'=>null,'shop_name'=>null,'online_order_no'=>null,
|
||||
'match_status'=>'未匹配','match_note'=>'结算表没有对应的单号及费用类型','settlement_ids'=>null,'matched_at'=>now()];
|
||||
$allowed=$names;
|
||||
if($factory){
|
||||
$ship=$ships[$wb]??[];
|
||||
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
|
||||
$allowed=array_values(array_filter(array_keys($ship['pairs'][$factory->warehouse]??[]),fn($express)=>
|
||||
!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[]));
|
||||
$belongs=$allowed!==[];
|
||||
if(!$belongs)$row['match_note']='无法确认该单属于本厂家代发快递及仓库';
|
||||
}
|
||||
$rows=array_values(array_filter($rows,fn($r)=>in_array($r->courier_name,$allowed,true)));
|
||||
if($rows===[]){
|
||||
$rows=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true)));
|
||||
if(isset($calculated['notes'][$wb][$type])&&(!$factory||$allowed!==[]))$row['match_note']=$calculated['notes'][$wb][$type];
|
||||
if(!$factory||$allowed!==[])$row=array_replace($row,$calculated['metadata'][$wb]??[]);
|
||||
}
|
||||
$identity=$wb.'|'.$type;
|
||||
if(isset($seen[$identity])){$row['self_amount']=0;$row['match_status']='重复';$row['match_note']='本月账单已提供该单号及费用类型,不重复结算';}
|
||||
elseif($rows!==[]){
|
||||
$unique=[];
|
||||
foreach($rows as $r){
|
||||
$identityKey=($r->source_key??'')!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'');
|
||||
$unique[$r->courier_name.'|'.($r->source_kind??'').'|'.$identityKey]=$r;
|
||||
}
|
||||
$rows=array_values($unique);
|
||||
$keyOf=fn($r)=>hash('sha256',implode('|',[$r->courier_name,$wb,$type,
|
||||
$r->source_kind??'', trim((string)($r->source_key??''))!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'')]));
|
||||
$notPaid=array_values(array_filter($rows,fn($r)=>!isset($prior[$keyOf($r)])));
|
||||
if($notPaid===[]){$row['self_amount']=0;$row['match_status']='历史已计入';$row['match_note']='对应费用已计入其他账单,不能重复结算';$seen[$identity]=true;}
|
||||
else {
|
||||
$partlyPaid=count($notPaid)!==count($rows);$rows=$notPaid;
|
||||
$seen[$identity]=true;$row['self_amount']=round(array_sum(array_map(fn($r)=>(float)$r->settlement_amount,$rows)),2);
|
||||
$row['match_status']='已匹配';$row['settlement_ids']=json_encode(array_map($keyOf,$rows));
|
||||
$row['match_note']='按单号、费用类型及快递匹配;归入'.$month.'账单'.($partlyPaid?';已扣除其他账单已计入费用':'');
|
||||
$evidence=array_values(array_unique(array_filter(array_map(fn($r)=>$r->evidence??null,$rows))));
|
||||
if($evidence!==[])$row['match_note'].=';'.implode(';',$evidence);
|
||||
foreach(['courier_name','platform_product_id','product_code','shop_name','online_order_no'] as $key)
|
||||
$row[$key]=implode('、',array_values(array_unique(array_filter(array_map(fn($r)=>trim((string)($r->$key??'')),$rows)))));
|
||||
}
|
||||
} elseif($rows===[] && ($source[$wb]??[])!==[]&&!isset($calculated['notes'][$wb][$type])) $row['match_note']='单号存在,但费用类型或快递归属不符';
|
||||
$output[]=$row;
|
||||
}
|
||||
$db->table(self::TABLE)->insert($output);
|
||||
}
|
||||
|
||||
public function query(string $scope,int $owner,?string $month=null)
|
||||
{
|
||||
return DB::connection('business_mirror')->table(self::TABLE)->where('scope',$scope)->where('owner_id',$owner)
|
||||
->when($month,fn($q)=>$q->where('bill_month',$month));
|
||||
}
|
||||
|
||||
public function write(StreamingWorkbook $book,string $scope,int $owner,?string $month=null): void
|
||||
{
|
||||
if(!$this->ready()||!$this->query($scope,$owner,$month)->exists())return;
|
||||
$sheet='附加费核对'.($scope==='courier'?'-'.$owner:'');$book->row($sheet,self::HEADERS,true);
|
||||
$this->query($scope,$owner,$month)->orderBy('id')->chunkById(300,function($rows)use($book,$sheet){
|
||||
foreach($rows as $r)$book->row($sheet,[$r->bill_month,$r->sheet,$r->row_no,$r->waybill_no,$r->item,
|
||||
$r->bill_amount===null?null:(float)$r->bill_amount,$r->self_amount===null?null:(float)$r->self_amount,
|
||||
$r->self_amount===null?null:round((float)$r->bill_amount-$r->self_amount,2),$r->match_status,$r->courier_name,
|
||||
$r->platform_product_id,$r->product_code,$r->shop_name,$r->online_order_no,$r->match_note]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -138,7 +138,6 @@ final class DropshipExporter
|
||||
}
|
||||
|
||||
$this->writeNotes($book, $rows, $originals);
|
||||
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
|
||||
$book->writeTo($output);
|
||||
}
|
||||
|
||||
@ -175,7 +174,7 @@ final class DropshipExporter
|
||||
}
|
||||
}
|
||||
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
|
||||
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
|
||||
// 厂家按模板填的「附加费」表:金额合计放一行(不逐单核对,简尚核对空着手工填)
|
||||
$fee = 0.0;
|
||||
$hasFee = false;
|
||||
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
|
||||
@ -214,7 +213,7 @@ final class DropshipExporter
|
||||
[$bill, $settle] = match (true) {
|
||||
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
|
||||
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
|
||||
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int)$factory->id,$month)],
|
||||
$label === $feeLabel => [round($fee, 2), null],
|
||||
default => [null, null],
|
||||
};
|
||||
$sums[0] += (float) $bill;
|
||||
@ -233,17 +232,6 @@ final class DropshipExporter
|
||||
$bill === null && $settle === null ? '' : round((float) $bill - (float) $settle, 2));
|
||||
}
|
||||
|
||||
private function surchargeSelf(int $factoryId,string $month): ?float
|
||||
{
|
||||
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
|
||||
if(!$matcher->ready())return null;
|
||||
if(!$this->store->db()->table('dropship_bill_surcharges')->where('factory_id',$factoryId)->where('bill_month',$month)->exists())return null;
|
||||
$state=app(DropshipConfirmation::class)->state($month,$factoryId,(int)(company_id()?:1));
|
||||
if(($state['status']??'')==='confirmed')return null;
|
||||
$sum=$matcher->query('dropship',$factoryId,$month)->sum('self_amount');
|
||||
return round((float)$sum,2);
|
||||
}
|
||||
|
||||
/** 原账单的表名:「厂家账单」;第 2 个文件起「厂家账单2」;一个文件几张表的加「-原表名」。 */
|
||||
private static function originalName(int $fileIndex, string $sheet, int $sheetCount): string
|
||||
{
|
||||
|
||||
@ -112,33 +112,6 @@ final class DropshipFees
|
||||
public function auto(string $month): array
|
||||
{
|
||||
$result = [];
|
||||
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
|
||||
$indexed=$matcher->ready()?$this->store->db()->table('dropship_bill_surcharges')->where('bill_month',$month)->distinct()->pluck('factory_id')->all():[];
|
||||
$hasMatchedFiles=$indexed!==[];
|
||||
if($hasMatchedFiles){
|
||||
$rows=$this->store->db()->table($matcher::TABLE)->where('scope','dropship')->where('bill_month',$month)
|
||||
->selectRaw('owner_id,item,SUM(self_amount) AS amount')->groupBy('owner_id','item')->get();
|
||||
foreach($rows as $row){
|
||||
if($row->amount===null)continue;
|
||||
$key=self::classify($row->item);$id=(int)$row->owner_id;
|
||||
if($key===null)$result[$id]['other'][$row->item]=(float)$row->amount;
|
||||
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+(float)$row->amount;
|
||||
}
|
||||
// 已确认账期维持原自动值,不因接入新的核对方式重写已确认金额。
|
||||
$states=app(DropshipConfirmation::class)->states($month,(int)(company_id()?:1));
|
||||
$confirmed=array_keys(array_filter($states,fn($s)=>($s['status']??'')==='confirmed'));
|
||||
foreach($confirmed as $id)unset($result[$id]);
|
||||
$legacy=$this->store->db()->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')
|
||||
->where(fn($q)=>$q->whereNotIn('factory_id',$indexed)->orWhereIn('factory_id',$confirmed));
|
||||
foreach($legacy->get(['id','factory_id','stored_path','sheets']) as $file){
|
||||
foreach($this->store->feesFor($file) as $type=>$amount){
|
||||
$key=self::classify($type);$id=(int)$file->factory_id;
|
||||
if($key===null)$result[$id]['other'][$type]=($result[$id]['other'][$type]??0)+$amount;
|
||||
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+$amount;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
$files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed')
|
||||
->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']);
|
||||
foreach ($files as $file) {
|
||||
|
||||
@ -6,7 +6,6 @@ use App\Support\CourierBills\BillWorkbookReader;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@ -85,21 +84,6 @@ final class DropshipFreightStore
|
||||
return $sheets;
|
||||
}
|
||||
|
||||
/** 新上传时在已有事务内保存;历史文件通过受限批处理命令回读。 */
|
||||
public function storeSurchargeRows(object $file,int $factoryId): void
|
||||
{
|
||||
if(!app(SurchargeSettlementMatcher::class)->ready())return;
|
||||
$db=$this->db();
|
||||
$db->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
|
||||
$rows=[];
|
||||
foreach((new FreightBillTemplate(new BillWorkbookReader()))->surchargeRows(
|
||||
Storage::disk(self::DISK)->path($file->stored_path),pathinfo($file->stored_path,PATHINFO_EXTENSION)) as $row){
|
||||
$rows[]=$row+['file_id'=>$file->id,'factory_id'=>$factoryId,'bill_month'=>$file->bill_month];
|
||||
if(count($rows)>=300){$db->table('dropship_bill_surcharges')->insert($rows);$rows=[];}
|
||||
}
|
||||
if($rows!==[])$db->table('dropship_bill_surcharges')->insert($rows);
|
||||
}
|
||||
|
||||
public function db(): ConnectionInterface
|
||||
{
|
||||
return DB::connection('business_mirror');
|
||||
@ -274,14 +258,9 @@ final class DropshipFreightStore
|
||||
}
|
||||
$this->db()->transaction(function () use ($file): void {
|
||||
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
||||
if(app(SurchargeSettlementMatcher::class)->ready()){
|
||||
$this->db()->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
|
||||
$this->db()->table(SurchargeSettlementMatcher::TABLE)->where('scope','dropship')->where('file_id',$file->id)->delete();
|
||||
}
|
||||
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
||||
});
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -430,7 +409,6 @@ final class DropshipFreightStore
|
||||
$lines = array_diff_key($lines, array_flip($others));
|
||||
}
|
||||
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
||||
$this->storeSurchargeRows($file,$factoryId);
|
||||
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
||||
foreach (array_chunk($lines, 500, true) as $chunk) {
|
||||
$insert = [];
|
||||
@ -449,7 +427,6 @@ final class DropshipFreightStore
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
});
|
||||
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
|
||||
}
|
||||
|
||||
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
||||
|
||||
@ -127,14 +127,6 @@ class SidebarPermissions
|
||||
$allowed[] = 'process-data/invoice-data';
|
||||
}
|
||||
|
||||
if (in_array('courier-payables/shipping-data', $allowed, true)) {
|
||||
$allowed[] = 'courier-payables/returned-parcels';
|
||||
}
|
||||
|
||||
if (in_array('supplier-reconciliation/finance-data', $allowed, true)) {
|
||||
$allowed[] = 'supplier-reconciliation/raw-statements';
|
||||
}
|
||||
|
||||
return array_values(array_unique($allowed));
|
||||
}
|
||||
|
||||
|
||||
@ -813,7 +813,6 @@ $navigation = [
|
||||
'icon' => 'fact_check',
|
||||
'pages' => [
|
||||
['slug' => 'finance-data', 'title' => '财务端数据'],
|
||||
['slug' => 'raw-statements', 'title' => '原始账单'],
|
||||
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
||||
],
|
||||
],
|
||||
|
||||
@ -10,9 +10,6 @@ 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',
|
||||
|
||||
@ -1,58 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 快递账单补记账:记账扣过的单,快递后来退回了,在后面的账期把多扣的补回去。
|
||||
* - courier_bill_rebooks:补记账台账,哪个单号、几月扣的、在哪个账期补了多少;补过的不再补。
|
||||
* - courier_bill_rebook_reviews:复核记账,这单现在应扣多少(逻辑定下来前由财务每月导入复核结果)。
|
||||
* - courier_bill_groups.rebook_months:补几个月(空 = 按小汇总识别,0 = 不补,1 = 补上月,2 = 补前两个月)。
|
||||
*/
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection('business_mirror');
|
||||
|
||||
$schema->create('courier_bill_rebooks', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('group_id')->nullable()->index();
|
||||
$table->string('waybill_no', 96)->index();
|
||||
$table->char('deduct_month', 7)->comment('扣款账期');
|
||||
$table->char('refund_month', 7)->index()->comment('补款账期');
|
||||
$table->decimal('deducted', 14, 2)->nullable()->comment('当时扣的');
|
||||
$table->decimal('current', 14, 2)->nullable()->comment('补款时应扣的');
|
||||
$table->decimal('amount', 14, 2)->comment('补款金额');
|
||||
$table->unsignedBigInteger('statement_id')->nullable()->index()->comment('空 = 历史导入');
|
||||
$table->string('source', 16)->default('statement');
|
||||
$table->json('details')->nullable()->comment('确认时的记账明细快照');
|
||||
$table->dateTime('created_at')->nullable();
|
||||
$table->unique(['waybill_no', 'deduct_month'], 'courier_bill_rebooks_identity');
|
||||
});
|
||||
|
||||
$schema->create('courier_bill_rebook_reviews', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('waybill_no', 96);
|
||||
$table->char('deduct_month', 7);
|
||||
$table->decimal('current_amount', 14, 2)->comment('复核后现在应扣');
|
||||
$table->string('source_name', 255)->nullable();
|
||||
$table->dateTime('updated_at')->nullable();
|
||||
$table->unique(['waybill_no', 'deduct_month'], 'courier_bill_rebook_reviews_identity');
|
||||
});
|
||||
|
||||
$schema->table('courier_bill_groups', function (Blueprint $table): void {
|
||||
$table->unsignedTinyInteger('rebook_months')->nullable()->comment('补记账补几个月:空=按小汇总识别,0=不补');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection('business_mirror');
|
||||
$schema->table('courier_bill_groups', function (Blueprint $table): void {
|
||||
$table->dropColumn('rebook_months');
|
||||
});
|
||||
$schema->dropIfExists('courier_bill_rebook_reviews');
|
||||
$schema->dropIfExists('courier_bill_rebooks');
|
||||
}
|
||||
};
|
||||
@ -1,59 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
};
|
||||
@ -1,60 +0,0 @@
|
||||
<?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 (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
|
||||
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
if (app()->environment('testing') && ! $schema->hasTable('courier_surcharge_settlement_rows')) return;
|
||||
if (! $schema->hasColumn('courier_surcharge_settlement_rows', 'source_kind')) {
|
||||
$schema->table('courier_surcharge_settlement_rows', function (Blueprint $table): void {
|
||||
$table->string('source_kind', 40)->nullable();
|
||||
$table->string('source_key', 80)->nullable();
|
||||
$table->dateTime('source_created_at', 6)->nullable();
|
||||
$table->unique(['rule_id','source_kind','source_key','surcharge_type'], 'surcharge_service_source_unique');
|
||||
$table->index(['source_kind','rule_id','source_created_at'], 'surcharge_service_window');
|
||||
});
|
||||
}
|
||||
if (! $schema->hasTable('courier_surcharge_service_stage')) {
|
||||
$schema->create('courier_surcharge_service_stage', function (Blueprint $table): void {
|
||||
$table->string('dataset_key', 100);
|
||||
$table->string('generation', 36);
|
||||
$table->unsignedInteger('rule_id');
|
||||
$table->string('source_kind', 40);
|
||||
$table->string('source_key', 80);
|
||||
$table->dateTime('source_created_at', 6);
|
||||
$table->string('surcharge_type', 40);
|
||||
foreach (['courier_name','waybill','platform_product_id','product_code','shop_name','online_order_no','return_waybill_no'] as $key) $table->string($key, 191)->nullable();
|
||||
$table->unsignedBigInteger('outbound_io_id')->nullable();
|
||||
foreach (['length','width','height','settlement_weight'] as $key) $table->decimal($key, 12, 2)->nullable();
|
||||
$table->decimal('volume', 16, 2)->nullable();
|
||||
$table->string('inspection_type', 60)->nullable();
|
||||
$table->string('inspection_reason', 120)->nullable();
|
||||
$table->decimal('settlement_amount', 12, 2);
|
||||
$table->string('settlement_status', 40);
|
||||
$table->string('evidence', 500)->nullable();
|
||||
$table->dateTime('shipped_at')->nullable();
|
||||
$table->dateTime('pulled_at');
|
||||
$table->timestamps();
|
||||
$table->unique(['dataset_key','rule_id','source_key','surcharge_type'], 'surcharge_service_stage_unique');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
|
||||
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$schema->dropIfExists('courier_surcharge_service_stage');
|
||||
$schema->table('courier_surcharge_settlement_rows', function (Blueprint $table): void {
|
||||
$table->dropUnique('surcharge_service_source_unique');
|
||||
$table->dropIndex('surcharge_service_window');
|
||||
$table->dropColumn(['source_kind','source_key','source_created_at']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -1,43 +0,0 @@
|
||||
<?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
|
||||
{
|
||||
$s = Schema::connection('business_mirror');
|
||||
if (! $s->hasTable('bill_surcharge_matches')) {
|
||||
$s->create('bill_surcharge_matches', function (Blueprint $t): void {
|
||||
$t->id(); $t->string('scope', 16); $t->unsignedBigInteger('owner_id');
|
||||
$t->unsignedBigInteger('file_id'); $t->string('sheet', 100); $t->unsignedInteger('row_no');
|
||||
$t->string('bill_month', 7); $t->string('waybill_no', 96); $t->string('item', 100);
|
||||
$t->string('summary_label', 100);
|
||||
$t->decimal('bill_amount', 16, 4)->nullable(); $t->decimal('self_amount', 16, 2)->nullable();
|
||||
$t->string('courier_name', 191)->nullable();
|
||||
foreach (['platform_product_id','product_code','shop_name','online_order_no'] as $k) $t->text($k)->nullable();
|
||||
$t->string('match_status', 40); $t->text('match_note')->nullable();
|
||||
$t->text('settlement_ids')->nullable(); $t->timestamp('matched_at')->nullable();
|
||||
$t->unique(['scope','owner_id','file_id','sheet','row_no'], 'bill_surcharge_source_unique');
|
||||
$t->index(['scope','owner_id','id'], 'bill_surcharge_owner');
|
||||
$t->index(['waybill_no','item','bill_month'], 'bill_surcharge_history');
|
||||
});
|
||||
}
|
||||
if (! $s->hasTable('dropship_bill_surcharges')) {
|
||||
$s->create('dropship_bill_surcharges', function (Blueprint $t): void {
|
||||
$t->id(); $t->unsignedBigInteger('file_id')->index(); $t->unsignedBigInteger('factory_id');
|
||||
$t->string('bill_month', 7); $t->string('sheet', 100); $t->unsignedInteger('row_no');
|
||||
$t->string('waybill_no', 96); $t->string('item', 100); $t->decimal('amount', 16, 4)->nullable();
|
||||
$t->index(['factory_id','bill_month','id'], 'dropship_surcharge_month');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->dropIfExists('bill_surcharge_matches');
|
||||
Schema::connection('business_mirror')->dropIfExists('dropship_bill_surcharges');
|
||||
}
|
||||
};
|
||||
@ -248,7 +248,6 @@ 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
|
||||
@ -268,8 +267,7 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
|
||||
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
@ -284,9 +282,6 @@ CRON_TZ=Asia/Shanghai
|
||||
# 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。
|
||||
30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1
|
||||
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
|
||||
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
|
||||
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
|
||||
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||
|
||||
|
||||
@ -252,7 +252,6 @@ 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
|
||||
@ -272,8 +271,7 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
|
||||
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
@ -288,9 +286,6 @@ CRON_TZ=Asia/Shanghai
|
||||
# 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。
|
||||
30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1
|
||||
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
|
||||
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
|
||||
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
|
||||
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
[
|
||||
"portal-freight:import-pending",
|
||||
"courier-surcharge:match-bills",
|
||||
"planting-reimbursement:auto-confirm",
|
||||
"jushuitan:apply-shipping-corrections",
|
||||
"actual-tax:import",
|
||||
|
||||
@ -8,10 +8,10 @@ is_import=0
|
||||
CAIWU_BATCH_CALLER_DIR="$PWD"
|
||||
export CAIWU_BATCH_CALLER_DIR
|
||||
case "${1:-}" in
|
||||
portal-freight:import-pending|courier-surcharge:match-bills) is_import=1 ;;
|
||||
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|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;
|
||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
|
||||
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
|
||||
@ -67,34 +67,6 @@ if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ];
|
||||
fi
|
||||
[ -n "$pending_request" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = 'all' ] && [ "${3:-}" = '--monthly' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] || exit 0
|
||||
current_month="$(TZ=Asia/Shanghai date +%Y-%m)"
|
||||
if python3 - "$storage_root" "$current_month" <<'PY'
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
storage_root, current_month = sys.argv[1:3]
|
||||
paths = glob.glob(os.path.join(storage_root, 'app/account-mapping/coverage-snapshots/all-*.json'))
|
||||
paths.sort(key=os.path.getmtime, reverse=True)
|
||||
for path in paths:
|
||||
try:
|
||||
snapshot = json.loads(open(path, encoding='utf-8').read())
|
||||
except (OSError, ValueError, TypeError):
|
||||
continue
|
||||
refreshed_at = str(snapshot.get('refreshed_at', ''))
|
||||
if refreshed_at.startswith(current_month + '-'):
|
||||
sys.exit(0)
|
||||
break
|
||||
sys.exit(1)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
|
||||
@ -153,15 +125,4 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then
|
||||
--name "$container_name" batch "$@"
|
||||
exit $?
|
||||
fi
|
||||
if [ "$1" = 'business-mirror:sync-returned-parcels' ] || [ "$1" = 'courier-surcharge:pull-customer-service' ]; 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 "$@"
|
||||
|
||||
@ -1,11 +1,5 @@
|
||||
# 上游业务镜像清单
|
||||
|
||||
## 客服核实附加费
|
||||
|
||||
`courier-surcharge:pull-customer-service --courier=常州中通快运` 读取现有 `js_jst_work_order_info` 查件工单镜像(类型 `0FE39FBE88E448D396B2E8ED62775284`),不依赖工单标题。费用子表 `TABLEField1413856620250814155027` 逐行取类型、金额和客服审核结果,仅结果为“通过”的行参与对应启用报价。改地址费统一到改地址,工单状态“待确认”不能代替费用行审核结果;商品数量不重复乘费用。
|
||||
|
||||
按公司、快递及报价生效日限制范围,每批 300 张工单按 `(created, Id)` 索引游标读取;同工单同类型通过金额合计,保留工单来源键。暂存和断点同事务提交,前后数量核验通过后仅替换该范围的客服核实派生行,失败保留上次结果。生产通过独立批入口、上游全局互斥锁、1 CPU / 3 GiB 容器、512 MiB PHP / 1800 秒上限执行,常州中通快运每天 06:45 校准生效日起记录,以覆盖后补审核和撤销。其他快递或重量条件报价不随此次任务回补。
|
||||
|
||||
## 发货线上重量精度
|
||||
|
||||
`operations_replica.rpt.jst_qmcust_salesoutbound` 的原始文本重量(含科学计数法)登记为 `ops_jst_precise_outbound`,仅同步 Id、io_id、l_id、io_date、weight、status、local_updated;按 Id 断点全量、local_updated 增量,io_id 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。
|
||||
@ -26,10 +20,6 @@
|
||||
|
||||
## 当前迁移状态
|
||||
|
||||
“快递应付 → 退回件明细”按 `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 个流程。 |
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
# 快递联合上传
|
||||
|
||||
入口:快递应付(及终版)→ 快递账单对账 → 上传账单 → 联合上传链接。
|
||||
选择月份、打开页面后复制地址给快递。仍使用统一逐单模板及 30 天签名有效期。
|
||||
|
||||
## 范围与归组
|
||||
|
||||
- 樵舍:江西新建中通、江西中通快运、樵舍中通、樵舍中通-上楼、山东中通快运、西安圆通、西安中通快运。
|
||||
- 圆通:常州圆通其他、常州圆通-上楼、小件宿迁圆通、睢宁宿迁圆通、苏北宿迁圆通。
|
||||
- 睢宁宿迁圆通是苏北宿迁圆通的既有快递名称,圆通共 5 个名称、4 个分组。
|
||||
- 河北中通与霸州百世:河北中通-江三、河北中通小件-江三、霸州百世快运-雅柏,3 个名称、2 个分组。
|
||||
- 德邦与顺丰干配:睢宁德邦、崔桥顺丰干配、山东顺丰干配、山东顺丰大件、苏北顺丰干配大件、苏北顺丰干配小件,6 个名称、4 个分组。
|
||||
- 睢宁德邦归入既有顺德德邦分组;链接只接受列出的 6 个名称,不额外授权顺德德邦名称。
|
||||
- 不改分组、机器人或既有单家链接。联合权限不继承文件名、机器人共用关系或合并账单配置。
|
||||
- 优先按系统单号归组;系统查不到快递名称时,使用模板内明确填写的范围内名称。
|
||||
- 无法归组、范围外名称、同单号不同归属、附加费缺少运费明细时,整份回滚并提示修改。
|
||||
- 附加费沿用同文件同单号运费的归属。重复文件沿用既有查重规则。
|
||||
- 签名和任务固定分组快照;排队后配置变化或任一分组确认结算时禁止写入。重读、重新匹配不扩大范围。
|
||||
- 已存在的 `extra_group_ids` JSON 列保存带 `joint_upload` 键的授权快照;普通文件仍为原数组结构,无迁移。
|
||||
|
||||
## 验证
|
||||
|
||||
2026-12-04 本地隔离容器,PHP 8.3、SQLite 内存测试库,禁止访问生产数据。
|
||||
|
||||
- `CourierJointUploadTest`:签名、别名、匿名上传、排队后配置变化/确认、归组、附加费、回滚、重读、查重、页面入口。
|
||||
- `PortalFreightBillTest`、`CourierBillReconciliationTest`、`CourierBillPagesTest`:原上传、金额及页面回归。
|
||||
- 相关回归 47 项,596 个断言通过;容量专项默认跳过,单独运行。
|
||||
- 容量专项:100,000 行 CSV,3,900,052 字节,交替两家,校验、流式读入、归组及原有完整对账均执行。
|
||||
- 100,000 行与 123,000 元合计完整,102.78 秒,PHP 峰值 154.5 MiB,数据库查询事件 101,823 次(包含既有逐行匹配更新)。
|
||||
- 不据此承诺生产 MySQL 耗时;未对生产执行压测或上传测试账单。生产查询时两组尚无已上传文件和当月对账单。
|
||||
- 河北及德邦/顺丰扩展:生产只读确认原分组、别名及账单为空;49 项回归、625 个断言通过,新增两组整单上传与别名范围校验已覆盖。增加入口显示断言后单独运行页面路径,16 个断言通过。
|
||||
- 本次扩展沿用同一流式导入及每批 500 行分配,不改变数据量上限、导入命令或频率;未重复执行已通过的 10 万行容量测试。
|
||||
|
||||
生产复用已登记的 `portal-freight:import-pending` 独立批处理,每次一份;现有锁、1 CPU、1 GiB 容器、PHP 512 MiB、1 小时超时继续生效。
|
||||
中断任务标记失败,联系财务核对后重传,不自动重复导入。
|
||||
@ -1,15 +0,0 @@
|
||||
# 附加费账单匹配
|
||||
|
||||
快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;允许匹配以前月份费用,不把账单金额当自算金额。客服费用以工单创建时间、其他费用以发货时间确定上界,不取账期之后的费用。
|
||||
|
||||
新文件导入时自动匹配,已有账单可用 `courier-surcharge:match-bills --month=2026-11 --statement=11` 或 `--factory=厂家ID` 校准,也可 `--all` 处理当月未确认账单。命令省略月份时取北京时间上月,生产每天 07:05 使用 `--all --existing-only` 更新已经建立匹配的账单;首次历史回补单独确认,部署和定时任务不会自动启用旧账单。命令必须走 `run-finance-batch.sh`,共用上游互斥锁和独立批容器,PHP 512 MiB、容器 1 GiB、最长 3600 秒,失败按同范围重跑。每份账单的更新在事务内;不改已确认快递账单或厂家确认状态,不重算原运费行,手工小汇总优先。
|
||||
|
||||
`bill_surcharge_matches` 保存来源文件/工作表/行号、账期、单号、类型、对方金额、自算金额、状态、商品/店铺/订单信息和稳定费用来源标识。`dropship_bill_surcharges` 保存厂家原始附加费行。Excel 使用项目现有流式读取器,每批匹配 300 行,来源按单号索引查询,明细页面 50 行分页,导出逐批写入“附加费核对”子表。类型只使用明确同义词(如改地址费→改地址),不把不明类型猜成其他费用。
|
||||
|
||||
同一账期重复提供的单号+费用类型只计一次;同一费用来源已被其他账单计入时不再计入,仅新出现的费用来源可继续计入。同一单号不同费用类型分别核对;匹配不到或快递归属不符时自算金额留空并显示原因。代发还要求发货仓库及快递名称同时属于该厂家,排除自有快递。多个商品信息去重后展示,金额按票汇总,不乘商品数。
|
||||
|
||||
查询/校准不会写上游报价或来源费用;删除账单文件时清除其派生匹配结果。真实账单、备份与生产日志保留在 Git 忽略的私有目录。
|
||||
|
||||
结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单“拦截退回”对应“拦截费”;客服明细“拦截退回运费”对应“退回费”。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。
|
||||
|
||||
客服费用通过现有单号索引读取共享工单,要求同一快递、费用类型一致、逐项审核通过且工单在账单月份结束前创建;按工单归集,不按商品数重复计费。“重量60kg以上”先检查本票已核算计费重量,低于门槛计0;缺重量、缺审核、无报价分别显示原因。原始账单、报价和发货运费均不改写。
|
||||
@ -63,7 +63,7 @@ class CourierSurchargeSettlementMirrorRepository
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function state(array $filters = []): array
|
||||
public function state(): array
|
||||
{
|
||||
if (! $this->available()) {
|
||||
return [
|
||||
@ -75,15 +75,8 @@ class CourierSurchargeSettlementMirrorRepository
|
||||
}
|
||||
|
||||
try {
|
||||
$query = $this->filteredQuery($filters);
|
||||
$lastPulledAt = (clone $query)->max('pulled_at');
|
||||
$rowCount = (int) (clone $query)->count();
|
||||
$serviceState = null;
|
||||
$courier = trim((string) ($filters['courier_name'] ?? ''));
|
||||
if ($courier !== '' && $this->connection->getSchemaBuilder()->hasTable('business_mirror_table_states')) {
|
||||
$serviceState = $this->connection->table('business_mirror_table_states')->where('dataset_key',
|
||||
\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::dataset((int) company_id(), $courier))->first();
|
||||
}
|
||||
$lastPulledAt = $this->connection->table(self::TABLE)->max('pulled_at');
|
||||
$rowCount = (int) $this->connection->table(self::TABLE)->count();
|
||||
} catch (Throwable) {
|
||||
return [
|
||||
'code' => 'pending',
|
||||
@ -94,9 +87,9 @@ class CourierSurchargeSettlementMirrorRepository
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => $serviceState ? ($serviceState->status === 'succeeded' ? 'fresh' : ($serviceState->status === 'failed' ? 'failed' : 'syncing')) : ($lastPulledAt === null ? 'pending' : 'fresh'),
|
||||
'status' => $serviceState->status ?? ($lastPulledAt === null ? 'pending' : 'succeeded'),
|
||||
'last_succeeded_at' => $serviceState->last_succeeded_at ?? $lastPulledAt,
|
||||
'code' => $lastPulledAt === null ? 'pending' : 'fresh',
|
||||
'status' => $lastPulledAt === null ? 'pending' : 'succeeded',
|
||||
'last_succeeded_at' => $lastPulledAt,
|
||||
'mirror_row_count' => $rowCount,
|
||||
];
|
||||
}
|
||||
@ -148,7 +141,7 @@ class CourierSurchargeSettlementMirrorRepository
|
||||
$data[] = $mapped;
|
||||
}
|
||||
|
||||
$state = $this->state($filters);
|
||||
$state = $this->state();
|
||||
|
||||
return [
|
||||
'data' => $data,
|
||||
@ -393,18 +386,6 @@ class CourierSurchargeSettlementMirrorRepository
|
||||
private function matchImportRow(iterable $rows, string $type, string $courier = ''): ?object
|
||||
{
|
||||
$fallback = null;
|
||||
$service = [];
|
||||
foreach ($rows as $row) {
|
||||
if (($row->source_kind ?? null) === \Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::KIND
|
||||
&& trim((string) $row->surcharge_type) === $type
|
||||
&& ($courier === '' || trim((string) $row->courier_name) === $courier)) $service[] = $row;
|
||||
}
|
||||
if ($service !== [] && count(array_unique(array_column($service, 'courier_name'))) === 1) {
|
||||
$sum = clone $service[0];
|
||||
$sum->settlement_amount = array_sum(array_map(fn ($r) => (float) $r->settlement_amount, $service));
|
||||
$sum->evidence = implode(';', array_map(fn ($r) => (string) $r->evidence, $service));
|
||||
return $sum;
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if (trim((string) $row->surcharge_type) !== $type) {
|
||||
|
||||
@ -163,13 +163,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
|
||||
/**
|
||||
* @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters
|
||||
* @return array{
|
||||
* data:list<array<string,mixed>>,
|
||||
* total:int,
|
||||
* page_payment_amount:string,
|
||||
* filtered_payment_amount:string,
|
||||
* store_summary:list<array{shop_name:string,work_order_count:int,payment_amount:string}>
|
||||
* }
|
||||
* @return array{data:list<array<string,mixed>>,total:int,page_payment_amount:string,filtered_payment_amount:string}
|
||||
*/
|
||||
public function paginate(array $filters, int $page, int $perPage): array
|
||||
{
|
||||
@ -194,7 +188,6 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
'total' => $summary['count'],
|
||||
'page_payment_amount' => $this->sumMoney(array_column($rows, 'payment_amount')),
|
||||
'filtered_payment_amount' => $summary['payment_amount'],
|
||||
'store_summary' => $summary['store_summary'],
|
||||
];
|
||||
}
|
||||
|
||||
@ -213,11 +206,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
|
||||
/**
|
||||
* @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters
|
||||
* @return array{
|
||||
* count:int,
|
||||
* payment_amount:string,
|
||||
* store_summary:list<array{shop_name:string,work_order_count:int,payment_amount:string}>
|
||||
* }
|
||||
* @return array{count:int,payment_amount:string}
|
||||
*/
|
||||
private function filteredSummary(array $filters, int $chunkSize = 1000): array
|
||||
{
|
||||
@ -235,11 +224,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
|
||||
/**
|
||||
* @param array{from:string,to:string,work_order_no:string,shop_name:string,transaction_no:string,online_order_no:string,status:string,payment_reason:string} $filters
|
||||
* @return array{
|
||||
* count:int,
|
||||
* payment_amount:string,
|
||||
* store_summary:list<array{shop_name:string,work_order_count:int,payment_amount:string}>
|
||||
* }
|
||||
* @return array{count:int,payment_amount:string}
|
||||
*/
|
||||
private function calculateFilteredSummary(array $filters, int $chunkSize): array
|
||||
{
|
||||
@ -252,49 +237,23 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
$cents = 0;
|
||||
$count = 0;
|
||||
$lastId = null;
|
||||
$shops = [];
|
||||
|
||||
do {
|
||||
$chunk = $this->boundedGet((clone $query)
|
||||
->select(['w.Id AS source_id', 'w.businessFieldList', 'p.shop_name'])
|
||||
->select(['w.Id AS source_id', 'w.businessFieldList'])
|
||||
->when($lastId !== null, static fn (Builder $q): Builder => $q->where('w.Id', '>', $lastId))
|
||||
->orderBy('w.Id')
|
||||
->limit($chunkSize));
|
||||
|
||||
foreach ($chunk as $row) {
|
||||
$rowCents = $this->centsFromMoney($this->paymentAmountOf($row->businessFieldList ?? null));
|
||||
$shopName = trim((string) ($row->shop_name ?? '')) ?: '未填写店铺';
|
||||
$shops[$shopName] ??= ['work_order_count' => 0, 'cents' => 0];
|
||||
$shops[$shopName]['work_order_count']++;
|
||||
$shops[$shopName]['cents'] += $rowCents;
|
||||
$cents += $rowCents;
|
||||
$cents += $this->centsFromMoney($this->paymentAmountOf($row->businessFieldList ?? null));
|
||||
}
|
||||
|
||||
$count += $chunk->count();
|
||||
$lastId = $chunk->isEmpty() ? null : $chunk->last()->source_id;
|
||||
} while ($chunk->count() === $chunkSize);
|
||||
|
||||
$storeSummary = [];
|
||||
foreach ($shops as $shopName => $shop) {
|
||||
$storeSummary[] = [
|
||||
'shop_name' => $shopName,
|
||||
'work_order_count' => $shop['work_order_count'],
|
||||
'payment_amount' => $this->formatCents($shop['cents']),
|
||||
];
|
||||
}
|
||||
usort($storeSummary, static function (array $left, array $right): int {
|
||||
$amountOrder = abs((float) $right['payment_amount']) <=> abs((float) $left['payment_amount']);
|
||||
|
||||
return $amountOrder !== 0
|
||||
? $amountOrder
|
||||
: strcmp($left['shop_name'], $right['shop_name']);
|
||||
});
|
||||
|
||||
return [
|
||||
'count' => $count,
|
||||
'payment_amount' => $this->formatCents($cents),
|
||||
'store_summary' => $storeSummary,
|
||||
];
|
||||
return ['count' => $count, 'payment_amount' => $this->formatCents($cents)];
|
||||
}
|
||||
|
||||
private function paymentAmountOf(mixed $businessFieldList): ?string
|
||||
@ -758,7 +717,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
||||
$normalized = array_map(static fn (mixed $value): string => trim((string) $value), $filters);
|
||||
ksort($normalized);
|
||||
|
||||
return 'small-payment-work-orders:summary:v2:' . hash(
|
||||
return 'small-payment-work-orders:summary:v1:' . hash(
|
||||
'sha256',
|
||||
(string) json_encode($normalized, JSON_UNESCAPED_UNICODE),
|
||||
);
|
||||
|
||||
@ -31,10 +31,6 @@ class AccountMappingCoverage
|
||||
|
||||
private const RETRY_SECONDS = 8;
|
||||
|
||||
private const ALL_SCOPE = 'all';
|
||||
|
||||
private const ALL_SCOPE_MONTHS = 60;
|
||||
|
||||
private const SOURCES = [
|
||||
'淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||
'淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||
@ -74,29 +70,18 @@ class AccountMappingCoverage
|
||||
|
||||
public function defaultMonth(): string
|
||||
{
|
||||
$timezone = trim((string) config('app.platform_timezone', ''));
|
||||
if ($timezone === '') {
|
||||
$timezone = (string) config('app.timezone', 'UTC');
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->platformNow()->subMonthNoOverflow()->format('Y-m');
|
||||
return CarbonImmutable::now($timezone)->subMonthNoOverflow()->format('Y-m');
|
||||
} catch (Throwable) {
|
||||
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
|
||||
}
|
||||
}
|
||||
|
||||
/** 本月是否还没有成功生成过跨月清单。 */
|
||||
public function monthlyRefreshDue(): bool
|
||||
{
|
||||
$snapshot = $this->readLatestSnapshot(self::ALL_SCOPE);
|
||||
if ($snapshot === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
return CarbonImmutable::parse($snapshot['refreshed_at'], $this->platformTimezone())
|
||||
->format('Y-m') !== $this->platformNow()->format('Y-m');
|
||||
} catch (Throwable) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function monthOptions(int $months = 18): array
|
||||
{
|
||||
@ -188,13 +173,13 @@ class AccountMappingCoverage
|
||||
return $lock->block(20, function () use ($period): array {
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => $this->platformNow()->toDateTimeString(),
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
try {
|
||||
$sourceKey = $this->rawCacheKey($period);
|
||||
$raw = $this->buildSourceCoverage($period);
|
||||
$refreshedAt = $this->platformNow()->toDateTimeString();
|
||||
$refreshedAt = now()->toDateTimeString();
|
||||
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
||||
$this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
@ -218,106 +203,13 @@ class AccountMappingCoverage
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面使用:读取跨月账单项目清单;不会在读取时自动创建扫描任务。
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function missingAcrossMonths(bool $refresh = false, bool $queueIfMissing = false): array
|
||||
{
|
||||
$snapshotKey = self::ALL_SCOPE;
|
||||
if (! $refresh) {
|
||||
// 页面只读最近一次成功快照。源数据版本或月份边界变化不能让已有清单失效,
|
||||
// 否则用户每次进入页面都会重新看到“尚未生成”。
|
||||
$snapshot = $this->readLatestSnapshot($snapshotKey);
|
||||
if ($snapshot !== null) {
|
||||
return $this->missingAcrossPayload($snapshot['raw'], $snapshot['refreshed_at']);
|
||||
}
|
||||
}
|
||||
|
||||
$sourceKey = $this->allSourceKey();
|
||||
$status = Cache::get($this->statusCacheKey($snapshotKey), []);
|
||||
$raw = Cache::get($sourceKey);
|
||||
if (! $refresh && is_array($raw)) {
|
||||
$refreshedAt = is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '';
|
||||
$this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt);
|
||||
|
||||
return $this->missingAcrossPayload($raw, $refreshedAt);
|
||||
}
|
||||
|
||||
if (is_array($status) && ($status['status'] ?? '') === 'refreshing') {
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($snapshotKey, 'failed', (string) ($status['message'] ?? ''));
|
||||
}
|
||||
if ($this->hasLiveRefreshRequest($snapshotKey)) {
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
if (! $refresh && ! $queueIfMissing) {
|
||||
return $this->waitingPayload($snapshotKey, 'missing');
|
||||
}
|
||||
|
||||
$requested = $this->requestRefresh($snapshotKey);
|
||||
if (($requested['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($snapshotKey, 'failed', (string) ($requested['message'] ?? ''));
|
||||
}
|
||||
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台命令使用:一次性按月份聚合最近 60 个月的全部账单项目。
|
||||
*
|
||||
* @return array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>}
|
||||
*/
|
||||
public function refreshAllMonths(): array
|
||||
{
|
||||
$snapshotKey = self::ALL_SCOPE;
|
||||
$lock = Cache::lock('account-mapping-coverage-refresh:' . $snapshotKey, 900);
|
||||
|
||||
try {
|
||||
return $lock->block(20, function () use ($snapshotKey): array {
|
||||
Cache::put($this->statusCacheKey($snapshotKey), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => $this->platformNow()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
try {
|
||||
$sourceKey = $this->allSourceKey();
|
||||
[$start, $end] = $this->allPeriodBounds();
|
||||
$raw = $this->buildAllSourceCoverage($start, $end);
|
||||
$refreshedAt = $this->platformNow()->toDateTimeString();
|
||||
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
||||
$this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt);
|
||||
Cache::put($this->statusCacheKey($snapshotKey), [
|
||||
'status' => 'ready',
|
||||
'refreshed_at' => $refreshedAt,
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
return $raw;
|
||||
} catch (Throwable $exception) {
|
||||
$this->markFailed($snapshotKey, $exception->getMessage());
|
||||
throw $exception;
|
||||
}
|
||||
});
|
||||
} catch (\Illuminate\Contracts\Cache\LockTimeoutException) {
|
||||
return [
|
||||
'status' => 'refreshing',
|
||||
'source_rows' => 0,
|
||||
'pending_sources' => [],
|
||||
'pairs' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function markFailed(string $month, string $message): void
|
||||
{
|
||||
$period = $this->normalizeRefreshKey($month);
|
||||
$period = $this->parseMonth($month);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'failed',
|
||||
'message' => $message,
|
||||
'failed_at' => $this->platformNow()->toDateTimeString(),
|
||||
'failed_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
}
|
||||
|
||||
@ -347,7 +239,6 @@ class AccountMappingCoverage
|
||||
|
||||
return [
|
||||
'status' => $raw['status'],
|
||||
'scope' => 'month',
|
||||
'month' => $period,
|
||||
'source_rows' => $raw['source_rows'],
|
||||
'missing_item_count' => count($items),
|
||||
@ -361,60 +252,12 @@ class AccountMappingCoverage
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>} $raw
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function missingAcrossPayload(array $raw, string $refreshedAt = ''): array
|
||||
{
|
||||
$mapping = $this->coverageMappingKeys($this->store->all());
|
||||
$items = [];
|
||||
$missingRows = 0;
|
||||
|
||||
foreach ($raw['pairs'] as $pair) {
|
||||
if ($this->isMapped($pair, $mapping)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$months = array_values(array_filter(
|
||||
(array) ($pair['months'] ?? []),
|
||||
static fn (mixed $month): bool => is_string($month) && $month !== '',
|
||||
));
|
||||
sort($months);
|
||||
$pair['months'] = $months;
|
||||
$missingRows += (int) $pair['source_rows'];
|
||||
$items[] = $pair;
|
||||
}
|
||||
|
||||
usort($items, static fn (array $left, array $right): int => (
|
||||
$right['source_rows'] <=> $left['source_rows']
|
||||
) ?: (
|
||||
strcmp((string) $left['platform'], (string) $right['platform'])
|
||||
) ?: strcmp((string) $left['item'], (string) $right['item']));
|
||||
|
||||
return [
|
||||
'status' => $raw['status'],
|
||||
'scope' => self::ALL_SCOPE,
|
||||
'month' => null,
|
||||
'source_rows' => $raw['source_rows'],
|
||||
'missing_item_count' => count($items),
|
||||
'missing_row_count' => $missingRows,
|
||||
'pending_sources' => $raw['pending_sources'],
|
||||
'items' => $items,
|
||||
'months' => [],
|
||||
'retry_after' => null,
|
||||
'message' => '',
|
||||
'refreshed_at' => $refreshedAt,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function waitingPayload(string $period, string $status, string $message = ''): array
|
||||
{
|
||||
return [
|
||||
'status' => $status,
|
||||
'scope' => $period === self::ALL_SCOPE ? self::ALL_SCOPE : 'month',
|
||||
'month' => $period === self::ALL_SCOPE ? null : $period,
|
||||
'month' => $period,
|
||||
'source_rows' => 0,
|
||||
'missing_item_count' => 0,
|
||||
'missing_row_count' => 0,
|
||||
@ -430,10 +273,9 @@ class AccountMappingCoverage
|
||||
/** @return array{status:string,message:string} */
|
||||
private function requestRefresh(string $period): array
|
||||
{
|
||||
$period = $this->normalizeRefreshKey($period);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => $this->platformNow()->toDateTimeString(),
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
try {
|
||||
@ -443,7 +285,7 @@ class AccountMappingCoverage
|
||||
$temporary = $pending . '.' . getmypid() . '.tmp';
|
||||
$payload = json_encode([
|
||||
'month' => $period,
|
||||
'requested_at' => $this->platformNow()->toDateTimeString(),
|
||||
'requested_at' => now()->toDateTimeString(),
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
if ($payload === false || File::put($temporary, $payload, true) === false) {
|
||||
throw new RuntimeException('无法写入未映射清单刷新请求。');
|
||||
@ -473,7 +315,7 @@ class AccountMappingCoverage
|
||||
continue;
|
||||
}
|
||||
$month = basename((string) $running, '.running');
|
||||
if ($this->isValidRefreshKey($month)) {
|
||||
if ($this->isValidMonth($month)) {
|
||||
File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true);
|
||||
}
|
||||
}
|
||||
@ -482,7 +324,7 @@ class AccountMappingCoverage
|
||||
sort($pendingFiles);
|
||||
foreach ($pendingFiles as $pending) {
|
||||
$month = basename((string) $pending, '.pending');
|
||||
if (! $this->isValidRefreshKey($month)) {
|
||||
if (! $this->isValidMonth($month)) {
|
||||
continue;
|
||||
}
|
||||
$running = $directory . DIRECTORY_SEPARATOR . $month . '.running';
|
||||
@ -515,7 +357,7 @@ class AccountMappingCoverage
|
||||
File::move($runningPath, $failed, true);
|
||||
File::put($failed, json_encode([
|
||||
'month' => $month,
|
||||
'failed_at' => $this->platformNow()->toDateTimeString(),
|
||||
'failed_at' => now()->toDateTimeString(),
|
||||
'message' => $error,
|
||||
], JSON_UNESCAPED_UNICODE), true);
|
||||
}
|
||||
@ -526,7 +368,7 @@ class AccountMappingCoverage
|
||||
return;
|
||||
}
|
||||
$month = basename($runningPath, '.running');
|
||||
if (! $this->isValidRefreshKey($month)) {
|
||||
if (! $this->isValidMonth($month)) {
|
||||
return;
|
||||
}
|
||||
File::move(
|
||||
@ -551,41 +393,7 @@ class AccountMappingCoverage
|
||||
*/
|
||||
private function readSnapshot(string $period, string $sourceKey): ?array
|
||||
{
|
||||
return $this->decodeSnapshot($this->snapshotPath($period, $sourceKey), $period, $sourceKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某类清单最近一次成功快照,不要求 source_key 与当前数据版本一致。
|
||||
* 这保证手动或月初刷新后的结果会一直保留到下一次成功刷新。
|
||||
*
|
||||
* @return array{
|
||||
* raw: array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>},
|
||||
* refreshed_at:string
|
||||
* }|null
|
||||
*/
|
||||
private function readLatestSnapshot(string $period): ?array
|
||||
{
|
||||
$paths = File::glob($this->snapshotDirectory() . DIRECTORY_SEPARATOR . $period . '-*.json') ?: [];
|
||||
usort($paths, static fn (string $left, string $right): int => @filemtime($right) <=> @filemtime($left));
|
||||
|
||||
foreach ($paths as $path) {
|
||||
$snapshot = $this->decodeSnapshot($path, $period);
|
||||
if ($snapshot !== null) {
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* raw: array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>},
|
||||
* refreshed_at:string
|
||||
* }|null
|
||||
*/
|
||||
private function decodeSnapshot(string $path, string $period, ?string $sourceKey = null): ?array
|
||||
{
|
||||
$path = $this->snapshotPath($period, $sourceKey);
|
||||
if (! File::isFile($path)) {
|
||||
return null;
|
||||
}
|
||||
@ -595,7 +403,7 @@ class AccountMappingCoverage
|
||||
if (! is_array($snapshot)
|
||||
|| (int) ($snapshot['version'] ?? 0) !== self::SNAPSHOT_VERSION
|
||||
|| (string) ($snapshot['month'] ?? '') !== $period
|
||||
|| ($sourceKey !== null && (string) ($snapshot['source_key'] ?? '') !== $sourceKey)
|
||||
|| (string) ($snapshot['source_key'] ?? '') !== $sourceKey
|
||||
|| ! is_array($snapshot['raw'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
@ -623,7 +431,7 @@ class AccountMappingCoverage
|
||||
'version' => self::SNAPSHOT_VERSION,
|
||||
'month' => $period,
|
||||
'source_key' => $sourceKey,
|
||||
'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : $this->platformNow()->toDateTimeString(),
|
||||
'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : now()->toDateTimeString(),
|
||||
'raw' => $raw,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
|
||||
@ -664,163 +472,6 @@ class AccountMappingCoverage
|
||||
. $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json';
|
||||
}
|
||||
|
||||
/** @return array{0:CarbonImmutable,1:CarbonImmutable} */
|
||||
private function allPeriodBounds(): array
|
||||
{
|
||||
try {
|
||||
$end = $this->platformNow()->endOfMonth();
|
||||
} catch (Throwable) {
|
||||
$end = CarbonImmutable::now()->endOfMonth();
|
||||
}
|
||||
|
||||
return [
|
||||
$end->startOfMonth()->subMonthsNoOverflow(self::ALL_SCOPE_MONTHS - 1),
|
||||
$end,
|
||||
];
|
||||
}
|
||||
|
||||
private function allSourceKey(): string
|
||||
{
|
||||
[$start, $end] = $this->allPeriodBounds();
|
||||
$parts = [$start->format('Y-m-d'), $end->format('Y-m-d')];
|
||||
foreach (self::SOURCES as $label => $source) {
|
||||
if ($source['periods'] === null) {
|
||||
$parts[] = $label . ':none';
|
||||
continue;
|
||||
}
|
||||
$parts[] = $label . ':' . implode(',', $this->generations(
|
||||
(string) $source['periods'],
|
||||
$start->toDateString(),
|
||||
$end->toDateString(),
|
||||
));
|
||||
}
|
||||
|
||||
return self::CACHE_PREFIX . self::ALL_SCOPE . ':' . hash('sha256', implode('|', $parts));
|
||||
}
|
||||
|
||||
private function monthSql(\Illuminate\Database\ConnectionInterface $connection, string $dateColumn): string
|
||||
{
|
||||
return match ($connection->getDriverName()) {
|
||||
'mysql', 'mariadb' => "DATE_FORMAT({$dateColumn}, '%Y-%m')",
|
||||
'pgsql' => "TO_CHAR({$dateColumn}, 'YYYY-MM')",
|
||||
'sqlite' => "strftime('%Y-%m', {$dateColumn})",
|
||||
default => throw new RuntimeException('当前数据库不支持跨月账单聚合。'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:string,
|
||||
* source_rows:int,
|
||||
* pending_sources:list<string>,
|
||||
* pairs:list<array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
private function buildAllSourceCoverage(CarbonImmutable $start, CarbonImmutable $end): array
|
||||
{
|
||||
$connection = $this->databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
$schema = $connection->getSchemaBuilder();
|
||||
$pairs = [];
|
||||
$sourceRows = 0;
|
||||
$pendingSources = [];
|
||||
|
||||
foreach (self::SOURCES as $label => $source) {
|
||||
$table = (string) $source['table'];
|
||||
if (! $schema->hasTable($table)) {
|
||||
throw new RuntimeException('账单表尚未迁移:' . $table);
|
||||
}
|
||||
|
||||
$dateColumn = (string) $source['date'];
|
||||
$query = $connection->table($table);
|
||||
if ($dateColumn === 'bill_date') {
|
||||
$query->whereBetween($dateColumn, [$start->toDateString(), $end->toDateString()]);
|
||||
} else {
|
||||
$query->whereBetween($dateColumn, [
|
||||
$start->toDateString() . ' 00:00:00',
|
||||
$end->toDateString() . ' 23:59:59',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($source['periods'] !== null) {
|
||||
$generations = $this->generations(
|
||||
(string) $source['periods'],
|
||||
$start->toDateString(),
|
||||
$end->toDateString(),
|
||||
);
|
||||
if ($generations === []) {
|
||||
$pendingSources[] = $label;
|
||||
continue;
|
||||
}
|
||||
$query->whereIn('generation', $generations);
|
||||
}
|
||||
|
||||
$monthExpression = $this->monthSql($connection, $dateColumn);
|
||||
$platformExpression = $this->platformSql($connection);
|
||||
$itemExpression = $this->normalizedItemSql();
|
||||
$groups = $query
|
||||
->selectRaw($monthExpression . ' AS bill_month')
|
||||
->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item')
|
||||
->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count')
|
||||
->groupByRaw($monthExpression . ', ' . $platformExpression . ', ' . $itemExpression)
|
||||
->cursor();
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$month = trim((string) $group->bill_month);
|
||||
if (! $this->isValidMonth($month)) {
|
||||
continue;
|
||||
}
|
||||
$rows = (int) $group->source_rows;
|
||||
$sourceRows += $rows;
|
||||
$item = trim((string) $group->item);
|
||||
$displayItem = $item === '' ? '(未填写账单项目)' : $item;
|
||||
$platform = trim((string) $group->platform);
|
||||
$key = $platform . "\0" . $displayItem;
|
||||
|
||||
if (! isset($pairs[$key])) {
|
||||
$pairs[$key] = [
|
||||
'platform' => $platform,
|
||||
'platform_label' => $platform === '' ? '未识别平台' : $platform,
|
||||
'item' => $displayItem,
|
||||
'source_rows' => 0,
|
||||
'store_count' => 0,
|
||||
'source_labels' => [],
|
||||
'raw_items' => [],
|
||||
'month_rows' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$pairs[$key]['source_rows'] += $rows;
|
||||
$pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows;
|
||||
$pairs[$key]['raw_items'][$displayItem] = true;
|
||||
$pairs[$key]['month_rows'][$month] = ($pairs[$key]['month_rows'][$month] ?? 0) + $rows;
|
||||
$pairs[$key]['store_count'] = max(
|
||||
(int) $pairs[$key]['store_count'],
|
||||
(int) $group->store_count,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($pairs as &$pair) {
|
||||
ksort($pair['month_rows']);
|
||||
$pair['months'] = array_keys($pair['month_rows']);
|
||||
$pair['raw_items'] = array_values(array_filter(
|
||||
array_keys($pair['raw_items']),
|
||||
static fn (string $item): bool => $item !== '',
|
||||
));
|
||||
$pair['source_labels'] = array_keys($pair['source_labels']);
|
||||
}
|
||||
unset($pair);
|
||||
|
||||
return [
|
||||
'status' => $sourceRows > 0 ? 'ready' : 'unavailable',
|
||||
'source_rows' => $sourceRows,
|
||||
'pending_sources' => $pendingSources,
|
||||
'pairs' => array_values($pairs),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:string,
|
||||
@ -1059,21 +710,6 @@ class AccountMappingCoverage
|
||||
return $month;
|
||||
}
|
||||
|
||||
private function normalizeRefreshKey(string $key): string
|
||||
{
|
||||
$key = trim($key);
|
||||
if ($key === self::ALL_SCOPE) {
|
||||
return self::ALL_SCOPE;
|
||||
}
|
||||
|
||||
return $this->parseMonth($key);
|
||||
}
|
||||
|
||||
private function isValidRefreshKey(string $key): bool
|
||||
{
|
||||
return $key === self::ALL_SCOPE || $this->isValidMonth($key);
|
||||
}
|
||||
|
||||
private function isValidMonth(string $month): bool
|
||||
{
|
||||
try {
|
||||
@ -1083,19 +719,4 @@ class AccountMappingCoverage
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function platformTimezone(): string
|
||||
{
|
||||
$timezone = trim((string) config('app.platform_timezone', ''));
|
||||
if ($timezone === '') {
|
||||
$timezone = (string) config('app.timezone', 'UTC');
|
||||
}
|
||||
|
||||
return $timezone;
|
||||
}
|
||||
|
||||
private function platformNow(): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::now($this->platformTimezone());
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,167 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
/**
|
||||
* 为「补映射」查找可复用的同名账单项目规则。
|
||||
*
|
||||
* 账单项目在多个平台出现时,科目模板通常完全相同(例如京东和京喜的
|
||||
* POP商家激励金)。这里只在规范化名称完全一致、并且所有候选规则的
|
||||
* 映射字段一致时自动带入;名称相似但口径可能不同的项目不做猜测。
|
||||
*/
|
||||
class AccountMappingSuggestion
|
||||
{
|
||||
/** @var list<string> */
|
||||
private const COPY_FIELDS = [
|
||||
'memo',
|
||||
'invoice',
|
||||
'category',
|
||||
'feeMemo',
|
||||
'dAcct',
|
||||
'dSub',
|
||||
'cAcct',
|
||||
'cSub',
|
||||
'basis',
|
||||
];
|
||||
|
||||
/** @var list<string> */
|
||||
private const REQUIRED_FIELDS = ['category', 'dAcct', 'cAcct', 'basis'];
|
||||
|
||||
public function __construct(
|
||||
private readonly AccountMappingStore $store,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* auto_fill:bool,
|
||||
* reason:string,
|
||||
* matched_count:int,
|
||||
* sources:list<array<string,mixed>>,
|
||||
* values:array<string,string>
|
||||
* }
|
||||
*/
|
||||
public function suggest(string $platform, string $item): array
|
||||
{
|
||||
return $this->suggestFromRules($this->store->all(), $platform, $item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,array<string,mixed>> $rules
|
||||
* @return array{
|
||||
* auto_fill:bool,
|
||||
* reason:string,
|
||||
* matched_count:int,
|
||||
* sources:list<array<string,mixed>>,
|
||||
* values:array<string,string>
|
||||
* }
|
||||
*/
|
||||
public function suggestFromRules(array $rules, string $platform, string $item): array
|
||||
{
|
||||
$platform = trim($platform);
|
||||
$item = trim($item);
|
||||
$itemKey = $this->normalizeItem($item);
|
||||
|
||||
if ($itemKey === '') {
|
||||
return $this->emptyResult('invalid_item');
|
||||
}
|
||||
|
||||
$matches = [];
|
||||
foreach ($rules as $rule) {
|
||||
if (! is_array($rule)
|
||||
|| $this->normalizeItem((string) ($rule['item'] ?? '')) !== $itemKey) {
|
||||
continue;
|
||||
}
|
||||
$matches[] = $rule;
|
||||
}
|
||||
|
||||
if ($matches === []) {
|
||||
return $this->emptyResult('no_same_item');
|
||||
}
|
||||
|
||||
usort($matches, static fn (array $left, array $right): int => (
|
||||
((string) ($left['platform'] ?? '') === $platform ? 0 : 1)
|
||||
<=> ((string) ($right['platform'] ?? '') === $platform ? 0 : 1)
|
||||
) ?: (((int) ($left['id'] ?? 0)) <=> ((int) ($right['id'] ?? 0))));
|
||||
|
||||
$templates = [];
|
||||
foreach ($matches as $rule) {
|
||||
$templates[$this->templateSignature($rule)] = true;
|
||||
}
|
||||
|
||||
$sources = array_map(
|
||||
static fn (array $rule): array => [
|
||||
'id' => (int) ($rule['id'] ?? 0),
|
||||
'platform' => trim((string) ($rule['platform'] ?? '')),
|
||||
'item' => trim((string) ($rule['item'] ?? '')),
|
||||
'memo' => trim((string) ($rule['memo'] ?? '')),
|
||||
],
|
||||
array_slice($matches, 0, 8),
|
||||
);
|
||||
$base = [
|
||||
'matched_count' => count($matches),
|
||||
'sources' => $sources,
|
||||
'values' => [],
|
||||
];
|
||||
|
||||
if (count($templates) > 1) {
|
||||
return ['auto_fill' => false, 'reason' => 'ambiguous_templates'] + $base;
|
||||
}
|
||||
|
||||
$template = $matches[0];
|
||||
foreach (self::REQUIRED_FIELDS as $field) {
|
||||
if (trim((string) ($template[$field] ?? '')) === '') {
|
||||
return ['auto_fill' => false, 'reason' => 'incomplete_template'] + $base;
|
||||
}
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach (self::COPY_FIELDS as $field) {
|
||||
$values[$field] = trim((string) ($template[$field] ?? ''));
|
||||
}
|
||||
|
||||
return [
|
||||
'auto_fill' => true,
|
||||
'reason' => 'same_item',
|
||||
] + array_replace($base, ['values' => $values]);
|
||||
}
|
||||
|
||||
public function normalizeItem(string $item): string
|
||||
{
|
||||
$item = mb_strtolower(trim($item));
|
||||
$item = preg_replace('/^wx/u', '', $item) ?? $item;
|
||||
|
||||
return preg_replace('/[\s\x{3000}\p{P}\p{S}]+/u', '', $item) ?? $item;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $rule */
|
||||
private function templateSignature(array $rule): string
|
||||
{
|
||||
$values = [];
|
||||
foreach (self::COPY_FIELDS as $field) {
|
||||
$values[$field] = trim((string) ($rule[$field] ?? ''));
|
||||
}
|
||||
|
||||
return json_encode($values, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* auto_fill:bool,
|
||||
* reason:string,
|
||||
* matched_count:int,
|
||||
* sources:list<array<string,mixed>>,
|
||||
* values:array<string,string>
|
||||
* }
|
||||
*/
|
||||
private function emptyResult(string $reason): array
|
||||
{
|
||||
return [
|
||||
'auto_fill' => false,
|
||||
'reason' => $reason,
|
||||
'matched_count' => 0,
|
||||
'sources' => [],
|
||||
'values' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -63,8 +63,6 @@ final class BankBillStatementImporter
|
||||
$bankName = BankBillTemplateExporter::storageBankName($templateBank);
|
||||
$isHuaxiaPersonal = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||
&& $templateBank === '华夏银行个人卡';
|
||||
$isCmbPersonal = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||
&& $templateBank === '招商银行个人卡';
|
||||
$isAgriculturalMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||
&& $templateBank === '农业银行';
|
||||
$isJiangnanMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||
@ -87,8 +85,6 @@ final class BankBillStatementImporter
|
||||
[$headerRow, $headers, $metadata] = $this->huaxiaMonthlyHeaderAndMetadata($reader);
|
||||
} elseif ($templateBank === '华夏银行个人卡') {
|
||||
[$headerRow, $headers, $metadata] = $this->huaxiaPersonalHeaderAndMetadata($reader);
|
||||
} elseif ($isCmbPersonal) {
|
||||
[$headerRow, $headers, $metadata] = $this->cmbPersonalHeaderAndMetadata($reader);
|
||||
} elseif ($templateBank === '农业银行') {
|
||||
[$headerRow, $headers, $metadata] = $this->agriculturalMonthlyHeaderAndMetadata($reader);
|
||||
} elseif ($templateBank === '江南农商行') {
|
||||
@ -196,10 +192,6 @@ final class BankBillStatementImporter
|
||||
if ($isHuaxiaPersonal && $this->isHuaxiaPersonalFooterRow($cells)) {
|
||||
continue;
|
||||
}
|
||||
if ($isCmbPersonal
|
||||
&& str_starts_with($this->normaliseCell($cells[0] ?? null), '#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rawData = [];
|
||||
foreach ($sourceIndexByKey as $sourceIndex => $columnKey) {
|
||||
@ -230,11 +222,10 @@ final class BankBillStatementImporter
|
||||
$accountNo = match (true) {
|
||||
$bankName === '网商银行',
|
||||
$isBocMonthly,
|
||||
$isCmbPersonal,
|
||||
$isHuaxiaPersonal,
|
||||
$isAgriculturalMonthly,
|
||||
$isJiangnanMonthly,
|
||||
$isAlipayMonthly => (string) ($metadata['account_no'] ?? ''),
|
||||
$isHuaxiaPersonal => $this->huaxiaPersonalAccountNumber($metadata, $accountsByNumber),
|
||||
default => $this->accountNumber($valuesByLabel),
|
||||
};
|
||||
$account = $accountsByNumber[$this->digits($accountNo)] ?? null;
|
||||
@ -252,7 +243,7 @@ final class BankBillStatementImporter
|
||||
$companyName = match (true) {
|
||||
$bankName === '网商银行' => (string) ($metadata['company_name'] ?? ''),
|
||||
$isBocMonthly => $this->bocAccountHolderName($valuesByLabel),
|
||||
$isHuaxiaPersonal, $isCmbPersonal, $isAgriculturalMonthly => (string) ($metadata['company_name'] ?? ''),
|
||||
$isHuaxiaPersonal, $isAgriculturalMonthly => (string) ($metadata['company_name'] ?? ''),
|
||||
$isJiangnanMonthly => (string) ($account->company_name ?? ''),
|
||||
default => (string) ($metadata['company_name'] ?? $this->firstValue(
|
||||
$valuesByLabel,
|
||||
@ -318,10 +309,6 @@ final class BankBillStatementImporter
|
||||
$counterpartyName = $counterparty['name'];
|
||||
$counterpartyAccount = $counterparty['account'];
|
||||
$counterpartyBank = $counterparty['bank'];
|
||||
} elseif ($isCmbPersonal) {
|
||||
$counterpartyName = $this->firstValue($valuesByLabel, ['交易备注']);
|
||||
$counterpartyAccount = '';
|
||||
$counterpartyBank = '';
|
||||
} else {
|
||||
$counterpartyName = $this->firstValue(
|
||||
$valuesByLabel,
|
||||
@ -368,7 +355,6 @@ final class BankBillStatementImporter
|
||||
'交易附言[ Remark ]',
|
||||
'用途[ Purpose ]',
|
||||
'备注[ Remarks ]',
|
||||
'交易备注',
|
||||
],
|
||||
);
|
||||
$currency = $bankName === '网商银行'
|
||||
@ -879,8 +865,11 @@ final class BankBillStatementImporter
|
||||
}
|
||||
|
||||
$companyName = trim((string) ($rawMetadata['company_name'] ?? ''));
|
||||
$accountNo = $this->digits((string) ($rawMetadata['account_no'] ?? ''));
|
||||
$cardNo = $this->digits((string) ($rawMetadata['card_no'] ?? ''));
|
||||
$accountNo = $this->digits((string) (
|
||||
$rawMetadata['account_no']
|
||||
?? $rawMetadata['card_no']
|
||||
?? ''
|
||||
));
|
||||
if ($accountNo === '') {
|
||||
throw new InvalidArgumentException('华夏银行个人卡明细缺少“账号”或“卡号”。');
|
||||
}
|
||||
@ -892,103 +881,12 @@ final class BankBillStatementImporter
|
||||
'company_name' => $companyName,
|
||||
'account_short' => $companyName,
|
||||
'account_no' => $accountNo,
|
||||
'card_no' => $cardNo,
|
||||
'card_no' => $this->digits((string) ($rawMetadata['card_no'] ?? '')),
|
||||
'currency' => trim((string) ($rawMetadata['currency'] ?? '')) ?: '人民币',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function huaxiaPersonalAccountNumber(array $metadata, array $accountsByNumber): string
|
||||
{
|
||||
$cardNo = $this->digits((string) ($metadata['card_no'] ?? ''));
|
||||
if ($cardNo !== '' && isset($accountsByNumber[$cardNo])) {
|
||||
return $cardNo;
|
||||
}
|
||||
|
||||
return $this->digits((string) ($metadata['account_no'] ?? ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:int,1:array<int,string>,2:array<string,mixed>}
|
||||
*/
|
||||
private function cmbPersonalHeaderAndMetadata(PayablesWorkbookStreamReader $reader): array
|
||||
{
|
||||
$requiredHeaders = BankBillTemplateExporter::headers(
|
||||
'招商银行个人卡',
|
||||
BankBillTemplateExporter::SCOPE_NON_DIRECT,
|
||||
);
|
||||
$headerRow = null;
|
||||
$headers = [];
|
||||
$maskedAccountNo = '';
|
||||
|
||||
foreach ($reader->rows(0, null, 20) as $rowNumber => $cells) {
|
||||
$values = array_map(fn (mixed $value): string => $this->normaliseCell($value), $cells);
|
||||
foreach ($values as $value) {
|
||||
if ($maskedAccountNo === ''
|
||||
&& preg_match('/一卡通\s*[::]\s*([0-9*]{8,})/u', $value, $matches) === 1) {
|
||||
$maskedAccountNo = trim($matches[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$candidateHeaders = [];
|
||||
foreach ($values as $index => $value) {
|
||||
if ($value !== '') {
|
||||
$candidateHeaders[(int) $index] = $value;
|
||||
}
|
||||
}
|
||||
if (count(array_intersect(array_values($candidateHeaders), $requiredHeaders))
|
||||
=== count($requiredHeaders)) {
|
||||
$headerRow = $rowNumber;
|
||||
$headers = $candidateHeaders;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($headerRow === null) {
|
||||
throw new InvalidArgumentException('没有找到招商银行个人卡交易明细表头。');
|
||||
}
|
||||
if (preg_match('/^(\d{4})\*+(\d{4})$/u', $maskedAccountNo, $matches) !== 1) {
|
||||
throw new InvalidArgumentException('招商银行个人卡明细缺少可用的一卡通账号信息。');
|
||||
}
|
||||
|
||||
$prefix = $matches[1];
|
||||
$suffix = $matches[2];
|
||||
$accounts = $this->connection->table('fin_accounts')
|
||||
->where('account_type', '个人卡')
|
||||
->where(static function ($query): void {
|
||||
$query->where('bank_name', 'like', '%招商银行%')
|
||||
->orWhere('account_short', 'like', '%招商银行%');
|
||||
})
|
||||
->whereNotNull('account_no')
|
||||
->where('account_no', '<>', '')
|
||||
->get(['id', 'company_name', 'account_short', 'account_no'])
|
||||
->filter(static function (object $account) use ($prefix, $suffix): bool {
|
||||
$accountNo = preg_replace('/\D+/', '', (string) $account->account_no) ?? '';
|
||||
|
||||
return str_starts_with($accountNo, $prefix) && str_ends_with($accountNo, $suffix);
|
||||
})
|
||||
->values();
|
||||
|
||||
if ($accounts->count() !== 1) {
|
||||
throw new InvalidArgumentException($accounts->isEmpty()
|
||||
? sprintf('未找到招商银行一卡通“%s********%s”对应的个人卡账户。', $prefix, $suffix)
|
||||
: sprintf('招商银行一卡通“%s********%s”匹配到多个个人卡账户,无法自动定位。', $prefix, $suffix));
|
||||
}
|
||||
|
||||
$account = $accounts->first();
|
||||
|
||||
return [
|
||||
$headerRow,
|
||||
$headers,
|
||||
[
|
||||
'company_name' => (string) $account->company_name,
|
||||
'account_short' => (string) $account->account_short,
|
||||
'account_no' => preg_replace('/\D+/', '', (string) $account->account_no) ?? '',
|
||||
'currency' => '人民币',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:int,1:array<int,string>,2:array<string,mixed>}
|
||||
*/
|
||||
|
||||
@ -124,15 +124,6 @@ final class BankBillTemplateExporter
|
||||
'对方开户行',
|
||||
'附言',
|
||||
],
|
||||
'招商银行个人卡' => [
|
||||
'交易日期',
|
||||
'交易时间',
|
||||
'收入',
|
||||
'支出',
|
||||
'余额',
|
||||
'交易类型',
|
||||
'交易备注',
|
||||
],
|
||||
'杭州银行' => [
|
||||
'序号',
|
||||
'交易时间',
|
||||
@ -281,7 +272,6 @@ final class BankBillTemplateExporter
|
||||
'label' => match ($bank) {
|
||||
'中国工商银行' => '工商银行 PDF 明细',
|
||||
'华夏银行个人卡' => '华夏银行个人卡明细',
|
||||
'招商银行个人卡' => '招商银行个人卡明细',
|
||||
'支付宝' => '支付宝账单模板',
|
||||
'农业银行' => '农业银行明细',
|
||||
default => $bank . '月度模板',
|
||||
@ -354,18 +344,16 @@ final class BankBillTemplateExporter
|
||||
|
||||
return match ($bank) {
|
||||
'中国工商银行' => 'pdf',
|
||||
'华夏银行个人卡', '招商银行个人卡', '农业银行', '江南农商行' => self::FORMAT_BANK_FILE,
|
||||
'华夏银行个人卡', '农业银行', '江南农商行' => self::FORMAT_BANK_FILE,
|
||||
default => 'xlsx',
|
||||
};
|
||||
}
|
||||
|
||||
public static function storageBankName(string $templateBank): string
|
||||
{
|
||||
return match ($templateBank) {
|
||||
'华夏银行个人卡' => '华夏银行',
|
||||
'招商银行个人卡' => '招商银行',
|
||||
default => $templateBank,
|
||||
};
|
||||
return $templateBank === '华夏银行个人卡'
|
||||
? '华夏银行'
|
||||
: $templateBank;
|
||||
}
|
||||
|
||||
public static function uploadOnlyMessage(string $bank, string $scope): ?string
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
/** 快递应付的记账明细,沿用财务手工表的 34 列。 */
|
||||
class CourierBookkeepingRegistry
|
||||
{
|
||||
public function fields(): array
|
||||
{
|
||||
$text = static fn (string $label): array => ['label' => $label, 'type' => 'text'];
|
||||
$money = static fn (string $label): array => ['label' => $label, 'type' => 'number'];
|
||||
|
||||
return [
|
||||
'tracking_no' => $text('物流单号'), 'tracking_no_clean' => $text('快递单号整理'), 'carrier' => $text('物流公司'),
|
||||
'online_order_no' => $text('线上订单号'), 'bookkeeping_reason' => $text('记账原因'), 'product_code' => $text('商品编码'),
|
||||
'product_name' => $text('商品名称'), 'amount' => $money('记账金额'), 'bookkeeping_data' => $text('记账数据'),
|
||||
'receiver' => $text('收货人'), 'initiator' => $text('发起人'), 'started_at' => $text('发起时间'),
|
||||
'shop_name' => $text('店铺名称'), 'buyer_nick' => $text('买家昵称'), 'province' => $text('省份'),
|
||||
'deducted_at' => $text('扣单时间'), 'cost' => $money('成本'), 'weight' => $money('重量'), 'loss' => $money('损耗'),
|
||||
'owner' => $text('负责人'), 'platform_product_id' => $text('平台商品id'), 'shipping_warehouse' => $text('订单发货仓库'),
|
||||
'supplier' => $text('供应商'), 'unshipped' => $text('未发出'), 'return_no' => $text('退回单号'), 'scrapped' => $text('报废'),
|
||||
'cost_bookkeeping' => $money('成本记账'), 'settle_bookkeeping' => $money('结算记账'), 'settle_freight' => $money('结算运费'),
|
||||
'analysis' => $text('记账分析'), 'dropship' => $text('是否代发'), 'courier_feedback' => $text('快递反馈'),
|
||||
'cs_reply' => $text('客服回复'), 'cause' => $text('原因'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -27,27 +27,19 @@ class CourierPayableFinalRegistry
|
||||
$month = static fn (string $label): array => ['label' => $label, 'type' => 'month'];
|
||||
|
||||
return match ($dataset) {
|
||||
// 表头照财务手工「记账」表(2026 年 10 月起)
|
||||
'bookkeeping-details' => [
|
||||
'started_at' => $text('发起时间'), 'work_order_no' => $text('工单编号'), 'initiator' => $text('发起人'),
|
||||
'bookkeeping_reason' => $text('记账原因'), 'reason_level_1' => $text('记账原因-一级选项'),
|
||||
'reason_level_2' => $text('记账原因-二级选项'), 'reason_level_3' => $text('记账原因-三级选项'),
|
||||
'bookkeeping_type' => $text('记账类型'), 'executor' => $text('执行人'), 'source' => $text('记账来源'),
|
||||
'amount' => $money('记账金额'), 'remark' => $text('记账备注说明'), 'attachment' => $text('上传附件'),
|
||||
'attachment_preview' => $text('上传附件(预览)'), 'online_order_no' => $text('线上订单号'),
|
||||
'internal_order_no' => $text('内部单号'), 'actual_paid_amount' => $money('实付金额'),
|
||||
'carrier' => $text('物流公司'), 'tracking_no' => $text('物流单号'), 'shop_name' => $text('店铺名称'),
|
||||
'platform' => $text('平台'), 'shipping_warehouse' => $text('订单发货仓库'),
|
||||
'processing_status' => $text('记账处理状态'), 'counterparty_agreed' => $text('被记账方是否同意记账'),
|
||||
'counterparty_note' => $text('被记账方处理说明'), 'specialist_result' => $text('专员记账判定结果'),
|
||||
'specialist_note' => $text('专员处理说明'), 'updated_at' => $text('修改时间'),
|
||||
'work_order_type' => $text('工单类型'), 'product_image' => $text('商品图片'),
|
||||
'product_code' => $text('商品编码'), 'style_code' => $text('款式编码'),
|
||||
'other_attribute_6' => $text('其它属性6'), 'product_name' => $text('商品名称'),
|
||||
'platform_sku_id' => $text('平台商品skuid'), 'platform_product_id' => $text('平台商品id'),
|
||||
'product_quantity' => $money('商品数量'), 'product_price' => $money('商品价格'),
|
||||
'product_amount' => $money('商品金额'), 'buyer_paid_amount' => $money('买家实付'),
|
||||
'supplier' => $text('供应商'), 'accepting_department' => $text('受理部门'),
|
||||
'order_shipped_at' => $text('订单发货时间'), 'work_order_remark' => $text('工单备注'),
|
||||
'tracking_no' => $text('物流单号'), 'tracking_no_clean' => $text('快递单号整理'), 'carrier' => $text('物流公司'),
|
||||
'online_order_no' => $text('线上订单号'), 'bookkeeping_reason' => $text('记账原因'), 'product_code' => $text('商品编码'),
|
||||
'product_name' => $text('商品名称'), 'amount' => $money('记账金额'), 'bookkeeping_data' => $text('记账数据'),
|
||||
'receiver' => $text('收货人'), 'initiator' => $text('发起人'), 'started_at' => $text('发起时间'),
|
||||
'shop_name' => $text('店铺名称'), 'buyer_nick' => $text('买家昵称'), 'province' => $text('省份'),
|
||||
'deducted_at' => $text('扣单时间'), 'cost' => $money('成本'), 'weight' => $money('重量'), 'loss' => $money('损耗'),
|
||||
'owner' => $text('负责人'), 'platform_product_id' => $text('平台商品id'), 'shipping_warehouse' => $text('订单发货仓库'),
|
||||
'supplier' => $text('供应商'), 'unshipped' => $text('未发出'), 'return_no' => $text('退回单号'), 'scrapped' => $text('报废'),
|
||||
'cost_bookkeeping' => $money('成本记账'), 'settle_bookkeeping' => $money('结算记账'), 'settle_freight' => $money('结算运费'),
|
||||
'analysis' => $text('记账分析'), 'dropship' => $text('是否代发'), 'courier_feedback' => $text('快递反馈'),
|
||||
'cs_reply' => $text('客服回复'), 'cause' => $text('原因'),
|
||||
],
|
||||
'compensation-details' => [
|
||||
'paid_at' => $date('赔付日期'), 'carrier' => $text('承运商'), 'tracking_no' => $text('快递单号'),
|
||||
|
||||
@ -1,199 +0,0 @@
|
||||
<?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 };
|
||||
}
|
||||
}
|
||||
@ -67,11 +67,7 @@ final class FinanceLedgerBankBalanceCurrentCalculator
|
||||
continue;
|
||||
}
|
||||
|
||||
$useBankBillBaseline = $bill !== null
|
||||
&& ($opening === null
|
||||
|| substr((string) $bill['txn_date'], 0, 10)
|
||||
>= substr((string) $opening->opening_date, 0, 10));
|
||||
$details[$accountShort] = $useBankBillBaseline
|
||||
$details[$accountShort] = $bill !== null
|
||||
? [
|
||||
'balance' => round((float) $bill['balance'], 2),
|
||||
'balance_source' => 'bank_bill_plus_transactions',
|
||||
|
||||
@ -1233,7 +1233,6 @@ final class FreightCarrierRules
|
||||
'四强圆通' => [
|
||||
'mode' => 'A',
|
||||
'coef' => 10000,
|
||||
'ceil' => true,
|
||||
],
|
||||
'木际邮政' => [
|
||||
'mode' => 'E',
|
||||
|
||||
@ -7,34 +7,6 @@ use Illuminate\Validation\ValidationException;
|
||||
/** 按字段定义校验并整理按表维护/导入的字段值。 */
|
||||
class PayablesFieldNormalizer
|
||||
{
|
||||
/** 导入允许清除 Excel 的微小十进制尾差,手工编辑仍执行严格精度校验。 */
|
||||
public function normalizeImport(array $fields, array $input): array
|
||||
{
|
||||
foreach ($fields as $field => $definition) {
|
||||
if ($definition['type'] !== 'number' || ! isset($input[$field])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$number = str_replace([',', ',', '¥', '¥'], '', trim((string) $input[$field]));
|
||||
if (preg_match('/^-?(?:\d+)?\.\d{5,}$/', $number) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 全程十进制运算,不把金额或大整数转成 float。
|
||||
$magnitude = ltrim($number, '-');
|
||||
$scale = strlen(explode('.', $number, 2)[1]);
|
||||
$rounded = bcadd($magnitude, '0.00005', 4);
|
||||
$difference = ltrim(bcsub($magnitude, $rounded, $scale), '-');
|
||||
if (bccomp($difference, '0.000000000001', max(12, $scale)) <= 0) {
|
||||
$input[$field] = str_starts_with($number, '-') && bccomp($rounded, '0', 4) !== 0
|
||||
? '-' . $rounded
|
||||
: $rounded;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->normalize($fields, $input);
|
||||
}
|
||||
|
||||
/** @param array<string,array{label:string,type:string}> $fields */
|
||||
public function normalize(array $fields, array $input): array
|
||||
{
|
||||
|
||||
@ -212,7 +212,7 @@ class PayablesFinalImportRunner
|
||||
unset($values['_action_key'], $values['__import_row_key']);
|
||||
|
||||
try {
|
||||
$normalized = $this->normalizer->normalizeImport($fields, $values);
|
||||
$normalized = $this->normalizer->normalize($fields, $values);
|
||||
} catch (ValidationException $exception) {
|
||||
$this->fail($meta, $line - 1, $created, $updated, $this->rowMessage($firstRow, $line, $exception));
|
||||
throw ValidationException::withMessages([
|
||||
|
||||
@ -99,7 +99,7 @@ class PayablesFinalImporter
|
||||
}
|
||||
|
||||
try {
|
||||
$values = $this->normalizer->normalizeImport($fields, $rawValues);
|
||||
$values = $this->normalizer->normalize($fields, $rawValues);
|
||||
} catch (ValidationException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),
|
||||
|
||||
@ -5,8 +5,8 @@ namespace Modules\EcommerceFinance\Services;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* 按表维护的数据登记:确定终版页签和快递记账明细的字段、标题与存储键。
|
||||
* 各目录的数据独立存放。
|
||||
* 「终版」目录的按表数据登记:确定每个页签的字段(决定导入模板与表格列)
|
||||
* 以及数据标题;数据本身独立存放,与基础目录互不影响。
|
||||
*/
|
||||
class PayablesFinalRegistry
|
||||
{
|
||||
@ -14,8 +14,6 @@ class PayablesFinalRegistry
|
||||
|
||||
public const SECTION_COURIER = 'courier-payables-final';
|
||||
|
||||
public const SECTION_COURIER_BASE = 'courier-payables';
|
||||
|
||||
/** @var array<string,string> 供应商应付(终版)页签 */
|
||||
private const SUPPLIER_TITLES = [
|
||||
'product-prices' => '商品价格',
|
||||
@ -119,7 +117,6 @@ class PayablesFinalRegistry
|
||||
private readonly SupplierPayableMaintenanceRegistry $supplier,
|
||||
private readonly ProductPriceWorkbookImporter $productPrices,
|
||||
private readonly CourierPayableFinalRegistry $courier,
|
||||
private readonly CourierBookkeepingRegistry $bookkeeping,
|
||||
) {
|
||||
}
|
||||
|
||||
@ -134,7 +131,6 @@ class PayablesFinalRegistry
|
||||
return match ($section) {
|
||||
self::SECTION_SUPPLIER => self::SUPPLIER_TITLES,
|
||||
self::SECTION_COURIER => $this->courier->titles(),
|
||||
self::SECTION_COURIER_BASE => ['bookkeeping-details' => '记账明细'],
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
@ -143,7 +139,7 @@ class PayablesFinalRegistry
|
||||
{
|
||||
$titles = $this->titles($section);
|
||||
if (! array_key_exists($dataset, $titles)) {
|
||||
throw ValidationException::withMessages(['dataset' => '不支持该数据维护页面。']);
|
||||
throw ValidationException::withMessages(['dataset' => '不支持该终版目录页面。']);
|
||||
}
|
||||
|
||||
return $titles[$dataset];
|
||||
@ -154,10 +150,6 @@ class PayablesFinalRegistry
|
||||
{
|
||||
$this->title($section, $dataset);
|
||||
|
||||
if ($section === self::SECTION_COURIER_BASE) {
|
||||
return self::MONTH_FIELD + $this->bookkeeping->fields();
|
||||
}
|
||||
|
||||
if ($section === self::SECTION_COURIER) {
|
||||
return self::MONTH_FIELD + $this->courier->fields($dataset);
|
||||
}
|
||||
@ -177,17 +169,6 @@ class PayablesFinalRegistry
|
||||
return self::MONTH_FIELD + $this->patchSupplierFields($dataset, $fields);
|
||||
}
|
||||
|
||||
public function storeDataset(string $section, string $dataset): string
|
||||
{
|
||||
$this->title($section, $dataset);
|
||||
|
||||
return match ($section) {
|
||||
self::SECTION_COURIER_BASE => 'courier:' . $dataset,
|
||||
self::SECTION_COURIER => 'final:courier:' . $dataset,
|
||||
default => 'final:supplier:' . $dataset,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,array{label:string,type:string}> $fields
|
||||
* @return array<string,array{label:string,type:string}>
|
||||
|
||||
@ -298,14 +298,12 @@ final class PerformanceDetailSubjectMatcher
|
||||
|
||||
private function rowDate(object $row): string
|
||||
{
|
||||
foreach (['occurred_date', 'occurred_at', 'report_month'] as $property) {
|
||||
$date = trim((string) ($row->{$property} ?? ''));
|
||||
if ($date !== '') {
|
||||
return substr($date, 0, 10);
|
||||
}
|
||||
$date = trim((string) ($row->occurred_date ?? ''));
|
||||
if ($date !== '') {
|
||||
return substr($date, 0, 10);
|
||||
}
|
||||
|
||||
return '';
|
||||
return substr(trim((string) ($row->report_month ?? '')), 0, 10);
|
||||
}
|
||||
|
||||
private function normalize(mixed $value): string
|
||||
|
||||
@ -1,137 +0,0 @@
|
||||
<?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()];
|
||||
}
|
||||
}
|
||||
@ -324,138 +324,6 @@ class SupplierPayableOverrideStore
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按记录顺序逐行读取数据集,供大文件导出使用。
|
||||
*
|
||||
* @return iterable<int,array<string,mixed>>
|
||||
*/
|
||||
public function streamRows(string $dataset, int $companyId): iterable
|
||||
{
|
||||
$records = $this->connection()->table('supplier_payable_overrides')
|
||||
->where('company_id', $companyId)
|
||||
->where('dataset', $dataset)
|
||||
->orderBy('id')
|
||||
->select(['record_key', 'values'])
|
||||
->cursor();
|
||||
|
||||
foreach ($records as $record) {
|
||||
$values = json_decode((string) $record->values, true) ?: [];
|
||||
$values['_action_key'] = (string) $record->record_key;
|
||||
|
||||
yield $values;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按厂家汇总指定筛选范围的数量和金额,供财务端进度概览使用。
|
||||
*
|
||||
* @return array<string,array{rows:int,qty:float,amount:float}>
|
||||
*/
|
||||
public function summarizeBySupplierForFilters(
|
||||
string $dataset,
|
||||
int $companyId,
|
||||
string $month = '',
|
||||
string $reconciler = '',
|
||||
): array {
|
||||
$connection = $this->connection();
|
||||
$query = $connection->table('supplier_payable_overrides')
|
||||
->where('company_id', $companyId)
|
||||
->where('dataset', $dataset);
|
||||
if ($month !== '') {
|
||||
$this->whereMonth($query, $connection, $month, false);
|
||||
}
|
||||
if ($reconciler !== '') {
|
||||
$query->where('values->reconciler', $reconciler);
|
||||
}
|
||||
|
||||
$supplierExpression = $this->jsonStringExpression($connection, 'supplier');
|
||||
$qtyExpression = $this->jsonNumberExpression($connection, 'qty');
|
||||
$amountExpression = $this->jsonNumberExpression($connection, 'amount');
|
||||
$rows = $query
|
||||
->selectRaw("{$supplierExpression} AS supplier_name")
|
||||
->selectRaw('COUNT(*) AS row_count')
|
||||
->selectRaw("SUM({$qtyExpression}) AS qty_total")
|
||||
->selectRaw("SUM({$amountExpression}) AS amount_total")
|
||||
->groupByRaw($supplierExpression)
|
||||
->get();
|
||||
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$supplier = trim((string) ($row->supplier_name ?? ''));
|
||||
if ($supplier === '') {
|
||||
continue;
|
||||
}
|
||||
$result[$supplier] = [
|
||||
'rows' => (int) ($row->row_count ?? 0),
|
||||
'qty' => round((float) ($row->qty_total ?? 0), 4),
|
||||
'amount' => round((float) ($row->amount_total ?? 0), 2),
|
||||
];
|
||||
}
|
||||
ksort($result, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按数据集前缀和业务月份批量汇总,供厂家对账单月度进度统计使用。
|
||||
*
|
||||
* @return array<string,array{rows:int,qty:float,amount:float}>
|
||||
*/
|
||||
public function summarizeByDatasetPrefixForMonth(
|
||||
string $prefix,
|
||||
int $companyId,
|
||||
string $month = '',
|
||||
string $monthField = 'createdAt',
|
||||
string $qtyField = 'qty',
|
||||
string $amountField = 'amount',
|
||||
): array {
|
||||
if ($prefix === ''
|
||||
|| preg_match('/^[A-Za-z0-9_]+$/', $monthField) !== 1
|
||||
|| preg_match('/^[A-Za-z0-9_]+$/', $qtyField) !== 1
|
||||
|| preg_match('/^[A-Za-z0-9_]+$/', $amountField) !== 1) {
|
||||
return [];
|
||||
}
|
||||
if ($month !== '' && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
$query = $connection->table('supplier_payable_overrides')
|
||||
->where('company_id', $companyId)
|
||||
->where('dataset', 'like', addcslashes($prefix, '%_\\') . '%');
|
||||
if ($month !== '') {
|
||||
$query->whereRaw(
|
||||
$this->jsonMonthExpression($connection, $monthField) . ' = ?',
|
||||
[$month],
|
||||
);
|
||||
}
|
||||
|
||||
$qtyExpression = $this->jsonNumberExpression($connection, $qtyField);
|
||||
$amountExpression = $this->jsonNumberExpression($connection, $amountField);
|
||||
$rows = $query
|
||||
->select('dataset')
|
||||
->selectRaw('COUNT(*) AS row_count')
|
||||
->selectRaw("SUM({$qtyExpression}) AS qty_total")
|
||||
->selectRaw("SUM({$amountExpression}) AS amount_total")
|
||||
->groupBy('dataset')
|
||||
->get();
|
||||
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$dataset = trim((string) ($row->dataset ?? ''));
|
||||
if ($dataset === '') {
|
||||
continue;
|
||||
}
|
||||
$result[$dataset] = [
|
||||
'rows' => (int) ($row->row_count ?? 0),
|
||||
'qty' => round((float) ($row->qty_total ?? 0), 4),
|
||||
'amount' => round((float) ($row->amount_total ?? 0), 2),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。
|
||||
*
|
||||
@ -765,100 +633,6 @@ class SupplierPayableOverrideStore
|
||||
return $suppliers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 退货数据优先按发货时间归月;MySQL 下使用已有日期索引列,避免逐行 JSON 函数计算。
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function distinctSuppliersForSendTimeMonth(
|
||||
string $dataset,
|
||||
int $companyId,
|
||||
string $month,
|
||||
string $reconciler = '',
|
||||
): array {
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
$schema = Schema::connection($connection->getName());
|
||||
if ($connection->getDriverName() !== 'mysql'
|
||||
|| ! $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')
|
||||
|| ! $schema->hasColumn('supplier_payable_overrides', 'record_date_key')
|
||||
|| ! $schema->hasColumn('supplier_payable_overrides', 'supplier_name_key')) {
|
||||
return $this->distinctSuppliersForFilters(
|
||||
$dataset,
|
||||
$companyId,
|
||||
$month,
|
||||
$reconciler,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
$start = $month . '-01';
|
||||
$next = \Illuminate\Support\Carbon::createFromFormat('!Y-m', $month, 'Asia/Shanghai')
|
||||
->addMonthNoOverflow()
|
||||
->toDateString();
|
||||
$sendTime = $this->jsonStringExpression($connection, 'send_time');
|
||||
$sendTimeEmpty = "COALESCE(NULLIF(NULLIF({$sendTime}, 'null'), ''), '') = ''";
|
||||
$sendTimePresent = "COALESCE(NULLIF(NULLIF({$sendTime}, 'null'), ''), '') <> ''";
|
||||
|
||||
$baseQuery = function () use ($connection, $dataset, $companyId, $reconciler): \Illuminate\Database\Query\Builder {
|
||||
$query = $connection->table('supplier_payable_overrides')
|
||||
->where('company_id', $companyId)
|
||||
->where('dataset', $dataset);
|
||||
if ($reconciler !== '') {
|
||||
$query->where('values->reconciler', $reconciler);
|
||||
}
|
||||
|
||||
return $query;
|
||||
};
|
||||
|
||||
$dateSuppliers = $baseQuery()
|
||||
->whereNotNull('record_date_key')
|
||||
->where('record_date_key', '>=', $start)
|
||||
->where('record_date_key', '<', $next)
|
||||
->whereNotNull('supplier_name_key')
|
||||
->where('supplier_name_key', '<>', '')
|
||||
->distinct()
|
||||
->pluck('supplier_name_key')
|
||||
->all();
|
||||
$emptySendSuppliers = $baseQuery()
|
||||
->where('summary_month_key', $month)
|
||||
->whereRaw($sendTimeEmpty)
|
||||
->whereNotNull('supplier_name_key')
|
||||
->where('supplier_name_key', '<>', '')
|
||||
->distinct()
|
||||
->pluck('supplier_name_key')
|
||||
->all();
|
||||
$legacySuppliers = $baseQuery()
|
||||
->whereNull('record_date_key')
|
||||
->where('summary_month_key', $month)
|
||||
->whereRaw($sendTimePresent)
|
||||
->whereRaw(
|
||||
$this->jsonMonthExpression($connection, 'send_time') . ' = ?',
|
||||
[$month],
|
||||
)
|
||||
->whereNotNull('supplier_name_key')
|
||||
->where('supplier_name_key', '<>', '')
|
||||
->distinct()
|
||||
->pluck('supplier_name_key')
|
||||
->all();
|
||||
|
||||
$suppliers = array_values(array_unique(array_merge(
|
||||
$dateSuppliers,
|
||||
$emptySendSuppliers,
|
||||
$legacySuppliers,
|
||||
)));
|
||||
$suppliers = array_values(array_filter(array_map(
|
||||
static fn (mixed $value): string => trim((string) $value),
|
||||
$suppliers,
|
||||
), static fn (string $supplier): bool => $supplier !== ''));
|
||||
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return $suppliers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只返回指定账期涉及的供应商,供月度催办统计使用。
|
||||
*
|
||||
@ -1143,31 +917,6 @@ class SupplierPayableOverrideStore
|
||||
. 'ELSE ' . $summaryMonth . ' END';
|
||||
}
|
||||
|
||||
private function jsonStringExpression(ConnectionInterface $connection, string $field): string
|
||||
{
|
||||
return $connection->getDriverName() === 'mysql'
|
||||
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$field}')))"
|
||||
: "TRIM(json_extract(\"values\", '$.{$field}'))";
|
||||
}
|
||||
|
||||
private function jsonNumberExpression(ConnectionInterface $connection, string $field): string
|
||||
{
|
||||
$text = $this->jsonStringExpression($connection, $field);
|
||||
|
||||
return $connection->getDriverName() === 'mysql'
|
||||
? "CAST(COALESCE(NULLIF({$text}, ''), '0') AS DECIMAL(20,4))"
|
||||
: "CAST(COALESCE(NULLIF({$text}, ''), '0') AS REAL)";
|
||||
}
|
||||
|
||||
private function jsonMonthExpression(ConnectionInterface $connection, string $field): string
|
||||
{
|
||||
$text = $this->jsonStringExpression($connection, $field);
|
||||
|
||||
return $connection->getDriverName() === 'mysql'
|
||||
? "LEFT(REPLACE(REPLACE(NULLIF(NULLIF({$text}, 'null'), ''), '/', '-'), '.', '-'), 7)"
|
||||
: "substr(replace(replace(NULLIF(NULLIF({$text}, 'null'), ''), '/', '-'), '.', '-'), 1, 7)";
|
||||
}
|
||||
|
||||
private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void
|
||||
{
|
||||
if ($this->supportsSupplierNameIndex()) {
|
||||
|
||||
@ -41,12 +41,6 @@ class SupplierStatementStore
|
||||
return $this->store->listRows(self::PREFIX . $supplier, $companyId);
|
||||
}
|
||||
|
||||
/** @return iterable<int,array<string,mixed>> */
|
||||
public function streamRows(string $supplier, int $companyId): iterable
|
||||
{
|
||||
yield from $this->store->streamRows(self::PREFIX . $supplier, $companyId);
|
||||
}
|
||||
|
||||
/** @return array{rows:list<array<string,mixed>>,total:int} */
|
||||
public function paginate(string $supplier, int $companyId, int $perPage, int $page): array
|
||||
{
|
||||
@ -83,33 +77,6 @@ class SupplierStatementStore
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按厂家汇总当前对账单在业务月份内的行数、数量和金额。
|
||||
*
|
||||
* @return array<string,array{rows:int,qty:float,amount:float}>
|
||||
*/
|
||||
public function totalsBySupplierForMonth(string $month, int $companyId): array
|
||||
{
|
||||
$datasets = $this->store->summarizeByDatasetPrefixForMonth(
|
||||
self::PREFIX,
|
||||
$companyId,
|
||||
$month,
|
||||
'createdAt',
|
||||
'qty',
|
||||
'amount',
|
||||
);
|
||||
$result = [];
|
||||
foreach ($datasets as $dataset => $totals) {
|
||||
$supplier = trim(substr($dataset, strlen(self::PREFIX)));
|
||||
if ($supplier !== '') {
|
||||
$result[$supplier] = $totals;
|
||||
}
|
||||
}
|
||||
ksort($result, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return list<string> 已经上传过对账单的厂家名称 */
|
||||
public function uploadedSuppliers(int $companyId): array
|
||||
{
|
||||
|
||||
@ -1,96 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/** 财务端导出厂家最新一版上传对账单。 */
|
||||
class SupplierStatementWorkbookExporter
|
||||
{
|
||||
private const FIELDS = [
|
||||
'expressName',
|
||||
'expressNo',
|
||||
'purchaseNo',
|
||||
'createdAt',
|
||||
'supplier',
|
||||
'barcode',
|
||||
'skuName',
|
||||
'qty',
|
||||
'unitPrice',
|
||||
'amount',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param iterable<int,array<string,mixed>> $rows
|
||||
*/
|
||||
public function download(
|
||||
iterable $rows,
|
||||
string $supplier,
|
||||
string $uploadedAt = '',
|
||||
): StreamedResponse {
|
||||
$safeSupplier = preg_replace('/[\\\\\\/:*?"<>|]+/u', '_', $supplier) ?: '厂家';
|
||||
$timestamp = $this->fileTimestamp($uploadedAt);
|
||||
$filename = $safeSupplier . '_原始账单_' . $timestamp . '.xlsx';
|
||||
|
||||
return response()->streamDownload(function () use ($rows): void {
|
||||
$writer = new StreamingWorkbook();
|
||||
$writer->row('原始账单', array_values(SupplierStatementTemplate::COLUMNS), true);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$cells = [];
|
||||
foreach (self::FIELDS as $field) {
|
||||
$value = $row[$field] ?? '';
|
||||
$cells[] = in_array($field, ['qty', 'unitPrice', 'amount'], true)
|
||||
? $this->numberCell($value)
|
||||
: trim((string) $value);
|
||||
}
|
||||
$writer->row('原始账单', $cells);
|
||||
}
|
||||
|
||||
$output = fopen('php://output', 'wb');
|
||||
if ($output === false) {
|
||||
throw new RuntimeException('无法创建原始账单导出文件。');
|
||||
}
|
||||
$writer->writeTo($output);
|
||||
}, $filename, [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
private function numberCell(mixed $value): int|float|string
|
||||
{
|
||||
$text = str_replace([',', ',', ' '], '', trim((string) $value));
|
||||
if ($text === '') {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^-?\d+$/', $text) === 1) {
|
||||
return (int) $text;
|
||||
}
|
||||
if (is_numeric($text)) {
|
||||
return (float) $text;
|
||||
}
|
||||
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
private function fileTimestamp(string $uploadedAt): string
|
||||
{
|
||||
$uploadedAt = trim($uploadedAt);
|
||||
if ($uploadedAt === '') {
|
||||
return now('Asia/Shanghai')->format('Ymd_His');
|
||||
}
|
||||
|
||||
try {
|
||||
return \Illuminate\Support\Carbon::createFromFormat(
|
||||
'Y-m-d H:i:s',
|
||||
$uploadedAt,
|
||||
'Asia/Shanghai',
|
||||
)->format('Ymd_His');
|
||||
} catch (\Throwable) {
|
||||
return now('Asia/Shanghai')->format('Ymd_His');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -135,35 +135,6 @@ class SupplierSummaryConfirmation
|
||||
], $companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 已经成功发送过货款确认的厂家;待厂家确认和厂家已确认都计入。
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function sentSupplierNames(string $month, int $companyId): array
|
||||
{
|
||||
$suppliers = [];
|
||||
foreach ($this->store->listRows(self::DATASET, $companyId) as $record) {
|
||||
$recordMonth = trim((string) ($record['month'] ?? ''));
|
||||
if ($month !== '' && $recordMonth !== $month) {
|
||||
continue;
|
||||
}
|
||||
$supplier = trim((string) ($record['supplier'] ?? ''));
|
||||
$status = trim((string) ($record['status'] ?? ''));
|
||||
if ($supplier !== '' && in_array($status, [
|
||||
self::STATUS_PENDING,
|
||||
self::STATUS_CONFIRMED,
|
||||
], true)) {
|
||||
$suppliers[$supplier] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$suppliers = array_keys($suppliers);
|
||||
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return $suppliers;
|
||||
}
|
||||
|
||||
public function companyIdFromOutTrackId(string $outTrackId): ?int
|
||||
{
|
||||
if (preg_match('/^supplier-summary-c(\d+)-[a-f0-9]{16,128}$/', strtolower($outTrackId), $matches) !== 1) {
|
||||
|
||||
@ -1,288 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 厂家上传对账单后,双方数据完全一致时自动发送货款确认。
|
||||
*/
|
||||
class SupplierZeroDifferenceConfirmation
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierReconciliationPageData $pageData,
|
||||
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
||||
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $records
|
||||
* @return list<string>
|
||||
*/
|
||||
public function statementMonths(array $records): array
|
||||
{
|
||||
$months = [];
|
||||
foreach ($records as $record) {
|
||||
$date = trim((string) ($record['createdAt'] ?? $record['summary_month'] ?? ''));
|
||||
if (preg_match('/^(\d{4})[-\/.](\d{1,2})/', $date, $matches) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$month = (int) $matches[2];
|
||||
if ($month >= 1 && $month <= 12) {
|
||||
$months[sprintf('%04d-%02d', (int) $matches[1], $month)] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$months = array_keys($months);
|
||||
sort($months);
|
||||
|
||||
return $months;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* eligible:bool,
|
||||
* month:string,
|
||||
* reason:string,
|
||||
* qty:float,
|
||||
* amount:float,
|
||||
* difference_count:int
|
||||
* }
|
||||
*/
|
||||
public function assess(string $supplier, int $companyId, string $month): array
|
||||
{
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
|
||||
return $this->assessment(false, $month, '账期格式无效');
|
||||
}
|
||||
|
||||
$detail = $this->pageData->financeDetailForFilters($supplier, $companyId, [
|
||||
'month' => $month,
|
||||
]);
|
||||
if (($detail['awaitingUpload'] ?? false) === true) {
|
||||
return $this->assessment(false, $month, '厂家尚未上传该账期对账单');
|
||||
}
|
||||
|
||||
$rows = (array) ($detail['rows'] ?? []);
|
||||
$differenceCount = (int) ($detail['difference_count'] ?? 0);
|
||||
if ($rows === []) {
|
||||
return $this->assessment(false, $month, '该账期没有可比对数据', 0, 0, $differenceCount);
|
||||
}
|
||||
if ($differenceCount > 0) {
|
||||
return $this->assessment(
|
||||
false,
|
||||
$month,
|
||||
"仍有 {$differenceCount} 条差异或未定价记录",
|
||||
0,
|
||||
0,
|
||||
$differenceCount,
|
||||
);
|
||||
}
|
||||
|
||||
$summary = (array) ($detail['summary'] ?? []);
|
||||
$sourceTotals = (array) ($detail['sourceTotals'] ?? []);
|
||||
$differenceRows = (int) ($summary['supplierExtra'] ?? 0)
|
||||
+ (int) ($summary['mismatch'] ?? 0)
|
||||
+ (int) ($summary['supplierMissing'] ?? 0)
|
||||
+ (int) ($summary['unpriced'] ?? 0);
|
||||
$mineQty = (float) ($sourceTotals['mineQty'] ?? 0);
|
||||
$mineAmount = (float) ($sourceTotals['mineAmount'] ?? 0);
|
||||
$theirsQty = (float) ($sourceTotals['theirsQty'] ?? 0);
|
||||
$theirsAmount = (float) ($sourceTotals['theirsAmount'] ?? 0);
|
||||
|
||||
if (
|
||||
$differenceRows > 0
|
||||
|| abs($mineQty - $theirsQty) >= 0.005
|
||||
|| abs($mineAmount - $theirsAmount) >= 0.005
|
||||
) {
|
||||
return $this->assessment(
|
||||
false,
|
||||
$month,
|
||||
'双方件数或货款金额仍不一致',
|
||||
0,
|
||||
0,
|
||||
max($differenceCount, $differenceRows),
|
||||
);
|
||||
}
|
||||
|
||||
$qty = (float) ($summary['settleQty'] ?? $theirsQty);
|
||||
$amount = (float) ($summary['settleAmount'] ?? $theirsAmount);
|
||||
if (abs($qty) < 0.00005 && abs($amount) < 0.005) {
|
||||
return $this->assessment(false, $month, '该账期没有可确认的货款数据', 0, 0, 0);
|
||||
}
|
||||
|
||||
return [
|
||||
'eligible' => true,
|
||||
'month' => $month,
|
||||
'reason' => '双方数据完全一致',
|
||||
'qty' => round($qty, 4),
|
||||
'amount' => round($amount, 2),
|
||||
'difference_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:'pushed'|'skipped'|'failed',
|
||||
* month:string,
|
||||
* reason:string,
|
||||
* qty:float,
|
||||
* amount:float,
|
||||
* difference_count:int
|
||||
* }
|
||||
*/
|
||||
public function pushMonth(
|
||||
string $supplier,
|
||||
int $companyId,
|
||||
string $month,
|
||||
?int $userId = null,
|
||||
bool $skipExistingConfirmation = true,
|
||||
): array {
|
||||
$assessment = $this->assess($supplier, $companyId, $month);
|
||||
if ($assessment['eligible'] !== true) {
|
||||
return ['status' => 'skipped'] + $assessment;
|
||||
}
|
||||
|
||||
if ($skipExistingConfirmation) {
|
||||
$existing = $this->summaryConfirmations->latest(
|
||||
$supplier,
|
||||
$month,
|
||||
'settlement',
|
||||
$companyId,
|
||||
);
|
||||
$existingStatus = trim((string) ($existing['status'] ?? ''));
|
||||
if (in_array($existingStatus, [
|
||||
SupplierSummaryConfirmation::STATUS_SENDING,
|
||||
SupplierSummaryConfirmation::STATUS_PENDING,
|
||||
SupplierSummaryConfirmation::STATUS_CONFIRMED,
|
||||
], true)) {
|
||||
return [
|
||||
'status' => 'skipped',
|
||||
'month' => $month,
|
||||
'reason' => $existingStatus === SupplierSummaryConfirmation::STATUS_CONFIRMED
|
||||
? '厂家已确认,默认不重复推送'
|
||||
: '该账期已有待确认推送,默认不重复推送',
|
||||
'qty' => $assessment['qty'],
|
||||
'amount' => $assessment['amount'],
|
||||
'difference_count' => 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->dingTalkNotifier->pushReconciliationSummary(
|
||||
$supplier,
|
||||
$month,
|
||||
$assessment['qty'],
|
||||
$assessment['amount'],
|
||||
$companyId,
|
||||
'settlement',
|
||||
$userId,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
return [
|
||||
'status' => 'failed',
|
||||
'month' => $month,
|
||||
'reason' => $exception->getMessage(),
|
||||
'qty' => $assessment['qty'],
|
||||
'amount' => $assessment['amount'],
|
||||
'difference_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'pushed',
|
||||
'month' => $month,
|
||||
'reason' => '已发送货款确认',
|
||||
'qty' => (float) ($result['qty'] ?? $assessment['qty']),
|
||||
'amount' => (float) ($result['amount'] ?? $assessment['amount']),
|
||||
'difference_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $records
|
||||
* @return array{
|
||||
* pushed:list<array<string,mixed>>,
|
||||
* skipped:list<array<string,mixed>>,
|
||||
* failed:list<array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
public function afterStatementUpload(
|
||||
string $supplier,
|
||||
int $companyId,
|
||||
array $records,
|
||||
?int $userId = null,
|
||||
): array {
|
||||
$result = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||
foreach ($this->statementMonths($records) as $month) {
|
||||
$push = $this->pushMonth(
|
||||
$supplier,
|
||||
$companyId,
|
||||
$month,
|
||||
$userId,
|
||||
false,
|
||||
);
|
||||
$result[$push['status']][] = $push;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @param array{pushed:list<array<string,mixed>>,failed:list<array<string,mixed>>} $result */
|
||||
public function uploadNotice(array $result): string
|
||||
{
|
||||
$notices = [];
|
||||
$pushed = (array) ($result['pushed'] ?? []);
|
||||
if ($pushed !== []) {
|
||||
$notices[] = '零差异对账确认已自动推送到该厂家钉钉群('
|
||||
. implode('、', array_map(
|
||||
fn (array $row): string => $this->displayMonth((string) $row['month']),
|
||||
$pushed,
|
||||
))
|
||||
. ')';
|
||||
}
|
||||
|
||||
$failed = (array) ($result['failed'] ?? []);
|
||||
if ($failed !== []) {
|
||||
$notices[] = '零差异对账确认自动推送失败('
|
||||
. implode('、', array_map(
|
||||
fn (array $row): string => $this->displayMonth((string) $row['month'])
|
||||
. ':' . (string) ($row['reason'] ?? '未知错误'),
|
||||
$failed,
|
||||
))
|
||||
. ')';
|
||||
}
|
||||
|
||||
return implode(';', array_filter($notices));
|
||||
}
|
||||
|
||||
private function assessment(
|
||||
bool $eligible,
|
||||
string $month,
|
||||
string $reason,
|
||||
float $qty = 0,
|
||||
float $amount = 0,
|
||||
int $differenceCount = 0,
|
||||
): array {
|
||||
return [
|
||||
'eligible' => $eligible,
|
||||
'month' => $month,
|
||||
'reason' => $reason,
|
||||
'qty' => $qty,
|
||||
'amount' => $amount,
|
||||
'difference_count' => $differenceCount,
|
||||
];
|
||||
}
|
||||
|
||||
private function displayMonth(string $month): string
|
||||
{
|
||||
if (preg_match('/^(\d{4})-(\d{1,2})$/', $month, $matches) !== 1) {
|
||||
return $month;
|
||||
}
|
||||
|
||||
return (int) $matches[1] . '年' . (int) $matches[2] . '月';
|
||||
}
|
||||
}
|
||||
@ -99,7 +99,7 @@ final class BankBillPageData
|
||||
}
|
||||
|
||||
if (($column['canonical'] ?? null) === 'account_no') {
|
||||
$options = collect($this->accountOptions())
|
||||
$options = collect($this->directAccountOptions())
|
||||
->map(static fn (array $account): array => [
|
||||
'value' => (string) $account['account_no'],
|
||||
'label' => (string) $account['label'],
|
||||
@ -567,42 +567,6 @@ final class BankBillPageData
|
||||
private function accountOptions(): array
|
||||
{
|
||||
return collect($this->directAccountOptions())
|
||||
->merge($this->personalBillAccountOptions())
|
||||
->unique(static fn (array $row): string => $row['bank_name'] . '|' . $row['account_no'])
|
||||
->sortBy(static fn (array $row): string => $row['label'])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
private function personalBillAccountOptions(): array
|
||||
{
|
||||
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$query = $connection->table('fin_accounts as a')
|
||||
->select([
|
||||
'a.company_name',
|
||||
'a.account_short',
|
||||
'a.account_no',
|
||||
'a.bank_name',
|
||||
])
|
||||
->where('a.account_type', '个人卡')
|
||||
->whereNotNull('a.account_no')
|
||||
->where('a.account_no', '<>', '')
|
||||
->whereExists(function (Builder $billQuery): void {
|
||||
$billQuery
|
||||
->selectRaw('1')
|
||||
->from(self::TABLE . ' as b')
|
||||
->whereColumn('b.account_no', 'a.account_no');
|
||||
})
|
||||
->distinct()
|
||||
->orderBy('a.account_short')
|
||||
->orderBy('a.account_no')
|
||||
->get();
|
||||
|
||||
return $query
|
||||
->map(fn (object $row): array => $this->accountOption($row))
|
||||
->filter(static fn (array $row): bool => $row['account_no'] !== '')
|
||||
->unique(static fn (array $row): string => $row['bank_name'] . '|' . $row['account_no'])
|
||||
->sortBy(static fn (array $row): string => $row['label'])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
@ -653,7 +617,25 @@ final class BankBillPageData
|
||||
->get();
|
||||
|
||||
return $query
|
||||
->map(fn (object $row): array => $this->accountOption($row))
|
||||
->map(function (object $row): array {
|
||||
$bank = $this->directAccountBank(
|
||||
(string) ($row->account_short ?? ''),
|
||||
(string) ($row->bank_name ?? ''),
|
||||
);
|
||||
|
||||
return [
|
||||
'bank_name' => $bank,
|
||||
'company_name' => (string) ($row->company_name ?? ''),
|
||||
'account_short' => (string) $row->account_short,
|
||||
'account_no' => preg_replace('/\D+/', '', (string) $row->account_no) ?? '',
|
||||
'label' => trim(implode(' · ', array_filter([
|
||||
$bank,
|
||||
(string) $row->account_short,
|
||||
(string) $row->account_no,
|
||||
(string) ($row->company_name ?? ''),
|
||||
]))),
|
||||
];
|
||||
})
|
||||
->filter(static fn (array $row): bool => $row['account_no'] !== '')
|
||||
->unique(static fn (array $row): string => $row['bank_name'] . '|' . $row['account_no'])
|
||||
->sortBy(static fn (array $row): string => $row['label'])
|
||||
@ -661,27 +643,6 @@ final class BankBillPageData
|
||||
->all();
|
||||
}
|
||||
|
||||
private function accountOption(object $row): array
|
||||
{
|
||||
$bank = $this->directAccountBank(
|
||||
(string) ($row->account_short ?? ''),
|
||||
(string) ($row->bank_name ?? ''),
|
||||
);
|
||||
|
||||
return [
|
||||
'bank_name' => $bank,
|
||||
'company_name' => (string) ($row->company_name ?? ''),
|
||||
'account_short' => (string) $row->account_short,
|
||||
'account_no' => preg_replace('/\D+/', '', (string) $row->account_no) ?? '',
|
||||
'label' => trim(implode(' · ', array_filter([
|
||||
$bank,
|
||||
(string) $row->account_short,
|
||||
(string) $row->account_no,
|
||||
(string) ($row->company_name ?? ''),
|
||||
]))),
|
||||
];
|
||||
}
|
||||
|
||||
private function directAccountBank(string $accountShort, string $bankName): string
|
||||
{
|
||||
if (str_contains($accountShort, '招行') || str_contains($bankName, '招商银行')) {
|
||||
|
||||
@ -113,7 +113,7 @@ class BillingDetailsPageData
|
||||
'remark' => ['备注', 'text'],
|
||||
];
|
||||
|
||||
/** 费用明细精简列:平台、店铺、按发生时间命中的主体资料、线上单号、账单费用、收支净额。 */
|
||||
/** 费用明细精简列:平台、店铺、当前主体资料、线上单号、账单费用、收支净额。 */
|
||||
public const EXPENSE_COLUMNS = [
|
||||
'platform' => ['平台', 'text'],
|
||||
'store_name' => ['店铺', 'text'],
|
||||
@ -248,7 +248,7 @@ class BillingDetailsPageData
|
||||
if (isset($want['custom_remark'])) { $add('custom_remark', $has('custom_remark') ? 'custom_remark' : null); }
|
||||
if (isset($want['remark'])) { $add('remark', $has('remark') ? 'remark' : null); }
|
||||
if (isset($want['type_text'])) { $add('type_text', $pick(is_string($meta['type']) ? (string) $meta['type'] : null)); }
|
||||
if (isset($want['occurred_at']) || $subject) { $add('occurred_at', (string) $meta['date']); }
|
||||
if (isset($want['occurred_at'])) { $add('occurred_at', (string) $meta['date']); }
|
||||
if (isset($want['income']) || isset($want['amount'])) { $add('income', (string) $meta['income']); }
|
||||
if (isset($want['expense']) || isset($want['amount'])) { $add('expense', (string) $meta['expense']); }
|
||||
|
||||
@ -1476,7 +1476,7 @@ class BillingDetailsPageData
|
||||
|
||||
$this->subjectMatcher ??= app(PerformanceDetailSubjectMatcher::class);
|
||||
|
||||
return $this->subjectMatcher->applyArray($row, $subjectMap);
|
||||
return $this->subjectMatcher->applyArrayCurrent($row, $subjectMap);
|
||||
}
|
||||
|
||||
/** @param list<string> $storeNames */
|
||||
|
||||
@ -15,7 +15,6 @@ use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
||||
/**
|
||||
* 「供应商对账」页面数据:
|
||||
* - 财务端数据:按供应商与商品编码汇总,区分一致、未定价、厂家多、厂家少和数量/金额差异
|
||||
* - 原始账单:只读查看厂家最新一版上传对账单原始行
|
||||
* - 厂家端数据:厂家上传的对账单(实时)与只读的退货明细
|
||||
*/
|
||||
class SupplierReconciliationPageData
|
||||
@ -33,9 +32,6 @@ class SupplierReconciliationPageData
|
||||
/** 厂家上传的对账数据表:每页行数(短表 + 翻页)。 */
|
||||
private const PER_PAGE = 15;
|
||||
|
||||
/** 财务端查看厂家原始账单:每页行数。 */
|
||||
private const RAW_STATEMENT_PER_PAGE = 50;
|
||||
|
||||
/** 退货明细行较高:每页 10 行,并在页面内固定表头滚动查看。 */
|
||||
private const RETURN_PER_PAGE = 10;
|
||||
|
||||
@ -66,17 +62,12 @@ class SupplierReconciliationPageData
|
||||
|
||||
$reconcilers = $this->financeReconcilers($mineDataset, $returnDataset, $companyId);
|
||||
$months = $this->financeMonths($mineDataset, $returnDataset, $companyId);
|
||||
$latestAccountingMonth = $this->latestAccountingMonth();
|
||||
if (! in_array($latestAccountingMonth, $months, true)) {
|
||||
$months[] = $latestAccountingMonth;
|
||||
rsort($months);
|
||||
}
|
||||
|
||||
$month = trim((string) request()->query('month', ''));
|
||||
if ($month !== '' && preg_match('/^\d{4}-\d{2}$/', $month) === 1) {
|
||||
// Keep the selected month for database-side filtering.
|
||||
} else {
|
||||
$month = $latestAccountingMonth;
|
||||
$month = '';
|
||||
}
|
||||
|
||||
$reconciler = trim((string) request()->query('reconciler', ''));
|
||||
@ -96,11 +87,12 @@ class SupplierReconciliationPageData
|
||||
) as $name) {
|
||||
$suppliers[$name] = true;
|
||||
}
|
||||
foreach ($this->store->distinctSuppliersForSendTimeMonth(
|
||||
foreach ($this->store->distinctSuppliersForFilters(
|
||||
$returnDataset,
|
||||
$companyId,
|
||||
$month,
|
||||
$reconciler,
|
||||
true,
|
||||
) as $name) {
|
||||
$suppliers[$name] = true;
|
||||
}
|
||||
@ -161,15 +153,6 @@ class SupplierReconciliationPageData
|
||||
);
|
||||
}
|
||||
|
||||
$reconciliationOverview = $selected === ''
|
||||
? $this->financeReconciliationOverview(
|
||||
$supplierNames,
|
||||
$companyId,
|
||||
$month,
|
||||
$reconciler,
|
||||
)
|
||||
: null;
|
||||
|
||||
$returnLatestMonths = [];
|
||||
$returnDisplayMonths = [];
|
||||
$returnCounts = [];
|
||||
@ -234,7 +217,6 @@ class SupplierReconciliationPageData
|
||||
'supplierPerPage' => self::SUPPLIER_PER_PAGE,
|
||||
'supplierQuery' => $supplierQuery,
|
||||
'supplierNotFound' => $supplierNotFound,
|
||||
'reconciliationOverview' => $reconciliationOverview,
|
||||
'uploads' => $uploads,
|
||||
'months' => $months,
|
||||
'month' => $month,
|
||||
@ -268,83 +250,6 @@ class SupplierReconciliationPageData
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 财务端当前筛选范围的对账进度概览。
|
||||
*
|
||||
* @param list<string> $supplierNames
|
||||
* @return array{
|
||||
* month:string,
|
||||
* total:array{count:int,suppliers:list<string>},
|
||||
* confirmed:array{count:int,suppliers:list<string>},
|
||||
* difference:array{count:int,suppliers:list<string>},
|
||||
* not_uploaded:array{count:int,suppliers:list<string>}
|
||||
* }
|
||||
*/
|
||||
private function financeReconciliationOverview(
|
||||
array $supplierNames,
|
||||
int $companyId,
|
||||
string $month,
|
||||
string $reconciler,
|
||||
): array {
|
||||
$mineDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation';
|
||||
$mineTotals = $this->store->summarizeBySupplierForFilters(
|
||||
$mineDataset,
|
||||
$companyId,
|
||||
$month,
|
||||
$reconciler,
|
||||
);
|
||||
$supplierScope = array_fill_keys($supplierNames, true);
|
||||
$reconciliationSuppliers = array_values(array_filter(
|
||||
array_keys($mineTotals),
|
||||
static fn (string $supplier): bool => isset($supplierScope[$supplier]),
|
||||
));
|
||||
sort($reconciliationSuppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
$statementTotals = $this->statements->totalsBySupplierForMonth($month, $companyId);
|
||||
$sentSuppliers = array_fill_keys(
|
||||
$this->summaryConfirmations->sentSupplierNames($month, $companyId),
|
||||
true,
|
||||
);
|
||||
$confirmed = [];
|
||||
$differences = [];
|
||||
$notUploaded = [];
|
||||
|
||||
foreach ($reconciliationSuppliers as $supplier) {
|
||||
if (isset($sentSuppliers[$supplier])) {
|
||||
$confirmed[] = $supplier;
|
||||
}
|
||||
|
||||
$theirs = $statementTotals[$supplier] ?? null;
|
||||
if ($theirs === null || (int) ($theirs['rows'] ?? 0) === 0) {
|
||||
$notUploaded[] = $supplier;
|
||||
continue;
|
||||
}
|
||||
|
||||
$mine = $mineTotals[$supplier];
|
||||
if (abs((float) $mine['qty'] - (float) $theirs['qty']) >= 0.005
|
||||
|| abs((float) $mine['amount'] - (float) $theirs['amount']) >= 0.005) {
|
||||
$differences[] = $supplier;
|
||||
}
|
||||
}
|
||||
|
||||
$payload = static function (array $suppliers): array {
|
||||
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return [
|
||||
'count' => count($suppliers),
|
||||
'suppliers' => array_values($suppliers),
|
||||
];
|
||||
};
|
||||
|
||||
return [
|
||||
'month' => $month,
|
||||
'total' => $payload($reconciliationSuppliers),
|
||||
'confirmed' => $payload($confirmed),
|
||||
'difference' => $payload($differences),
|
||||
'not_uploaded' => $payload($notUploaded),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function supplierData(): array
|
||||
{
|
||||
@ -448,79 +353,6 @@ class SupplierReconciliationPageData
|
||||
] + $this->vendorPeriodContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* 财务端只读查看厂家最新一版上传对账单的原始行。
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function rawStatementsData(): array
|
||||
{
|
||||
$companyId = $this->companyId();
|
||||
$mineDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation';
|
||||
$returnDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation';
|
||||
$supplierNames = $this->financeSupplierNames($mineDataset, $returnDataset, $companyId);
|
||||
$uploadedSuppliers = $this->statements->uploadedSuppliers($companyId);
|
||||
sort($uploadedSuppliers, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
$supplierQuery = trim((string) request()->query('supplier', ''));
|
||||
$selected = in_array($supplierQuery, $supplierNames, true) ? $supplierQuery : '';
|
||||
if ($supplierQuery === '' && $uploadedSuppliers !== []) {
|
||||
$selected = $uploadedSuppliers[0];
|
||||
}
|
||||
$supplierNotFound = $supplierQuery !== '' && $selected === '';
|
||||
|
||||
$month = trim((string) request()->query('month', ''));
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
|
||||
$month = $this->latestAccountingMonth();
|
||||
}
|
||||
|
||||
$statementRows = [];
|
||||
$statementTotal = 0;
|
||||
$rowsPage = 1;
|
||||
$statementPages = 1;
|
||||
$uploads = [];
|
||||
if ($selected !== '') {
|
||||
$rowsPage = max((int) request()->query('rows_page', 1), 1);
|
||||
$statementPage = $this->statements->paginate(
|
||||
$selected,
|
||||
$companyId,
|
||||
self::RAW_STATEMENT_PER_PAGE,
|
||||
$rowsPage,
|
||||
);
|
||||
$statementTotal = (int) ($statementPage['total'] ?? 0);
|
||||
$statementPages = max((int) ceil($statementTotal / self::RAW_STATEMENT_PER_PAGE), 1);
|
||||
if ($rowsPage > $statementPages) {
|
||||
$rowsPage = $statementPages;
|
||||
$statementPage = $this->statements->paginate(
|
||||
$selected,
|
||||
$companyId,
|
||||
self::RAW_STATEMENT_PER_PAGE,
|
||||
$rowsPage,
|
||||
);
|
||||
}
|
||||
$statementRows = (array) ($statementPage['rows'] ?? []);
|
||||
$uploads = $this->statements->uploads($selected, $companyId, 10);
|
||||
}
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.supplier-reconciliation.raw-statements',
|
||||
'sectionSlug' => 'supplier-reconciliation',
|
||||
'pageSlug' => 'raw-statements',
|
||||
'supplierNames' => $supplierNames,
|
||||
'supplierQuery' => $supplierQuery,
|
||||
'supplierNotFound' => $supplierNotFound,
|
||||
'selectedSupplier' => $selected,
|
||||
'statementRows' => $statementRows,
|
||||
'statementTotal' => $statementTotal,
|
||||
'rowsPage' => $rowsPage,
|
||||
'statementPages' => $statementPages,
|
||||
'perPage' => self::RAW_STATEMENT_PER_PAGE,
|
||||
'uploads' => $uploads,
|
||||
'latestUpload' => $uploads[0] ?? null,
|
||||
'month' => $month,
|
||||
];
|
||||
}
|
||||
|
||||
private function isSupplier(string $name): bool
|
||||
{
|
||||
try {
|
||||
@ -1561,13 +1393,4 @@ class SupplierReconciliationPageData
|
||||
{
|
||||
return (int) (company_id() ?: 1);
|
||||
}
|
||||
|
||||
private function latestAccountingMonth(): string
|
||||
{
|
||||
$timezone = trim((string) config('app.platform_timezone', ''));
|
||||
|
||||
return now($timezone !== '' ? $timezone : 'Asia/Shanghai')
|
||||
->subMonthNoOverflow()
|
||||
->format('Y-m');
|
||||
}
|
||||
}
|
||||
|
||||
@ -78,15 +78,6 @@
|
||||
<label>合并账单<input type="text" name="bundle" maxlength="128" value="{{ old('bundle', $editing->bundle ?? '') }}" placeholder="几家放一张表发来的,填同一个名称"></label>
|
||||
<label>负责人<input type="text" name="owner" maxlength="64" value="{{ old('owner', $editing->owner ?? '') }}"></label>
|
||||
<label>文件名关键字<input type="text" name="keywords" maxlength="255" value="{{ old('keywords', $editing->keywords ?? '') }}" placeholder="逗号分隔"></label>
|
||||
@php($rebook = (string) old('rebook_months', isset($editing->rebook_months) ? (string) $editing->rebook_months : ''))
|
||||
<label>补记账
|
||||
<select name="rebook_months">
|
||||
<option value="" @selected($rebook === '')>按上月小汇总识别</option>
|
||||
@foreach (\App\Support\CourierBills\Rebooks::RULES as $value => $text)
|
||||
<option value="{{ $value }}" @selected($rebook === (string) $value)>{{ $text }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label>发货数据「快递名称1」(每行一个,或用逗号分隔)
|
||||
<textarea name="express_names" rows="3" required>{{ old('express_names', implode("\n", $editing->express_names ?? [])) }}</textarea>
|
||||
@ -117,7 +108,7 @@
|
||||
</form>
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">分组名称</th><th scope="col">快递名称1</th><th scope="col">归到承运商</th><th scope="col">合并账单</th><th scope="col">负责人</th><th scope="col">文件名关键字</th><th scope="col">指定表头</th><th scope="col">补记账</th><th scope="col">钉钉对账群</th><th scope="col"></th></tr></thead>
|
||||
<thead><tr><th scope="col">分组名称</th><th scope="col">快递名称1</th><th scope="col">归到承运商</th><th scope="col">合并账单</th><th scope="col">负责人</th><th scope="col">文件名关键字</th><th scope="col">指定表头</th><th scope="col">钉钉对账群</th><th scope="col"></th></tr></thead>
|
||||
<tbody>
|
||||
@forelse ($cbGroups as $group)
|
||||
<tr>
|
||||
@ -128,7 +119,6 @@
|
||||
<td>{{ $group->owner }}</td>
|
||||
<td>{{ $group->keywords }}</td>
|
||||
<td>{{ collect([$group->waybill_header, $group->amount_header, $group->weight_header])->filter()->implode(' / ') ?: '自动' }}</td>
|
||||
<td>{{ ($group->rebook_months ?? null) === null ? '按小汇总' : (\App\Support\CourierBills\Rebooks::RULES[(int) $group->rebook_months] ?? '') }}</td>
|
||||
@php($robot = $cbRobots[$group->name] ?? [])
|
||||
<td class="wrap">
|
||||
<details>
|
||||
@ -162,7 +152,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td colspan="10" class="cbr-empty">还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。</td></tr>
|
||||
<tr><td colspan="9" class="cbr-empty">还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@ -13,12 +13,6 @@
|
||||
@empty
|
||||
<div class="cbr-muted">{{ $cbSearch }} 没有结算记录。</div>
|
||||
@endforelse
|
||||
@foreach ($cbRebookHits ?? [] as $hit)
|
||||
<div>补记账:{{ $hit->deduct_month }} 扣的,{{ $hit->refund_month }} 已补 {{ $money($hit->amount) }}{{ $hit->group_name ? '(' . $hit->group_name . ')' : '' }}{{ $hit->statement_id ? '' : '(历史导入)' }}</div>
|
||||
@endforeach
|
||||
@foreach ($cbRebookReviewHits ?? [] as $hit)
|
||||
<div class="cbr-muted">复核记账:{{ $hit->deduct_month }} 扣的,现在应扣 {{ $money($hit->current_amount) }}</div>
|
||||
@endforeach
|
||||
</div>
|
||||
@endif
|
||||
</section>
|
||||
@ -33,45 +27,6 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="cbr-metrics" style="grid-template-columns:1fr 1fr">
|
||||
<section class="cbr-panel" style="margin:0" aria-label="导入已补记录">
|
||||
<h3>补记账 · 导入已补记录</h3>
|
||||
<form method="POST" action="{{ $action('import-rebooks') }}" enctype="multipart/form-data" class="cbr-form cbr-panel-body">
|
||||
@csrf
|
||||
<label>已补记录(xlsx / csv)<input type="file" name="rebooks" required accept=".xlsx,.xls,.csv"></label>
|
||||
<button type="submit">导入</button>
|
||||
<p class="cbr-muted" style="flex-basis:100%">系统上线前已经在账单里补过的记账。表头须含「单号」「扣款月份」「补款账期」「补款金额」,可带「对账分组」。同一单号、同一扣款月份只补一次,重复导入或更换补款账期都不会再补。</p>
|
||||
</form>
|
||||
</section>
|
||||
<section class="cbr-panel" style="margin:0" aria-label="导入复核记账">
|
||||
<h3>补记账 · 导入复核记账</h3>
|
||||
<form method="POST" action="{{ $action('import-rebook-reviews') }}" enctype="multipart/form-data" class="cbr-form cbr-panel-body">
|
||||
@csrf
|
||||
<label>复核记账(xlsx / csv)<input type="file" name="reviews" required accept=".xlsx,.xls,.csv"></label>
|
||||
<button type="submit">导入</button>
|
||||
<p class="cbr-muted" style="flex-basis:100%">这单现在应扣多少(如「11.19记账」)。表头须含「单号」「扣款月份」「现应扣」。本期补款 = 记账明细里当时扣的「结算记账」− 现应扣;没复核的单先不补。同一单号同一扣款月份再导会覆盖。</p>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="cbr-panel" aria-label="补记账台账">
|
||||
<h3>补记账台账(按补款账期、扣款月份)</h3>
|
||||
<p class="cbr-muted cbr-panel-body" style="padding-bottom:0">对账单「确认结算」时,这期补的单记到这里,以后不再补。每家补几个月在「对账分组」里设,没设就按上月小汇总里的补记账类目识别,最多补两个月。
|
||||
@if (($cbRebookReviews ?? collect())->isNotEmpty())已导复核:@foreach ($cbRebookReviews as $r){{ $r->deduct_month }} 扣的 {{ number_format($r->n) }} 单@if (! $loop->last)、@endif @endforeach。@endif</p>
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">补款账期</th><th scope="col">扣款月份</th><th scope="col">对账分组</th><th scope="col">来源</th><th scope="col" class="num">单号数</th><th scope="col" class="num">补款金额</th></tr></thead>
|
||||
<tbody>
|
||||
@forelse ($cbRebookStats ?? [] as $row)
|
||||
<tr><td>{{ $row->refund_month }}</td><td>{{ $row->deduct_month }}</td><td>{{ $row->group_name ?? '—' }}</td><td>{{ $row->source === 'import' ? '历史导入' : '对账单确认' }}</td><td class="num">{{ number_format($row->n) }}</td><td class="num">{{ $money($row->amount) }}</td></tr>
|
||||
@empty
|
||||
<tr><td colspan="6" class="cbr-empty">还没有补记账记录。</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cbr-panel" aria-label="结算台账">
|
||||
<h3>结算台账(按分组、结算月份)</h3>
|
||||
<div class="cbr-scroll">
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
<div class="cbr-heading">
|
||||
<div>
|
||||
<h2>快递账单对账</h2>
|
||||
<p>上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。附加费按账单单号、费用类型和快递归属匹配结算金额。</p>
|
||||
<p>上传账单 → 自动对账 → 逐家核对 → 确认结算。小汇总按财务规则归集到「快递应付汇总」。第一期只核运费,附加费等在对账单里手工加行。</p>
|
||||
</div>
|
||||
<div class="cbr-form">
|
||||
<a class="cbr-button" href="{{ route('business.pages.show', ['section' => $cbSection, 'page' => 'courier-payable-summary', 'month' => $month]) }}">去快递应付汇总</a>
|
||||
|
||||
@ -59,16 +59,6 @@
|
||||
<tfoot><tr><td>合计</td><td class="num">{{ $billMoney($bill) }}</td><td class="num">{{ $money($self) }}</td><td class="num cbr-diff">{{ $money($bill - $self) }}</td><td></td><td></td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
@if (! empty($cbRebook))
|
||||
<p class="cbr-muted cbr-panel-body" style="padding-bottom:0">
|
||||
补记账:{{ \App\Support\CourierBills\Rebooks::RULES[$cbRebook['months']] ?? '' }}({{ match ($cbRebook['source']) { 'group' => '对账分组里设的', 'confirmed' => '按确认时记录', default => '按上月小汇总识别' } }})
|
||||
@if ($cbRebook['window'] !== [])
|
||||
· 扣款月份 {{ implode('、', $cbRebook['window']) }} · 本期补 {{ number_format($cbRebook['count']) }} 单 {{ $money($cbRebook['amount']) }}
|
||||
@if ($cbRebook['pending'] > 0) · {{ number_format($cbRebook['pending']) }} 单还没复核,先不补(在「结算台账」导入复核记账)@endif
|
||||
@if ($cbRebook['done'] > 0) · {{ number_format($cbRebook['done']) }} 单以前补过,不再补@endif
|
||||
@endif
|
||||
</p>
|
||||
@endif
|
||||
@if ($open)
|
||||
<form method="POST" action="{{ $action('add-item', ['statement' => $cbStatement->id]) }}" class="cbr-form cbr-panel-body">
|
||||
@csrf
|
||||
@ -149,8 +139,6 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $cbSurchargeRows ?? null])
|
||||
|
||||
<section class="cbr-panel" aria-label="账单文件">
|
||||
<h3>账单文件</h3>
|
||||
<div class="cbr-scroll">
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
<x-layouts.signed>
|
||||
<x-slot name="title">{{ $uploadLabel }} · {{ $monthLabel }} 账单上传</x-slot>
|
||||
<x-slot name="title">{{ $group->name }} · {{ $monthLabel }} 账单上传</x-slot>
|
||||
|
||||
<x-slot name="buttons">
|
||||
<a href="{{ $templateUrl }}" class="text-white px-3 py-1.5 mb-3 sm:mb-0 rounded-lg text-sm font-medium leading-6" style="background:#856632">下载上传模板</a>
|
||||
@ -30,16 +30,12 @@
|
||||
<div class="alert is-error" role="alert">{{ $errors->first() }}</div>
|
||||
@endif
|
||||
<section class="head">
|
||||
<h1>{{ $uploadLabel }} · {{ $monthLabel }} 运费账单上传</h1>
|
||||
@if ($joint)
|
||||
<p><strong>可上传范围:</strong>{{ implode('、', $joint['names']) }}</p>
|
||||
<p class="muted">这几家的逐单运费明细可以合在一份文件中。优先按系统中的单号归组;系统查不到的单号,请在「快递名称」列填写上述名称。无法归组、填入范围外的快递或附加费缺少对应运费明细时,整份文件退回,修改后重新上传。范围内任一分组已确认结算时,请先联系财务。</p>
|
||||
@endif
|
||||
<h1>{{ $group->name }} · {{ $monthLabel }} 运费账单上传</h1>
|
||||
<div class="muted">
|
||||
请先点右上角「下载上传模板」,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」;
|
||||
「账单」表:单号、运费必填,重量、面单、费率填数字,省可空,快递名称{{ $joint ? '仅在系统能查到单号时可空' : '可空' }};「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。
|
||||
「账单」表:单号、运费必填,重量、面单、费率填数字,省、快递名称可空;「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。
|
||||
同一个月可以分几次上传,每份最多 50MB、100,000 行。上传后等待校验和读入,刷新本页查看结果。
|
||||
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传{{ $joint ? '上述快递' : '本快递' }}本月的账单。
|
||||
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传本快递本月的账单。
|
||||
</div>
|
||||
</section>
|
||||
<section class="card">
|
||||
|
||||
@ -1,20 +1,3 @@
|
||||
@if (! empty($cbJointUploads))
|
||||
<section class="cbr-panel" aria-label="联合上传链接">
|
||||
<h3>联合上传链接</h3>
|
||||
<div class="cbr-panel-body">
|
||||
<p class="cbr-muted">同组快递可将逐单运费明细合在一份模板中上传,系统分别归入原有对账分组。打开后复制页面地址即可发给快递,链接 30 天有效。</p>
|
||||
@foreach ($cbJointUploads as $key => $set)
|
||||
<form method="GET" action="{{ $action('joint-upload-link') }}" target="_blank" class="cbr-form">
|
||||
<input type="hidden" name="joint" value="{{ $key }}">
|
||||
<label>{{ $set['label'] }}<input type="month" name="month" value="{{ $cbPushMonth ?? $month }}" required></label>
|
||||
<button type="submit" class="cbr-primary">打开联合上传页</button>
|
||||
<span class="cbr-muted">{{ implode('、', $set['names']) }}</span>
|
||||
</form>
|
||||
@endforeach
|
||||
</div>
|
||||
</section>
|
||||
@endif
|
||||
|
||||
<section class="cbr-panel" aria-label="让快递自己上传">
|
||||
<h3>让快递自己上传账单</h3>
|
||||
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-panel-body cbr-form"
|
||||
|
||||
@ -41,16 +41,6 @@
|
||||
@endif
|
||||
</section>
|
||||
|
||||
@if (($dfSurchargeSummary ?? collect())->isNotEmpty())
|
||||
<section class="cbr-panel" aria-label="附加费小汇总">
|
||||
<h3>附加费小汇总</h3><div class="cbr-scroll"><table>
|
||||
<thead><tr><th>项目</th><th class="num">厂家提供金额</th><th class="num">自算金额</th><th class="num">差额</th></tr></thead>
|
||||
<tbody>@foreach ($dfSurchargeSummary as $fee)<tr><td>{{ $fee->item }}</td><td class="num">{{ $money($fee->bill) }}</td><td class="num">{{ $money($fee->self) }}</td><td class="num">{{ $fee->self === null ? '—' : $money((float)$fee->bill - (float)$fee->self) }}</td></tr>@endforeach</tbody>
|
||||
</table></div>
|
||||
</section>
|
||||
@endif
|
||||
@include('business.pages.courier-payables.partials.surcharge-matches', ['surchargeRows' => $dfSurchargeRows ?? null])
|
||||
|
||||
<nav class="cbr-tabs" aria-label="按状态看">
|
||||
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month]) }}" class="{{ $dfStatus === '' ? 'is-active' : '' }}">全部<span>{{ array_sum($s['counts']) }}</span></a>
|
||||
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month, 'status' => 'attention']) }}" class="{{ $dfStatus === 'attention' ? 'is-active' : '' }}">要看的<span>{{ $s['attention'] }}</span></a>
|
||||
|
||||
@ -52,7 +52,7 @@
|
||||
@endforeach
|
||||
<label>备注<input type="text" name="note" maxlength="255" value="{{ $fee['note'] }}"></label>
|
||||
<button type="submit">保存</button>
|
||||
<span class="cbr-muted">空着 = 用厂家附加费单号匹配结算表的自算金额。</span>
|
||||
<span class="cbr-muted">空着 = 用厂家附加费表自动带入的值。</span>
|
||||
</form>
|
||||
</details>
|
||||
</td>
|
||||
|
||||
@ -1,17 +0,0 @@
|
||||
@if ($surchargeRows !== null && $surchargeRows->total() > 0)
|
||||
<section class="cbr-panel" aria-label="附加费核对明细">
|
||||
<h3>附加费核对明细</h3>
|
||||
<p class="cbr-muted cbr-panel-body">按账单月份归集,以单号、附加费类型和快递归属匹配结算金额,可匹配以前月份的费用。未匹配的金额留空,重复费用不再计入;不会将对方金额作为自算金额。</p>
|
||||
<div class="cbr-scroll"><table>
|
||||
<thead><tr>@foreach (['来源工作表','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'] as $label)<th scope="col">{{ $label }}</th>@endforeach</tr></thead>
|
||||
<tbody>@foreach ($surchargeRows as $fee)<tr>
|
||||
<td>{{ $fee->sheet }} · {{ $fee->row_no }}</td><td>{{ $fee->waybill_no }}</td><td>{{ $fee->item }}</td>
|
||||
<td class="num">{{ $money($fee->bill_amount) }}</td><td class="num">{{ $money($fee->self_amount) }}</td>
|
||||
<td class="num">{{ $fee->self_amount === null ? '—' : $money((float)$fee->bill_amount - (float)$fee->self_amount) }}</td>
|
||||
<td>{{ $fee->match_status }}</td><td>{{ $fee->courier_name ?: '—' }}</td><td>{{ $fee->platform_product_id ?: '—' }}</td>
|
||||
<td>{{ $fee->product_code ?: '—' }}</td><td>{{ $fee->shop_name ?: '—' }}</td><td>{{ $fee->online_order_no ?: '—' }}</td><td class="wrap">{{ $fee->match_note }}</td>
|
||||
</tr>@endforeach</tbody>
|
||||
</table></div>
|
||||
<div class="cbr-footer cbr-pager">共 {{ number_format($surchargeRows->total()) }} 条 {{ $surchargeRows->links('business.partials.previous-next-pagination') }}</div>
|
||||
</section>
|
||||
@endif
|
||||
@ -1,61 +0,0 @@
|
||||
<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
|
||||
@ -116,8 +116,7 @@
|
||||
|
||||
.bank-bills__filters {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(12rem, 1fr) minmax(10rem, .8fr) minmax(23rem, 1.8fr) auto;
|
||||
align-items: end;
|
||||
grid-template-columns: minmax(11rem, 1.1fr) minmax(12rem, 1.35fr) minmax(15rem, 1.5fr) minmax(9rem, .8fr);
|
||||
gap: .75rem;
|
||||
padding: .9rem 1rem;
|
||||
}
|
||||
@ -152,15 +151,10 @@
|
||||
}
|
||||
|
||||
.bank-bills__actions {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: .5rem;
|
||||
padding-bottom: .05rem;
|
||||
}
|
||||
|
||||
.bank-bills__filters .ledger-field--date-range {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bank-bills__btn {
|
||||
@ -885,65 +879,6 @@
|
||||
</style>
|
||||
|
||||
<div class="bank-bills">
|
||||
<form class="bank-bills__filters" method="GET" action="{{ request()->url() }}" aria-label="银行账单筛选">
|
||||
<input type="hidden" name="tab" value="bills">
|
||||
@if ($filters['search'] !== '')
|
||||
<input type="hidden" name="bills_search" value="{{ $filters['search'] }}">
|
||||
@endif
|
||||
@if ($filters['filter_column'] !== '')
|
||||
<input type="hidden" name="bills_filter_column" value="{{ $filters['filter_column'] }}">
|
||||
<input type="hidden" name="bills_filter_values" value="{{ json_encode($filters['filter_values'], JSON_UNESCAPED_UNICODE) }}">
|
||||
@endif
|
||||
@if ($filters['sort_column'] !== '' && in_array($filters['sort_direction'], ['asc', 'desc'], true))
|
||||
<input type="hidden" name="bills_sort_column" value="{{ $filters['sort_column'] }}">
|
||||
<input type="hidden" name="bills_sort_direction" value="{{ $filters['sort_direction'] }}">
|
||||
@endif
|
||||
|
||||
<label class="bank-bills__field">
|
||||
<span>账户</span>
|
||||
<select name="bills_account_no">
|
||||
<option value="">全部账户</option>
|
||||
@foreach ($accountOptions as $account)
|
||||
<option
|
||||
value="{{ $account['account_no'] }}"
|
||||
data-bank="{{ $account['bank_name'] }}"
|
||||
@selected($filters['account_no'] === $account['account_no'])
|
||||
>{{ $account['label'] }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="bank-bills__field">
|
||||
<span>来源</span>
|
||||
<select name="bills_bank">
|
||||
<option value="all" @selected($filters['bank'] === 'all')>全部</option>
|
||||
@foreach ($bankOptions as $bank)
|
||||
<option value="{{ $bank }}" @selected($filters['bank'] === $bank)>{{ $bank }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
|
||||
@include('business.pages.financial-ledger.partials.date-range-filter', [
|
||||
'id' => 'bank-bills-period',
|
||||
'label' => '查询时间段',
|
||||
'startName' => 'bills_from',
|
||||
'endName' => 'bills_to',
|
||||
'from' => $filters['from'],
|
||||
'to' => $filters['to'],
|
||||
])
|
||||
|
||||
<div class="bank-bills__actions">
|
||||
<a class="bank-bills__btn" href="{{ request()->url() . '?tab=bills' }}">
|
||||
<span class="material-icons-outlined" aria-hidden="true">refresh</span>
|
||||
重置
|
||||
</a>
|
||||
<button class="bank-bills__btn bank-bills__btn--primary" type="submit">
|
||||
<span class="material-icons-outlined" aria-hidden="true">search</span>
|
||||
查询
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section class="bank-bills__table-panel">
|
||||
<header class="bank-bills__table-head">
|
||||
<div>
|
||||
|
||||
@ -169,7 +169,7 @@
|
||||
数据源=各平台已导入账单(与「店铺收款账户账单」同源);<b>财务备注</b>、<b>财务类型</b>由科目映射表按「平台+账单项目(wx 自动去前缀)」带出,匹配不到的留空并标红。
|
||||
@if ($expenseOnly)
|
||||
本页只展示科目映射表中<b>财务类型=费用</b>的账单;费用按<b>账单费用</b>分类汇总,金额单位为<b>万</b>。
|
||||
<b>税务类型</b>和<b>公司主体</b>按账单发生时间匹配店铺主体有效期,跨主体变更的明细分别显示对应主体。
|
||||
<b>税务类型</b>和<b>公司主体</b>按店铺当前存续主体带出。
|
||||
@else
|
||||
同一交易单号跨月合并后已与订单实付对平的,差额备注优先显示为<b>差额=跨月收款(合并已对平)</b>;未对平仍显示<b>差额待核实</b>。
|
||||
@endif
|
||||
|
||||
@ -227,6 +227,14 @@
|
||||
color: var(--nsm-warning);
|
||||
}
|
||||
|
||||
.nsm-table-note {
|
||||
display: block;
|
||||
margin-top: .25rem;
|
||||
color: var(--nsm-muted);
|
||||
font-size: .625rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.nsm-distribution-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
@ -1962,6 +1970,10 @@
|
||||
<div class="nsm-fund-kpi @if(($fundOverview['opening_missing_accounts'] ?? 0) > 0) nsm-fund-kpi--warning @endif">
|
||||
<span>期初余额</span>
|
||||
<strong>{{ $moneyWanOptional($fundOverview['opening_balance']) }}</strong>
|
||||
<small>
|
||||
{{ number_format((int) $fundOverview['opening_accounts']) }} /
|
||||
{{ number_format((int) $fundOverview['total_accounts']) }} 户已锁定月度期初
|
||||
</small>
|
||||
</div>
|
||||
<div class="nsm-fund-kpi">
|
||||
<span>期末总余额</span>
|
||||
@ -2041,6 +2053,10 @@
|
||||
<td class="num">
|
||||
{{ $moneyWanOptional($distribution['opening_balance']) }}
|
||||
@if ($distribution['opening_balance'] !== null) 万 @endif
|
||||
<small class="nsm-table-note">
|
||||
{{ number_format((int) $distribution['opening_accounts']) }} /
|
||||
{{ number_format((int) $distribution['count']) }} 户
|
||||
</small>
|
||||
</td>
|
||||
<td class="num">{{ $moneyWan($distribution['current_balance']) }} 万</td>
|
||||
<td class="num">{{ $moneyWan($distribution['available_balance']) }} 万</td>
|
||||
@ -2069,6 +2085,10 @@
|
||||
<td class="num">
|
||||
{{ $moneyWanOptional($fundOverview['opening_balance']) }}
|
||||
@if ($fundOverview['opening_balance'] !== null) 万 @endif
|
||||
<small class="nsm-table-note">
|
||||
{{ number_format((int) $fundOverview['opening_accounts']) }} /
|
||||
{{ number_format((int) $fundOverview['total_accounts']) }} 户
|
||||
</small>
|
||||
</td>
|
||||
<td class="num">{{ $moneyWan($fundOverview['current_balance']) }} 万</td>
|
||||
<td class="num">{{ $moneyWan($fundOverview['available_balance']) }} 万</td>
|
||||
|
||||
@ -11,6 +11,22 @@
|
||||
|
||||
$platforms = $amOptions['platforms'] ?? [];
|
||||
$categories = $amOptions['categories'] ?? [];
|
||||
$coverageTimezone = trim((string) config('app.platform_timezone', ''))
|
||||
?: (string) config('app.timezone', 'UTC');
|
||||
$coverageDefaultMonth = \Carbon\CarbonImmutable::now($coverageTimezone)
|
||||
->subMonthNoOverflow()
|
||||
->format('Y-m');
|
||||
$coverageMonth = trim((string) request()->query('am_month', $coverageDefaultMonth));
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $coverageMonth) !== 1) {
|
||||
$coverageMonth = $coverageDefaultMonth;
|
||||
}
|
||||
$coverageMonths = [];
|
||||
$coverageMonthCursor = \Carbon\CarbonImmutable::createFromFormat('!Y-m', $coverageMonth);
|
||||
for ($coverageMonthIndex = 0; $coverageMonthIndex < 18; $coverageMonthIndex++) {
|
||||
$coverageMonths[] = $coverageMonthCursor
|
||||
->subMonthsNoOverflow($coverageMonthIndex)
|
||||
->format('Y-m');
|
||||
}
|
||||
$coverageInitialView = request()->query('am_view') === 'unmapped' ? 'unmapped' : 'rules';
|
||||
$outBase = 0;
|
||||
$inBase = 0;
|
||||
@ -186,11 +202,6 @@
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.am-coverage-range {
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-toolbar select {
|
||||
min-width: 9rem;
|
||||
height: 2.125rem;
|
||||
@ -243,13 +254,12 @@
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-notice[hidden] { display: none; }
|
||||
.am-coverage-table { min-width: 72rem; table-layout: fixed; }
|
||||
.am-coverage-table { min-width: 62rem; table-layout: fixed; }
|
||||
.am-coverage-table th,
|
||||
.am-coverage-table td { overflow: hidden; text-overflow: ellipsis; }
|
||||
.am-coverage-table .am-coverage-index { width: 3.5rem; }
|
||||
.am-coverage-table .am-coverage-platform { width: 7.5rem; }
|
||||
.am-coverage-table .am-coverage-item { width: 18rem; }
|
||||
.am-coverage-table .am-coverage-months { width: 10rem; }
|
||||
.am-coverage-table .am-coverage-source { width: 12rem; }
|
||||
.am-coverage-table .am-coverage-count { width: 7rem; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.am-coverage-table .am-coverage-stores { width: 10rem; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
@ -264,35 +274,7 @@
|
||||
font-size: 0.6875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.am-coverage-month-tag {
|
||||
display: inline-block;
|
||||
margin: 0.1rem 0.2rem 0.1rem 0;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border: 1px solid #ddd5c7;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #595959;
|
||||
font-size: 0.6875rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.am-coverage-store-hint { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; }
|
||||
.am-mapping-suggestion {
|
||||
margin: 0 0 0.75rem;
|
||||
padding: 0.65rem 0.8rem;
|
||||
border: 1px solid #d8c69b;
|
||||
border-radius: 8px;
|
||||
background: #fffaf0;
|
||||
color: #5f4a1f;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.am-mapping-suggestion--warning {
|
||||
border-color: #e4c8a2;
|
||||
background: #fff7ed;
|
||||
color: #8a541b;
|
||||
}
|
||||
.am-mapping-suggestion[hidden] { display: none; }
|
||||
|
||||
/* 表格必须锁列宽(table-layout:fixed)。默认的自动列宽会按内容互相挤压,
|
||||
「借方/贷方科目」两列会被挤到文字被截断;锁死后按上面 th 的宽度分配,
|
||||
@ -894,17 +876,24 @@
|
||||
>
|
||||
<div class="am-coverage-toolbar">
|
||||
<div class="am-coverage-toolbar__fields">
|
||||
<span class="am-coverage-range">统计最近 60 个月;清单生成后持续保留,每月自动更新一次</span>
|
||||
<button type="button" class="am-btn" id="amCoverageRefresh">立即刷新清单</button>
|
||||
<label for="amCoverageMonth">
|
||||
账单月份
|
||||
<select id="amCoverageMonth">
|
||||
@foreach ($coverageMonths as $monthOption)
|
||||
<option value="{{ $monthOption }}" @selected($monthOption === $coverageMonth)>{{ $monthOption }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="am-btn" id="amCoverageRefresh">生成最新清单</button>
|
||||
</div>
|
||||
<div class="am-coverage-summary" id="amCoverageSummary" aria-live="polite">
|
||||
<strong>跨月全部账单</strong>
|
||||
<span>正在读取未映射账单项目……</span>
|
||||
<strong>{{ $coverageMonth }}</strong>
|
||||
<span>正在读取该月账单项目……</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="am-coverage-notice" id="amCoverageNotice" role="status" hidden></div>
|
||||
<div class="am-coverage-state" id="amCoverageState">
|
||||
正在读取最近 60 个月的账单项目,请稍候。
|
||||
正在读取该月账单项目,请稍候。
|
||||
</div>
|
||||
<div class="upstream-data-table-panel" id="amCoverageTableWrap" hidden>
|
||||
<div class="upstream-data-table-scroll">
|
||||
@ -914,7 +903,6 @@
|
||||
<th class="am-coverage-index">序号</th>
|
||||
<th class="am-coverage-platform">平台</th>
|
||||
<th class="am-coverage-item">账单项目</th>
|
||||
<th class="am-coverage-months">账单月份</th>
|
||||
<th class="am-coverage-source">来源账单</th>
|
||||
<th class="am-coverage-count">影响行数</th>
|
||||
<th class="am-coverage-stores">店铺数</th>
|
||||
@ -946,7 +934,6 @@
|
||||
<button type="button" class="am-modal__close" id="amCoverageMappingClose">✕</button>
|
||||
</div>
|
||||
<div class="am-modal__body">
|
||||
<div class="am-mapping-suggestion" id="amCoverageMappingSuggestion" role="status" hidden></div>
|
||||
<div class="am-mapping-form" id="amCoverageMappingForm"></div>
|
||||
<div class="am-mapping-error" id="amCoverageMappingError" role="alert" hidden></div>
|
||||
</div>
|
||||
@ -969,6 +956,7 @@
|
||||
var ROWS = @json($amRows, JSON_UNESCAPED_UNICODE);
|
||||
var OPTIONS = @json($amOptions, JSON_UNESCAPED_UNICODE);
|
||||
var SUMMARY = @json($amSummary, JSON_UNESCAPED_UNICODE);
|
||||
var INITIAL_COVERAGE_MONTH = @json($coverageMonth);
|
||||
var INITIAL_VIEW = @json($coverageInitialView);
|
||||
var COA = null;
|
||||
var editingId = null;
|
||||
@ -1227,6 +1215,7 @@
|
||||
/* ---------- 账单覆盖:已配置规则 / 未映射账单项目 ---------- */
|
||||
var viewButtons = Array.prototype.slice.call(document.querySelectorAll('[data-am-view-tab]'));
|
||||
var viewPanels = Array.prototype.slice.call(document.querySelectorAll('[data-am-view-panel]'));
|
||||
var coverageMonthEl = document.getElementById('amCoverageMonth');
|
||||
var coverageCountEl = document.getElementById('amCoverageCount');
|
||||
var coverageSummaryEl = document.getElementById('amCoverageSummary');
|
||||
var coverageStateEl = document.getElementById('amCoverageState');
|
||||
@ -1236,7 +1225,6 @@
|
||||
var coverageNoticeEl = document.getElementById('amCoverageNotice');
|
||||
var coverageMappingModal = document.getElementById('amCoverageMappingModal');
|
||||
var coverageMappingFormEl = document.getElementById('amCoverageMappingForm');
|
||||
var coverageMappingSuggestionEl = document.getElementById('amCoverageMappingSuggestion');
|
||||
var coverageMappingErrorEl = document.getElementById('amCoverageMappingError');
|
||||
var coverageNoticeTimer = null;
|
||||
|
||||
@ -1270,18 +1258,18 @@
|
||||
if (updateUrl !== false) {
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.set('am_view', selected);
|
||||
url.searchParams.delete('am_month');
|
||||
url.searchParams.set('am_month', coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH);
|
||||
window.history.replaceState({}, '', url);
|
||||
}
|
||||
if (selected === 'unmapped' && !coverageData && !coverageLoading) {
|
||||
loadCoverage();
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCoverageSummary(data) {
|
||||
if (!coverageSummaryEl) { return; }
|
||||
coverageSummaryEl.innerHTML = '';
|
||||
var month = data && data.scope === 'all' ? '跨月全部账单' : String(data && data.month || '');
|
||||
var month = String(data && data.month ? data.month : (coverageMonthEl ? coverageMonthEl.value : ''));
|
||||
var title = document.createElement('strong');
|
||||
title.textContent = month;
|
||||
coverageSummaryEl.appendChild(title);
|
||||
@ -1318,7 +1306,6 @@
|
||||
|
||||
function coverageRowHtml(row, index) {
|
||||
var rawItems = Array.isArray(row.raw_items) ? row.raw_items : [];
|
||||
var months = Array.isArray(row.months) ? row.months : [];
|
||||
var sourceLabels = Array.isArray(row.source_labels) ? row.source_labels : [];
|
||||
var storeSamples = Array.isArray(row.store_samples) ? row.store_samples : [];
|
||||
var platform = String(row.platform || '');
|
||||
@ -1330,9 +1317,6 @@
|
||||
+ '<td title="' + esc(row.platform_label || row.platform || '未识别平台') + '">' + esc(row.platform_label || row.platform || '未识别平台') + '</td>'
|
||||
+ '<td title="' + esc(rawHint ? item + ';原始项目:' + rawHint : item) + '"><strong>' + esc(item) + '</strong>'
|
||||
+ (rawHint ? '<div class="am-coverage-store-hint">原始:' + esc(rawHint) + '</div>' : '') + '</td>'
|
||||
+ '<td title="' + esc(months.join('、')) + '">' + months.map(function (month) {
|
||||
return '<span class="am-coverage-month-tag">' + esc(month) + '</span>';
|
||||
}).join('') + '</td>'
|
||||
+ '<td>' + sourceLabels.map(function (label) {
|
||||
return '<span class="am-coverage-source-tag">' + esc(label) + '</span>';
|
||||
}).join('') + '</td>'
|
||||
@ -1350,10 +1334,10 @@
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '正在读取最近 60 个月的账单项目,请稍候。';
|
||||
coverageStateEl.textContent = '正在读取该月账单项目,请稍候。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>跨月全部账单</strong><span>正在读取……</span>';
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>正在读取……</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -1365,7 +1349,7 @@
|
||||
coverageStateEl.textContent = coverageError;
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>跨月全部账单</strong><span>读取失败</span>';
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>读取失败</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -1374,7 +1358,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '切换到此视图后读取跨月已有快照。';
|
||||
coverageStateEl.textContent = '切换到此视图后读取该月已有快照。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
return;
|
||||
}
|
||||
@ -1383,7 +1367,7 @@
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '后台正在生成跨月清单。批处理完成后,点击“读取生成结果”;本页不会自动轮询。';
|
||||
coverageStateEl.textContent = '后台正在按月生成。批处理完成后,点击“读取生成结果”;本页不会自动轮询。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1393,7 +1377,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '跨月未映射清单尚未生成;每月会自动刷新一次,也可点击“立即刷新清单”。';
|
||||
coverageStateEl.textContent = '所选月份尚未生成未映射清单,请点击“生成最新清单”。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1403,7 +1387,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state am-coverage-state--error';
|
||||
coverageStateEl.textContent = coverageData.message || '跨月未映射清单生成失败,请点击“立即刷新清单”重试。';
|
||||
coverageStateEl.textContent = coverageData.message || '该月未映射清单生成失败,请点击“生成最新清单”重试。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1413,7 +1397,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '最近 60 个月暂无已导入账单,暂时无法生成未映射科目清单。';
|
||||
coverageStateEl.textContent = '所选月份暂无已导入账单,暂时无法生成未映射科目清单。请更换月份或等待账单同步完成。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1425,7 +1409,7 @@
|
||||
if (!items.length) {
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '当前账单中的所有账单项目均已配置科目映射。';
|
||||
coverageStateEl.textContent = '所选月份的所有账单项目均已配置科目映射。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
coverageBodyEl.innerHTML = '';
|
||||
return;
|
||||
@ -1436,17 +1420,28 @@
|
||||
coverageBodyEl.innerHTML = items.map(coverageRowHtml).join('');
|
||||
}
|
||||
|
||||
function loadCoverage(bypassLocalCache, refreshServer) {
|
||||
function loadCoverage(month, bypassLocalCache, refreshServer) {
|
||||
if (coverageLoading) { return; }
|
||||
if (!bypassLocalCache && coverageData) {
|
||||
month = String(month || INITIAL_COVERAGE_MONTH || '');
|
||||
if (!bypassLocalCache && coverageData && coverageData.month === month) {
|
||||
renderCoverage();
|
||||
return;
|
||||
}
|
||||
coverageLoading = true;
|
||||
coverageError = '';
|
||||
renderCoverage();
|
||||
api('GET', '/coverage' + (refreshServer ? '?refresh=1' : '')).then(function (data) {
|
||||
api('GET', '/coverage?month=' + encodeURIComponent(month) + (refreshServer ? '&refresh=1' : '')).then(function (data) {
|
||||
coverageData = data;
|
||||
if (Array.isArray(data.months) && coverageMonthEl) {
|
||||
var current = coverageMonthEl.value;
|
||||
coverageMonthEl.innerHTML = data.months.map(function (value) {
|
||||
return '<option value="' + esc(value) + '">' + esc(value) + '</option>';
|
||||
}).join('');
|
||||
coverageMonthEl.value = data.months.indexOf(current) >= 0 ? current : month;
|
||||
if (coverageMonthEl.value !== month && data.months.indexOf(month) >= 0) {
|
||||
coverageMonthEl.value = month;
|
||||
}
|
||||
}
|
||||
}).catch(function (error) {
|
||||
coverageData = null;
|
||||
coverageError = '未映射账单项目读取失败:' + error.message;
|
||||
@ -1456,7 +1451,7 @@
|
||||
if (coverageRefreshEl) {
|
||||
coverageRefreshEl.textContent = coverageData && coverageData.status === 'refreshing'
|
||||
? '读取生成结果'
|
||||
: (coverageData && coverageData.status === 'failed' ? '重新刷新' : '立即刷新清单');
|
||||
: (coverageData && coverageData.status === 'failed' ? '重新生成' : '生成最新清单');
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -1476,10 +1471,16 @@
|
||||
selectView(button.getAttribute('data-am-view-tab'));
|
||||
});
|
||||
});
|
||||
coverageMonthEl?.addEventListener('change', function () {
|
||||
coverageData = null;
|
||||
hideCoverageNotice();
|
||||
loadCoverage(coverageMonthEl.value, true, false);
|
||||
});
|
||||
coverageRefreshEl?.addEventListener('click', function () {
|
||||
var month = coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH;
|
||||
var readOnly = coverageData && coverageData.status === 'refreshing';
|
||||
hideCoverageNotice();
|
||||
loadCoverage(true, !readOnly);
|
||||
loadCoverage(month, true, !readOnly);
|
||||
});
|
||||
|
||||
function mappingField(label, control, fullWidth) {
|
||||
@ -1501,34 +1502,6 @@
|
||||
+ mappingField('贷方科目', acctEditor('cAcct', 'cSub'));
|
||||
}
|
||||
|
||||
function renderCoverageSuggestion(suggestion) {
|
||||
if (!coverageMappingSuggestionEl) { return; }
|
||||
coverageMappingSuggestionEl.className = 'am-mapping-suggestion';
|
||||
coverageMappingSuggestionEl.hidden = true;
|
||||
coverageMappingSuggestionEl.textContent = '';
|
||||
if (!suggestion || !suggestion.auto_fill) {
|
||||
if (suggestion && suggestion.reason === 'ambiguous_templates') {
|
||||
coverageMappingSuggestionEl.className = 'am-mapping-suggestion am-mapping-suggestion--warning';
|
||||
coverageMappingSuggestionEl.textContent = '已找到同名账单项目,但历史规则使用了不同科目,未自动带入,请手动核对。';
|
||||
coverageMappingSuggestionEl.hidden = false;
|
||||
} else if (suggestion && suggestion.reason === 'incomplete_template') {
|
||||
coverageMappingSuggestionEl.className = 'am-mapping-suggestion am-mapping-suggestion--warning';
|
||||
coverageMappingSuggestionEl.textContent = '已找到同名账单项目,但原规则字段不完整,未自动带入,请手动补齐。';
|
||||
coverageMappingSuggestionEl.hidden = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var source = Array.isArray(suggestion.sources) && suggestion.sources.length ? suggestion.sources[0] : null;
|
||||
var sourceLabel = source
|
||||
? String(source.platform || '') + ' · ' + String(source.item || '')
|
||||
: '已有同名账单项目';
|
||||
coverageMappingSuggestionEl.textContent = '已根据「' + sourceLabel + '」自动带入'
|
||||
+ (Number(suggestion.matched_count || 0) > 1 ? '(共 ' + Number(suggestion.matched_count) + ' 条一致规则)' : '')
|
||||
+ ',请核对后保存。';
|
||||
coverageMappingSuggestionEl.hidden = false;
|
||||
}
|
||||
|
||||
function showCoverageMappingError(message) {
|
||||
if (!coverageMappingErrorEl) { return; }
|
||||
coverageMappingErrorEl.textContent = message;
|
||||
@ -1538,10 +1511,6 @@
|
||||
function closeCoverageMapping() {
|
||||
if (coverageMappingModal) { coverageMappingModal.hidden = true; }
|
||||
if (coverageMappingErrorEl) { coverageMappingErrorEl.hidden = true; }
|
||||
if (coverageMappingSuggestionEl) {
|
||||
coverageMappingSuggestionEl.hidden = true;
|
||||
coverageMappingSuggestionEl.textContent = '';
|
||||
}
|
||||
closeMemoPicker();
|
||||
editingId = null;
|
||||
draft = null;
|
||||
@ -1553,13 +1522,7 @@
|
||||
return;
|
||||
}
|
||||
hideCoverageNotice();
|
||||
var suggestionRequest = api(
|
||||
'GET',
|
||||
'/suggest?platform=' + encodeURIComponent(platform || '')
|
||||
+ '&item=' + encodeURIComponent(item || '')
|
||||
).catch(function () { return null; });
|
||||
Promise.all([loadCoa(), suggestionRequest]).then(function (results) {
|
||||
var suggestion = results[1];
|
||||
loadCoa().then(function () {
|
||||
draft = {
|
||||
platform: platform || '',
|
||||
item: item || '',
|
||||
@ -1574,18 +1537,7 @@
|
||||
cSub: '',
|
||||
basis: '支出基准'
|
||||
};
|
||||
if (suggestion && suggestion.auto_fill && suggestion.values) {
|
||||
[
|
||||
'memo', 'invoice', 'category', 'feeMemo',
|
||||
'dAcct', 'dSub', 'cAcct', 'cSub', 'basis'
|
||||
].forEach(function (field) {
|
||||
if (Object.prototype.hasOwnProperty.call(suggestion.values, field)) {
|
||||
draft[field] = suggestion.values[field];
|
||||
}
|
||||
});
|
||||
}
|
||||
editingId = 'coverage-modal';
|
||||
renderCoverageSuggestion(suggestion);
|
||||
renderCoverageMappingForm();
|
||||
var saveButton = document.getElementById('amCoverageMappingSave');
|
||||
if (saveButton) {
|
||||
@ -1621,7 +1573,7 @@
|
||||
showCoverageNotice('已保存映射:' + savedLabel + '。未映射清单已按新规则更新。');
|
||||
toast('映射已保存。');
|
||||
coverageData = null;
|
||||
loadCoverage(true, false);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
}).catch(function (e) {
|
||||
showCoverageMappingError(e.message);
|
||||
toast(e.message, 'err');
|
||||
|
||||
@ -28,7 +28,6 @@
|
||||
['label' => '完成时间', 'field' => 'completed_at'],
|
||||
];
|
||||
$syncCode = $smallPaymentSyncStatus['code'] ?? 'unavailable';
|
||||
$storeSummary = $smallPaymentStoreSummary ?? [];
|
||||
$syncLabel = match ($syncCode) {
|
||||
'healthy' => '业务镜像已同步',
|
||||
'syncing' => '业务镜像同步中,当前显示最近成功数据',
|
||||
@ -74,26 +73,6 @@
|
||||
border-radius: 0.5rem;
|
||||
background: var(--vip-surface, #ffffff);
|
||||
}
|
||||
.small-payment-summary__drilldown {
|
||||
display: block;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.small-payment-summary__drilldown:hover {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
background: var(--vip-content-accent-soft, #f7f0de);
|
||||
}
|
||||
.small-payment-summary__drilldown:focus-visible {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2);
|
||||
outline: none;
|
||||
}
|
||||
.small-payment-summary__drilldown:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.small-payment-summary__label {
|
||||
display: block;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
@ -107,160 +86,6 @@
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
}
|
||||
.small-payment-summary__hint {
|
||||
display: block;
|
||||
margin-top: 0.3rem;
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.small-payment-store-dialog {
|
||||
width: min(44rem, calc(100vw - 2rem));
|
||||
max-width: none;
|
||||
max-height: calc(100vh - 2rem);
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 0.75rem;
|
||||
background: var(--vip-surface, #ffffff);
|
||||
color: var(--vip-content-ink, #171717);
|
||||
box-shadow: 0 10px 30px rgba(23, 23, 23, 0.18);
|
||||
}
|
||||
.small-payment-store-dialog::backdrop { background: rgba(23, 23, 23, 0.38); }
|
||||
.small-payment-store-dialog[open] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.small-payment-store-dialog__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.1rem 0.8rem;
|
||||
border-bottom: 1px solid var(--vip-border, #d8d2c7);
|
||||
}
|
||||
.small-payment-store-dialog__head h2 {
|
||||
margin: 0;
|
||||
font-size: 0.9375rem;
|
||||
}
|
||||
.small-payment-store-dialog__head p {
|
||||
margin: 0.25rem 0 0;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.small-payment-store-dialog__side {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
}
|
||||
.small-payment-store-dialog__total {
|
||||
text-align: right;
|
||||
}
|
||||
.small-payment-store-dialog__total span {
|
||||
display: block;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.small-payment-store-dialog__total strong {
|
||||
display: block;
|
||||
margin-top: 0.2rem;
|
||||
font-size: 1rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.small-payment-store-dialog__close {
|
||||
display: inline-flex;
|
||||
width: 1.8rem;
|
||||
height: 1.8rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 50%;
|
||||
background: var(--vip-surface, #ffffff);
|
||||
color: var(--vip-content-muted, #595959);
|
||||
cursor: pointer;
|
||||
}
|
||||
.small-payment-store-dialog__filter {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(14rem, 22rem);
|
||||
gap: 0.75rem;
|
||||
padding: 0.8rem 1.1rem;
|
||||
border-bottom: 1px solid var(--vip-border, #d8d2c7);
|
||||
}
|
||||
.small-payment-store-dialog__filter span {
|
||||
display: block;
|
||||
margin-bottom: 0.25rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.small-payment-store-dialog__filter select {
|
||||
width: 100%;
|
||||
height: 2.1rem;
|
||||
padding: 0 0.5rem;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 0.375rem;
|
||||
background: var(--vip-surface, #ffffff);
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.small-payment-store-dialog__scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 0 1.1rem 0.65rem;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-color: var(--vip-content-accent, #b9954f) #f1ece3;
|
||||
scrollbar-gutter: stable;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.small-payment-store-dialog__table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
font-size: 0.75rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.small-payment-store-dialog__table col:first-child { width: 68%; }
|
||||
.small-payment-store-dialog__table col:last-child { width: 32%; }
|
||||
.small-payment-store-dialog__table th,
|
||||
.small-payment-store-dialog__table td {
|
||||
padding: 0.7rem 0.65rem;
|
||||
border-bottom: 1px solid #eee8dd;
|
||||
line-height: 1.5;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.small-payment-store-dialog__table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
background: var(--vip-content-accent-soft, #f7f0de);
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-weight: 600;
|
||||
}
|
||||
.small-payment-store-dialog__table .is-number {
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.small-payment-store-dialog__empty {
|
||||
padding: 2rem 0.5rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
text-align: center;
|
||||
}
|
||||
.small-payment-store-dialog__foot {
|
||||
padding: 0.65rem 1.1rem;
|
||||
border-top: 1px solid var(--vip-border, #d8d2c7);
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.small-payment-store-dialog__table tr[hidden] { display: none; }
|
||||
@media (max-width: 720px) {
|
||||
.small-payment-store-dialog__head { flex-direction: column; }
|
||||
.small-payment-store-dialog__side { width: 100%; justify-content: space-between; }
|
||||
.small-payment-store-dialog__filter { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
.small-payment-table--wide { min-width: 204rem; }
|
||||
.small-payment-table td.is-number,
|
||||
.small-payment-table th.is-number {
|
||||
@ -733,88 +558,12 @@
|
||||
<span class="small-payment-summary__label">筛选结果</span>
|
||||
<span class="small-payment-summary__value">{{ number_format($rows->total()) }} 条</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="small-payment-summary__item small-payment-summary__drilldown"
|
||||
data-small-payment-store-open
|
||||
aria-label="查看按店铺汇总的小额打款金额"
|
||||
@disabled($smallPaymentError || $smallPaymentPending || $smallPaymentIndexPending)
|
||||
>
|
||||
<div class="small-payment-summary__item">
|
||||
<span class="small-payment-summary__label">筛选出的打款金额合计</span>
|
||||
<span class="small-payment-summary__value">¥ {{ $smallPaymentFilteredAmount }}</span>
|
||||
<span class="small-payment-summary__hint">店铺金额 →</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dialog
|
||||
class="small-payment-store-dialog"
|
||||
id="small-payment-store-dialog"
|
||||
aria-labelledby="small-payment-store-dialog-title"
|
||||
>
|
||||
<div class="small-payment-store-dialog__head">
|
||||
<div>
|
||||
<h2 id="small-payment-store-dialog-title">小额打款 · 店铺汇总</h2>
|
||||
<p>按当前筛选条件汇总各店铺的打款金额</p>
|
||||
</div>
|
||||
<div class="small-payment-store-dialog__side">
|
||||
<div class="small-payment-store-dialog__total">
|
||||
<span>当前筛选合计</span>
|
||||
<strong data-small-payment-store-total>¥ {{ $smallPaymentFilteredAmount }}</strong>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="small-payment-store-dialog__close"
|
||||
data-small-payment-store-close
|
||||
aria-label="关闭小额打款店铺汇总"
|
||||
>×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="small-payment-store-dialog__filter">
|
||||
<label>
|
||||
<span>店铺名称</span>
|
||||
<select data-small-payment-store-filter aria-label="筛选小额打款店铺">
|
||||
<option value="">全部店铺</option>
|
||||
@foreach ($storeSummary as $store)
|
||||
<option value="{{ $store['shop_name'] }}">{{ $store['shop_name'] }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="small-payment-store-dialog__scroll">
|
||||
<table class="small-payment-store-dialog__table">
|
||||
<colgroup>
|
||||
<col>
|
||||
<col>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">店铺名称</th>
|
||||
<th scope="col" class="is-number">打款金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($storeSummary as $store)
|
||||
<tr
|
||||
data-small-payment-store-row
|
||||
data-shop-name="{{ $store['shop_name'] }}"
|
||||
data-payment-amount="{{ $store['payment_amount'] }}"
|
||||
>
|
||||
<td>{{ $store['shop_name'] }}</td>
|
||||
<td class="is-number">¥ {{ number_format((float) $store['payment_amount'], 2) }}</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="2" class="small-payment-store-dialog__empty">当前筛选范围没有店铺打款金额。</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="small-payment-store-dialog__foot">
|
||||
<span data-small-payment-store-count>共 {{ number_format(count($storeSummary)) }} 家店铺</span>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<div class="upstream-data-table-panel">
|
||||
<div class="upstream-data-table-scroll">
|
||||
<table
|
||||
@ -1274,88 +1023,8 @@
|
||||
syncClear();
|
||||
}
|
||||
|
||||
function setupStoreSummary() {
|
||||
var trigger = root.querySelector('[data-small-payment-store-open]');
|
||||
var dialog = document.getElementById('small-payment-store-dialog');
|
||||
if (!trigger || !dialog) {
|
||||
return;
|
||||
}
|
||||
|
||||
var filter = dialog.querySelector('[data-small-payment-store-filter]');
|
||||
var total = dialog.querySelector('[data-small-payment-store-total]');
|
||||
var count = dialog.querySelector('[data-small-payment-store-count]');
|
||||
var rows = Array.prototype.slice.call(
|
||||
dialog.querySelectorAll('[data-small-payment-store-row]')
|
||||
);
|
||||
|
||||
function centsFromMoney(value) {
|
||||
var match = /^(-?)(\d+)\.(\d{2})$/.exec(String(value || ''));
|
||||
if (!match) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var cents = (Number(match[2]) * 100) + Number(match[3]);
|
||||
return match[1] === '-' ? -cents : cents;
|
||||
}
|
||||
|
||||
function formatCents(cents) {
|
||||
var sign = cents < 0 ? '-' : '';
|
||||
var absolute = Math.abs(cents);
|
||||
var whole = Math.floor(absolute / 100).toLocaleString('zh-CN');
|
||||
return sign + '¥ ' + whole + '.' + String(absolute % 100).padStart(2, '0');
|
||||
}
|
||||
|
||||
function render() {
|
||||
var selected = filter ? filter.value : '';
|
||||
var visible = rows.filter(function (row) {
|
||||
return selected === '' || row.dataset.shopName === selected;
|
||||
});
|
||||
rows.forEach(function (row) {
|
||||
row.hidden = visible.indexOf(row) === -1;
|
||||
});
|
||||
|
||||
var amount = visible.reduce(function (sum, row) {
|
||||
return sum + centsFromMoney(row.dataset.paymentAmount);
|
||||
}, 0);
|
||||
|
||||
total.textContent = formatCents(amount);
|
||||
count.textContent = '共 ' + visible.length.toLocaleString('zh-CN') + ' 家店铺';
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (typeof dialog.close === 'function') {
|
||||
dialog.close();
|
||||
} else {
|
||||
dialog.removeAttribute('open');
|
||||
}
|
||||
}
|
||||
|
||||
trigger.addEventListener('click', function () {
|
||||
if (filter) {
|
||||
filter.value = '';
|
||||
}
|
||||
render();
|
||||
if (typeof dialog.showModal === 'function') {
|
||||
dialog.showModal();
|
||||
} else {
|
||||
dialog.setAttribute('open', '');
|
||||
}
|
||||
});
|
||||
|
||||
if (filter) {
|
||||
filter.addEventListener('change', render);
|
||||
}
|
||||
dialog.querySelector('[data-small-payment-store-close]').addEventListener('click', close);
|
||||
dialog.addEventListener('click', function (event) {
|
||||
if (event.target === dialog) {
|
||||
close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
root.querySelectorAll('[data-filter-combobox]').forEach(setupCombobox);
|
||||
root.querySelectorAll('[data-date-picker]').forEach(setupDatePicker);
|
||||
setupStoreSummary();
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
|
||||
@ -999,7 +999,7 @@
|
||||
{{-- 钉钉单页入口(菜单隐藏时)才需要目录内页签;网页端有左侧菜单和已打开页面标签栏,不再重复。 --}}
|
||||
@include('business.pages.partials.section-page-tabs', ['section' => $section])
|
||||
@elseif (($section['slug'] ?? '') === 'supplier-reconciliation')
|
||||
{{-- 供应商对账:财务端数据 / 原始账单 / 厂家端数据。 --}}
|
||||
{{-- 供应商对账:财务端数据 / 厂家端数据两个页签。 --}}
|
||||
@include('business.pages.partials.section-page-tabs', ['section' => $section])
|
||||
@elseif (($section['slug'] ?? '') === 'negative-alerts')
|
||||
{{-- 负数预警:供应商负数预警 / 快递负数预警两个页签。 --}}
|
||||
|
||||
@ -20,24 +20,6 @@
|
||||
.supplier-reconciliation-page .sr-button.is-small { height: 26px; padding: 0 9px; font-size: .75rem; }
|
||||
.supplier-reconciliation-page .sr-list-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.supplier-reconciliation-page .sr-list-actions form { margin: 0; }
|
||||
.supplier-reconciliation-page .sr-overview { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
|
||||
.supplier-reconciliation-page .sr-overview-stat { min-width: 0; border: 1px solid var(--vip-border, #D8D2C7); border-radius: 8px; background: #fff; }
|
||||
.supplier-reconciliation-page .sr-overview-stat summary { display: grid; gap: 3px; padding: 10px 12px; cursor: pointer; list-style: none; }
|
||||
.supplier-reconciliation-page .sr-overview-stat summary::-webkit-details-marker { display: none; }
|
||||
.supplier-reconciliation-page .sr-overview-stat summary::after { content: "点击查看明细"; margin-top: 2px; color: var(--vip-content-accent-dark, #856632); font-size: .6875rem; font-weight: 600; }
|
||||
.supplier-reconciliation-page .sr-overview-stat[open] summary::after { content: "收起明细"; }
|
||||
.supplier-reconciliation-page .sr-overview-stat.is-confirmed summary { border-top: 3px solid #53793E; }
|
||||
.supplier-reconciliation-page .sr-overview-stat.is-difference summary { border-top: 3px solid #935F07; }
|
||||
.supplier-reconciliation-page .sr-overview-stat.is-missing summary { border-top: 3px solid #006395; }
|
||||
.supplier-reconciliation-page .sr-overview-stat.is-total summary { border-top: 3px solid var(--vip-content-accent, #B9954F); }
|
||||
.supplier-reconciliation-page .sr-overview-label { color: #5B5343; font-size: .75rem; font-weight: 600; }
|
||||
.supplier-reconciliation-page .sr-overview-value { color: var(--vip-content-ink, #171717); font-size: 1.375rem; font-weight: 700; line-height: 1.2; font-variant-numeric: tabular-nums; }
|
||||
.supplier-reconciliation-page .sr-overview-detail { max-height: 18rem; overflow: auto; padding: 9px 12px 12px; border-top: 1px solid #EFEAE0; }
|
||||
.supplier-reconciliation-page .sr-overview-names { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; }
|
||||
.supplier-reconciliation-page .sr-overview-name { display: inline-flex; min-height: 26px; align-items: center; padding: 0 8px; border: 1px solid #DED3BD; border-radius: 999px; background: #FCFAF5; color: var(--vip-content-accent-dark, #856632); font-size: .75rem; font-weight: 600; text-decoration: none; }
|
||||
.supplier-reconciliation-page .sr-overview-name:hover,
|
||||
.supplier-reconciliation-page .sr-overview-name:focus-visible { border-color: var(--vip-content-accent-dark, #856632); background: var(--vip-content-accent-soft, #F7F0DE); }
|
||||
.supplier-reconciliation-page .sr-overview-empty { color: var(--vip-content-muted, #595959); font-size: .75rem; }
|
||||
.supplier-reconciliation-page .sr-batch-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 10px 12px; border: 1px solid #E4DCCB; border-radius: 8px; background: var(--vip-content-accent-soft, #F7F0DE); }
|
||||
.supplier-reconciliation-page .sr-batch-selection { display: flex; align-items: center; gap: 7px; color: #5B5343; font-size: .8125rem; font-weight: 600; }
|
||||
.supplier-reconciliation-page .sr-batch-selection input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); }
|
||||
@ -150,13 +132,9 @@
|
||||
@media (max-width: 900px) {
|
||||
.supplier-reconciliation-page .sr-robot-form { grid-template-columns: minmax(0, 1fr); }
|
||||
.supplier-reconciliation-page .sr-detail-actions { width: 100%; margin-left: 0; }
|
||||
.supplier-reconciliation-page .sr-overview { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.supplier-reconciliation-page .sr-summary-push { grid-template-columns: minmax(0, 1fr); }
|
||||
.supplier-reconciliation-page .sr-push-basis-values { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.supplier-reconciliation-page .sr-overview { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
.supplier-reconciliation-page .sr-empty { padding: 28px; border: 1px dashed var(--vip-border, #D8D2C7); border-radius: 8px; color: var(--vip-content-muted, #595959); font-size: .8125rem; text-align: center; }
|
||||
</style>
|
||||
|
||||
@ -186,6 +164,7 @@
|
||||
<div class="sr-filters">
|
||||
<label class="sr-field"><span>月份</span>
|
||||
<select name="month" onchange="this.form.submit()">
|
||||
<option value="">全部月份</option>
|
||||
@foreach ($months as $optionMonth)
|
||||
<option value="{{ $optionMonth }}" @selected($month === $optionMonth)>{{ $optionMonth }}</option>
|
||||
@endforeach
|
||||
@ -274,12 +253,6 @@
|
||||
'comparison_filter' => $comparisonFilter,
|
||||
], static fn (mixed $value): bool => $value !== '' && $value !== null)) }}"
|
||||
class="sr-button">导出当前筛选</a>
|
||||
<a href="{{ route('business.pages.show', [
|
||||
'section' => $section['slug'],
|
||||
'page' => 'raw-statements',
|
||||
'supplier' => $selectedSupplier,
|
||||
'month' => $month,
|
||||
]) }}" class="sr-button">查看原始账单</a>
|
||||
<form id="summary-push-form"
|
||||
method="POST"
|
||||
action="{{ route('business.supplier-reconciliation.push-summary') }}">
|
||||
@ -397,78 +370,16 @@
|
||||
<div class="sr-card">
|
||||
<h2>各厂家上传情况(实时)</h2>
|
||||
<p class="sr-hint">
|
||||
每页显示 15 家。月份默认显示最新账期,12 月默认显示 2026-11,1 月默认显示上一年 12 月;切换月份可查看历史账期。
|
||||
每页显示 15 家。选择具体月份后,退货推送按该月份统计;全部月份下优先显示各厂家最新有数据的退货月份。
|
||||
整月退货会包含待确认、已确认和异议中记录,钉钉群发送汇总和明细表格链接,不再在群内堆叠明细。勾选本页多家已配置机器人的厂家后,可批量推送。
|
||||
</p>
|
||||
@php
|
||||
$overviewDetailUrl = fn (string $supplier): string => route('business.pages.show', array_filter([
|
||||
'section' => $section['slug'],
|
||||
'page' => $page['slug'],
|
||||
'month' => $month,
|
||||
'reconciler' => $reconciler,
|
||||
'supplier' => $supplier,
|
||||
'supplier_page' => $supplierPage > 1 ? $supplierPage : null,
|
||||
], static fn (mixed $value): bool => $value !== '' && $value !== null));
|
||||
$overviewCards = [
|
||||
[
|
||||
'key' => 'total',
|
||||
'label' => '需要对账厂家',
|
||||
'className' => 'is-total',
|
||||
'data' => $reconciliationOverview['total'],
|
||||
],
|
||||
[
|
||||
'key' => 'confirmed',
|
||||
'label' => '已确认(发送即计入)',
|
||||
'className' => 'is-confirmed',
|
||||
'data' => $reconciliationOverview['confirmed'],
|
||||
],
|
||||
[
|
||||
'key' => 'difference',
|
||||
'label' => '有差异',
|
||||
'className' => 'is-difference',
|
||||
'data' => $reconciliationOverview['difference'],
|
||||
],
|
||||
[
|
||||
'key' => 'not_uploaded',
|
||||
'label' => '未上传账单',
|
||||
'className' => 'is-missing',
|
||||
'data' => $reconciliationOverview['not_uploaded'],
|
||||
],
|
||||
];
|
||||
$batchEligibleCount = count(array_filter(
|
||||
$supplierListRows,
|
||||
fn (string $supplier): bool => (int) ($returnCounts[$supplier] ?? 0) > 0
|
||||
&& (bool) ($robotConfigurations[$supplier]['configured'] ?? false),
|
||||
));
|
||||
@endphp
|
||||
<div class="sr-overview" aria-label="{{ $reconciliationOverview['month'] !== '' ? $reconciliationOverview['month'] : '全部月份' }}供应商对账进度">
|
||||
@foreach ($overviewCards as $card)
|
||||
<details class="sr-overview-stat {{ $card['className'] }}" data-overview="{{ $card['key'] }}">
|
||||
<summary>
|
||||
<span class="sr-overview-label">{{ $card['label'] }}</span>
|
||||
<strong class="sr-overview-value">{{ number_format((int) ($card['data']['count'] ?? 0)) }} 家</strong>
|
||||
</summary>
|
||||
<div class="sr-overview-detail">
|
||||
@if (($card['data']['suppliers'] ?? []) !== [])
|
||||
<ul class="sr-overview-names">
|
||||
@foreach ($card['data']['suppliers'] as $overviewSupplier)
|
||||
<li>
|
||||
<a class="sr-overview-name" href="{{ $overviewDetailUrl($overviewSupplier) }}">{{ $overviewSupplier }}</a>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@else
|
||||
<span class="sr-overview-empty">当前筛选范围没有厂家。</span>
|
||||
@endif
|
||||
</div>
|
||||
</details>
|
||||
@endforeach
|
||||
</div>
|
||||
<p class="sr-hint">
|
||||
统计跟随月份和对账人筛选;需要对账厂家按当前账期我方货款对账数据统计,“有差异”按双方数量或金额合计不一致统计,
|
||||
“未上传账单”按账单业务日期所属月份判断;已确认按“货款确认已成功发送”计数,厂家后续是否点击确认不影响这里。
|
||||
同一厂家可同时出现在“已确认”和“有差异”中,表示确认发送后对账数据又发生变化。
|
||||
</p>
|
||||
<form id="batch-return-push-form"
|
||||
method="POST"
|
||||
action="{{ route('business.supplier-reconciliation.push-returns-batch') }}">
|
||||
@ -521,12 +432,6 @@
|
||||
'supplier' => $supplier,
|
||||
'supplier_page' => $supplierPage > 1 ? $supplierPage : null,
|
||||
], static fn (mixed $value): bool => $value !== '' && $value !== null));
|
||||
$rawStatementUrl = route('business.pages.show', [
|
||||
'section' => $section['slug'],
|
||||
'page' => 'raw-statements',
|
||||
'supplier' => $supplier,
|
||||
'month' => $month,
|
||||
]);
|
||||
@endphp
|
||||
<tr>
|
||||
<td class="sr-list-select-cell">
|
||||
@ -550,7 +455,6 @@
|
||||
<td>
|
||||
<div class="sr-list-actions">
|
||||
<a class="sr-button is-small" href="{{ $detailUrl }}">查看比对</a>
|
||||
<a class="sr-button is-small" href="{{ $rawStatementUrl }}">原始账单</a>
|
||||
@if ($returnCount > 0)
|
||||
@if ($robotConfigured)
|
||||
<form method="POST"
|
||||
|
||||
@ -1,422 +0,0 @@
|
||||
<div class="raw-statement-page">
|
||||
<style>
|
||||
.raw-statement-page {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-card {
|
||||
min-width: 0;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 10px;
|
||||
background: var(--vip-surface, #FFFFFF);
|
||||
}
|
||||
|
||||
.raw-statement-page h2 {
|
||||
margin: 0;
|
||||
font-size: .875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-hint {
|
||||
margin: 5px 0 0;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: .75rem;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 9px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-field {
|
||||
display: grid;
|
||||
flex: 1 1 320px;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-field span {
|
||||
color: #5B5343;
|
||||
font-size: .75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-field input {
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font: inherit;
|
||||
font-size: .8125rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-field input:focus {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
outline: 0;
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, .20);
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-button {
|
||||
display: inline-flex;
|
||||
min-height: 34px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font-size: .8125rem;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-button.is-primary {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
background: var(--vip-content-accent-dark, #856632);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-button.is-small {
|
||||
min-height: 27px;
|
||||
padding: 0 9px;
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-alert {
|
||||
margin-top: 10px;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid #E2B7B2;
|
||||
border-radius: 8px;
|
||||
background: #FFF2F0;
|
||||
color: #8C2F26;
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-head-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-meta {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-meta-item {
|
||||
min-width: 0;
|
||||
padding: 9px 10px;
|
||||
border: 1px solid #E4DCCB;
|
||||
border-radius: 8px;
|
||||
background: #FCFAF5;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-meta-item span {
|
||||
display: block;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: .6875rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-meta-item strong {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
margin-top: 3px;
|
||||
font-size: .8125rem;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-history {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
margin: 10px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-history li {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(150px, .8fr) minmax(0, 1.5fr) 90px;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid #EFEAE0;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-history li:first-child {
|
||||
border-top: 1px solid #EFEAE0;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-history-file {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-table-wrap {
|
||||
max-height: min(66vh, 680px);
|
||||
overflow: auto;
|
||||
margin-top: 10px;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.raw-statement-page table {
|
||||
width: 100%;
|
||||
min-width: 1320px;
|
||||
border-collapse: collapse;
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.raw-statement-page th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
padding: 8px 9px;
|
||||
border-bottom: 1px solid var(--vip-border, #D8D2C7);
|
||||
background: var(--vip-content-accent-soft, #F7F0DE);
|
||||
color: #5B5343;
|
||||
font-size: .75rem;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.raw-statement-page td {
|
||||
padding: 7px 9px;
|
||||
border-bottom: 1px solid #EFEAE0;
|
||||
vertical-align: top;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.raw-statement-page td.is-number {
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
margin-top: 10px;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: .75rem;
|
||||
}
|
||||
|
||||
.raw-statement-page .rs-empty {
|
||||
margin-top: 12px;
|
||||
padding: 26px 16px;
|
||||
border: 1px dashed var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: .8125rem;
|
||||
line-height: 1.65;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.raw-statement-page .rs-meta { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.raw-statement-page .rs-meta { grid-template-columns: minmax(0, 1fr); }
|
||||
.raw-statement-page .rs-history li { grid-template-columns: minmax(0, 1fr); gap: 2px; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="rs-card">
|
||||
<h2>厂家上传原始账单</h2>
|
||||
<p class="rs-hint">
|
||||
这里只读查看厂家当前最新一版上传对账单的原始行,不参与比对结果修改。
|
||||
当前表格展示整份上传账单,不按月份拆行;上方上传记录可查看最近版本的上传时间和文件名。
|
||||
</p>
|
||||
<form method="GET"
|
||||
action="{{ route('business.pages.show', ['section' => $sectionSlug, 'page' => $pageSlug]) }}"
|
||||
class="rs-toolbar">
|
||||
<input type="hidden" name="section" value="{{ $sectionSlug }}">
|
||||
<input type="hidden" name="page" value="{{ $pageSlug }}">
|
||||
<input type="hidden" name="month" value="{{ $month }}">
|
||||
<label class="rs-field">
|
||||
<span>厂家名称</span>
|
||||
<input type="search"
|
||||
name="supplier"
|
||||
value="{{ $supplierQuery !== '' ? $supplierQuery : $selectedSupplier }}"
|
||||
list="raw-statement-supplier-options"
|
||||
placeholder="输入厂家名称搜索"
|
||||
autocomplete="off"
|
||||
required>
|
||||
<datalist id="raw-statement-supplier-options">
|
||||
@foreach ($supplierNames as $supplierName)
|
||||
<option value="{{ $supplierName }}"></option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
</label>
|
||||
<button type="submit" class="rs-button is-primary">查询厂家</button>
|
||||
</form>
|
||||
@if ($supplierNotFound)
|
||||
<div class="rs-alert" role="alert">未找到名为“{{ $supplierQuery }}”的厂家,请输入完整名称并从搜索建议中选择。</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@if ($selectedSupplier !== '')
|
||||
<div class="rs-card">
|
||||
<div class="rs-head">
|
||||
<div>
|
||||
<h2>{{ $selectedSupplier }} · 原始账单</h2>
|
||||
<p class="rs-hint">当前显示最新一版上传数据,共 {{ number_format($statementTotal) }} 行。</p>
|
||||
</div>
|
||||
<div class="rs-head-actions">
|
||||
@if ($latestUpload)
|
||||
<a class="rs-button is-primary" href="{{ route('business.supplier-reconciliation.raw-statement.export', [
|
||||
'supplier' => $selectedSupplier,
|
||||
]) }}">导出 Excel</a>
|
||||
@endif
|
||||
<a class="rs-button" href="{{ route('business.pages.show', [
|
||||
'section' => $sectionSlug,
|
||||
'page' => 'finance-data',
|
||||
'supplier' => $selectedSupplier,
|
||||
'month' => $month,
|
||||
]) }}">查看对账比对</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if ($latestUpload)
|
||||
<div class="rs-meta">
|
||||
<div class="rs-meta-item">
|
||||
<span>最近上传时间</span>
|
||||
<strong>{{ $latestUpload['uploaded_at'] ?? '—' }}</strong>
|
||||
</div>
|
||||
<div class="rs-meta-item">
|
||||
<span>文件名</span>
|
||||
<strong title="{{ $latestUpload['filename'] ?? '' }}">{{ $latestUpload['filename'] ?? '—' }}</strong>
|
||||
</div>
|
||||
<div class="rs-meta-item">
|
||||
<span>上传行数</span>
|
||||
<strong>{{ number_format((int) ($latestUpload['rows'] ?? 0)) }}</strong>
|
||||
</div>
|
||||
<div class="rs-meta-item">
|
||||
<span>当前比对账期</span>
|
||||
<strong>{{ $month }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (count($uploads) > 1)
|
||||
<ul class="rs-history" aria-label="最近上传记录">
|
||||
@foreach ($uploads as $upload)
|
||||
<li>
|
||||
<span>{{ $upload['uploaded_at'] ?? '—' }}</span>
|
||||
<span class="rs-history-file">{{ $upload['filename'] ?? '—' }}</span>
|
||||
<span>{{ number_format((int) ($upload['rows'] ?? 0)) }} 行</span>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
@endif
|
||||
|
||||
@if ($statementTotal > 0)
|
||||
<div class="rs-table-wrap">
|
||||
<table aria-label="{{ $selectedSupplier }} 最新上传原始账单">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">序号</th>
|
||||
<th scope="col">快递名称</th>
|
||||
<th scope="col">快递单号</th>
|
||||
<th scope="col">单据编号(采购单号)</th>
|
||||
<th scope="col">创建时间</th>
|
||||
<th scope="col">供应商</th>
|
||||
<th scope="col">条码</th>
|
||||
<th scope="col">规格名称</th>
|
||||
<th scope="col">数量</th>
|
||||
<th scope="col">单价</th>
|
||||
<th scope="col">金额</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($statementRows as $index => $row)
|
||||
<tr>
|
||||
<td>{{ number_format(($rowsPage - 1) * $perPage + $index + 1) }}</td>
|
||||
<td>{{ $row['expressName'] ?? '—' }}</td>
|
||||
<td>{{ $row['expressNo'] ?? '—' }}</td>
|
||||
<td>{{ $row['purchaseNo'] ?? '—' }}</td>
|
||||
<td>{{ $row['createdAt'] ?? '—' }}</td>
|
||||
<td>{{ $row['supplier'] ?? '—' }}</td>
|
||||
<td>{{ $row['barcode'] ?? '—' }}</td>
|
||||
<td>{{ $row['skuName'] ?? '—' }}</td>
|
||||
<td class="is-number">{{ $row['qty'] ?? '—' }}</td>
|
||||
<td class="is-number">{{ $row['unitPrice'] ?? '—' }}</td>
|
||||
<td class="is-number">{{ $row['amount'] ?? '—' }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@if ($statementPages > 1)
|
||||
@php
|
||||
$pageStart = max(1, min($rowsPage - 4, $statementPages - 8));
|
||||
$pageEnd = min($statementPages, $pageStart + 8);
|
||||
$pageUrl = fn (int $number): string => route('business.pages.show', [
|
||||
'section' => $sectionSlug,
|
||||
'page' => $pageSlug,
|
||||
'supplier' => $selectedSupplier,
|
||||
'month' => $month,
|
||||
'rows_page' => $number,
|
||||
]);
|
||||
@endphp
|
||||
<div class="rs-pagination">
|
||||
<span>第 {{ $rowsPage }} / {{ $statementPages }} 页,每页 {{ $perPage }} 行</span>
|
||||
@if ($rowsPage > 1)
|
||||
<a class="rs-button is-small" href="{{ $pageUrl($rowsPage - 1) }}">上一页</a>
|
||||
@endif
|
||||
@for ($number = $pageStart; $number <= $pageEnd; $number++)
|
||||
<a class="rs-button is-small {{ $number === $rowsPage ? 'is-primary' : '' }}"
|
||||
@if ($number === $rowsPage) aria-current="page" @endif
|
||||
href="{{ $pageUrl($number) }}">{{ $number }}</a>
|
||||
@endfor
|
||||
@if ($rowsPage < $statementPages)
|
||||
<a class="rs-button is-small" href="{{ $pageUrl($rowsPage + 1) }}">下一页</a>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
@else
|
||||
<div class="rs-empty">
|
||||
该厂家还没有上传对账单。厂家上传后,这里会显示最新一版原始账单和上传记录。
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@elseif (! $supplierNotFound)
|
||||
<div class="rs-card">
|
||||
<div class="rs-empty">
|
||||
还没有厂家上传过对账单。厂家上传后,可在上方选择厂家并查看原始账单。
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@ -522,7 +522,6 @@ Route::prefix('workspace/financial-rules/account-mapping/actions')
|
||||
Route::delete('rules/{id}', [AccountMappingActions::class, 'destroy'])->whereNumber('id')->name('rules.destroy');
|
||||
Route::get('accounts', [AccountMappingActions::class, 'accounts'])->name('accounts');
|
||||
Route::get('coverage', [AccountMappingActions::class, 'coverage'])->name('coverage');
|
||||
Route::get('suggest', [AccountMappingActions::class, 'suggest'])->name('suggest');
|
||||
// 操作记录:新增 / 修改 / 删除 / 导入 / 重置 的历史,供页面「操作记录」查看
|
||||
Route::get('history', [AccountMappingActions::class, 'history'])->name('history');
|
||||
Route::get('history/export', [AccountMappingActions::class, 'historyExport'])->name('history.export');
|
||||
@ -536,9 +535,8 @@ Route::prefix('workspace/financial-rules/account-mapping/actions')
|
||||
Route::get('template', [AccountMappingActions::class, 'template'])->name('template');
|
||||
});
|
||||
|
||||
// 终版页签和快递记账明细复用维护动作,各入口的数据独立存放。
|
||||
// 「终版」目录的按表数据独立存放,界面与基础页面一致。
|
||||
$payablesFinalDatasets = [
|
||||
'courier-payables' => ['bookkeeping-details'],
|
||||
'supplier-payables-final' => [
|
||||
'product-prices', 'payment-reconciliation', 'return-reconciliation', 'invoice-deductions',
|
||||
'board-deductions', 'compensation-details', 'advance-details', 'sample-deductions',
|
||||
@ -614,10 +612,6 @@ Route::get('workspace/supplier-reconciliation/comparison/export', [SupplierRecon
|
||||
->middleware('business.page:supplier-reconciliation,finance-data')
|
||||
->name('business.supplier-reconciliation.comparison.export');
|
||||
|
||||
Route::get('workspace/supplier-reconciliation/raw-statement/export', [SupplierReconciliationActions::class, 'exportRawStatement'])
|
||||
->middleware('business.page:supplier-reconciliation,finance-data')
|
||||
->name('business.supplier-reconciliation.raw-statement.export');
|
||||
|
||||
// 退货扣减确认:逐行确认/异议 + 一键全部确认
|
||||
Route::post('workspace/supplier-reconciliation/returns/confirm', [SupplierReconciliationActions::class, 'confirmReturn'])
|
||||
->middleware('business.page:supplier-reconciliation,supplier-data')
|
||||
@ -775,10 +769,6 @@ 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')
|
||||
@ -814,11 +804,8 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection)
|
||||
Route::post('groups/{group}/delete', [$controller, 'deleteGroup'])->whereNumber('group')->name('delete-group')->defaults('section', $courierBillSection);
|
||||
Route::post('groups/{group}/robot', [$controller, 'saveRobot'])->whereNumber('group')->name('save-robot')->defaults('section', $courierBillSection);
|
||||
Route::post('upload-links', [$controller, 'pushUploadLinks'])->name('push-upload-links')->defaults('section', $courierBillSection);
|
||||
Route::get('joint-upload-link', [$controller, 'jointUploadLink'])->name('joint-upload-link')->defaults('section', $courierBillSection);
|
||||
Route::post('groups/{group}/express-names', [$controller, 'addExpressName'])->whereNumber('group')->name('add-express-name')->defaults('section', $courierBillSection);
|
||||
Route::post('ledger/import', [$controller, 'importLedger'])->name('import-ledger')->defaults('section', $courierBillSection);
|
||||
Route::post('rebooks/import', [$controller, 'importRebooks'])->name('import-rebooks')->defaults('section', $courierBillSection);
|
||||
Route::post('rebooks/reviews', [$controller, 'importRebookReviews'])->name('import-rebook-reviews')->defaults('section', $courierBillSection);
|
||||
Route::post('summary-templates/import', [$controller, 'importSummaryTemplates'])->name('import-summary-templates')->defaults('section', $courierBillSection);
|
||||
});
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# 聚胜算每日账单导出(淘系微信 / 头条放心购 / 京东日账单 / 小红书 / 得物支付宝)
|
||||
# 聚胜算每日账单导出(头条放心购 / 京东日账单 / 小红书 / 得物支付宝)
|
||||
|
||||
把聚胜算「经营中心 → 平台原始账单[新]」的账单**定时导出并导入财务系统**(浏览器自动化 + 受控导入)。
|
||||
|
||||
@ -6,7 +6,6 @@
|
||||
|
||||
| `-Platform` | 胜算页签 | 导入命令 | 财务系统落点 |
|
||||
| --- | --- | --- | --- |
|
||||
| `taobao-wechat` | 淘系 → 微信账单 | `taobao-wechat-bills:import-authoritative` | **淘系微信账户** |
|
||||
| `toutiao` | 头条放心购 → 资金流水 | `business-mirror:import-douyin-authoritative` | 账单流水数据 › 店铺收款账户账单 › **抖音账户** |
|
||||
| `jd` | 京东商城 → 京东日账单 | `business-mirror:import-jd-daily` | **京东账单 + 京喜账单**(一次导入按店铺名拆两边,两边合计恒等于导出行数) |
|
||||
| `jd-wallet` | 京东商城 → 京东钱包 | `business-mirror:import-jd-wallet` | **京东网银钱包账户** |
|
||||
@ -19,9 +18,6 @@
|
||||
# 全部平台都跑:区间「月初 → 昨日」
|
||||
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1
|
||||
|
||||
# 补导淘系微信完整月份
|
||||
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform taobao-wechat -Start 2026-11-01 -Through 2026-11-30 -ForceImport
|
||||
|
||||
# 只跑京东,补历史月份
|
||||
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform jd -Through 2026-07-31
|
||||
|
||||
@ -39,8 +35,6 @@ pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform toutiao -Through
|
||||
```
|
||||
|
||||
- 归期:`--through`(默认昨日)所在月份;每月 1 日自动导出**上一个整月**。
|
||||
- **先核后拉**:每个平台先比较前一自然日的聚胜算源账单与财务系统同范围笔数、收入、支出;发现差异时先重导差异所属完整月份并复核,复核通过后才继续拉取新账单。
|
||||
- **月初回看**:每月 1-5 日额外核对上月末最后 5 个自然日,覆盖每月末账单在次月上旬才补到的情况;这 5 天存在差异时先补上月完整月份,再拉取当前月数据。
|
||||
- **先补旧账再拉新账**:每次运行先核对 `2026-07-01` 至本次截止日的覆盖情况。发现历史月份缺失、截止日不足、行数或金额不一致时,按月份从旧到新重导并复核;历史补数未通过时,不继续拉取该平台的新日期。
|
||||
- 每日失败自动顺延:当天任一平台导出、上传或导入失败,不写成功状态;次日覆盖核查会重新发现缺口并优先补齐。
|
||||
- **无差异跳过**:京东、京东钱包和头条该月已导入且笔数/收入/支出完全一致时跳过导入;小红书明细量小且会事后修订,每天重新导入最新版本。`-ForceImport` 可强制重刷其它平台;状态记在 `runtime/private/erp-exports/imported-state.json`。
|
||||
@ -96,5 +90,5 @@ sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=202
|
||||
|
||||
- 导入走财务系统既有受控导入命令(带笔数/收支核对、原子切换、保留旧版本可回滚),不改上游数据。
|
||||
- 凭据、导出文件、日志都写 `runtime/private/`(`.gitignore` 忽略),不进仓库。
|
||||
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(默认同时拉取淘系微信、头条、京东、京东钱包、小红书和得物支付宝;区间为本月月初→昨日,每月 1 日取上一整月)。
|
||||
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(默认同时拉取头条、京东、京东钱包、小红书和得物支付宝;区间为本月月初→昨日,每月 1 日取上一整月)。
|
||||
- 得物支付宝可单独安装定时任务:`pwsh -File scripts\erp-daily-bills\install-dewu-alipay-task.ps1`。默认每天 11:20 拉取,16:20 再执行一次兜底重试。
|
||||
|
||||
@ -1,14 +1,9 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { launchEdge, CDP, openPage, goto, evaluate, sleep } from './cdp.mjs';
|
||||
|
||||
const BASE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(BASE, '..', '..');
|
||||
const PROFILE = process.env.ERP_PROFILE
|
||||
|| path.join(REPO_ROOT, 'runtime', 'private', 'erp-profile');
|
||||
const PROFILE = 'F:\\Ai Code\\CaiWuXiTong\\runtime\\private\\erp-profile';
|
||||
const SECRET_FILE = process.env.ERP_SECRET_FILE
|
||||
|| path.join(REPO_ROOT, 'runtime', 'private', '敏感信息.md');
|
||||
|| 'F:\\Ai Code\\CaiWuXiTong\\runtime\\private\\敏感信息.md';
|
||||
|
||||
export function credentials() {
|
||||
const text = fs.readFileSync(SECRET_FILE, 'utf8');
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
/*
|
||||
* 聚胜算「平台原始账单[新]」每日账单导出(统一脚本,用 --platform 选平台)
|
||||
*
|
||||
* --platform=taobao-wechat 淘系 → 微信账单(导入 taobao-wechat-bills:import-authoritative → 淘系微信账户)
|
||||
* --platform=toutiao 头条放心购 → 资金流水 (导入 import-douyin-authoritative → 抖音账户)
|
||||
* --platform=jd 京东商城 → 京东日账单 (导入 import-jd-daily → 京东账单 + 京喜账单,按店铺名拆分)
|
||||
* --platform=jd-wallet 京东商城 → 京东钱包 (导入 import-jd-wallet → 京东网银钱包账户)
|
||||
@ -26,13 +25,6 @@ const BASE = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
/** 平台配置:页签、子页签、导出文件名前缀。 */
|
||||
const PLATFORMS = {
|
||||
'taobao-wechat': {
|
||||
label: '淘系',
|
||||
subTab: '微信账单',
|
||||
filePrefix: '淘系微信账单',
|
||||
exportMainName: '淘宝天猫微信账单',
|
||||
omitChannel: true,
|
||||
},
|
||||
toutiao: { label: '头条放心购', subTab: '资金流水', filePrefix: '头条放心购_资金流水', exportMainName: '头条放心购头条资金流水' },
|
||||
jd: { label: '京东商城', subTab: '京东日账单', filePrefix: '京东日账单', exportMainName: '京东商城京东日账单' },
|
||||
'jd-wallet': { label: '京东商城', subTab: '京东钱包', filePrefix: '京东钱包', exportMainName: '京东商城京东钱包' },
|
||||
@ -65,7 +57,7 @@ const accountNos = arg('account-nos', '')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
if (!platform) {
|
||||
throw new Error('未知平台:' + platformKey + '(可选 taobao-wechat / toutiao / jd / jd-wallet / xiaohongshu / dewu-alipay)');
|
||||
throw new Error('未知平台:' + platformKey + '(可选 toutiao / jd / jd-wallet / xiaohongshu / dewu-alipay)');
|
||||
}
|
||||
if (platform.accountFilter && accountNos.length === 0) {
|
||||
throw new Error('得物支付宝导出必须提供 --account-nos');
|
||||
@ -82,15 +74,8 @@ const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
|
||||
const conditions = [
|
||||
{ SerachFldName: 'ab.create_time', serachColName: '结算时间', value: monthStart, operatorSymbol: 'GreaterThanOrEqual' },
|
||||
{ SerachFldName: 'ab.create_time', serachColName: '结算时间', value: through, operatorSymbol: 'LessThan' },
|
||||
{ SerachFldName: 'ab.channel', value: platform.channel || 'TouTiaoFXGZJ', serachColName: '渠道', operatorSymbol: 'In' },
|
||||
];
|
||||
if (!platform.omitChannel) {
|
||||
conditions.push({
|
||||
SerachFldName: 'ab.channel',
|
||||
value: platform.channel || 'TouTiaoFXGZJ',
|
||||
serachColName: '渠道',
|
||||
operatorSymbol: 'In',
|
||||
});
|
||||
}
|
||||
|
||||
async function clickPoint(cdp, sid, x, y) {
|
||||
const pt = { x: Math.round(x), y: Math.round(y) };
|
||||
|
||||
@ -1,71 +0,0 @@
|
||||
function New-ErpBillWindow {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Label,
|
||||
[Parameter(Mandatory = $true)][datetime]$Start,
|
||||
[Parameter(Mandatory = $true)][datetime]$Through
|
||||
)
|
||||
|
||||
[pscustomobject]@{
|
||||
Label = $Label
|
||||
Start = $Start.Date
|
||||
Through = $Through.Date
|
||||
}
|
||||
}
|
||||
|
||||
function Get-ErpBillReconcileWindows {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][datetime]$PullThroughDate,
|
||||
[datetime]$RunDate = (Get-Date).Date
|
||||
)
|
||||
|
||||
$windows = [System.Collections.Generic.List[object]]::new()
|
||||
$previousDay = $PullThroughDate.Date
|
||||
|
||||
# 账单常在次月上旬才补到上月末。每月 1-5 日额外核对上月最后 5 个自然日。
|
||||
$previousMonthEnd = $null
|
||||
$previousMonthWindowStart = $null
|
||||
if ($RunDate.Day -le 5) {
|
||||
$previousMonthEnd = $RunDate.Date.AddDays(-$RunDate.Day)
|
||||
$previousMonthWindowStart = $previousMonthEnd.AddDays(-4)
|
||||
}
|
||||
|
||||
if ($null -eq $previousMonthEnd -or
|
||||
$previousDay -lt $previousMonthWindowStart -or
|
||||
$previousDay -gt $previousMonthEnd) {
|
||||
$windows.Add((New-ErpBillWindow -Label '前一日' -Start $previousDay -Through $previousDay))
|
||||
}
|
||||
if ($RunDate.Day -le 5) {
|
||||
$windows.Add((New-ErpBillWindow -Label '上月末5日' -Start $previousMonthWindowStart -Through $previousMonthEnd))
|
||||
}
|
||||
|
||||
$seen = @{}
|
||||
foreach ($window in $windows) {
|
||||
$key = '{0}:{1}' -f $window.Start.ToString('yyyy-MM-dd'), $window.Through.ToString('yyyy-MM-dd')
|
||||
if ($seen.ContainsKey($key)) {
|
||||
continue
|
||||
}
|
||||
$seen[$key] = $true
|
||||
$window
|
||||
}
|
||||
}
|
||||
|
||||
function Get-ErpBillMonthWindow {
|
||||
param([Parameter(Mandatory = $true)][datetime]$Date)
|
||||
|
||||
$monthStart = Get-Date -Year $Date.Year -Month $Date.Month -Day 1
|
||||
New-ErpBillWindow `
|
||||
-Label ('{0} 月补数' -f $Date.ToString('yyyy-MM')) `
|
||||
-Start $monthStart `
|
||||
-Through $monthStart.AddMonths(1).AddDays(-1)
|
||||
}
|
||||
|
||||
function Test-ErpBillSummaryMatch {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]$Source,
|
||||
[Parameter(Mandatory = $true)]$Server
|
||||
)
|
||||
|
||||
return ([int]$Source.rows -eq [int]$Server.row_count -and
|
||||
[long]$Source.incomeCents -eq [long]$Server.income_cents -and
|
||||
[long]$Source.expenseCents -eq [long]$Server.expense_cents)
|
||||
}
|
||||
@ -7,13 +7,221 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$arguments = @{
|
||||
Platform = 'dewu-alipay'
|
||||
}
|
||||
if ($Start) { $arguments.Start = $Start }
|
||||
if ($Through) { $arguments.Through = $Through }
|
||||
if ($SkipImport) { $arguments.SkipImport = $true }
|
||||
if ($ForceImport) { $arguments.ForceImport = $true }
|
||||
$root = $PSScriptRoot
|
||||
$self = (Get-Process -Id $PID).Path
|
||||
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {}
|
||||
. (Join-Path $root '..\deploy-auth.ps1')
|
||||
|
||||
& (Join-Path $PSScriptRoot 'run-erp-daily.ps1') @arguments
|
||||
exit $LASTEXITCODE
|
||||
$node = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
|
||||
$python = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe'
|
||||
$exportDir = Join-Path $root '..\..\runtime\private\erp-exports'
|
||||
$logDir = Join-Path $exportDir 'logs'
|
||||
$stateFile = Join-Path $exportDir 'dewu-alipay-state.json'
|
||||
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
|
||||
$logFile = Join-Path $logDir ((Get-Date -Format 'yyyyMMdd') + '.log')
|
||||
$accountsPath = Join-Path $root 'dewu-alipay-accounts.json'
|
||||
$accounts = @(Get-Content -LiteralPath $accountsPath -Raw | ConvertFrom-Json)
|
||||
if ($accounts.Count -eq 0) {
|
||||
throw '得物支付宝账号映射为空。'
|
||||
}
|
||||
|
||||
function Write-Log {
|
||||
param([string]$Message)
|
||||
$line = '{0} {1}' -f (Get-Date -Format 'HH:mm:ss'), $Message
|
||||
Write-Host $line
|
||||
Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8
|
||||
}
|
||||
|
||||
. (Join-Path $root 'erp-remote.ps1')
|
||||
$remoteSshScript = Join-Path $root '..\..\runtime\private\server-ssh.ps1'
|
||||
$remoteUploaderScript = Join-Path $root '..\..\runtime\private\upload-to-server.ps1'
|
||||
$remoteBatchRunner = '/opt/caiwuxitong/run-finance-batch.sh'
|
||||
$auth = $null
|
||||
|
||||
function Invoke-Remote {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Body,
|
||||
[string]$LocalFile = '',
|
||||
[string]$RemoteFile = ''
|
||||
)
|
||||
|
||||
return Invoke-ErpRemote `
|
||||
-PwshPath $self `
|
||||
-SshScript $remoteSshScript `
|
||||
-UploaderScript $remoteUploaderScript `
|
||||
-Body $Body `
|
||||
-LocalFile $LocalFile `
|
||||
-RemoteFile $RemoteFile `
|
||||
-RetryDelaySeconds 60 `
|
||||
-Log { param($message) Write-Log $message }
|
||||
}
|
||||
|
||||
try {
|
||||
$throughDate = if ($Through) {
|
||||
[datetime]::ParseExact($Through, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
|
||||
} else {
|
||||
(Get-Date).Date.AddDays(-1)
|
||||
}
|
||||
$through = $throughDate.ToString('yyyy-MM-dd')
|
||||
$monthStart = if ($Start) {
|
||||
([datetime]::ParseExact($Start, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)).ToString('yyyy-MM-dd')
|
||||
} else {
|
||||
$throughDate.ToString('yyyy-MM-01')
|
||||
}
|
||||
if ($monthStart.Substring(0, 7) -ne $through.Substring(0, 7)) {
|
||||
throw '得物支付宝单次导入必须位于同一个月份。'
|
||||
}
|
||||
$month = $monthStart.Substring(0, 7)
|
||||
$accountNos = ($accounts | ForEach-Object { [string]$_.merchant_no }) -join ','
|
||||
$storeNames = @($accounts | ForEach-Object { [string]$_.alipay_name })
|
||||
$storeArgs = ($storeNames | ForEach-Object { "--store='" + $_ + "'" }) -join ' '
|
||||
|
||||
Write-Log ('=== 得物支付宝:{0} ~ {1} ===' -f $monthStart, $through)
|
||||
$auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root'
|
||||
|
||||
$exportArgs = @(
|
||||
(Join-Path $root 'export-daily.mjs'),
|
||||
'--platform=dewu-alipay',
|
||||
('--out=' + $exportDir),
|
||||
('--account-nos=' + $accountNos),
|
||||
'--port=9360',
|
||||
('--profile=' + (Join-Path $exportDir '..\erp-profile-dewu-alipay')),
|
||||
('--start=' + $monthStart),
|
||||
('--through=' + $through)
|
||||
)
|
||||
$exportOk = $false
|
||||
for ($attempt = 1; $attempt -le 3 -and -not $exportOk; $attempt++) {
|
||||
$output = (& $node @exportArgs 2>&1 | Out-String)
|
||||
Write-Log ('导出:' + ($output.Trim() -replace "`r?`n", ' | '))
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$exportOk = $true
|
||||
break
|
||||
}
|
||||
if ($attempt -lt 3) { Start-Sleep -Seconds 20 }
|
||||
}
|
||||
if (-not $exportOk) {
|
||||
throw '得物支付宝导出连续失败。'
|
||||
}
|
||||
|
||||
$summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json
|
||||
if ($summary.empty) {
|
||||
Write-Log '该区间聚水潭得物支付宝暂无数据,未改动生产。'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$rawFiles = @($summary.files | ForEach-Object { [string]$_ })
|
||||
if ($rawFiles.Count -eq 0) {
|
||||
throw '导出结果没有文件。'
|
||||
}
|
||||
$rawFile = $rawFiles[0]
|
||||
$csvFile = if ($rawFiles.Count -gt 1) {
|
||||
[IO.Path]::ChangeExtension(($rawFile -replace '_part\d+(?=\.[^.]+$)', ''), '.csv')
|
||||
} else {
|
||||
[IO.Path]::ChangeExtension($rawFile, '.csv')
|
||||
}
|
||||
if ($rawFiles.Count -gt 1) {
|
||||
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') '--merge' $csvFile @rawFiles 2>&1 | Out-String)
|
||||
$importFile = [IO.Path]::ChangeExtension($csvFile, '.merged.xlsx')
|
||||
$merge = (& $python -X utf8 (Join-Path $root 'merge-xlsx.py') $importFile @rawFiles 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw ('XLSX 分片合并失败:' + ($merge.Trim() -replace "`r?`n", ' | '))
|
||||
}
|
||||
} else {
|
||||
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String)
|
||||
$importFile = $rawFile
|
||||
}
|
||||
|
||||
$line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1)
|
||||
if (-not $line) {
|
||||
throw ('账单转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | '))
|
||||
}
|
||||
$rows = [int]([regex]::Match($line, 'rows=(\d+)').Groups[1].Value)
|
||||
$income = [double]([regex]::Match($line, 'income=([\-\d\.]+)').Groups[1].Value)
|
||||
$expense = [double]([regex]::Match($line, 'expense=([\-\d\.]+)').Groups[1].Value)
|
||||
$limited = (& $python -X utf8 (Join-Path $root 'dewu-alipay-summary.py') $csvFile ('--accounts-json=' + $accountsPath) 2>&1 | Out-String)
|
||||
$limitedJson = (($limited -split "`n") | Where-Object { $_.TrimStart().StartsWith('{') } | Select-Object -Last 1)
|
||||
if (-not $limitedJson) {
|
||||
throw ('得物支付宝范围校验失败:' + ($limited.Trim() -replace "`r?`n", ' | '))
|
||||
}
|
||||
$limitedSummary = $limitedJson | ConvertFrom-Json
|
||||
if (([int]$limitedSummary.rows -ne $rows) -or
|
||||
([math]::Abs([double]$limitedSummary.income - $income) -ge 0.005) -or
|
||||
([math]::Abs([double]$limitedSummary.expense - $expense) -ge 0.005)) {
|
||||
throw '得物支付宝汇总与账户范围校验结果不一致。'
|
||||
}
|
||||
if ([int]$summary.pageCount -ne $rows) {
|
||||
throw ('页面笔数 {0} 与导出行数 {1} 不一致。' -f $summary.pageCount, $rows)
|
||||
}
|
||||
Write-Log ('核对数:笔数 {0},收入 {1},支出 {2}' -f $rows, $income, $expense)
|
||||
if ($SkipImport) {
|
||||
Write-Log '已指定 -SkipImport,未改动生产。'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$state = if (Test-Path -LiteralPath $stateFile) {
|
||||
Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
|
||||
} else {
|
||||
New-Object psobject
|
||||
}
|
||||
$previous = $state.$month
|
||||
if (-not $ForceImport -and $previous -and [int]$previous.rows -eq $rows -and
|
||||
[math]::Abs([double]$previous.income - $income) -lt 0.005 -and
|
||||
[math]::Abs([double]$previous.expense - $expense) -lt 0.005) {
|
||||
Write-Log '该月本地状态无差异,跳过导入。'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$remoteFile = '/tmp/dewu-alipay_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.xlsx'
|
||||
$invariant = [Globalization.CultureInfo]::InvariantCulture
|
||||
$verifyPhp = @"
|
||||
cat > /tmp/verify_dewu_alipay.php <<'PHP'
|
||||
<?php
|
||||
require '/var/www/html/vendor/autoload.php';
|
||||
`$app = require '/var/www/html/bootstrap/app.php';
|
||||
`$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
`$result = app(Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository::class)
|
||||
->paginate(['start' => '$monthStart', 'end' => '$through'], 'occurred_at', 'desc', 1, 1);
|
||||
echo 'PAGE total=' . `$result['total'] . ' ' . json_encode(`$result['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
if ((int) `$result['total'] !== $rows
|
||||
|| (int) round((float) `$result['summary']['income'] * 100) !== (int) round($($income.ToString('0.00', $invariant)) * 100)
|
||||
|| (int) round((float) `$result['summary']['expense'] * 100) !== (int) round($($expense.ToString('0.00', $invariant)) * 100)) {
|
||||
fwrite(STDERR, '得物支付宝页面回验不一致' . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
PHP
|
||||
docker exec -i -u www-data caiwu_app php < /tmp/verify_dewu_alipay.php
|
||||
rm -f /tmp/verify_dewu_alipay.php
|
||||
"@
|
||||
$body = @"
|
||||
set -e
|
||||
cleanup() {
|
||||
docker exec caiwu_app rm -f "$remoteFile" >/dev/null 2>&1 || true
|
||||
rm -f $remoteFile
|
||||
}
|
||||
trap cleanup EXIT
|
||||
sh $remoteBatchRunner taobao-alipay-bills:import-authoritative "$remoteFile" --from=$monthStart --to=$through --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=1000 $storeArgs
|
||||
$verifyPhp
|
||||
"@
|
||||
$import = Invoke-Remote -Body $body -LocalFile $importFile -RemoteFile $remoteFile
|
||||
Write-Log ('导入/回验:' + ($import.Output.Trim() -replace "`r?`n", ' | '))
|
||||
if (-not $import.Ok) {
|
||||
throw '得物支付宝导入或页面回验失败。'
|
||||
}
|
||||
|
||||
$state | Add-Member -NotePropertyName $month -NotePropertyValue ([pscustomobject]@{
|
||||
rows = $rows
|
||||
income = $income
|
||||
expense = $expense
|
||||
start = $monthStart
|
||||
through = $through
|
||||
file = $importFile
|
||||
at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
|
||||
}) -Force
|
||||
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
|
||||
Write-Log '=== 得物支付宝:完成 ==='
|
||||
} catch {
|
||||
Write-Log ('得物支付宝同步失败:' + $_.Exception.Message)
|
||||
exit 1
|
||||
} finally {
|
||||
if ($auth) { Stop-CaiwuDeploymentAuth $auth }
|
||||
}
|
||||
|
||||
@ -1,20 +1,17 @@
|
||||
<#
|
||||
聚胜算每日账单 → 财务系统(统一入口)
|
||||
|
||||
平台:taobao-wechat = 淘系→微信账单(落 淘系微信账户)
|
||||
toutiao = 头条放心购→资金流水(落 抖音账户)
|
||||
平台:toutiao = 头条放心购→资金流水(落 抖音账户)
|
||||
jd = 京东商城→京东日账单(一次导入按店铺名拆 京东账单 + 京喜账单)
|
||||
jd-wallet = 京东商城→京东钱包(落 京东网银钱包账户)
|
||||
xiaohongshu = 小红书→订单结算明细(落 小红书账户)
|
||||
dewu-alipay = 淘系支付宝账单,按得物店铺映射的 8 个支付宝账号拉取
|
||||
|
||||
流程:覆盖核查 → 前一日/月初上月末5日核对并补齐 → 补齐历史缺口 → 导出
|
||||
→ 汇总核验 / 与已导入期间比对(无差异则跳过)
|
||||
流程:覆盖核查 → 补齐历史缺口 → 导出 → 汇总核验 / 与已导入期间比对(无差异则跳过)
|
||||
→ 上传 → 受限批处理容器导入 → 页面回验 → 归档 → 写日志
|
||||
|
||||
用法:
|
||||
pwsh -File run-erp-daily.ps1 # 全部平台,区间「月初 → 昨日」
|
||||
pwsh -File run-erp-daily.ps1 -Platform taobao-wechat -Start 2026-11-01 -Through 2026-11-30 -ForceImport
|
||||
pwsh -File run-erp-daily.ps1 # 三个平台,区间「月初 → 昨日」
|
||||
pwsh -File run-erp-daily.ps1 -Platform jd -Through 2026-07-31
|
||||
pwsh -File run-erp-daily.ps1 -Platform jd-wallet -Through 2026-07-31
|
||||
pwsh -File run-erp-daily.ps1 -Platform toutiao -SkipImport
|
||||
@ -23,36 +20,23 @@
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('taobao-wechat', 'toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay', 'both')][string]$Platform = 'both',
|
||||
[ValidateSet('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay', 'both')][string]$Platform = 'both',
|
||||
[string]$Through,
|
||||
[string]$Start,
|
||||
[string]$CoverageFrom = '2026-07-01',
|
||||
[switch]$SkipImport,
|
||||
[switch]$ForceImport,
|
||||
[switch]$SkipCoverageCheck,
|
||||
[switch]$SkipPreviousDayCheck,
|
||||
[switch]$AuditOnly
|
||||
[switch]$SkipCoverageCheck
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = $PSScriptRoot
|
||||
$self = (Get-Process -Id $PID).Path
|
||||
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {}
|
||||
$invariant = [Globalization.CultureInfo]::InvariantCulture
|
||||
. (Join-Path $root '..\deploy-auth.ps1')
|
||||
. (Join-Path $root 'reconcile-windows.ps1')
|
||||
|
||||
$runtimeBase = Join-Path $HOME '.cache\codex-runtimes\codex-primary-runtime\dependencies'
|
||||
$node = if (Test-Path (Join-Path $runtimeBase 'node\bin\node.exe')) {
|
||||
Join-Path $runtimeBase 'node\bin\node.exe'
|
||||
} else {
|
||||
'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
|
||||
}
|
||||
$python = if (Test-Path (Join-Path $runtimeBase 'python\python.exe')) {
|
||||
Join-Path $runtimeBase 'python\python.exe'
|
||||
} else {
|
||||
'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe'
|
||||
}
|
||||
$node = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
|
||||
$python = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe'
|
||||
$exportDir = Join-Path $root '..\..\runtime\private\erp-exports'
|
||||
$logDir = Join-Path $exportDir 'logs'
|
||||
$stateFile = Join-Path $exportDir 'imported-state.json'
|
||||
@ -68,7 +52,6 @@ function Write-Log {
|
||||
|
||||
# 平台 → 导入命令 / 页面回验页签
|
||||
$specs = @{
|
||||
'taobao-wechat' = @{ label = '淘系微信'; artifact = 'taobao-wechat'; importCmd = 'taobao-wechat-bills:import-authoritative'; verifyTabs = @('taobao-wechat'); split = $false; uploadExtension = '.xlsx' }
|
||||
toutiao = @{ label = '头条放心购'; artifact = 'douyin'; importCmd = 'business-mirror:import-douyin-authoritative'; verifyTabs = @('douyin'); split = $false }
|
||||
jd = @{ label = '京东日账单'; artifact = 'jd'; importCmd = 'business-mirror:import-jd-daily'; verifyTabs = @('jd-transactions', 'jingxi'); split = $true }
|
||||
'jd-wallet' = @{ label = '京东钱包'; artifact = 'jd-wallet'; importCmd = 'business-mirror:import-jd-wallet'; verifyTabs = @('jd-wallet'); split = $false }
|
||||
@ -81,7 +64,7 @@ $coverageKeys = @{
|
||||
'jd-wallet' = 'jd-wallet'
|
||||
}
|
||||
|
||||
$targets = if ($Platform -eq 'both') { @('taobao-wechat', 'toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay') } else { @($Platform) }
|
||||
$targets = if ($Platform -eq 'both') { @('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay') } else { @($Platform) }
|
||||
$state = if (Test-Path -LiteralPath $stateFile) { (Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json) } else { New-Object psobject }
|
||||
$dewuAlipayAccounts = @()
|
||||
if ($targets -contains 'dewu-alipay') {
|
||||
@ -93,13 +76,13 @@ if ($targets -contains 'dewu-alipay') {
|
||||
|
||||
$auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root'
|
||||
$sshOptions = $auth.Options + @('-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1', '-o', 'ConnectTimeout=15')
|
||||
$sshTarget = 'root@218.93.190.75'
|
||||
|
||||
. (Join-Path $root 'erp-remote.ps1')
|
||||
$remoteSshScript = Join-Path $root '..\..\runtime\private\server-ssh.ps1'
|
||||
$remoteUploaderScript = Join-Path $root '..\..\runtime\private\upload-to-server.ps1'
|
||||
$remoteBatchRunner = '/opt/caiwuxitong/run-finance-batch.sh'
|
||||
|
||||
# 远程执行包装:失败自动重试(含重新上传文件),并返回 { Ok; Output; Attempts }。
|
||||
# 直接使用本机部署凭据,不依赖未入库的 runtime/private 辅助脚本。
|
||||
# 远程执行包装:失败自动重试(含重新上传 CSV),并返回 { Ok; Output; Attempts }
|
||||
function Invoke-Remote {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Body,
|
||||
@ -107,54 +90,14 @@ function Invoke-Remote {
|
||||
[string]$RemoteFile = ''
|
||||
)
|
||||
|
||||
$attempts = 3
|
||||
$output = ''
|
||||
$tmp = [IO.Path]::GetTempFileName() + '.sh'
|
||||
[IO.File]::WriteAllText($tmp, ($Body -replace "`r`n", "`n"), [Text.UTF8Encoding]::new($false))
|
||||
try {
|
||||
for ($attempt = 1; $attempt -le $attempts; $attempt++) {
|
||||
if ($LocalFile -and $RemoteFile) {
|
||||
$output = (& scp @($sshOptions) $LocalFile "${sshTarget}:${RemoteFile}" 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Log ('上传失败(第 {0}/{1} 次):{2}' -f $attempt, $attempts, ($output.Trim() -replace "`r?`n", ' | '))
|
||||
if ($attempt -lt $attempts) {
|
||||
Start-Sleep -Seconds 10
|
||||
continue
|
||||
}
|
||||
|
||||
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempt }
|
||||
}
|
||||
}
|
||||
|
||||
$remoteScript = '/tmp/caiwu-erp-daily-' + [guid]::NewGuid().ToString('N') + '.sh'
|
||||
$output = (& scp @($sshOptions) $tmp "${sshTarget}:${remoteScript}" 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Log ('远程脚本上传失败(第 {0}/{1} 次):{2}' -f $attempt, $attempts, ($output.Trim() -replace "`r?`n", ' | '))
|
||||
if ($attempt -lt $attempts) {
|
||||
Start-Sleep -Seconds 10
|
||||
continue
|
||||
}
|
||||
|
||||
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempt }
|
||||
}
|
||||
|
||||
$output = (& ssh @($sshOptions) $sshTarget "sh '$remoteScript'" 2>&1 | Out-String)
|
||||
$remoteExitCode = $LASTEXITCODE
|
||||
& ssh @($sshOptions) $sshTarget "rm -f '$remoteScript'" 2>&1 | Out-Null
|
||||
if ($remoteExitCode -eq 0) {
|
||||
return [pscustomobject]@{ Ok = $true; Output = $output; Attempts = $attempt }
|
||||
}
|
||||
|
||||
Write-Log ('远程执行失败(第 {0}/{1} 次,exit={2}):{3}' -f $attempt, $attempts, $remoteExitCode, ($output.Trim() -replace "`r?`n", ' | '))
|
||||
if ($attempt -lt $attempts) {
|
||||
Start-Sleep -Seconds 10
|
||||
}
|
||||
}
|
||||
|
||||
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempts }
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
return Invoke-ErpRemote `
|
||||
-PwshPath $self `
|
||||
-SshScript $remoteSshScript `
|
||||
-UploaderScript $remoteUploaderScript `
|
||||
-Body $Body `
|
||||
-LocalFile $LocalFile `
|
||||
-RemoteFile $RemoteFile `
|
||||
-Log { param($message) Write-Log $message }
|
||||
}
|
||||
|
||||
function Get-ErpDailyCoverage {
|
||||
@ -184,31 +127,6 @@ exit "`$status"
|
||||
return @($jsonLine | ConvertFrom-Json)
|
||||
}
|
||||
|
||||
function Get-ErpBillRangeSummary {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string[]]$Tabs,
|
||||
[Parameter(Mandatory = $true)][string]$From,
|
||||
[Parameter(Mandatory = $true)][string]$To,
|
||||
[int]$CompanyId = 1
|
||||
)
|
||||
|
||||
$tabsArg = $Tabs -join ','
|
||||
$body = "docker exec -u www-data caiwu_app php /var/www/html/artisan bill-sync:summarize-range --tabs=$tabsArg --from=$From --to=$To --company-id=$CompanyId --json"
|
||||
$result = Invoke-Remote -Body $body
|
||||
if (-not $result.Ok) {
|
||||
throw ('账单范围汇总失败:' + ($result.Output.Trim() -replace "`r?`n", ' | '))
|
||||
}
|
||||
|
||||
$jsonLine = (($result.Output -split "`r?`n") |
|
||||
Where-Object { $_.TrimStart().StartsWith('{') } |
|
||||
Select-Object -Last 1)
|
||||
if (-not $jsonLine) {
|
||||
throw ('账单范围汇总没有返回 JSON:' + ($result.Output.Trim() -replace "`r?`n", ' | '))
|
||||
}
|
||||
|
||||
return $jsonLine | ConvertFrom-Json
|
||||
}
|
||||
|
||||
$failed = $false
|
||||
try {
|
||||
$pullThroughDate = if ($Through) {
|
||||
@ -253,81 +171,13 @@ try {
|
||||
$targets = @()
|
||||
}
|
||||
|
||||
:targetLoop foreach ($target in $targets) {
|
||||
foreach ($target in $targets) {
|
||||
$spec = $specs[$target]
|
||||
Write-Log ('=== ' + $spec.label + ':开始 ===')
|
||||
$coverageKey = $coverageKeys[$target]
|
||||
$currentIssue = @($coverageReport | Where-Object { $_.dataset -eq $coverageKey -and $_.month -eq $pullMonth -and $_.status -ne 'ok' })
|
||||
$forceThisImport = [bool]$ForceImport -or $currentIssue.Count -gt 0
|
||||
|
||||
# 每次拉取新账单前,先用同口径源账单核对前一自然日;每月 1-5 日再
|
||||
# 核对上月末最后 5 个自然日。发现差异先补完整所属月份,复验通过后才继续。
|
||||
if (-not $SkipPreviousDayCheck -and -not $AuditOnly -and [string]::IsNullOrWhiteSpace($Start)) {
|
||||
$reconcileWindows = @(Get-ErpBillReconcileWindows -PullThroughDate $pullThroughDate -RunDate (Get-Date).Date)
|
||||
foreach ($window in $reconcileWindows) {
|
||||
$windowStart = $window.Start.ToString('yyyy-MM-dd')
|
||||
$windowThrough = $window.Through.ToString('yyyy-MM-dd')
|
||||
Write-Log ('核对 {0}:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
|
||||
|
||||
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
|
||||
-Platform $target `
|
||||
-Start $windowStart `
|
||||
-Through $windowThrough `
|
||||
-CoverageFrom $CoverageFrom `
|
||||
-AuditOnly `
|
||||
-SkipCoverageCheck `
|
||||
-SkipPreviousDayCheck
|
||||
$auditExitCode = $LASTEXITCODE
|
||||
if ($auditExitCode -eq 0) {
|
||||
Write-Log ('{0}核对一致:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
|
||||
continue
|
||||
}
|
||||
if ($auditExitCode -ne 2) {
|
||||
Write-Log ('{0}核对失败(exit={1}),已停止该平台的新账单拉取' -f $window.Label, $auditExitCode)
|
||||
$failed = $true
|
||||
continue targetLoop
|
||||
}
|
||||
if ($SkipImport) {
|
||||
Write-Log ('{0}发现差异,但已指定 -SkipImport;已停止该平台的新账单拉取' -f $window.Label)
|
||||
$failed = $true
|
||||
continue targetLoop
|
||||
}
|
||||
|
||||
$monthWindow = Get-ErpBillMonthWindow -Date $window.Start
|
||||
$monthStart = $monthWindow.Start.ToString('yyyy-MM-dd')
|
||||
$monthThrough = $monthWindow.Through.ToString('yyyy-MM-dd')
|
||||
Write-Log ('{0}存在差异,先补齐所属月份 {1} ~ {2}' -f $window.Label, $monthStart, $monthThrough)
|
||||
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
|
||||
-Platform $target `
|
||||
-Start $monthStart `
|
||||
-Through $monthThrough `
|
||||
-CoverageFrom $CoverageFrom `
|
||||
-ForceImport `
|
||||
-SkipCoverageCheck `
|
||||
-SkipPreviousDayCheck
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Log ('{0}所属月份补齐失败,已停止该平台的新账单拉取' -f $window.Label)
|
||||
$failed = $true
|
||||
continue targetLoop
|
||||
}
|
||||
|
||||
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
|
||||
-Platform $target `
|
||||
-Start $windowStart `
|
||||
-Through $windowThrough `
|
||||
-CoverageFrom $CoverageFrom `
|
||||
-AuditOnly `
|
||||
-SkipCoverageCheck `
|
||||
-SkipPreviousDayCheck
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Log ('{0}补齐后复验仍未通过,已停止该平台的新账单拉取' -f $window.Label)
|
||||
$failed = $true
|
||||
continue targetLoop
|
||||
}
|
||||
Write-Log ('{0}已补齐并复验一致:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
|
||||
}
|
||||
}
|
||||
|
||||
# 先补此前月份的缺口;历史仍不完整时,不继续拉取本月新数据。
|
||||
$historicalIssues = if ($coverageKey) {
|
||||
@(Get-ErpCoverageBackfillJobs -CoverageReport $coverageReport -Dataset $coverageKey -CurrentMonth $pullMonth)
|
||||
@ -403,22 +253,8 @@ try {
|
||||
|
||||
$summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json
|
||||
if ($summary.empty) {
|
||||
if ($AuditOnly) {
|
||||
$serverSummary = Get-ErpBillRangeSummary `
|
||||
-Tabs @($spec.verifyTabs) `
|
||||
-From ([string]$summary.monthStart) `
|
||||
-To ([string]$summary.through)
|
||||
if ([int]$serverSummary.row_count -ne 0 -or
|
||||
[long]$serverSummary.income_cents -ne 0 -or
|
||||
[long]$serverSummary.expense_cents -ne 0) {
|
||||
Write-Log ($spec.label + ':胜算无数据,但财务系统仍有流水;需要回补核对')
|
||||
exit 2
|
||||
}
|
||||
Write-Log ($spec.label + ':胜算和财务系统该区间均无数据')
|
||||
continue targetLoop
|
||||
}
|
||||
Write-Log ($spec.label + ':该区间胜算暂无数据,跳过(未改动生产)')
|
||||
continue targetLoop
|
||||
continue
|
||||
}
|
||||
# 胜算超过同步导出上限时会拆成多个分片(summary.files),逐片转 CSV 后合并成一份再导入。
|
||||
# 小红书导入命令只接受原始 XLSX,因此独立汇总,不上传转换后的 CSV。
|
||||
@ -429,7 +265,6 @@ try {
|
||||
$rawFile = $rawFiles[0]
|
||||
$isXiaohongshu = $target -eq 'xiaohongshu'
|
||||
$isDewuAlipay = $target -eq 'dewu-alipay'
|
||||
$isFullMonthXlsx = $target -eq 'taobao-wechat'
|
||||
$csvFile = $null
|
||||
$importFile = $rawFile
|
||||
if ($isXiaohongshu) {
|
||||
@ -495,35 +330,6 @@ try {
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
} elseif ($isFullMonthXlsx) {
|
||||
$csvFile = if ($rawFiles.Count -gt 1) {
|
||||
[IO.Path]::ChangeExtension(($rawFile -replace '_part\d+(?=\.[^.]+$)', ''), '.csv')
|
||||
} else {
|
||||
[IO.Path]::ChangeExtension($rawFile, '.csv')
|
||||
}
|
||||
if ($rawFiles.Count -gt 1) {
|
||||
Write-Log ('{0}导出分片 {1} 个,转为合并 CSV 并合并 XLSX' -f $spec.label, $rawFiles.Count)
|
||||
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') '--merge' $csvFile @rawFiles 2>&1 | Out-String)
|
||||
$mergedFile = [IO.Path]::ChangeExtension($csvFile, '.merged.xlsx')
|
||||
$merge = (& $python -X utf8 (Join-Path $root 'merge-xlsx.py') $mergedFile @rawFiles 2>&1 | Out-String)
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Log ($spec.label + ' XLSX 合并失败:' + ($merge.Trim() -replace "`r?`n", ' | '))
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
$importFile = $mergedFile
|
||||
} else {
|
||||
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String)
|
||||
}
|
||||
$line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1)
|
||||
if (-not $line) {
|
||||
Write-Log ($spec.label + ' 转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | '))
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
$rows = [int]([regex]::Match($line, 'rows=(\d+)').Groups[1].Value)
|
||||
$income = [double]([regex]::Match($line, 'income=([\-\d\.]+)').Groups[1].Value)
|
||||
$expense = [double]([regex]::Match($line, 'expense=([\-\d\.]+)').Groups[1].Value)
|
||||
} else {
|
||||
# 多分片时 CSV 用合并后的名字(不带 _partN),避免看起来只落了第一片
|
||||
$csvFile = if ($rawFiles.Count -gt 1) {
|
||||
@ -558,61 +364,107 @@ try {
|
||||
continue
|
||||
}
|
||||
|
||||
# 2) 以财务数据库同日期范围的汇总为准判断是否需要导入。
|
||||
# 2) 无差异跳过
|
||||
$key = $target + ':' + $month
|
||||
$prev = $state.$key
|
||||
$sourceSummary = [pscustomobject]@{
|
||||
rows = [int]$rows
|
||||
incomeCents = [long][math]::Round([double]$income * 100)
|
||||
expenseCents = [long][math]::Round([double]$expense * 100)
|
||||
}
|
||||
$serverSummary = Get-ErpBillRangeSummary `
|
||||
-Tabs @($spec.verifyTabs) `
|
||||
-From ([string]$summary.monthStart) `
|
||||
-To ([string]$summary.through)
|
||||
$serverMatchesExport = Test-ErpBillSummaryMatch -Source $sourceSummary -Server $serverSummary
|
||||
Write-Log ('财务系统同范围:笔数 {0},收入 {1},支出 {2};源账单:笔数 {3},收入 {4},支出 {5}' -f
|
||||
[int]$serverSummary.row_count,
|
||||
(([long]$serverSummary.income_cents) / 100).ToString('0.00', $invariant),
|
||||
(([long]$serverSummary.expense_cents) / 100).ToString('0.00', $invariant),
|
||||
$rows,
|
||||
$income.ToString('0.00', $invariant),
|
||||
$expense.ToString('0.00', $invariant))
|
||||
|
||||
if ($AuditOnly) {
|
||||
if ($serverMatchesExport) {
|
||||
Write-Log ('{0} 与财务系统一致,无需补数:{1} ~ {2}' -f $spec.label, $summary.monthStart, $summary.through)
|
||||
continue targetLoop
|
||||
# 小红书和得物支付宝的明细量较小,且聚水潭会事后调整字段;每天重新导入以保留最新版本。
|
||||
$same = -not $isXiaohongshu -and -not $isDewuAlipay -and $prev -and ([string]$prev.through -eq [string]$summary.through) -and ([int]$prev.rows -eq $rows) -and ([math]::Abs([double]$prev.income - $income) -lt 0.005) -and ([math]::Abs([double]$prev.expense - $expense) -lt 0.005)
|
||||
$currentCoverage = @($coverageReport | Where-Object { $_.dataset -eq $coverageKey -and $_.month -eq $month } | Select-Object -First 1)
|
||||
$serverMatchesExport = $currentCoverage.Count -eq 1 -and
|
||||
$currentCoverage[0].status -eq 'ok' -and
|
||||
[int]$currentCoverage[0].row_count -eq $rows -and
|
||||
[math]::Abs([double]$currentCoverage[0].income - $income) -lt 0.005 -and
|
||||
[math]::Abs([double]$currentCoverage[0].expense - $expense) -lt 0.005
|
||||
if (($same -or $serverMatchesExport) -and -not $forceThisImport) {
|
||||
if (-not $same -and $serverMatchesExport) {
|
||||
# 服务端覆盖已正确、只是本机状态滞后时,回填状态,避免每天重复导入同一批账单。
|
||||
$state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; through = $summary.through; file = $csvFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force
|
||||
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
|
||||
Write-Log ('服务端覆盖已核对且与导出无差异,已回填本机状态({0} 笔 / {1} / {2}),跳过导入' -f $rows, $income, $expense)
|
||||
} else {
|
||||
Write-Log ('该月已导入且无差异({0} 笔 / {1} / {2}),跳过导入' -f $rows, $income, $expense)
|
||||
}
|
||||
Write-Log ('{0} 与财务系统不一致:{1} ~ {2}' -f $spec.label, $summary.monthStart, $summary.through)
|
||||
exit 2
|
||||
}
|
||||
|
||||
if ($serverMatchesExport -and -not $forceThisImport) {
|
||||
# 服务端已经一致时,只回填本机状态,避免重复导入同一批账单。
|
||||
$state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; through = $summary.through; file = $csvFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force
|
||||
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
|
||||
Write-Log ('服务器同范围汇总与导出完全一致({0} 笔 / {1} / {2}),跳过导入' -f $rows, $income, $expense)
|
||||
continue
|
||||
}
|
||||
if ($SkipImport) {
|
||||
Write-Log '同范围汇总不一致,但已指定 -SkipImport;本次视为失败'
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
if ($SkipImport) { Write-Log '已指定 -SkipImport,跳过导入'; continue }
|
||||
|
||||
# 3) 上传 + 导入 + 页面回验。统一交给 Invoke-Remote,上传断开时会重新上传并重试,
|
||||
# 整段失败则本平台失败,不写状态、不归档。
|
||||
$uploadExtension = if ($spec.uploadExtension) { [string]$spec.uploadExtension } else { '.csv' }
|
||||
$remoteFile = '/tmp/' + $target + '_daily_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + $uploadExtension
|
||||
|
||||
$verifyPhp = @"
|
||||
cat > /tmp/verify_daily.php <<'PHP'
|
||||
<?php
|
||||
require '/var/www/html/vendor/autoload.php';
|
||||
`$app = require '/var/www/html/bootstrap/app.php';
|
||||
`$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
`$tabs = ['__TABS__'];
|
||||
`$total = 0;
|
||||
`$incomeCents = 0;
|
||||
`$expenseCents = 0;
|
||||
if (`$tabs === ['xiaohongshu']) {
|
||||
`$query = Illuminate\Support\Facades\DB::table('ec_account_bills')
|
||||
->where('company_id', 1)
|
||||
->where('bill_type', 'xiaohongshu')
|
||||
->where('occurred_at', '>=', '__START__ 00:00:00')
|
||||
->where('occurred_at', '<', date('Y-m-d', strtotime('__THROUGH__ +1 day')) . ' 00:00:00');
|
||||
`$summary = (clone `$query)->selectRaw(
|
||||
'COUNT(*) AS count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
|
||||
)->first();
|
||||
`$total = (int) `$summary->count;
|
||||
`$incomeCents = (int) round((float) `$summary->income * 100);
|
||||
`$expenseCents = (int) round((float) `$summary->expense * 100);
|
||||
echo 'PAGE xiaohongshu total=' . `$total . ' ' . json_encode(`$summary, JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
} elseif (`$tabs === ['dewu-alipay']) {
|
||||
`$result = app(Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository::class)
|
||||
->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1);
|
||||
`$total = (int) `$result['total'];
|
||||
`$incomeCents = (int) round((float) `$result['summary']['income'] * 100);
|
||||
`$expenseCents = (int) round((float) `$result['summary']['expense'] * 100);
|
||||
echo 'PAGE dewu-alipay total=' . `$total . ' ' . json_encode(`$result['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
} else {
|
||||
`$repo = app(Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository::class);
|
||||
foreach (`$tabs as `$tab) {
|
||||
`$r = match (`$tab) {
|
||||
'douyin' => `$repo->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
|
||||
'jd-wallet' => app(Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository::class)->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
|
||||
default => app(Modules\EcommerceFinance\Repositories\JdDailyBillRepository::class)
|
||||
->forPlatform(`$tab === 'jingxi' ? 'jingxi' : 'jd')
|
||||
->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
|
||||
};
|
||||
`$total += (int) `$r['total'];
|
||||
`$incomeCents += (int) round((float) `$r['summary']['income'] * 100);
|
||||
`$expenseCents += (int) round((float) `$r['summary']['expense'] * 100);
|
||||
echo 'PAGE ' . `$tab . ' total=' . `$r['total'] . ' ' . json_encode(`$r['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
|
||||
}
|
||||
}
|
||||
if (`$total !== __COUNT__
|
||||
|| `$incomeCents !== (int) round(__INCOME__ * 100)
|
||||
|| `$expenseCents !== (int) round(__EXPENSE__ * 100)) {
|
||||
fwrite(STDERR, sprintf(
|
||||
'页面回验不一致:导入 %d 笔 / %s / %s,页面 %d 笔 / %.2f / %.2f%s',
|
||||
__COUNT__, __INCOME__, __EXPENSE__, `$total, `$incomeCents / 100, `$expenseCents / 100, PHP_EOL
|
||||
));
|
||||
exit(1);
|
||||
}
|
||||
PHP
|
||||
docker exec -i -u www-data caiwu_app php < /tmp/verify_daily.php
|
||||
rm -f /tmp/verify_daily.php
|
||||
"@
|
||||
$invariant = [Globalization.CultureInfo]::InvariantCulture
|
||||
$verifyPhp = $verifyPhp.Replace('__TABS__', ($spec.verifyTabs -join "','"))
|
||||
$verifyPhp = $verifyPhp.Replace('__START__', $summary.monthStart)
|
||||
$verifyPhp = $verifyPhp.Replace('__THROUGH__', $summary.through)
|
||||
$verifyPhp = $verifyPhp.Replace('__COUNT__', [string]$rows)
|
||||
$verifyPhp = $verifyPhp.Replace('__INCOME__', $income.ToString('0.00', $invariant))
|
||||
$verifyPhp = $verifyPhp.Replace('__EXPENSE__', $expense.ToString('0.00', $invariant))
|
||||
|
||||
$importCommand = if ($isXiaohongshu) {
|
||||
"sh $remoteBatchRunner $($spec.importCmd) `"$remoteFile`" --company-id=1 --from=$($summary.monthStart) --to=$($summary.through) --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=500"
|
||||
} elseif ($isDewuAlipay) {
|
||||
$storeArgs = ($dewuAlipayAccounts | ForEach-Object { "--store='" + [string]$_.alipay_name + "'" }) -join ' '
|
||||
"sh $remoteBatchRunner $($spec.importCmd) `"$remoteFile`" --from=$($summary.monthStart) --to=$($summary.through) --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=1000 $storeArgs"
|
||||
} elseif ($isFullMonthXlsx) {
|
||||
"sh $remoteBatchRunner $($spec.importCmd) `"$remoteFile`" --from=$($summary.monthStart) --to=$($summary.through) --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=1000"
|
||||
} else {
|
||||
"sh $remoteBatchRunner $($spec.importCmd) $remoteFile $month --through=$($summary.through) --count=$rows --income=$income --expense=$expense"
|
||||
}
|
||||
@ -627,33 +479,16 @@ cleanup() {
|
||||
}
|
||||
trap cleanup EXIT
|
||||
$importCommand
|
||||
$verifyPhp
|
||||
"@
|
||||
$import = Invoke-Remote -Body $body -LocalFile $importFile -RemoteFile $remoteFile
|
||||
Write-Log ('导入/回验:' + ($import.Output.Trim() -replace "`r?`n", ' | '))
|
||||
if (-not $import.Ok) {
|
||||
Write-Log ($spec.label + ' 导入失败(已尝试 ' + $import.Attempts + ' 次):未写入本地状态、未归档,下次运行会重新导入')
|
||||
Write-Log ($spec.label + ' 导入/回验失败(已尝试 ' + $import.Attempts + ' 次):未写入本地状态、未归档,下次运行会重新导入')
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
|
||||
$verifiedSummary = Get-ErpBillRangeSummary `
|
||||
-Tabs @($spec.verifyTabs) `
|
||||
-From ([string]$summary.monthStart) `
|
||||
-To ([string]$summary.through)
|
||||
if (-not (Test-ErpBillSummaryMatch -Source $sourceSummary -Server $verifiedSummary)) {
|
||||
Write-Log ('{0} 导入后回验仍不一致:源 {1} 笔 / {2} / {3},财务 {4} 笔 / {5} / {6}' -f
|
||||
$spec.label,
|
||||
$rows,
|
||||
$income.ToString('0.00', $invariant),
|
||||
$expense.ToString('0.00', $invariant),
|
||||
[int]$verifiedSummary.row_count,
|
||||
(([long]$verifiedSummary.income_cents) / 100).ToString('0.00', $invariant),
|
||||
(([long]$verifiedSummary.expense_cents) / 100).ToString('0.00', $invariant))
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
Write-Log ('导入后回验一致:{0} 笔 / {1} / {2}' -f $rows, $income.ToString('0.00', $invariant), $expense.ToString('0.00', $invariant))
|
||||
|
||||
# 4) 记录状态 + 归档
|
||||
$state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; through = $summary.through; file = $importFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force
|
||||
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
|
||||
@ -682,7 +517,6 @@ $importCommand
|
||||
Write-Log '本次运行存在失败平台(详见上面日志):相关平台未写状态、未归档'
|
||||
exit 1
|
||||
}
|
||||
exit 0
|
||||
} finally {
|
||||
Stop-CaiwuDeploymentAuth $auth
|
||||
}
|
||||
|
||||
@ -103,18 +103,14 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertSeeText('已配置规则')
|
||||
->assertSeeText('未映射账单项目')
|
||||
->assertSee('id="amCoveragePanel"', false)
|
||||
->assertSee('统计最近 60 个月')
|
||||
->assertSee('清单生成后持续保留,每月自动更新一次')
|
||||
->assertSee('am-coverage-months">账单月份</th>', false)
|
||||
->assertSee('id="amCoverageMonth"', false)
|
||||
->assertSee('data-am-coverage-add', false)
|
||||
->assertSee('立即刷新清单')
|
||||
->assertSee('生成最新清单')
|
||||
->assertSee('本页不会自动轮询', false)
|
||||
->assertSee('读取生成结果', false)
|
||||
->assertDontSee('coveragePollTimer', false)
|
||||
->assertSee('data-am-memo-picker', false)
|
||||
->assertSee('id="amCoverageMappingModal"', false)
|
||||
->assertSee('id="amCoverageMappingSuggestion"', false)
|
||||
->assertSee('/suggest?platform=', false)
|
||||
->assertSee('id="amCoverageNotice"', false)
|
||||
->assertSee('保存映射')
|
||||
->assertDontSee('商品名称关键词', false)
|
||||
@ -137,14 +133,13 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertJsonStructure(['rules', 'summary', 'options' => ['platforms', 'categories', 'basis', 'invoices']]);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_returns_unmapped_items_across_months(): void
|
||||
public function test_coverage_endpoint_returns_unmapped_items_for_selected_month(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingAcrossMonths')->once()->with(false, false)->andReturn([
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', false, false)->andReturn([
|
||||
'status' => 'ready',
|
||||
'scope' => 'all',
|
||||
'month' => null,
|
||||
'month' => '2026-11',
|
||||
'source_rows' => 120,
|
||||
'missing_item_count' => 1,
|
||||
'missing_row_count' => 7,
|
||||
@ -158,69 +153,43 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
'store_count' => 3,
|
||||
'store_samples' => ['抖音-甲店'],
|
||||
'source_labels' => ['抖音'],
|
||||
'months' => ['2026-10', '2026-11'],
|
||||
]],
|
||||
'months' => [],
|
||||
'months' => ['2026-11', '2026-10'],
|
||||
]);
|
||||
$this->app->instance(AccountMappingCoverage::class, $coverage);
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage'))
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-11')
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'ready')
|
||||
->assertJsonPath('scope', 'all')
|
||||
->assertJsonPath('missing_item_count', 1)
|
||||
->assertJsonPath('items.0.platform', '抖音')
|
||||
->assertJsonPath('items.0.item', '商家货款入账')
|
||||
->assertJsonPath('items.0.source_rows', 7);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_can_queue_a_manual_cross_month_refresh(): void
|
||||
public function test_coverage_endpoint_can_queue_a_manual_month_refresh(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingAcrossMonths')->once()->with(true, false)->andReturn([
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', true, false)->andReturn([
|
||||
'status' => 'refreshing',
|
||||
'scope' => 'all',
|
||||
'month' => null,
|
||||
'month' => '2026-11',
|
||||
'source_rows' => 0,
|
||||
'missing_item_count' => 0,
|
||||
'missing_row_count' => 0,
|
||||
'pending_sources' => [],
|
||||
'items' => [],
|
||||
'months' => [],
|
||||
'months' => ['2026-11', '2026-10'],
|
||||
'retry_after' => 8,
|
||||
'message' => '',
|
||||
'refreshed_at' => null,
|
||||
]);
|
||||
$this->app->instance(AccountMappingCoverage::class, $coverage);
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?refresh=1')
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-11&refresh=1')
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'refreshing')
|
||||
->assertJsonPath('scope', 'all');
|
||||
}
|
||||
|
||||
public function test_suggestion_endpoint_returns_a_same_item_mapping_template(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
app(AccountMappingStore::class)->create([
|
||||
'platform' => '京喜',
|
||||
'item' => 'POP商家激励金',
|
||||
'memo' => '优惠收入',
|
||||
'invoice' => '-',
|
||||
'category' => '收入',
|
||||
'dAcct' => '其他货币资金',
|
||||
'cAcct' => '主营业务收入',
|
||||
'basis' => '收入基准',
|
||||
]);
|
||||
|
||||
$this->loginAs()->getJson(
|
||||
$this->actionUrl('suggest') . '?platform=' . urlencode('京东') . '&item=' . urlencode('POP商家激励金')
|
||||
)->assertOk()
|
||||
->assertJsonPath('auto_fill', true)
|
||||
->assertJsonPath('reason', 'same_item')
|
||||
->assertJsonPath('values.memo', '优惠收入')
|
||||
->assertJsonPath('sources.0.platform', '京喜');
|
||||
->assertJsonPath('month', '2026-11');
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_rejects_invalid_month(): void
|
||||
|
||||
@ -88,27 +88,6 @@ class BankBillPageTest extends FeatureTestCase
|
||||
$this->assertStringContainsString('12,000.00', $html);
|
||||
$this->assertStringContainsString('列设置', $html);
|
||||
$this->assertStringContainsString('data-bank-bill-column-picker', $html);
|
||||
$this->assertStringContainsString('data-ledger-date-range', $html);
|
||||
$this->assertStringContainsString('name="bills_bank"', $html);
|
||||
$this->assertStringContainsString('name="bills_account_no"', $html);
|
||||
$this->assertStringContainsString('name="bills_from"', $html);
|
||||
$this->assertStringContainsString('name="bills_to"', $html);
|
||||
$this->assertStringContainsString('value="2026-11-01"', $html);
|
||||
$this->assertStringContainsString('value="2026-11-30"', $html);
|
||||
$this->assertStringContainsString('查询时间段', $html);
|
||||
}
|
||||
|
||||
public function test_bank_bill_filters_default_to_the_current_month(): void
|
||||
{
|
||||
$html = $this->loginAs()->get($this->ledgerUrl([
|
||||
'tab' => 'bills',
|
||||
]))->assertOk()->getContent();
|
||||
|
||||
$this->assertStringContainsString('data-ledger-date-range', $html);
|
||||
$this->assertStringContainsString('value="2026-11-01"', $html);
|
||||
$this->assertStringContainsString('value="2026-11-30"', $html);
|
||||
$this->assertStringContainsString('>全部账户</option>', $html);
|
||||
$this->assertStringContainsString('value="all" selected>全部</option>', $html);
|
||||
}
|
||||
|
||||
public function test_configured_headers_are_visible_when_the_bank_has_no_bill_rows(): void
|
||||
@ -231,7 +210,7 @@ class BankBillPageTest extends FeatureTestCase
|
||||
|
||||
$response->assertSee('data-bank-bill-header-filter', false);
|
||||
$response->assertSee('筛选和排序:银行账号', false);
|
||||
$response->assertSee('data-ledger-date-range', false);
|
||||
$response->assertDontSee('data-bank-bill-date-filter', false);
|
||||
$response->assertSee('data-bank-bill-header-filter', false);
|
||||
$response->assertSee('筛选和排序:账务时间', false);
|
||||
$response->assertSeeText('升序');
|
||||
@ -261,83 +240,6 @@ class BankBillPageTest extends FeatureTestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_personal_card_bill_accounts_are_selected_and_available_in_header_filters(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_accounts')->insert([
|
||||
'company_name' => '个人测试公司',
|
||||
'account_short' => '华夏个人测试',
|
||||
'account_type' => '个人卡',
|
||||
'bank_name' => '华夏银行',
|
||||
'account_no' => '6222000000000188',
|
||||
'account_should_keep' => '是',
|
||||
'current_balance' => 100,
|
||||
'daily_available' => 100,
|
||||
'blocked_amount' => 0,
|
||||
]);
|
||||
$connection->table('fin_accounts')->insert([
|
||||
'company_name' => '无账单个人测试公司',
|
||||
'account_short' => '华夏无账单个人测试',
|
||||
'account_type' => '个人卡',
|
||||
'bank_name' => '华夏银行',
|
||||
'account_no' => '6222000000000189',
|
||||
'account_should_keep' => '是',
|
||||
'current_balance' => 100,
|
||||
'daily_available' => 100,
|
||||
'blocked_amount' => 0,
|
||||
]);
|
||||
$connection->table('fin_bank_direct_bills')->insert([
|
||||
'bank_name' => '华夏银行',
|
||||
'company_name' => '个人测试公司',
|
||||
'account_short' => '华夏个人测试',
|
||||
'account_no' => '6222000000000188',
|
||||
'txn_date' => '2026-11-22',
|
||||
'txn_at' => '2026-11-22 10:00:00',
|
||||
'record_code' => 'HX-PERSONAL-001',
|
||||
'detail' => '个人卡账单测试',
|
||||
'income' => 100,
|
||||
'expense' => 0,
|
||||
'balance' => 100,
|
||||
'source_file_name' => '华夏个人测试.xls',
|
||||
'source_file_sha256' => str_repeat('e', 64),
|
||||
'row_key' => hash('sha256', 'hx-personal-account-filter'),
|
||||
'imported_at' => '2026-11-24 08:30:00',
|
||||
]);
|
||||
|
||||
$response = $this->loginAs()->get($this->ledgerUrl([
|
||||
'tab' => 'bills',
|
||||
'bills_bank' => '华夏银行',
|
||||
'bills_account_no' => '6222000000000188',
|
||||
'bills_from' => '2026-11-01',
|
||||
'bills_to' => '2026-11-30',
|
||||
]))->assertOk();
|
||||
|
||||
$response
|
||||
->assertSeeText('华夏银行 · 华夏个人测试 · 6222000000000188 · 个人测试公司')
|
||||
->assertSeeText('HX-PERSONAL-001')
|
||||
->assertSeeText('个人卡账单测试');
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/<option\s+value="6222000000000188"[^>]*\bselected\b[^>]*>/s',
|
||||
$response->getContent(),
|
||||
);
|
||||
|
||||
$optionsUrl = route('business.financial-ledger.bank-bills.filter-options', [
|
||||
'company_id' => $this->company->id,
|
||||
'column_key' => 'account_no',
|
||||
'bills_bank' => '华夏银行',
|
||||
'bills_from' => '2026-11-01',
|
||||
'bills_to' => '2026-11-30',
|
||||
]);
|
||||
$this->loginAs()->get($optionsUrl)
|
||||
->assertOk()
|
||||
->assertJsonFragment([
|
||||
'value' => '6222000000000188',
|
||||
'label' => '华夏银行 · 华夏个人测试 · 6222000000000188 · 个人测试公司',
|
||||
'bank' => '华夏银行',
|
||||
])
|
||||
->assertJsonMissing(['value' => '6222000000000189']);
|
||||
}
|
||||
|
||||
public function test_raw_header_filter_applies_to_the_server_query(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
@ -612,10 +514,9 @@ class BankBillPageTest extends FeatureTestCase
|
||||
BankBillTemplateExporter::SCOPE_NON_DIRECT,
|
||||
));
|
||||
|
||||
$this->assertCount(9, $templates);
|
||||
$this->assertCount(8, $templates);
|
||||
$huaXia = $templates->firstWhere('bank', '华夏银行');
|
||||
$huaXiaPersonal = $templates->firstWhere('bank', '华夏银行个人卡');
|
||||
$cmbPersonal = $templates->firstWhere('bank', '招商银行个人卡');
|
||||
$hangzhou = $templates->firstWhere('bank', '杭州银行');
|
||||
$agricultural = $templates->firstWhere('bank', '农业银行');
|
||||
$jiangnan = $templates->firstWhere('bank', '江南农商行');
|
||||
@ -624,7 +525,6 @@ class BankBillPageTest extends FeatureTestCase
|
||||
$alipay = $templates->firstWhere('bank', '支付宝');
|
||||
$this->assertIsArray($huaXia);
|
||||
$this->assertIsArray($huaXiaPersonal);
|
||||
$this->assertIsArray($cmbPersonal);
|
||||
$this->assertIsArray($hangzhou);
|
||||
$this->assertIsArray($agricultural);
|
||||
$this->assertIsArray($jiangnan);
|
||||
@ -662,17 +562,6 @@ class BankBillPageTest extends FeatureTestCase
|
||||
'附言',
|
||||
], $huaXiaPersonal['headers']);
|
||||
$this->assertSame('bank_file', $huaXiaPersonal['format']);
|
||||
$this->assertSame('招商银行个人卡明细', $cmbPersonal['label']);
|
||||
$this->assertSame([
|
||||
'交易日期',
|
||||
'交易时间',
|
||||
'收入',
|
||||
'支出',
|
||||
'余额',
|
||||
'交易类型',
|
||||
'交易备注',
|
||||
], $cmbPersonal['headers']);
|
||||
$this->assertSame('bank_file', $cmbPersonal['format']);
|
||||
$this->assertSame([
|
||||
'序号',
|
||||
'交易时间',
|
||||
@ -1457,7 +1346,7 @@ class BankBillPageTest extends FeatureTestCase
|
||||
'account_short' => '李金林华夏',
|
||||
'account_type' => '个人卡',
|
||||
'bank_name' => '华夏银行',
|
||||
'account_no' => '6222000000000099',
|
||||
'account_no' => '1315000000000099',
|
||||
'account_should_keep' => '是',
|
||||
'current_balance' => 1000,
|
||||
]);
|
||||
@ -1528,7 +1417,7 @@ class BankBillPageTest extends FeatureTestCase
|
||||
'bank_name' => '华夏银行',
|
||||
'company_name' => '李金林测试',
|
||||
'account_short' => '李金林华夏',
|
||||
'account_no' => '6222000000000099',
|
||||
'account_no' => '1315000000000099',
|
||||
'txn_at' => '2026-11-25 17:39:29',
|
||||
'counterparty_name' => '测试收款方',
|
||||
'counterparty_account' => '6222000000000001',
|
||||
@ -1555,92 +1444,6 @@ class BankBillPageTest extends FeatureTestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_cmb_personal_csv_import_maps_masked_card_number_and_transactions(): void
|
||||
{
|
||||
$this->user->roles()->sync([
|
||||
Role::where('name', 'admin')->firstOrFail()->id,
|
||||
]);
|
||||
$this->user->unsetRelation('roles');
|
||||
$connection = DB::connection('business_mirror');
|
||||
$accountId = $connection->table('fin_accounts')->insertGetId([
|
||||
'company_name' => '招商个人测试',
|
||||
'account_short' => '招商个人测试',
|
||||
'account_type' => '个人卡',
|
||||
'bank_name' => '招商银行常州分行营业部',
|
||||
'account_no' => '6214850340219999',
|
||||
'account_should_keep' => '是',
|
||||
'current_balance' => 77737.85,
|
||||
]);
|
||||
$path = sys_get_temp_dir() . '/cmb-personal-' . bin2hex(random_bytes(6)) . '.csv';
|
||||
file_put_contents($path, implode("\n", [
|
||||
'"# 招商银行交易记录"',
|
||||
'"# 导出时间: [2026-12-03 11:19:39]"',
|
||||
'"# 账 号: [一卡通:6214********9999 招商银行]"',
|
||||
'"# 币 种: [人民币]"',
|
||||
'"# 起始日期: [20261101] 终止日期: [20261130]"',
|
||||
'"# 过滤设置: 无"',
|
||||
'',
|
||||
'"交易日期","交易时间","收入","支出","余额","交易类型","交易备注"',
|
||||
'" 20261130"," 16:52:36","","3729.44","53276.77","转账汇款"," 济南顺拓电子商务有限公司"',
|
||||
'" 20261129"," 09:47:10","3395.00","","77737.85","银联代付","支付宝支付科技有限公司"',
|
||||
'',
|
||||
'"# 收入合计: 1 笔,共 3395.00 元"',
|
||||
'"# 支出合计: 1 笔,共 3729.44 元"',
|
||||
]));
|
||||
$payload = [
|
||||
'scope' => BankBillTemplateExporter::SCOPE_NON_DIRECT,
|
||||
'bank' => '招商银行个人卡',
|
||||
'file' => new UploadedFile($path, '招商个人测试招行11.csv', null, null, true),
|
||||
];
|
||||
$previewUrl = route('business.financial-ledger.bank-bills.import.preview', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
$importUrl = route('business.financial-ledger.bank-bills.import', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
|
||||
try {
|
||||
$this->loginAs()->post($previewUrl, $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('result.rows', 2)
|
||||
->assertJsonPath('result.accounts', 1)
|
||||
->assertJsonPath('result.skipped', 0)
|
||||
->assertJsonPath('result.first_date', '2026-11-29')
|
||||
->assertJsonPath('result.last_date', '2026-11-30');
|
||||
|
||||
$this->loginAs()->post($importUrl, $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('result.inserted', 2)
|
||||
->assertJsonPath('result.synced_accounts', 0);
|
||||
|
||||
$this->assertDatabaseHas('fin_bank_direct_bills', [
|
||||
'finance_account_id' => $accountId,
|
||||
'bank_name' => '招商银行',
|
||||
'company_name' => '招商个人测试',
|
||||
'account_short' => '招商个人测试',
|
||||
'account_no' => '6214850340219999',
|
||||
'txn_at' => '2026-11-30 16:52:36',
|
||||
'counterparty_name' => '济南顺拓电子商务有限公司',
|
||||
'income' => 0,
|
||||
'expense' => 3729.44,
|
||||
'balance' => 53276.77,
|
||||
'source' => 'bank-monthly',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_bank_direct_bills', [
|
||||
'finance_account_id' => $accountId,
|
||||
'account_no' => '6214850340219999',
|
||||
'txn_at' => '2026-11-29 09:47:10',
|
||||
'counterparty_name' => '支付宝支付科技有限公司',
|
||||
'income' => 3395,
|
||||
'expense' => 0,
|
||||
'balance' => 77737.85,
|
||||
'source' => 'bank-monthly',
|
||||
], 'business_mirror');
|
||||
} finally {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_agricultural_bank_import_maps_metadata_account_and_validates_footer_totals(): void
|
||||
{
|
||||
$this->user->roles()->sync([
|
||||
|
||||
@ -1,253 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||
use App\Support\CourierBills\StatementExporter;
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use App\Support\DropshipFreight\DropshipExporter;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class BillSurchargeMatchingTest extends FeatureTestCase
|
||||
{
|
||||
private array $temp=[];
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();Storage::fake('local');
|
||||
self::createSettlementTable();
|
||||
}
|
||||
|
||||
public static function createSettlementTable(): void
|
||||
{
|
||||
$s=Schema::connection('business_mirror');
|
||||
if($s->hasTable('courier_surcharge_settlement_rows'))return;
|
||||
$s->create('courier_surcharge_settlement_rows',function(Blueprint $t):void{
|
||||
$t->id();$t->integer('rule_id')->default(1);$t->integer('outbound_io_id')->nullable();
|
||||
foreach(['courier_name','waybill','surcharge_type','settlement_status','platform_product_id','product_code','shop_name','online_order_no','source_kind','source_key'] as $key)$t->string($key)->nullable();
|
||||
$t->decimal('settlement_amount',16,2);$t->dateTime('shipped_at')->nullable();$t->dateTime('pulled_at')->nullable();$t->dateTime('source_created_at')->nullable();
|
||||
$t->index(['waybill']);
|
||||
});
|
||||
}
|
||||
|
||||
private function fee(string $waybill,string $type,float $amount,string $courier='常州中通快运',string $date='2026-10-02'): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('courier_surcharge_settlement_rows')->insert([
|
||||
'waybill'=>$waybill,'surcharge_type'=>$type,'settlement_amount'=>$amount,'courier_name'=>$courier,
|
||||
'settlement_status'=>'已计算','shipped_at'=>$date.' 12:00:00','source_key'=>'GD-'.$waybill.'-'.$type,
|
||||
'source_kind'=>'work_order_customer_service','platform_product_id'=>'12345678901234567890',
|
||||
'product_code'=>'SKU-TEST','shop_name'=>'测试店铺','online_order_no'=>'123456789012345678901']);
|
||||
}
|
||||
|
||||
private function ship(string $no,string $courier,string $warehouse='测试仓'): void
|
||||
{
|
||||
$db=app(ShippingLookup::class)->connection();
|
||||
$id=$db->table('jst_oms_shipping')->insertGetId(['express_no'=>$no,'express_name1'=>$courier,'warehouse_name'=>$warehouse,'ship_time'=>'2026-11-02 12:00:00']);
|
||||
$db->table('jst_oms_shipping')->where('id',$id)->update(['source_id'=>$id]);
|
||||
$db->table('jst_oms_shipping_freight')->insert(['source_id'=>$id,'freight'=>10,'status'=>'OK']);
|
||||
}
|
||||
|
||||
private function book(array $sheets): string
|
||||
{
|
||||
$book=new Spreadsheet();$book->removeSheetByIndex(0);
|
||||
foreach($sheets as $name=>$rows){$sheet=$book->createSheet();$sheet->setTitle($name);
|
||||
foreach($rows as $r=>$row)foreach($row as $c=>$value)if($value!==null)$sheet->setCellValueExplicit([$c+1,$r+1],$value,is_string($value)?'s':'n');}
|
||||
$path=tempnam(sys_get_temp_dir(),'fee_bill_').'.xlsx';$this->temp[]=$path;(new Xlsx($book))->save($path);$book->disconnectWorksheets();return $path;
|
||||
}
|
||||
|
||||
public function test_courier_import_matches_prior_month_fees_and_preserves_metadata_and_duplicates(): void
|
||||
{
|
||||
$store=app(CourierBillStore::class);$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
|
||||
foreach(['001234567890','001234567891','001234567892','001234567893'] as $no)$this->ship($no,'常州中通快运');
|
||||
$this->fee('001234567890','上楼费',13.44);$this->fee('001234567891','改地址',5);
|
||||
$this->fee('001234567892','上楼费',99,'别家快递');$this->fee('001234567893','上楼费',88,'常州中通快运','2026-12-01');
|
||||
$path=$this->book(['账单'=>[['单号','运费'],['001234567890',10],['001234567891',10],['001234567892',10],['001234567893',10]],
|
||||
'附加费'=>[['快递单号','附加费金额','附加费类型'],['001234567890',20,'上楼费'],['001234567890',20,'上楼费'],['001234567891',8,'改地址费'],['001234567892',99,'上楼费'],['001234567893',88,'上楼费']]]);
|
||||
$fileId=$store->upload([new UploadedFile($path,'常州中通快运11月.xlsx',null,null,true)],'2026-11',[],'测试')[0];
|
||||
$db=$store->db();$id=(int)$db->table('courier_bill_files')->where('id',$fileId)->value('statement_id');
|
||||
$matches=app(SurchargeSettlementMatcher::class)->query('courier',$id)->orderBy('id')->get();
|
||||
$this->assertSame(['已匹配','重复','已匹配','未匹配','未匹配'],$matches->pluck('match_status')->all());
|
||||
$this->assertEquals(18.44,round($matches->sum('self_amount'),2));$this->assertSame('12345678901234567890',$matches[0]->platform_product_id);
|
||||
$this->assertSame('SKU-TEST',$matches[0]->product_code);$this->assertSame('测试店铺',$matches[0]->shop_name);
|
||||
$this->assertSame('123456789012345678901',$matches[0]->online_order_no);
|
||||
$this->assertEquals(18.44,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->value('self_amount'));
|
||||
$store->rematch($id);$this->assertSame(5,app(SurchargeSettlementMatcher::class)->query('courier',$id)->count());
|
||||
$this->assertEquals(18.44,round((float)app(SurchargeSettlementMatcher::class)->query('courier',$id)->sum('self_amount'),2));
|
||||
$out=tempnam(sys_get_temp_dir(),'fees_out');$this->temp[]=$out;$h=fopen($out,'wb');app(StatementExporter::class)->export($id,$h);fclose($h);
|
||||
$book=IOFactory::load($out);$sheet=$book->getSheetByName('附加费核对-'.$id);$this->assertNotNull($sheet);
|
||||
$cell=$sheet->getCell('K2')->getValue();
|
||||
$this->assertSame('12345678901234567890',$cell instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText?$cell->getPlainText():$cell);$book->disconnectWorksheets();
|
||||
$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','11月运费')->update(['self_amount'=>123.45]);
|
||||
$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->update(['manual'=>true,'self_amount'=>17.12]);
|
||||
app(CourierBillMatcher::class)->refreshSurchargeSummary($id);
|
||||
$this->assertEquals(123.45,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','11月运费')->value('self_amount'));
|
||||
$this->assertEquals(17.12,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->value('self_amount'));
|
||||
$this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail());
|
||||
$this->loginAs()->get(route('business.pages.show',['section'=>'courier-payables-final','page'=>'courier-bill-reconciliation','cb_view'=>'statement','statement'=>$id]))
|
||||
->assertOk()->assertSeeText('附加费核对明细')->assertSeeText('SKU-TEST')->assertSeeText('12345678901234567890');
|
||||
}
|
||||
|
||||
public function test_dropship_import_uses_system_fee_not_factory_quote_and_checks_warehouse(): void
|
||||
{
|
||||
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'测试代发','warehouse'=>'工厂-测试代发仓','keywords'=>'代发快递']);
|
||||
$this->ship('YT0012345678','测试代发快递','工厂-测试代发仓');$this->fee('YT0012345678','改地址',4.25,'测试代发快递');
|
||||
$path=$this->book(['账单'=>[['单号','运费'],['YT0012345678',10]],'附加费'=>[['快递单号','附加费金额','附加费类型'],['YT0012345678',50,'改地址费']]]);
|
||||
$store->uploadFor('测试代发11月.xlsx',$path,'2026-11',$id,'测试');
|
||||
$row=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->first();
|
||||
$this->assertEquals(50,$row->bill_amount);$this->assertEquals(4.25,$row->self_amount);
|
||||
$auto=app(\App\Support\DropshipFreight\DropshipFees::class)->auto('2026-11');$this->assertEquals(4.25,$auto[$id]['fees']['readdress']);
|
||||
$out=tempnam(sys_get_temp_dir(),'df_out');$this->temp[]=$out;$h=fopen($out,'wb');app(DropshipExporter::class)->export(collect($store->factories())->sole(),'2026-11',$h);fclose($h);
|
||||
$book=IOFactory::load($out);$this->assertNotNull($book->getSheetByName('附加费核对'));$summary=$book->getSheetByName('汇总')->toArray(null,false,false);$feeRow=current(array_filter($summary,fn($r)=>$r[0]==='厂家账单-附加费'));$this->assertEquals(4.25,$feeRow[2]);$book->disconnectWorksheets();
|
||||
}
|
||||
|
||||
public function test_other_month_cannot_pay_the_same_settlement_again_and_confirmed_is_frozen(): void
|
||||
{
|
||||
$db=DB::connection('business_mirror');$store=app(CourierBillStore::class);$group=$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
|
||||
$this->fee('HISTORY1234','上楼费',10);
|
||||
foreach(['2026-10','2026-11'] as $month){$sid=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>$month,'status'=>'open','created_at'=>now(),'updated_at'=>now()]);
|
||||
$fid=$db->table('courier_bill_files')->insertGetId(['statement_id'=>$sid,'bill_month'=>$month,'group_id'=>$group,'original_name'=>'test','stored_path'=>'test','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
|
||||
$db->table('courier_bill_surcharges')->insert(['file_id'=>$fid,'sheet'=>'上楼费','row_no'=>2,'waybill_no'=>'HISTORY1234','item'=>'上楼费','amount'=>50]);
|
||||
app(SurchargeSettlementMatcher::class)->courier($sid);$last=$sid;}
|
||||
$row=app(SurchargeSettlementMatcher::class)->query('courier',$last)->first();$this->assertSame('历史已计入',$row->match_status);$this->assertEquals(0,$row->self_amount);
|
||||
$db->table('courier_bill_statements')->where('id',$last)->update(['status'=>'confirmed']);
|
||||
$db->table('courier_surcharge_settlement_rows')->update(['settlement_amount'=>123]);app(SurchargeSettlementMatcher::class)->courier($last);
|
||||
$this->assertEquals(0,app(SurchargeSettlementMatcher::class)->query('courier',$last)->value('self_amount'));
|
||||
}
|
||||
|
||||
public function test_monthly_surcharge_batch_defaults_to_previous_month_and_requires_a_scope(): void
|
||||
{
|
||||
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11'])->assertFailed();
|
||||
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-13','--all'=>true])->assertFailed();
|
||||
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true])->assertSuccessful();
|
||||
}
|
||||
|
||||
public function test_daily_refresh_does_not_enable_legacy_bills_and_only_new_sources_are_counted(): void
|
||||
{
|
||||
$db=DB::connection('business_mirror');$store=app(CourierBillStore::class);
|
||||
$group=$store->saveGroup(null,['name'=>'常州中通快运','express_names'=>['常州中通快运']]);
|
||||
$this->fee('PARTIAL1234','上楼费',10);
|
||||
$ids=[];
|
||||
foreach(['2026-10','2026-11'] as $month){
|
||||
$sid=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>$month,'status'=>'open','created_at'=>now(),'updated_at'=>now()]);
|
||||
$fid=$db->table('courier_bill_files')->insertGetId(['statement_id'=>$sid,'bill_month'=>$month,'group_id'=>$group,'original_name'=>'test','stored_path'=>'test','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
|
||||
$db->table('courier_bill_surcharges')->insert(['file_id'=>$fid,'sheet'=>'上楼费','row_no'=>2,'waybill_no'=>'PARTIAL1234','item'=>'上楼费','amount'=>20]);
|
||||
$ids[]=$sid;
|
||||
}
|
||||
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($ids[0]);
|
||||
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true,'--existing-only'=>true])->assertSuccessful();
|
||||
$this->assertSame(0,$matcher->query('courier',$ids[1])->count());
|
||||
$source=(array)$db->table('courier_surcharge_settlement_rows')->first();unset($source['id']);
|
||||
$source['source_key']='GD-NEW';$source['settlement_amount']=3.25;$source['shipped_at']='2026-11-05 12:00:00';
|
||||
$db->table('courier_surcharge_settlement_rows')->insert($source);
|
||||
$matcher->courier($ids[1]);$row=$matcher->query('courier',$ids[1])->first();
|
||||
$this->assertEquals(3.25,$row->self_amount);$this->assertStringContainsString('已扣除',$row->match_note);
|
||||
$db->table('courier_surcharge_settlement_rows')->where('source_key','GD-NEW')->update(['settlement_amount'=>4.25]);
|
||||
$this->artisan('courier-surcharge:match-bills',['--month'=>'2026-11','--all'=>true,'--existing-only'=>true])->assertSuccessful();
|
||||
$this->assertEquals(4.25,$matcher->query('courier',$ids[1])->value('self_amount'));
|
||||
$matcher->courier($ids[0]);$this->assertEquals(10,$matcher->query('courier',$ids[0])->value('self_amount'));
|
||||
}
|
||||
|
||||
public function test_dropship_rejects_a_matching_courier_from_another_factory_warehouse(): void
|
||||
{
|
||||
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'本厂','warehouse'=>'本厂仓','keywords'=>'代发快递']);
|
||||
$this->ship('WRONG12345','测试代发快递','其他厂仓');$this->fee('WRONG12345','改地址',15,'测试代发快递');
|
||||
$db=$store->db();$file=$db->table('dropship_bill_files')->insertGetId(['factory_id'=>$id,'bill_month'=>'2026-11','original_name'=>'test.xlsx','stored_path'=>'test.xlsx','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]);
|
||||
$db->table('dropship_bill_surcharges')->insert(['factory_id'=>$id,'file_id'=>$file,'bill_month'=>'2026-11','sheet'=>'附加费','row_no'=>2,'waybill_no'=>'WRONG12345','item'=>'改地址','amount'=>30]);
|
||||
app(SurchargeSettlementMatcher::class)->dropship($id,'2026-11');
|
||||
$row=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->first();
|
||||
$this->assertNull($row->self_amount);$this->assertSame('未匹配',$row->match_status);
|
||||
}
|
||||
|
||||
protected function tearDown(): void {foreach($this->temp as $path)@unlink($path);parent::tearDown();}
|
||||
|
||||
private function quote(string $courier,string $type,string $mode,string $standard,string $condition,string $scope='代发仓'): int
|
||||
{
|
||||
return DB::table('business_courier_surcharge_quotes')->insertGetId(['company_id'=>(int)$this->company->id,
|
||||
'courier'=>$courier,'scope'=>$scope,'reconciler'=>'测试','types'=>json_encode([$type]),'mode'=>$mode,
|
||||
'standard'=>$standard,'condition'=>$condition,'effective_at'=>'2026-01-01','status'=>'active','created_at'=>now(),'updated_at'=>now()]);
|
||||
}
|
||||
|
||||
private function workOrder(string $no,string $courier,string $type,string $amount,?string $approved,string $created='2026-11-03 10:00:00'): void
|
||||
{
|
||||
$schema=Schema::connection('business_mirror');
|
||||
if(!$schema->hasTable('js_jst_work_order_info'))$schema->create('js_jst_work_order_info',function(Blueprint $t){
|
||||
$t->string('_mirror_key')->primary();$t->integer('Id');$t->string('woNo');$t->string('title');$t->string('status');$t->dateTime('created');$t->text('businessFieldList');
|
||||
});
|
||||
$fields=[['fieldId'=>'lIdField','value'=>$no],['fieldId'=>'logisticsField','value'=>$courier],
|
||||
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_TABLE,'childFieldList'=>[[
|
||||
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_TYPE,'value'=>$type],
|
||||
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_AMOUNT,'value'=>$amount],
|
||||
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_APPROVAL,'value'=>$approved],
|
||||
]]]];
|
||||
$db=DB::connection('business_mirror');$id=$db->table('js_jst_work_order_info')->count()+1;
|
||||
$row=['_mirror_key'=>'work-'.$id,'Id'=>$id,'woNo'=>'GD-'.$id,'title'=>'查件','status'=>'WAIT_CONFIRM','created'=>$created,'businessFieldList'=>json_encode($fields)];
|
||||
$db->table('js_jst_work_order_info')->insert($row);
|
||||
app(\Modules\EcommerceFinance\Services\WorkOrderWaybillLookup::class)->storeBatch([$row]);
|
||||
$db->table('work_order_waybill_lookup_states')->updateOrInsert(['id'=>1],['completed_at'=>now(),'updated_at'=>now()]);
|
||||
}
|
||||
|
||||
public function test_import_calculates_outbound_freight_and_does_not_apply_other_courier_rules(): void
|
||||
{
|
||||
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'测试厂家','warehouse'=>'测试仓','keywords'=>'测试']);
|
||||
$this->quote('测试圆通','拦截费','取发出运费','等于发出运费','取发出运费');
|
||||
$this->ship('YT11111111','测试圆通');$this->ship('ST11111111','测试申通');
|
||||
$db=$store->db();$db->table('jst_oms_shipping')->where('express_no','YT11111111')->update(['item_id'=>'12345678901234567890','barcode'=>'SKU001','shop_name'=>'测试店','trade_no'=>'ORDER001']);
|
||||
$path=$this->book(['账单'=>[['单号','运费'],['YT11111111',2],['ST11111111',3]],
|
||||
'附加费'=>[['快递单号','附加费金额','附加费类型'],['YT11111111',999,'拦截退回'],['YT11111111',999,'拦截费'],['ST11111111',999,'拦截退回']]]);
|
||||
$store->uploadFor('测试厂家11月.xlsx',$path,'2026-11',$id,'测试');
|
||||
$rows=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->orderBy('id')->get();
|
||||
$this->assertEquals(10,$rows[0]->self_amount);$this->assertEquals(0,$rows[1]->self_amount);$this->assertNull($rows[2]->self_amount);
|
||||
$this->assertSame('重复',$rows[1]->match_status);$this->assertSame('SKU001',$rows[0]->product_code);
|
||||
$this->assertSame('12345678901234567890',$rows[0]->platform_product_id);$this->assertSame('ORDER001',$rows[0]->online_order_no);
|
||||
$this->assertStringContainsString('取本票已核算发出运费',$rows[0]->match_note);
|
||||
$this->assertStringContainsString('没有启用',$rows[2]->match_note);
|
||||
}
|
||||
|
||||
public function test_customer_service_approval_weight_gate_and_missing_rule_are_explicit(): void
|
||||
{
|
||||
$store=app(CourierBillStore::class);$group=$store->saveGroup(null,['name'=>'测试德邦','express_names'=>['测试德邦']]);
|
||||
$this->quote('测试德邦','上楼费','聚工单客服核实','读取聚工单附加费明细','重量60kg以上,上楼费聚工单客服回复通过','自有快递');
|
||||
foreach(['DP11111111','DP22222222','DP33333333','DP44444444','DP55555555'] as $n)$this->ship($n,'测试德邦');
|
||||
$db=$store->db();$db->table('jst_oms_shipping_freight')->update(['charge_weight'=>60]);
|
||||
$sid=$db->table('jst_oms_shipping')->where('express_no','DP22222222')->value('source_id');$db->table('jst_oms_shipping_freight')->where('source_id',$sid)->update(['charge_weight'=>59.99]);
|
||||
$this->workOrder('DP11111111','测试德邦','上楼费','37.50','通过');
|
||||
$this->workOrder('DP22222222','测试德邦','上楼费','77','通过');
|
||||
$this->workOrder('DP33333333','测试德邦','上楼费','77',null);
|
||||
$this->workOrder('DP44444444','测试德邦','上楼费','77','通过','2026-12-01 00:00:00');
|
||||
$path=$this->book(['账单'=>[['单号','运费'],['DP11111111',10]],'附加费'=>[['快递单号','附加费金额','附加费类型'],
|
||||
['DP11111111',99,'上楼费'],['DP22222222',99,'上楼费'],['DP33333333',99,'上楼费'],['DP44444444',99,'上楼费'],['DP55555555',99,'改地址费']]]);
|
||||
$fid=$store->upload([new UploadedFile($path,'测试德邦11月.xlsx',null,null,true)],'2026-11',[],'测试')[0];
|
||||
$id=(int)$db->table('courier_bill_files')->where('id',$fid)->value('statement_id');$rows=app(SurchargeSettlementMatcher::class)->query('courier',$id)->orderBy('id')->get();
|
||||
$this->assertEquals(37.50,$rows[0]->self_amount);$this->assertEquals(0,$rows[1]->self_amount);$this->assertNull($rows[2]->self_amount);$this->assertNull($rows[3]->self_amount);
|
||||
$this->assertStringContainsString('未达到',$rows[1]->match_note);$this->assertStringContainsString('未审核通过',$rows[2]->match_note);
|
||||
$this->assertStringContainsString('没有启用',$rows[4]->match_note);
|
||||
}
|
||||
|
||||
public function test_quote_scope_effective_date_missing_freight_and_size_boundaries(): void
|
||||
{
|
||||
$this->ship('QA11111111','测试快递');$this->ship('QA22222222','测试快递');
|
||||
$this->quote('测试快递','超长费','按尺寸/最长边','7元/单','单边超160cm','自有快递');
|
||||
$db=DB::connection('business_mirror');$db->table('jst_oms_shipping')->update(['length_cm'=>160,'width_cm'=>20,'height_cm'=>20]);
|
||||
$db->table('jst_oms_shipping')->where('express_no','QA22222222')->update(['length_cm'=>160.01]);
|
||||
$input=[['waybill_no'=>'QA11111111','item'=>'超长费'],['waybill_no'=>'QA22222222','item'=>'超长费']];$calc=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class);
|
||||
$result=$calc->calculate($input,'courier','2026-11',['测试快递']);$this->assertEquals(0,$result['rows']['QA11111111']['超长费'][0]->settlement_amount);$this->assertEquals(7,$result['rows']['QA22222222']['超长费'][0]->settlement_amount);
|
||||
$this->assertSame([],$calc->calculate($input,'dropship','2026-11',['测试快递'])['rows']);
|
||||
DB::table('business_courier_surcharge_quotes')->update(['effective_at'=>'2026-12-01']);$this->assertSame([],$calc->calculate($input,'courier','2026-11',['测试快递'])['rows']);
|
||||
DB::table('business_courier_surcharge_quotes')->update(['effective_at'=>'2026-01-01','mode'=>'取发出运费','standard'=>'等于发出运费','condition'=>'取发出运费']);
|
||||
$db->table('jst_oms_shipping_freight')->update(['status'=>'FAILED']);$this->assertStringContainsString('尚未核算完成',$calc->calculate($input,'courier','2026-11',['测试快递'])['notes']['QA11111111']['超长费']);
|
||||
$db->table('jst_oms_shipping')->where('express_no','QA11111111')->update(['ship_time'=>'2026-12-01 00:00:00']);
|
||||
$this->assertStringContainsString('晚于账单月份',$calc->calculate($input,'courier','2026-11',['测试快递'])['notes']['QA11111111']['超长费']);
|
||||
$db->table('jst_oms_shipping')->where('express_no','QA11111111')->update(['ship_time'=>'2026-11-02 00:00:00']);
|
||||
DB::table('business_courier_surcharge_quotes')->update(['deleted_at'=>now()]);$this->assertSame([],$calc->calculate($input,'courier','2026-11',['测试快递'])['rows']);
|
||||
}
|
||||
}
|
||||
@ -1,137 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\Rebooks;
|
||||
use App\Support\CourierBills\StatementExporter;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use RuntimeException;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
final class CourierBillRebookIntegrityTest extends FeatureTestCase
|
||||
{
|
||||
private function statement(): int
|
||||
{
|
||||
Storage::fake('local');
|
||||
$group = app(CourierBillStore::class)->saveGroup(null, [
|
||||
'name' => '边界测试快递', 'express_names' => ['边界测试快递'], 'rebook_months' => 1,
|
||||
]);
|
||||
DB::connection(config('database.supplier_payable_maintenance_connection'))->table('supplier_payable_overrides')->insert([
|
||||
'company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
|
||||
'record_key' => 'boundary:1', 'values' => json_encode([
|
||||
'summary_month' => '2026-10', 'tracking_no' => 'BOUNDARY100', 'carrier' => '边界测试快递',
|
||||
'settle_bookkeeping' => '100.00', 'product_name' => '确认时商品',
|
||||
]), 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
Rebooks::db()->table('courier_bill_rebook_reviews')->insert([
|
||||
'waybill_no' => 'BOUNDARY100', 'deduct_month' => '2026-10', 'current_amount' => 0, 'updated_at' => now(),
|
||||
]);
|
||||
return Rebooks::db()->table('courier_bill_statements')->insertGetId([
|
||||
'group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_carrier_matching_keeps_trimming_surrounding_whitespace(): void
|
||||
{
|
||||
$id = $this->statement();
|
||||
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
|
||||
$record = $connection->table('supplier_payable_overrides')->where('record_key', 'boundary:1')->first();
|
||||
$values = json_decode($record->values, true);
|
||||
$values['carrier'] = " \t边界测试快递\r\n ";
|
||||
$connection->table('supplier_payable_overrides')->where('id', $record->id)
|
||||
->update(['values' => json_encode($values)]);
|
||||
$rows = app(Rebooks::class)->forStatement($id)['rows'];
|
||||
$this->assertCount(1, $rows);
|
||||
$this->assertSame('边界测试快递', $rows[0]['carrier']);
|
||||
$this->assertSame(100.0, $rows[0]['amount']);
|
||||
}
|
||||
|
||||
public function test_refund_imported_in_same_month_is_not_paid_again(): void
|
||||
{
|
||||
$id = $this->statement();
|
||||
Rebooks::db()->table('courier_bill_rebooks')->insert([
|
||||
'waybill_no' => 'BOUNDARY100', 'deduct_month' => '2026-10', 'refund_month' => '2026-11',
|
||||
'amount' => 100, 'source' => 'import', 'created_at' => now(),
|
||||
]);
|
||||
$rows = app(Rebooks::class)->forStatement($id)['rows'];
|
||||
$this->assertSame(0.0, (float) array_sum(array_column($rows, 'amount')));
|
||||
$this->assertSame('已补(2026-11)', $rows[0]['status']);
|
||||
app(CourierBillMatcher::class)->refreshSummary($id);
|
||||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||||
$this->assertSame(0, Rebooks::db()->table('courier_bill_rebooks')->where('statement_id', $id)->count());
|
||||
}
|
||||
|
||||
public function test_confirmed_amount_and_export_are_frozen_after_review_and_group_changes(): void
|
||||
{
|
||||
$id = $this->statement();
|
||||
app(CourierBillMatcher::class)->refreshSummary($id);
|
||||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||||
Rebooks::db()->table('courier_bill_rebook_reviews')->where('waybill_no', 'BOUNDARY100')->update(['current_amount' => 40]);
|
||||
Rebooks::db()->table('courier_bill_groups')->update(['rebook_months' => 0]);
|
||||
DB::connection(config('database.supplier_payable_maintenance_connection'))->table('supplier_payable_overrides')->delete();
|
||||
$rows = app(Rebooks::class)->forStatement($id)['rows'];
|
||||
$this->assertSame(100.0, $rows[0]['amount']);
|
||||
$this->assertSame(0.0, $rows[0]['current']);
|
||||
$this->assertSame('确认时商品', $rows[0]['info']['product_name']);
|
||||
$path = tempnam(sys_get_temp_dir(), 'rebook-frozen-');
|
||||
try {
|
||||
$stream = fopen($path, 'wb');
|
||||
try { app(StatementExporter::class)->export($id, $stream); } finally { fclose($stream); }
|
||||
$book = IOFactory::createReader('Xlsx')->load($path);
|
||||
try {
|
||||
$sheet = $book->getSheetByName('补10月记账');
|
||||
$this->assertNotNull($sheet);
|
||||
$this->assertEquals([100, 0, 100], array_slice($sheet->toArray(null, false, false)[1], -3));
|
||||
} finally { $book->disconnectWorksheets(); }
|
||||
} finally { @unlink($path); }
|
||||
}
|
||||
|
||||
public function test_manual_summary_mismatch_blocks_confirmation_without_writing_ledger(): void
|
||||
{
|
||||
$id = $this->statement();
|
||||
app(CourierBillMatcher::class)->refreshSummary($id);
|
||||
app(CourierBillStore::class)->addSummaryItem($id, '补10月记账', null, 60);
|
||||
try {
|
||||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||||
$this->fail('不同金额不应确认成功。');
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->assertStringContainsString('小汇总与逐单复核金额不一致', $exception->getMessage());
|
||||
}
|
||||
$this->assertSame('open', Rebooks::db()->table('courier_bill_statements')->where('id', $id)->value('status'));
|
||||
$this->assertSame(0, Rebooks::db()->table('courier_bill_rebooks')->count());
|
||||
}
|
||||
|
||||
public function test_stale_summary_blocks_confirmation_and_refresh_recovers(): void
|
||||
{
|
||||
$id = $this->statement();
|
||||
app(CourierBillMatcher::class)->refreshSummary($id);
|
||||
Rebooks::db()->table('courier_bill_rebook_reviews')->update(['current_amount' => 40]);
|
||||
try {
|
||||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||||
$this->fail('过期金额不应被悄悄确认。');
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->assertStringContainsString('小汇总与逐单复核金额不一致', $exception->getMessage());
|
||||
}
|
||||
app(CourierBillMatcher::class)->refreshSummary($id);
|
||||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||||
$this->assertSame(60.0, (float) Rebooks::db()->table('courier_bill_rebooks')->where('statement_id', $id)->sum('amount'));
|
||||
app(CourierBillStore::class)->unconfirm($id);
|
||||
$this->assertSame(0, Rebooks::db()->table('courier_bill_rebooks')->count());
|
||||
}
|
||||
|
||||
public function test_same_deduction_cannot_be_imported_as_refunded_twice_across_months(): void
|
||||
{
|
||||
$this->statement();
|
||||
$path = tempnam(sys_get_temp_dir(), 'rebook-dedup-');
|
||||
file_put_contents($path, "单号,扣款月份,补款账期,补款金额\nBOUNDARY100,2026-10,2026-11,100\nBOUNDARY100,2026-10,2026-12,100\n");
|
||||
try {
|
||||
$result = app(Rebooks::class)->importRefunds($path, 'csv');
|
||||
$this->assertSame(1, $result['inserted']);
|
||||
$this->assertSame(100.0, (float) Rebooks::db()->table('courier_bill_rebooks')->sum('amount'));
|
||||
} finally { @unlink($path); }
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user