Compare commits
62 Commits
fix/limeng
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f94f40c218 | |||
| f809de684a | |||
| 19688075d8 | |||
| d334392c33 | |||
| f876c793af | |||
| e6cb7c098f | |||
| 9114b3727b | |||
| 97dc21cc50 | |||
| b93aef72d1 | |||
| 5937d0cc0b | |||
| 875e8c3700 | |||
| 04f9e25ba5 | |||
| abacecfd1e | |||
| 773681773f | |||
| 46825fc165 | |||
| 43cf75734d | |||
| 6952d6c3b7 | |||
| 303972e90a | |||
| 7f8afd290d | |||
| 43bd01493b | |||
| 824ab74c1a | |||
| cab621058a | |||
| bb2082730b | |||
| d5b4f4d476 | |||
| 1840d98f32 | |||
| eeb3b33d64 | |||
| ffcd457d12 | |||
| de1888879b | |||
| 0a5f8744ce | |||
| 9cf28bcb3a | |||
| 42014e56a3 | |||
| 5349a3c8a5 | |||
| ebcec21bd1 | |||
| 341e298981 | |||
| c24615450b | |||
| 632a8407da | |||
| 2197444889 | |||
| 0a3a09dbd5 | |||
| 398cf9690c | |||
| aea68c2d2d | |||
| 9b465c111a | |||
| b7f768d371 | |||
| a75b0ee1ac | |||
| 4722c93d57 | |||
| d6842648e3 | |||
| 50359f10fb | |||
| db28cf4f0f | |||
| aadf5682e2 | |||
| d7b664ad53 | |||
| 2a908b9292 | |||
| 2cab94b773 | |||
| ef7e3acbc8 | |||
| 19c5555373 | |||
| b33b87a161 | |||
| dd822e59ba | |||
| 3953c69192 | |||
| 3f1bfc5f79 | |||
| b591eff505 | |||
| ea3d428262 | |||
| 00811970fc | |||
| d9ae8fdffe | |||
| 28247a0897 |
@ -49,10 +49,7 @@ class ImportPayablesFinal extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
$fields = $registry->fields($section, $dataset);
|
$fields = $registry->fields($section, $dataset);
|
||||||
$storeDataset = 'final:'
|
$storeDataset = $registry->storeDataset($section, $dataset);
|
||||||
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
|
|
||||||
. ':'
|
|
||||||
. $dataset;
|
|
||||||
$totalCreated = 0;
|
$totalCreated = 0;
|
||||||
$totalUpdated = 0;
|
$totalUpdated = 0;
|
||||||
$totalRows = 0;
|
$totalRows = 0;
|
||||||
|
|||||||
58
app/Console/Commands/MatchBillSurcharges.php
Normal file
58
app/Console/Commands/MatchBillSurcharges.php
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
<?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;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||||
|
|
||||||
|
class MatchBillSurcharges extends Command
|
||||||
|
{
|
||||||
|
public const AUTO_MATCH_HOLDS = 'bill-surcharge-auto-match-holds';
|
||||||
|
|
||||||
|
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=[];
|
||||||
|
$holds=[];
|
||||||
|
if($this->option('existing-only'))foreach(app(SupplierPayableOverrideStore::class)->listRows(self::AUTO_MATCH_HOLDS,(int)$this->option('company')) as $hold){
|
||||||
|
if(($hold['enabled']??false)===true)$holds[$hold['_action_key']]=true;
|
||||||
|
}
|
||||||
|
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){
|
||||||
|
if(isset($holds['dropship|'.$id.'|'.$month])){$this->line('厂家 #'.$id.' 已保留当前附加费,跳过自动重匹配');continue;}
|
||||||
|
$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();}
|
||||||
|
}
|
||||||
|
}
|
||||||
60
app/Console/Commands/MatchReverseCourierBill.php
Normal file
60
app/Console/Commands/MatchReverseCourierBill.php
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Common\Company;
|
||||||
|
use App\Support\CourierBills\CourierBillMatcher;
|
||||||
|
use App\Support\CourierBills\ReturnPickupLookup;
|
||||||
|
use App\Support\CourierBills\ShippingLookup;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
|
||||||
|
/** 指定一张逆向账单预演/重算,保留原始账单与手工处理。 */
|
||||||
|
final class MatchReverseCourierBill extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'courier-bills:match-reverse {statement : 对账单ID} {--company=1} {--apply : 备份后更新该未确认账单}';
|
||||||
|
protected $description = '按退件取件资料和当前有效报价核对指定逆向快递账单';
|
||||||
|
|
||||||
|
public function handle(ShippingLookup $lookup, CourierBillMatcher $matcher): int
|
||||||
|
{
|
||||||
|
Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
|
||||||
|
$id = (int) $this->argument('statement');
|
||||||
|
$lock = Cache::lock('courier-bills:match-reverse:' . $id, 600);
|
||||||
|
if (! $lock->get()) { $this->error('该账单正在核对'); return self::FAILURE; }
|
||||||
|
try {
|
||||||
|
$start = microtime(true);
|
||||||
|
$db = CourierBillMatcher::db();
|
||||||
|
$statement = $db->table('courier_bill_statements')->find($id);
|
||||||
|
if (! $statement || $statement->status === 'confirmed') { $this->error('账单不存在或已确认'); return self::FAILURE; }
|
||||||
|
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||||||
|
$names = (array) json_decode($group->express_names, true);
|
||||||
|
if (! ReturnPickupLookup::supports($names)) { $this->error('指定账单不属于逆向快递'); return self::FAILURE; }
|
||||||
|
$lines = $db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->get();
|
||||||
|
$rows = $lookup->summaries($lines->pluck('waybill_no')->unique()->all(), $names);
|
||||||
|
$total = $calculated = $matched = 0;
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$matched += ($row['data_source'] ?? '') === '退件取件管理' ? 1 : 0;
|
||||||
|
if ($row['calc_freight'] !== null) { $calculated++; $total += $row['calc_freight']; }
|
||||||
|
}
|
||||||
|
$this->line(json_encode(['statement' => $id, 'group' => $group->name, 'month' => $statement->bill_month,
|
||||||
|
'lines' => $lines->count(), 'return_matches' => $matched, 'calculated_waybills' => $calculated,
|
||||||
|
'calculated_total' => round($total, 2)], JSON_UNESCAPED_UNICODE));
|
||||||
|
if ($this->option('apply')) {
|
||||||
|
$path = 'private/operation-backups/reverse-bill-' . $id . '-' . gmdate('Ymd-His') . '.json';
|
||||||
|
$tables = ['courier_bill_lines', 'courier_bill_unprovided', 'courier_bill_summary_items'];
|
||||||
|
$backup = ['statement' => $statement, 'group' => $group];
|
||||||
|
foreach ($tables as $table) $backup[$table] = $db->table($table)->where('statement_id', $id)->get()->all();
|
||||||
|
Storage::disk('local')->put($path, json_encode($backup, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
|
$this->line('备份:' . $path);
|
||||||
|
$matcher->match($id);
|
||||||
|
$this->line(json_encode(['categories' => $db->table('courier_bill_lines')->where('statement_id', $id)
|
||||||
|
->groupBy('category')->selectRaw('category, COUNT(*) as count, SUM(bill_amount) as bill, SUM(self_amount) as self')->get(),
|
||||||
|
'unprovided' => $db->table('courier_bill_unprovided')->where('statement_id', $id)->count()], JSON_UNESCAPED_UNICODE));
|
||||||
|
}
|
||||||
|
$this->line(json_encode(['elapsed_seconds' => round(microtime(true) - $start, 3),
|
||||||
|
'peak_memory_mb' => round(memory_get_peak_usage(true) / 1048576, 1)]));
|
||||||
|
return self::SUCCESS;
|
||||||
|
} finally { $lock->release(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -13,7 +13,7 @@ use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
|
|||||||
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */
|
/** 每天 11:20 推送种菜报销批次汇总;逐单不予报销通知须已启用。不改聚工单。 */
|
||||||
class PlantingReimbursementDailyDigest extends Command
|
class PlantingReimbursementDailyDigest extends Command
|
||||||
{
|
{
|
||||||
protected $signature = 'planting-reimbursement:daily-digest
|
protected $signature = 'planting-reimbursement:daily-digest
|
||||||
@ -48,7 +48,9 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, ! $this->option('dry-run'));
|
$liveRun = ! $this->option('dry-run');
|
||||||
|
$sendNotices = $liveRun && $robot->cancelNoticesEnabled();
|
||||||
|
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, $liveRun, $sendNotices);
|
||||||
if ($this->option('dry-run')) {
|
if ($this->option('dry-run')) {
|
||||||
$this->line($title . "\n" . $text);
|
$this->line($title . "\n" . $text);
|
||||||
continue;
|
continue;
|
||||||
@ -67,7 +69,7 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{0:string,1:string} */
|
/** @return array{0:string,1:string} */
|
||||||
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $sendNotices): array
|
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $liveRun, bool $sendNotices): array
|
||||||
{
|
{
|
||||||
$sync = $repository->syncStatus();
|
$sync = $repository->syncStatus();
|
||||||
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
||||||
@ -92,7 +94,7 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
$confirmedNow = false;
|
$confirmedNow = false;
|
||||||
if ($result === null) {
|
if ($result === null) {
|
||||||
$result = $workbench->build($companyId, $date);
|
$result = $workbench->build($companyId, $date);
|
||||||
if ($sendNotices && Gate::check($result)['ok']) {
|
if ($liveRun && Gate::check($result)['ok']) {
|
||||||
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
|
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
|
||||||
$confirmedNow = true;
|
$confirmedNow = true;
|
||||||
}
|
}
|
||||||
@ -118,6 +120,8 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
|
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
|
||||||
} elseif ($s['notices'] === []) {
|
} elseif ($s['notices'] === []) {
|
||||||
$lines[] = '- 没有要取消或复查的工单';
|
$lines[] = '- 没有要取消或复查的工单';
|
||||||
|
} elseif (! $robot->cancelNoticesEnabled()) {
|
||||||
|
$lines[] = '- 取消 / 待复查逐单通知已暂停,测试完成前不会发送';
|
||||||
} elseif ($sendNotices) {
|
} elseif ($sendNotices) {
|
||||||
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
|
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
|
||||||
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
|
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
|
||||||
|
|||||||
41
app/Console/Commands/PullCustomerServiceSurcharges.php
Normal file
41
app/Console/Commands/PullCustomerServiceSurcharges.php
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
<?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(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
110
app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php
Normal file
110
app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
<?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,13 +7,14 @@ use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
|||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 后台重建某月账单项目覆盖快照,供科目映射页即时读取。
|
* 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。
|
||||||
*/
|
*/
|
||||||
class RefreshAccountMappingCoverage extends Command
|
class RefreshAccountMappingCoverage extends Command
|
||||||
{
|
{
|
||||||
protected $signature = 'account-mapping:refresh-coverage
|
protected $signature = 'account-mapping:refresh-coverage
|
||||||
{month? : 账单月份,格式 YYYY-MM}
|
{month? : all 或账单月份 YYYY-MM}
|
||||||
{--pending : 处理页面登记的下一个刷新请求}';
|
{--pending : 处理页面登记的下一个刷新请求}
|
||||||
|
{--monthly : 本月尚未成功刷新时执行跨月刷新}';
|
||||||
|
|
||||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||||
|
|
||||||
@ -21,6 +22,12 @@ class RefreshAccountMappingCoverage extends Command
|
|||||||
{
|
{
|
||||||
$runningPath = null;
|
$runningPath = null;
|
||||||
$month = trim((string) $this->argument('month')) ?: 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')) {
|
if ($this->option('pending')) {
|
||||||
$request = $coverage->claimPendingRefresh();
|
$request = $coverage->claimPendingRefresh();
|
||||||
if ($request === null) {
|
if ($request === null) {
|
||||||
@ -31,9 +38,20 @@ class RefreshAccountMappingCoverage extends Command
|
|||||||
$month = $request['month'];
|
$month = $request['month'];
|
||||||
$runningPath = $request['path'];
|
$runningPath = $request['path'];
|
||||||
}
|
}
|
||||||
|
if ($monthly) {
|
||||||
|
if (! $coverage->monthlyRefreshDue()) {
|
||||||
|
$this->line('本月未映射清单已生成,无需重复刷新。');
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
$month = 'all';
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$raw = $coverage->refreshForMonth($month);
|
$isAll = $month === 'all';
|
||||||
|
$raw = $isAll
|
||||||
|
? $coverage->refreshAllMonths()
|
||||||
|
: $coverage->refreshForMonth($month);
|
||||||
if (($raw['status'] ?? '') === 'refreshing') {
|
if (($raw['status'] ?? '') === 'refreshing') {
|
||||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||||
if ($runningPath !== null) {
|
if ($runningPath !== null) {
|
||||||
@ -43,10 +61,12 @@ class RefreshAccountMappingCoverage extends Command
|
|||||||
return self::SUCCESS;
|
return self::SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
$summary = $coverage->missingForMonth($month);
|
$summary = $isAll
|
||||||
|
? $coverage->missingAcrossMonths()
|
||||||
|
: $coverage->missingForMonth($month);
|
||||||
$this->info(sprintf(
|
$this->info(sprintf(
|
||||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
||||||
(string) $summary['month'],
|
$isAll ? '跨月全部账单' : (string) $summary['month'],
|
||||||
(int) $summary['missing_item_count'],
|
(int) $summary['missing_item_count'],
|
||||||
(int) $summary['missing_row_count'],
|
(int) $summary['missing_row_count'],
|
||||||
(int) $summary['source_rows'],
|
(int) $summary['source_rows'],
|
||||||
|
|||||||
@ -89,12 +89,13 @@ class SendSupplierStatementReminders extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->line(sprintf(
|
$this->line(sprintf(
|
||||||
'#%d %s %s %s:00: 入库供应商 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,本时段已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
|
'#%d %s %s %s:00: 需上传供应商 %d 家,无需上传 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,本时段已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
|
||||||
$company->id,
|
$company->id,
|
||||||
$company->name,
|
$company->name,
|
||||||
$result['accounting_month'],
|
$result['accounting_month'],
|
||||||
$slot,
|
$slot,
|
||||||
$result['source_suppliers'],
|
$result['source_suppliers'],
|
||||||
|
count($result['exempt_suppliers']),
|
||||||
$result['configured'],
|
$result['configured'],
|
||||||
$dryRun ? '将提醒' : '已发送',
|
$dryRun ? '将提醒' : '已发送',
|
||||||
count($dryRun ? $result['previewed'] : $result['sent']),
|
count($dryRun ? $result['previewed'] : $result['sent']),
|
||||||
|
|||||||
192
app/Console/Commands/SummarizeBillRange.php
Normal file
192
app/Console/Commands/SummarizeBillRange.php
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
<?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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,9 @@ use Illuminate\Console\Command;
|
|||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
use InvalidArgumentException;
|
use InvalidArgumentException;
|
||||||
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
|
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\LinehaulFreightRepository;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
|
||||||
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
||||||
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
|
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
|
||||||
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
||||||
@ -92,6 +95,19 @@ class SyncBusinessMirrors extends Command
|
|||||||
$result['batches'],
|
$result['batches'],
|
||||||
$result['rows'],
|
$result['rows'],
|
||||||
));
|
));
|
||||||
|
if ($key === LinehaulFreightRepository::DATASET && $result['status'] === 'succeeded'
|
||||||
|
&& ((bool) $task['full'] || $result['rows'] > 0)) {
|
||||||
|
try {
|
||||||
|
$freight = app(ShippingFreightService::class)->recalculate(
|
||||||
|
FreightCarrierRules::START_DATE, now()->addDay()->format('Y-m-d'), LinehaulFreightRepository::CARRIERS);
|
||||||
|
$this->info(sprintf('专线运费已更新:%d 个包裹,匹配成功 %d 个,待核对 %d 个。',
|
||||||
|
$freight['packages'], $freight['ok'], $freight['packages'] - $freight['ok']));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$failed = true;
|
||||||
|
Log::error('专线镜像已同步,核算结果更新失败。', ['exception' => $exception::class]);
|
||||||
|
$this->error('专线镜像已同步,发货数据核算结果未完成更新,请重跑专线运费核算。');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 每日退款专属批次只处理配置内的退款表,不能继续进入
|
// 每日退款专属批次只处理配置内的退款表,不能继续进入
|
||||||
|
|||||||
52
app/Console/Commands/SyncReturnedParcels.php
Normal file
52
app/Console/Commands/SyncReturnedParcels.php
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class SyncReturnedParcels extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)}';
|
||||||
|
protected $description = '同步聚水潭售后退货退款到快递应付退回件明细';
|
||||||
|
|
||||||
|
public function handle(ReturnedParcelSynchronizer $synchronizer): int
|
||||||
|
{
|
||||||
|
$from = (string) ($this->option('from') ?: ReturnedParcelSynchronizer::START);
|
||||||
|
$to = (string) ($this->option('to') ?: now('Asia/Shanghai')->toDateString());
|
||||||
|
foreach ([$from, $to] as $date) {
|
||||||
|
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts)
|
||||||
|
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
|
||||||
|
$this->error('日期需要 YYYY-MM-DD。');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($from < ReturnedParcelSynchronizer::START || $from > $to) {
|
||||||
|
$this->error('开始日期不得早于 2026-10-01,且不能晚于结束日期。');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
|
||||||
|
$this->error('请通过服务器 run-finance-batch.sh 执行同步。');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$lock = Cache::lock('courier-returned-parcels-sync', 2100);
|
||||||
|
if (! $lock->get()) {
|
||||||
|
$this->warn('退回件同步正在运行,本次跳过。');
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行"));
|
||||||
|
$this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
|
||||||
|
$from, $to, $result['rows'], $result['seconds'], $result['peak_mb']));
|
||||||
|
return self::SUCCESS;
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。');
|
||||||
|
return self::FAILURE;
|
||||||
|
} finally {
|
||||||
|
$lock->release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -71,6 +71,14 @@ class Kernel extends ConsoleKernel
|
|||||||
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
|
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
|
||||||
->runInBackground();
|
->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')
|
$schedule->command('business-mirror:archive-store-information')
|
||||||
->dailyAt('07:00')
|
->dailyAt('07:00')
|
||||||
|
|||||||
@ -12,6 +12,7 @@ use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
|||||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||||
|
use Modules\EcommerceFinance\Services\AccountMappingSuggestion;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
@ -74,6 +75,7 @@ class AccountMappingActions extends Controller
|
|||||||
private readonly AccountMappingCoa $coa,
|
private readonly AccountMappingCoa $coa,
|
||||||
private readonly AccountMappingWorkbookImporter $importer,
|
private readonly AccountMappingWorkbookImporter $importer,
|
||||||
private readonly AccountMappingCoverage $coverage,
|
private readonly AccountMappingCoverage $coverage,
|
||||||
|
private readonly AccountMappingSuggestion $suggestion,
|
||||||
) {
|
) {
|
||||||
$this->middleware('auth');
|
$this->middleware('auth');
|
||||||
$this->middleware('company.identify');
|
$this->middleware('company.identify');
|
||||||
@ -96,11 +98,13 @@ class AccountMappingActions extends Controller
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return response()->json($this->coverage->missingForMonth(
|
$month = trim((string) ($data['month'] ?? ''));
|
||||||
trim((string) ($data['month'] ?? '')) ?: null,
|
$refresh = (bool) ($data['refresh'] ?? false);
|
||||||
(bool) ($data['refresh'] ?? false),
|
$payload = $month === ''
|
||||||
false,
|
? $this->coverage->missingAcrossMonths($refresh, false)
|
||||||
));
|
: $this->coverage->missingForMonth($month, $refresh, false);
|
||||||
|
|
||||||
|
return response()->json($payload);
|
||||||
} catch (\InvalidArgumentException $exception) {
|
} catch (\InvalidArgumentException $exception) {
|
||||||
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
@ -112,6 +116,20 @@ 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
|
public function store(Request $request): JsonResponse
|
||||||
{
|
{
|
||||||
$values = $this->payloadValues($request);
|
$values = $this->payloadValues($request);
|
||||||
|
|||||||
@ -7,6 +7,7 @@ use App\Support\CourierBills\CourierBillMatcher;
|
|||||||
use App\Support\CourierBills\CourierBillStore;
|
use App\Support\CourierBills\CourierBillStore;
|
||||||
use App\Support\CourierBills\StatementExporter;
|
use App\Support\CourierBills\StatementExporter;
|
||||||
use App\Support\CourierBills\StreamingWorkbook;
|
use App\Support\CourierBills\StreamingWorkbook;
|
||||||
|
use App\Support\CourierBills\Rebooks;
|
||||||
use App\Support\CourierBills\Waybill;
|
use App\Support\CourierBills\Waybill;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@ -80,7 +81,7 @@ final class CourierBillController extends Controller
|
|||||||
})->all();
|
})->all();
|
||||||
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
||||||
|
|
||||||
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [
|
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbConfirmationStates' => app(\App\Support\CourierBills\FreightConfirmation::class)->states($month,(int)(company_id()?:1)), 'cbTotals' => [
|
||||||
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
||||||
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
||||||
]];
|
]];
|
||||||
@ -120,6 +121,8 @@ final class CourierBillController extends Controller
|
|||||||
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
'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 = $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);
|
||||||
|
$items=app(Rebooks::class)->summaryItems((int)$statement->id,$items);
|
||||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
$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();
|
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||||||
$shippingSync = null;
|
$shippingSync = null;
|
||||||
@ -133,9 +136,31 @@ final class CourierBillController extends Controller
|
|||||||
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
||||||
|
|
||||||
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
||||||
|
'cbConfirmation' => app(\App\Support\CourierBills\FreightConfirmation::class)->state($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
|
'cbDisputes' => app(\App\Support\CourierBills\FreightConfirmation::class)->disputes($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
|
'cbConfirmHistory' => app(\App\Support\CourierBills\FreightConfirmation::class)->history($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
||||||
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
|
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
|
||||||
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id)];
|
'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()];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function detailsData(Request $request, string $month): array
|
private function detailsData(Request $request, string $month): array
|
||||||
@ -191,10 +216,28 @@ final class CourierBillController extends Controller
|
|||||||
|
|
||||||
private function uploadData(string $month): array
|
private function uploadData(string $month): array
|
||||||
{
|
{
|
||||||
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
$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')
|
||||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
->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
|
private function ledgerData(Request $request): array
|
||||||
{
|
{
|
||||||
$db = $this->store->db();
|
$db = $this->store->db();
|
||||||
@ -208,6 +251,16 @@ 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')
|
'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']),
|
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||||||
'cbSearch' => $search,
|
'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(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -409,14 +462,17 @@ final class CourierBillController extends Controller
|
|||||||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
'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'],
|
'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'],
|
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||||||
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
|
'rebook_months' => ['nullable', 'in:0,1,2'],
|
||||||
|
], [], ['name' => '分组名称', 'express_names' => '快递名称1', 'rebook_months' => '补记账']);
|
||||||
|
$data['rebook_months'] ??= null;
|
||||||
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
$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();
|
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||||||
if ($exists) {
|
if ($exists) {
|
||||||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||||||
}
|
}
|
||||||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||||||
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
$id = $this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||||||
|
$this->refreshOpenStatements($id);
|
||||||
|
|
||||||
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
||||||
}
|
}
|
||||||
@ -437,6 +493,49 @@ final class CourierBillController extends Controller
|
|||||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
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)
|
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')
|
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Controllers\Business;
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
use App\Support\CourierBills\CourierBillStore;
|
use App\Support\CourierBills\CourierBillStore;
|
||||||
|
use App\Support\CourierBills\CourierJointUploads;
|
||||||
use App\Support\CourierBills\CourierUploadLink;
|
use App\Support\CourierBills\CourierUploadLink;
|
||||||
use App\Support\CourierBills\FreightBillTemplate;
|
use App\Support\CourierBills\FreightBillTemplate;
|
||||||
use App\Support\CourierBills\PortalFreightBillImports;
|
use App\Support\CourierBills\PortalFreightBillImports;
|
||||||
@ -30,17 +31,20 @@ final class CourierUploadShare extends Controller
|
|||||||
{
|
{
|
||||||
$t = $this->target($request, $token);
|
$t = $this->target($request, $token);
|
||||||
$expires = $this->expiresAt($request);
|
$expires = $this->expiresAt($request);
|
||||||
$files = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month'])
|
$query = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']);
|
||||||
->orderByDesc('id')->limit(20)->get();
|
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();
|
||||||
$pending = array_map(static fn (array $file): object => (object) [
|
$pending = array_map(static fn (array $file): object => (object) [
|
||||||
'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'],
|
'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'],
|
||||||
'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'],
|
'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']));
|
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'], $t['joint']['key'] ?? null));
|
||||||
$files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values();
|
$files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values();
|
||||||
|
|
||||||
return response()->view('business.pages.courier-payables.courier-bills.upload-share', [
|
return response()->view('business.pages.courier-payables.courier-bills.upload-share', [
|
||||||
'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files,
|
'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files,
|
||||||
'expiresAt' => $expires, 'confirmed' => $t['confirmed'],
|
'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),
|
'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),
|
'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',
|
])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive',
|
||||||
@ -51,7 +55,7 @@ final class CourierUploadShare extends Controller
|
|||||||
{
|
{
|
||||||
$t = $this->target($request, $token);
|
$t = $this->target($request, $token);
|
||||||
|
|
||||||
return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx');
|
return $this->template->download(($t['joint']['label'] ?? $t['group']->name) . '_' . $t['month'] . '_账单上传模板.xlsx');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function upload(Request $request, string $token): RedirectResponse
|
public function upload(Request $request, string $token): RedirectResponse
|
||||||
@ -71,13 +75,14 @@ final class CourierUploadShare extends Controller
|
|||||||
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
|
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
|
||||||
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
|
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
|
||||||
'source' => 'courier_upload_link',
|
'source' => 'courier_upload_link',
|
||||||
|
'joint' => $t['payload']['joint'],
|
||||||
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
|
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
|
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{companyId:int,group:object,month:string,confirmed:bool} */
|
/** @return array{companyId:int,group:object,month:string,confirmed:bool,joint:?array,payload:array} */
|
||||||
private function target(Request $request, string $token): array
|
private function target(Request $request, string $token): array
|
||||||
{
|
{
|
||||||
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
|
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
|
||||||
@ -85,10 +90,15 @@ final class CourierUploadShare extends Controller
|
|||||||
abort_if($payload === null, 404, '链接无效或已过期。');
|
abort_if($payload === null, 404, '链接无效或已过期。');
|
||||||
$group = collect($this->store->groups())->firstWhere('id', $payload['group_id']);
|
$group = collect($this->store->groups())->firstWhere('id', $payload['group_id']);
|
||||||
abort_if($group === null, 404, '链接无效或已过期。');
|
abort_if($group === null, 404, '链接无效或已过期。');
|
||||||
$confirmed = $this->store->db()->table('courier_bill_statements')->where('group_id', $group->id)
|
$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])
|
||||||
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
|
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
|
||||||
|
|
||||||
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed];
|
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed, 'joint' => $joint, 'payload' => $payload];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function expiresAt(Request $request): CarbonImmutable
|
private function expiresAt(Request $request): CarbonImmutable
|
||||||
|
|||||||
@ -95,6 +95,17 @@ final class DropshipFreightController extends Controller
|
|||||||
$result = $this->reconciler->factoryMonth($factory, $month);
|
$result = $this->reconciler->factoryMonth($factory, $month);
|
||||||
$status = (string) $request->query('status', '');
|
$status = (string) $request->query('status', '');
|
||||||
$rows = $result['rows'];
|
$rows = $result['rows'];
|
||||||
|
$state = $this->confirmations->state($month, (int) $factory->id, self::companyId());
|
||||||
|
$disputes = $this->confirmations->disputes($month, (int) $factory->id, self::companyId());
|
||||||
|
$currentDisputes = array_values(array_filter($disputes, fn ($d) => (int) $d['version'] === (int) ($state['version'] ?? 0)));
|
||||||
|
$disputeMap = array_column($currentDisputes, null, 'waybill');
|
||||||
|
if ($status === 'disputed') {
|
||||||
|
$rows = array_values(array_filter($rows, fn ($r) => isset($disputeMap[$r['waybill']])));
|
||||||
|
}
|
||||||
|
$search = mb_substr(trim((string) $request->query('q', '')), 0, 64);
|
||||||
|
if ($search !== '') {
|
||||||
|
$rows = array_values(array_filter($rows, fn ($r) => str_contains(strtoupper($r['waybill']), strtoupper($search))));
|
||||||
|
}
|
||||||
if ($status === 'attention') {
|
if ($status === 'attention') {
|
||||||
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
|
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
|
||||||
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
|
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
|
||||||
@ -106,9 +117,15 @@ final class DropshipFreightController extends Controller
|
|||||||
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
|
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
|
||||||
|
|
||||||
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
|
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
|
||||||
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()),
|
'dfState' => $state, 'dfDisputes' => $disputes, 'dfCurrentDisputes' => $currentDisputes, 'dfDisputeMap' => $disputeMap,
|
||||||
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()),
|
'dfSearch' => $search, 'dfFactoryStates' => $this->confirmations->states($month,self::companyId()), 'dfHistory' => $this->confirmations->history($month, (int)$factory->id, self::companyId()),
|
||||||
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)];
|
'dfFeesDetail' => app(DropshipFees::class)->rows($month, [(int)$factory->id => $result['summary']['settle']], self::companyId())[(int)$factory->id],
|
||||||
|
'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()];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function uploadData(string $month): array
|
private function uploadData(string $month): array
|
||||||
@ -238,13 +255,19 @@ final class DropshipFreightController extends Controller
|
|||||||
$f = $this->factory($factory);
|
$f = $this->factory($factory);
|
||||||
$result = $this->reconciler->factoryMonth($f, $month);
|
$result = $this->reconciler->factoryMonth($f, $month);
|
||||||
$summary = $result['summary'];
|
$summary = $result['summary'];
|
||||||
|
$feeDetail = app(DropshipFees::class)->rows($month, [(int)$f->id => $summary['settle']], self::companyId())[(int)$f->id];
|
||||||
|
$summary['total'] = $feeDetail['total'];
|
||||||
|
$fees = [];
|
||||||
|
foreach (DropshipFees::COLUMNS as $key => $label) {
|
||||||
|
$fees[] = ['label' => $label, 'amount' => $key === 'booking' ? -abs($feeDetail['values'][$key]) : $feeDetail['values'][$key]];
|
||||||
|
}
|
||||||
$attention = self::attention($result['rows']);
|
$attention = self::attention($result['rows']);
|
||||||
$notifier = app(SupplierDingTalkNotifier::class);
|
$notifier = app(SupplierDingTalkNotifier::class);
|
||||||
if (! $notifier->configuration((string) $f->name)['configured']) {
|
if (! $notifier->configuration((string) $f->name)['configured']) {
|
||||||
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
|
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
|
||||||
}
|
}
|
||||||
$companyId = self::companyId();
|
$companyId = self::companyId();
|
||||||
$version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user()));
|
$version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user(), $result['rows'], $fees));
|
||||||
$url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version);
|
$url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version);
|
||||||
try {
|
try {
|
||||||
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
|
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
|
||||||
|
|||||||
@ -2,180 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers\Business;
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
use App\Support\CourierBills\Category;
|
final class DropshipFreightShare extends FreightConfirmationShare
|
||||||
use App\Support\CourierBills\StreamingWorkbook;
|
|
||||||
use App\Support\DropshipFreight\DropshipConfirmation;
|
|
||||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
|
||||||
use App\Support\DropshipFreight\DropshipReconciler;
|
|
||||||
use App\Support\DropshipFreight\DropshipShareLink;
|
|
||||||
use Carbon\CarbonImmutable;
|
|
||||||
use Illuminate\Http\RedirectResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Routing\Controller;
|
|
||||||
use Illuminate\Validation\ValidationException;
|
|
||||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
|
||||||
use RuntimeException;
|
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
||||||
use Throwable;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 钉钉群推送的代发运费确认页(免登录,同供应商对账的货款确认页):
|
|
||||||
* 厂家看本账期每一单的结算结果,没有异议点「确认无异议」,对某一单有异议就勾选那一单写原因提交。
|
|
||||||
*/
|
|
||||||
final class DropshipFreightShare extends Controller
|
|
||||||
{
|
{
|
||||||
/** 确认页上逐单列出的「要看的单」最多这么多行,其余可下载 Excel 后在文本框里填。 */
|
protected string $kind = 'dropship';
|
||||||
private const MAX_ROWS = 500;
|
}
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
private readonly DropshipFreightStore $store,
|
|
||||||
private readonly DropshipReconciler $reconciler,
|
|
||||||
private readonly DropshipConfirmation $confirmations,
|
|
||||||
private readonly DropshipShareLink $links,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function show(Request $request, string $token): Response
|
|
||||||
{
|
|
||||||
$t = $this->target($request, $token);
|
|
||||||
$current = (int) ($t['state']['version'] ?? 0) === $t['version'];
|
|
||||||
$rows = $t['rows'];
|
|
||||||
$attention = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] !== Category::MATCH));
|
|
||||||
$expires = $this->expiresAt($request);
|
|
||||||
$submitted = in_array($t['state']['status'] ?? '', [DropshipConfirmation::CONFIRMED, DropshipConfirmation::DISPUTED], true);
|
|
||||||
|
|
||||||
return response()->view('business.pages.courier-payables.dropship-freight.share', [
|
|
||||||
'factory' => $t['factory']->name, 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']),
|
|
||||||
'version' => $t['version'], 'current' => $current, 'state' => $t['state'], 'submitted' => $current && $submitted,
|
|
||||||
'summary' => $t['summary'], 'attention' => array_slice($attention, 0, self::MAX_ROWS), 'attentionTotal' => count($attention),
|
|
||||||
'matchCount' => count($rows) - count($attention), 'maxRows' => self::MAX_ROWS,
|
|
||||||
'disputes' => $current ? $this->confirmations->disputes($t['month'], (int) $t['factory']->id, $t['companyId'], $t['version']) : [],
|
|
||||||
'expiresAt' => $expires,
|
|
||||||
'submitUrl' => $this->links->signedRoute('signed.dropship-freight.submit', $token, $t['companyId'], $expires),
|
|
||||||
'excelUrl' => $this->links->signedRoute('signed.dropship-freight.excel', $token, $t['companyId'], $expires),
|
|
||||||
])->withHeaders([
|
|
||||||
'Cache-Control' => 'private, no-store, max-age=0',
|
|
||||||
'X-Robots-Tag' => 'noindex, nofollow, noarchive',
|
|
||||||
'Referrer-Policy' => 'no-referrer',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function submit(Request $request, string $token): RedirectResponse
|
|
||||||
{
|
|
||||||
$t = $this->target($request, $token);
|
|
||||||
$data = $request->validate([
|
|
||||||
'd' => ['nullable', 'array', 'max:' . self::MAX_ROWS], 'd.*' => ['string', 'max:64'],
|
|
||||||
'r' => ['nullable', 'array'], 'r.*' => ['nullable', 'string', 'max:200'],
|
|
||||||
'other' => ['nullable', 'string', 'max:20000'],
|
|
||||||
]);
|
|
||||||
$billed = array_flip(array_map(static fn (array $r): string => strtoupper((string) $r['waybill']), $t['rows']));
|
|
||||||
$byUpper = [];
|
|
||||||
foreach ($t['rows'] as $r) {
|
|
||||||
$byUpper[strtoupper((string) $r['waybill'])] = (string) $r['waybill'];
|
|
||||||
}
|
|
||||||
$disputes = [];
|
|
||||||
foreach ((array) ($data['d'] ?? []) as $waybill) {
|
|
||||||
$reason = trim((string) (($data['r'] ?? [])[$waybill] ?? ''));
|
|
||||||
if ($reason === '') {
|
|
||||||
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 勾选了有异议,请写上原因。']);
|
|
||||||
}
|
|
||||||
$disputes[$waybill] = $reason;
|
|
||||||
}
|
|
||||||
foreach (preg_split('/\R/u', (string) ($data['other'] ?? '')) ?: [] as $line) {
|
|
||||||
$line = trim($line);
|
|
||||||
if ($line === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$parts = preg_split('/[\s,,::\t]+/u', $line, 2) ?: [];
|
|
||||||
$waybill = trim((string) ($parts[0] ?? ''), " \t@");
|
|
||||||
$reason = trim((string) ($parts[1] ?? ''));
|
|
||||||
if ($reason === '') {
|
|
||||||
throw ValidationException::withMessages(['dispute' => '「' . $line . '」:请按「单号 原因」填写,单号后面写上原因。']);
|
|
||||||
}
|
|
||||||
$disputes[$waybill] = mb_substr($reason, 0, 200);
|
|
||||||
}
|
|
||||||
$normalized = [];
|
|
||||||
foreach ($disputes as $waybill => $reason) {
|
|
||||||
$key = strtoupper(trim((string) $waybill));
|
|
||||||
if (! isset($billed[$key])) {
|
|
||||||
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 不在本账期你们开的运费账单里,请核对单号。']);
|
|
||||||
}
|
|
||||||
$normalized[$byUpper[$key]] = $reason;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$state = $this->confirmations->submit($t['month'], (int) $t['factory']->id, $t['version'], $normalized, $t['companyId']);
|
|
||||||
} catch (RuntimeException $error) {
|
|
||||||
throw ValidationException::withMessages(['dispute' => $error->getMessage()]);
|
|
||||||
}
|
|
||||||
$message = $normalized === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($normalized) . ' 单异议,财务核实后会在群里回复。';
|
|
||||||
try {
|
|
||||||
if (app(SupplierDingTalkNotifier::class)->sendDropshipFreightReceipt((string) $t['factory']->name, $t['month'],
|
|
||||||
(float) ($state['settle'] ?? $t['summary']['settle']), $normalized)) {
|
|
||||||
$message .= '回执已发到钉钉群。';
|
|
||||||
}
|
|
||||||
} catch (Throwable $error) {
|
|
||||||
report($error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return redirect()->to($this->links->signedRoute('signed.dropship-freight.show', $token, $t['companyId'], $this->expiresAt($request)))
|
|
||||||
->with('success', $message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 厂家版对账单:汇总 + 明细(每单的厂家运费、应结运费、状态和说明),不含内部核算公式。 */
|
|
||||||
public function excel(Request $request, string $token): StreamedResponse
|
|
||||||
{
|
|
||||||
$t = $this->target($request, $token);
|
|
||||||
$s = $t['summary'];
|
|
||||||
$name = str_replace(['/', '\\'], '-', (string) $t['factory']->name) . '_' . $t['month'] . '_代发运费对账单.xlsx';
|
|
||||||
|
|
||||||
return response()->streamDownload(function () use ($t, $s): void {
|
|
||||||
$book = new StreamingWorkbook();
|
|
||||||
$book->row('汇总', ['厂家', '账期', '厂家开运费单数', '厂家运费', '应结运费', '差额(厂家−应结)'], true);
|
|
||||||
$book->row('汇总', [$t['factory']->name, self::monthLabel($t['month']), $s['billed'], $s['bill'], $s['settle'], $s['diff']]);
|
|
||||||
$book->row('汇总', []);
|
|
||||||
$book->row('汇总', ['分类', '单数'], true);
|
|
||||||
foreach (DropshipReconciler::LABELS as $key => $label) {
|
|
||||||
if ($key !== Category::UNPROVIDED && ($s['counts'][$key] ?? 0) > 0) {
|
|
||||||
$book->row('汇总', [$label, $s['counts'][$key]]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$book->row('明细', ['快递单号', '发货时间', '快递名称', '厂家运费', '应结运费', '差额(厂家−应结)', '状态', '说明'], true);
|
|
||||||
foreach ($t['rows'] as $r) {
|
|
||||||
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'] ?? $r['settle'] ?? 0,
|
|
||||||
round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle'] ?? 0), 2), $r['label'], $r['note']]);
|
|
||||||
}
|
|
||||||
$book->writeTo(fopen('php://output', 'wb'));
|
|
||||||
}, $name);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array{companyId:int,factory:object,month:string,version:int,state:array,rows:list<array>,summary:array} */
|
|
||||||
private function target(Request $request, string $token): array
|
|
||||||
{
|
|
||||||
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
|
|
||||||
$payload = $this->links->resolveToken($token, $companyId);
|
|
||||||
abort_if($payload === null, 404, '链接无效或已过期。');
|
|
||||||
$factory = collect($this->store->factories())->firstWhere('id', $payload['factory_id']);
|
|
||||||
abort_if($factory === null, 404, '链接无效或已过期。');
|
|
||||||
$result = $this->reconciler->factoryMonth($factory, $payload['month']);
|
|
||||||
// 厂家看的是他们开了运费的单;厂家没开的单(厂家未提供)本来就不付,不放在确认页
|
|
||||||
$rows = array_values(array_filter($result['rows'], static fn (array $r): bool => $r['bill'] !== null));
|
|
||||||
|
|
||||||
return ['companyId' => $companyId, 'factory' => $factory, 'month' => $payload['month'], 'version' => $payload['version'],
|
|
||||||
'state' => $this->confirmations->state($payload['month'], (int) $factory->id, $companyId) ?? [],
|
|
||||||
'rows' => $rows, 'summary' => $result['summary']];
|
|
||||||
}
|
|
||||||
|
|
||||||
private function expiresAt(Request $request): CarbonImmutable
|
|
||||||
{
|
|
||||||
$expires = (int) $request->query('expires', 0);
|
|
||||||
|
|
||||||
return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(DropshipShareLink::TTL_DAYS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function monthLabel(string $month): string
|
|
||||||
{
|
|
||||||
[$y, $m] = explode('-', $month);
|
|
||||||
|
|
||||||
return (int) $y . '年' . (int) $m . '月';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
160
app/Http/Controllers/Business/FreightConfirmationController.php
Normal file
160
app/Http/Controllers/Business/FreightConfirmationController.php
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\{Category, CourierBillStore, CourierFreightLink, FreightConfirmation, Rebooks, SurchargeSettlementMatcher};
|
||||||
|
use App\Support\DropshipFreight\{DropshipConfirmation, DropshipFreightStore, DropshipReconciler};
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Routing\Controller;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
final class FreightConfirmationController extends Controller
|
||||||
|
{
|
||||||
|
public static function courierData(int $id): array
|
||||||
|
{
|
||||||
|
$db = app(CourierBillStore::class)->db();
|
||||||
|
$statement = $db->table('courier_bill_statements')->find($id);
|
||||||
|
abort_if(!$statement, 404);
|
||||||
|
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||||||
|
$party = (object) ['id' => $id, 'name' => $group->name];
|
||||||
|
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get();
|
||||||
|
$items = app(SurchargeSettlementMatcher::class)->summaryItems($id, $items);
|
||||||
|
$items = app(Rebooks::class)->summaryItems($id, $items);
|
||||||
|
$sum = $db->table('courier_bill_lines')->where('statement_id', $id)->selectRaw('COUNT(*) as n, SUM(bill_amount) as bill, SUM(self_amount) as settle')->first();
|
||||||
|
$summary = ['billed' => (int) $sum->n, 'bill' => round((float) $sum->bill, 2), 'settle' => round((float) $sum->settle, 2), 'diff' => round((float) $sum->bill - (float) $sum->settle, 2), 'total' => round($items->sum(fn ($r) => (float) $r->self_amount), 2)];
|
||||||
|
$fees = $items->map(fn ($r) => ['label' => $r->label, 'amount' => (float) $r->self_amount])->all();
|
||||||
|
return compact('statement', 'party', 'summary', 'fees');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function push(Request $request, int $statement)
|
||||||
|
{
|
||||||
|
$t = self::courierData($statement);
|
||||||
|
$company = (int) (company_id() ?: 1);
|
||||||
|
if ($t['statement']->status !== 'confirmed') {
|
||||||
|
throw ValidationException::withMessages(['confirmation' => '请先完成核对并确认结算,再推送本组账单。']);
|
||||||
|
}
|
||||||
|
$notifier = app(SupplierDingTalkNotifier::class);
|
||||||
|
if (!$notifier->configuration($t['party']->name)['configured']) {
|
||||||
|
throw ValidationException::withMessages(['confirmation' => '请先为这个对账分组配置钉钉群机器人。']);
|
||||||
|
}
|
||||||
|
$c = app(FreightConfirmation::class);
|
||||||
|
$month = $t['statement']->bill_month;
|
||||||
|
$db = app(CourierBillStore::class)->db();
|
||||||
|
$attention = $db->table('courier_bill_lines')->where('statement_id', $statement)->where('category', '<>', Category::MATCH)->count();
|
||||||
|
try {
|
||||||
|
if (!$c->state($month, $statement, $company)) {
|
||||||
|
$c->check($month, $t['party'], $t['summary'], true, $company, user()?->id, self::by());
|
||||||
|
}
|
||||||
|
$rows = (function () use ($db, $statement) {
|
||||||
|
foreach ($db->table('courier_bill_lines')->where('statement_id', $statement)->orderBy('id')->lazyById(500) as $r) {
|
||||||
|
yield ['waybill' => $r->waybill_no, 'ship_time' => $r->ship_time, 'express' => $r->express_name, 'bill' => $r->bill_amount === null ? null : (float) $r->bill_amount, 'final' => $r->self_amount === null ? null : (float) $r->self_amount, 'status' => $r->category, 'label' => Category::label($r->category, $r->category_month), 'note' => Category::RESOLUTIONS[$r->resolution ?? ''] ?? Category::label($r->category, $r->category_month)];
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
$version = $db->transaction(function () use ($db, $statement, $c, $month, $t, $attention, $company, $rows) {
|
||||||
|
// Prevent an unconfirm/rematch from changing the source while this version is copied.
|
||||||
|
$locked = $db->table('courier_bill_statements')->lockForUpdate()->find($statement);
|
||||||
|
if (!$locked || $locked->status !== 'confirmed' || $locked->updated_at !== $t['statement']->updated_at) {
|
||||||
|
throw new RuntimeException('对账单已发生变化,请刷新后再推送。');
|
||||||
|
}
|
||||||
|
return $c->startPush($month, $t['party'], $t['summary'], $attention, $company, user()?->id, self::by(), $rows, $t['fees']);
|
||||||
|
});
|
||||||
|
} catch (RuntimeException $e) {
|
||||||
|
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$url = app(CourierFreightLink::class)->pageUrl($company, $statement, $month, $version);
|
||||||
|
$notifier->pushFreightConfirmation($t['party']->name, $month, $t['summary'], $version, $url);
|
||||||
|
$c->markPushed($month, $statement, $company);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
$c->markFailed($month, $statement, $company, '群推送失败,请检查机器人后重试。');
|
||||||
|
report($e);
|
||||||
|
throw ValidationException::withMessages(['confirmation' => '群推送失败,账单已保留,可重新推送。']);
|
||||||
|
}
|
||||||
|
return back()->with('courier_bills_message', '已推送到「' . $t['party']->name . '」钉钉群,版本 V' . $version . '。');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function review(Request $request, int $owner)
|
||||||
|
{
|
||||||
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'version' => ['required', 'integer', 'min:1'], 'waybill' => ['required', 'string', 'max:64'], 'decision' => ['required', 'in:accept,reject'], 'reply' => ['required', 'string', 'max:1000']]);
|
||||||
|
$kind = $request->route('kind');
|
||||||
|
$company = (int) (company_id() ?: 1);
|
||||||
|
[$c, $party] = $this->context($kind, $owner, $data['month']);
|
||||||
|
// Refresh only this owner's existing calculation. No source price or ledger changes are made by feedback.
|
||||||
|
if ($kind === 'dropship') {
|
||||||
|
$row = collect(app(DropshipReconciler::class)->factoryMonth($party, $data['month'])['rows'])->firstWhere('waybill', $data['waybill']);
|
||||||
|
$amount = $row['final'] ?? null;
|
||||||
|
} else {
|
||||||
|
$row = app(CourierBillStore::class)->db()->table('courier_bill_lines')->where('statement_id', $owner)->where('waybill_no', $data['waybill'])->selectRaw('SUM(self_amount) as amount')->first();
|
||||||
|
$amount = $row?->amount === null ? null : (float) $row->amount;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$review = $c->review($data['month'], $owner, (int) $data['version'], $data['waybill'], $data['decision'], $data['reply'], $amount, $company, user()?->id, self::by());
|
||||||
|
} catch (RuntimeException $e) {
|
||||||
|
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
|
||||||
|
}
|
||||||
|
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], (int) $data['version'], $company, $review);
|
||||||
|
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '已保存财务处理结果;金额有变化时请重新推送新版账单。');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function retry(Request $request, int $owner)
|
||||||
|
{
|
||||||
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'waybill' => ['nullable', 'string', 'max:64']]);
|
||||||
|
$kind = $request->route('kind');
|
||||||
|
$company = (int) (company_id() ?: 1);
|
||||||
|
[$c, $party] = $this->context($kind, $owner, $data['month']);
|
||||||
|
$state = $c->state($data['month'], $owner, $company);
|
||||||
|
abort_if(!$state, 404);
|
||||||
|
$version = (int) $state['version'];
|
||||||
|
if (!empty($data['waybill'])) {
|
||||||
|
$review = collect($c->disputes($data['month'], $owner, $company, $version))->firstWhere('waybill', $data['waybill']);
|
||||||
|
abort_if(!$review || !isset($review['decision']) || ($review['receipt_status'] ?? '') === 'sent', 422);
|
||||||
|
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], $version, $company, $review);
|
||||||
|
} else {
|
||||||
|
abort_if(($state['receipt_status'] ?? '') !== 'failed', 422);
|
||||||
|
$disputes = array_column($c->disputes($data['month'], $owner, $company, $version), 'reason', 'waybill');
|
||||||
|
$error = null;
|
||||||
|
try {
|
||||||
|
$n = app(SupplierDingTalkNotifier::class);
|
||||||
|
$sent = $kind === 'dropship' ? $n->sendDropshipFreightReceipt($party->name, $data['month'], (float) $state['settle'], $disputes) : $n->sendFreightConfirmationReceipt($party->name, $data['month'], (float) $state['settle'], $disputes);
|
||||||
|
if (!$sent) {
|
||||||
|
throw new RuntimeException('未配置群机器人');
|
||||||
|
}
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
report($e);
|
||||||
|
$error = '群回执发送失败,请检查机器人后重试。';
|
||||||
|
}
|
||||||
|
$c->markReceipt($data['month'], $owner, $version, $company, $error);
|
||||||
|
}
|
||||||
|
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '回执发送已处理,请查看回执状态。');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function context(string $kind, int $owner, string $month): array
|
||||||
|
{
|
||||||
|
if ($kind === 'dropship') {
|
||||||
|
$party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner);
|
||||||
|
abort_if(!$party, 404);
|
||||||
|
return [app(DropshipConfirmation::class), $party];
|
||||||
|
}
|
||||||
|
$t = self::courierData($owner);
|
||||||
|
abort_if($t['statement']->bill_month !== $month, 404);
|
||||||
|
return [app(FreightConfirmation::class), $t['party']];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sendReview(FreightConfirmation $c, string $name, string $kind, int $owner, string $month, int $version, int $company, array $review): void
|
||||||
|
{
|
||||||
|
$error = null;
|
||||||
|
try {
|
||||||
|
app(SupplierDingTalkNotifier::class)->sendFreightReview($name, $kind, $month, $version, $review);
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
report($e);
|
||||||
|
$error = '群回复发送失败,请重试。';
|
||||||
|
}
|
||||||
|
$c->markReceipt($month, $owner, $version, $company, $error, $review['waybill']);
|
||||||
|
}
|
||||||
|
private static function by(): string
|
||||||
|
{
|
||||||
|
return (string) (user()?->name ?? user()?->email ?? 'system');
|
||||||
|
}
|
||||||
|
}
|
||||||
181
app/Http/Controllers/Business/FreightConfirmationShare.php
Normal file
181
app/Http/Controllers/Business/FreightConfirmationShare.php
Normal file
@ -0,0 +1,181 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\{Category, CourierBillStore, CourierFreightLink, FreightConfirmation, StreamingWorkbook};
|
||||||
|
use App\Support\DropshipFreight\{DropshipConfirmation, DropshipFreightStore, DropshipReconciler, DropshipShareLink};
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Routing\Controller;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
class FreightConfirmationShare extends Controller
|
||||||
|
{
|
||||||
|
protected string $kind = 'courier';
|
||||||
|
protected function confirmations(): FreightConfirmation
|
||||||
|
{
|
||||||
|
return app($this->kind === 'dropship' ? DropshipConfirmation::class : FreightConfirmation::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function links(): DropshipShareLink|CourierFreightLink
|
||||||
|
{
|
||||||
|
return app($this->kind === 'dropship' ? DropshipShareLink::class : CourierFreightLink::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function url(Request $request, string $token, int $company, string $action, array $query = []): string
|
||||||
|
{
|
||||||
|
return $this->links()->signedRoute('signed.' . ($this->kind === 'dropship' ? 'dropship' : 'courier') . '-freight.' . $action, $token, $company, CarbonImmutable::createFromTimestamp((int) $request->query('expires')), $query);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function target(Request $request, string $token): array
|
||||||
|
{
|
||||||
|
$company = (int) (($request->route('company_id') ?: company_id()) ?: 1);
|
||||||
|
$p = $this->links()->resolveToken($token, $company);
|
||||||
|
abort_if(!$p, 404);
|
||||||
|
$owner = $p['factory_id'];
|
||||||
|
$month = $p['month'];
|
||||||
|
$version = $p['version'];
|
||||||
|
if ($this->kind === 'dropship') {
|
||||||
|
$party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner);
|
||||||
|
} else {
|
||||||
|
$db = app(CourierBillStore::class)->db();
|
||||||
|
$statement = $db->table('courier_bill_statements')->where('id', $owner)->where('bill_month', $month)->first();
|
||||||
|
$party = $statement ? $db->table('courier_bill_groups')->find($statement->group_id) : null;
|
||||||
|
}
|
||||||
|
abort_if(!$party, 404);
|
||||||
|
$c = $this->confirmations();
|
||||||
|
$state = $c->state($month, $owner, $company) ?? [];
|
||||||
|
$snapshot = $c->snapshot($month, $owner, $version, $company);
|
||||||
|
$legacy = [];
|
||||||
|
$legacyVersion = !$snapshot;
|
||||||
|
if (!$snapshot && $this->kind === 'dropship') {
|
||||||
|
$result = app(DropshipReconciler::class)->factoryMonth($party, $month);
|
||||||
|
$legacy = array_values(array_filter($result['rows'], fn ($r) => $r['bill'] !== null));
|
||||||
|
$snapshot = ['summary' => $result['summary'], 'fees' => [], 'rows' => count($legacy)];
|
||||||
|
}
|
||||||
|
abort_if(!$snapshot, 404);
|
||||||
|
return compact('company', 'owner', 'month', 'version', 'party', 'state', 'snapshot', 'legacy', 'legacyVersion');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Request $request, string $token)
|
||||||
|
{
|
||||||
|
$t = $this->target($request, $token);
|
||||||
|
$data = $request->validate(['q' => ['nullable', 'string', 'max:64'], 'filter' => ['nullable', 'in:all,attention'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||||
|
$q = trim($data['q'] ?? '');
|
||||||
|
$filter = $data['filter'] ?? 'attention';
|
||||||
|
$page = max(1, (int) ($data['page'] ?? 1));
|
||||||
|
$c = $this->confirmations();
|
||||||
|
if ($t['legacy'] !== []) {
|
||||||
|
$all = array_values(array_filter($t['legacy'], fn ($r) => ($filter === 'all' || $r['status'] !== Category::MATCH) && ($q === '' || str_contains($r['waybill'], $q))));
|
||||||
|
$rows = array_slice($all, ($page - 1) * 50, 50);
|
||||||
|
$total = count($all);
|
||||||
|
} else {
|
||||||
|
$query = $c->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company']);
|
||||||
|
if ($filter !== 'all') {
|
||||||
|
$query->where('values->status', '<>', Category::MATCH);
|
||||||
|
}
|
||||||
|
if ($q !== '') {
|
||||||
|
$query->where('values->waybill', 'like', '%' . addcslashes($q, '%_\\') . '%');
|
||||||
|
}
|
||||||
|
$total = (clone $query)->count();
|
||||||
|
$rows = $query->orderBy('id')->offset(($page - 1) * 50)->limit(50)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
|
||||||
|
}
|
||||||
|
$current = (int) ($t['state']['version'] ?? 0) === $t['version'];
|
||||||
|
$disputes = $c->disputes($t['month'], $t['owner'], $t['company'], $t['version']);
|
||||||
|
return response()->view('business.pages.courier-payables.confirmation.share', $t + ['kind' => $this->kind, 'q' => $q, 'filter' => $filter, 'rows' => $rows, 'total' => $total, 'page' => $page, 'current' => $current, 'submitted' => in_array($t['state']['status'] ?? '', [FreightConfirmation::CONFIRMED, FreightConfirmation::DISPUTED], true), 'disputes' => $disputes, 'summary' => $t['snapshot']['summary'], 'draftKey' => hash('sha256', $token), 'expiresAt' => CarbonImmutable::createFromTimestamp((int) $request->query('expires'))->setTimezone('Asia/Shanghai'), 'submitUrl' => $this->url($request, $token, $t['company'], 'submit'), 'viewUrl' => $this->url($request, $token, $t['company'], 'view'), 'excelUrl' => $this->url($request, $token, $t['company'], 'excel'), 'prevUrl' => $page > 1 ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page - 1]) : null, 'nextUrl' => $page * 50 < $total ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page + 1]) : null])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive', 'Referrer-Policy' => 'no-referrer']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function submit(Request $request, string $token)
|
||||||
|
{
|
||||||
|
$t = $this->target($request, $token);
|
||||||
|
$data = $request->validate(['d' => ['nullable', 'array', 'max:500'], 'd.*' => ['string', 'max:64'], 'r' => ['nullable', 'array', 'max:500'], 'r.*' => ['nullable', 'string', 'max:200'], 'other' => ['nullable', 'string', 'max:20000'], 'draft' => ['nullable', 'json', 'max:200000']]);
|
||||||
|
$disputes = [];
|
||||||
|
if (!empty($data['draft'])) {
|
||||||
|
$draft = json_decode($data['draft'], true);
|
||||||
|
if (!is_array($draft) || count($draft) > 500) throw ValidationException::withMessages(['dispute' => '一次最多提交 500 单异议。']);
|
||||||
|
foreach ($draft as $waybill => $reason) {
|
||||||
|
if (!is_string($reason) || trim($reason) === '' || mb_strlen($reason) > 200 || strlen((string)$waybill) > 64) {
|
||||||
|
throw ValidationException::withMessages(['dispute' => '请检查异议单号及原因,每单原因最多 200 字。']);
|
||||||
|
}
|
||||||
|
$disputes[strtoupper(trim((string)$waybill))] = trim($reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($data['d'] ?? [] as $waybill) {
|
||||||
|
$reason = trim($data['r'][$waybill] ?? '');
|
||||||
|
if ($reason === '') {
|
||||||
|
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 请写上异议原因。']);
|
||||||
|
}
|
||||||
|
$disputes[strtoupper(trim($waybill))] = $reason;
|
||||||
|
}
|
||||||
|
foreach (preg_split('/\R/u', $data['other'] ?? '') as $line) {
|
||||||
|
if (trim($line) === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$parts = preg_split('/[\s,,::]+/u', trim($line), 2);
|
||||||
|
if (count($parts) !== 2) {
|
||||||
|
throw ValidationException::withMessages(['dispute' => '请按「单号 原因」逐行填写。']);
|
||||||
|
}
|
||||||
|
$disputes[strtoupper($parts[0])] = mb_substr(trim($parts[1]), 0, 200);
|
||||||
|
}
|
||||||
|
if ($t['legacy'] !== []) {
|
||||||
|
$allowed = [];
|
||||||
|
foreach ($t['legacy'] as $row) $allowed[strtoupper($row['waybill'])] = $row['waybill'];
|
||||||
|
if (array_diff(array_keys($disputes), array_keys($allowed))) {
|
||||||
|
throw ValidationException::withMessages(['dispute' => '单号不在本期账单中。']);
|
||||||
|
}
|
||||||
|
$normalized = [];
|
||||||
|
foreach ($disputes as $waybill => $reason) $normalized[$allowed[$waybill]] = $reason;
|
||||||
|
$disputes = $normalized;
|
||||||
|
}
|
||||||
|
$c = $this->confirmations();
|
||||||
|
try {
|
||||||
|
$state = $c->submit($t['month'], $t['owner'], $t['version'], $disputes, $t['company']);
|
||||||
|
} catch (RuntimeException $e) {
|
||||||
|
throw ValidationException::withMessages(['dispute' => $e->getMessage()]);
|
||||||
|
}
|
||||||
|
$message = $disputes === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($disputes) . ' 单异议,财务核实后会在群里回复。';
|
||||||
|
$error = null;
|
||||||
|
try {
|
||||||
|
$notifier = app(SupplierDingTalkNotifier::class);
|
||||||
|
$sent = $this->kind === 'dropship' ? $notifier->sendDropshipFreightReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes) : $notifier->sendFreightConfirmationReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes);
|
||||||
|
if (!$sent) {
|
||||||
|
throw new RuntimeException('未配置群机器人');
|
||||||
|
}
|
||||||
|
$message .= '回执已发到钉钉群。';
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
report($e);
|
||||||
|
$error = '群回执发送失败,请财务重发。';
|
||||||
|
$message .= $error;
|
||||||
|
}
|
||||||
|
$c->markReceipt($t['month'], $t['owner'], $t['version'], $t['company'], $error);
|
||||||
|
return redirect()->to($this->url($request, $token, $t['company'], 'show'))->with('success', $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function excel(Request $request, string $token)
|
||||||
|
{
|
||||||
|
$t = $this->target($request, $token);
|
||||||
|
return response()->streamDownload(function () use ($t) {
|
||||||
|
$book = new StreamingWorkbook();
|
||||||
|
$s = $t['snapshot']['summary'];
|
||||||
|
$book->row('汇总', ['合作方', '账期', '账单金额', '应结运费', '差额', '版本'], true);
|
||||||
|
$book->row('汇总', [$t['party']->name, $t['month'], $s['bill'], $s['settle'], $s['diff'], $t['version']]);
|
||||||
|
$book->row('费用', ['项目', '应结金额'], true);
|
||||||
|
foreach ($t['snapshot']['fees'] ?? [] as $fee) {
|
||||||
|
$book->row('费用', [$fee['label'], $fee['amount']]);
|
||||||
|
}
|
||||||
|
$book->row('明细', ['快递单号', '发货时间', '快递名称', '账单运费', '应结运费', '差额', '状态', '说明'], true);
|
||||||
|
$rows = $t['legacy'] ?: $this->confirmations()->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company'])->orderBy('id')->lazyById(500);
|
||||||
|
foreach ($rows as $record) {
|
||||||
|
$r = is_array($record) ? $record : json_decode($record->values, true);
|
||||||
|
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'], round($r['bill'] - (float) $r['final'], 2), $r['label'], $r['note']]);
|
||||||
|
}
|
||||||
|
$book->row('异议处理', ['快递单号', '异议原因', '财务结果', '回复', '复核应结运费'], true);
|
||||||
|
foreach ($this->confirmations()->disputes($t['month'], $t['owner'], $t['company'], $t['version']) as $d) {
|
||||||
|
$book->row('异议处理', [$d['waybill'], $d['reason'], ['accept' => '采纳', 'reject' => '不采纳'][$d['decision'] ?? ''] ?? '待处理', $d['reply'] ?? '', $d['review_amount'] ?? null]);
|
||||||
|
}
|
||||||
|
$book->writeTo(fopen('php://output', 'wb'));
|
||||||
|
}, str_replace(['/', '\\'], '-', $t['party']->name) . '_' . $t['month'] . '_对账确认V' . $t['version'] . '.xlsx', ['Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5038,17 +5038,14 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。
|
* 按表维护的页面数据:终版页签及快递记账明细使用各自的独立数据集。
|
||||||
*
|
*
|
||||||
* @return array<string,mixed>|null
|
* @return array<string,mixed>|null
|
||||||
*/
|
*/
|
||||||
protected function payablesFinalData(array $section, ?array $page): ?array
|
protected function payablesFinalData(array $section, ?array $page): ?array
|
||||||
{
|
{
|
||||||
$sectionSlug = (string) ($section['slug'] ?? '');
|
$sectionSlug = (string) ($section['slug'] ?? '');
|
||||||
if (empty($page) || ! in_array($sectionSlug, [
|
if (empty($page)) {
|
||||||
PayablesFinalRegistry::SECTION_SUPPLIER,
|
|
||||||
PayablesFinalRegistry::SECTION_COURIER,
|
|
||||||
], true)) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -5067,9 +5064,7 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$keyword = trim((string) request('keyword', ''));
|
$keyword = trim((string) request('keyword', ''));
|
||||||
$storeDataset = PayablesFinalActions::DATASET_PREFIX
|
$storeDataset = $registry->storeDataset($sectionSlug, $dataset);
|
||||||
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
|
|
||||||
. $dataset;
|
|
||||||
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
||||||
$requestedMonth = trim((string) request('month', ''));
|
$requestedMonth = trim((string) request('month', ''));
|
||||||
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
||||||
@ -5977,6 +5972,7 @@ class Pages extends Controller
|
|||||||
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
||||||
'shipping-data' => $this->contentForShippingData(),
|
'shipping-data' => $this->contentForShippingData(),
|
||||||
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
||||||
|
'returned-parcels' => app(ReturnedParcelController::class)->page(request()),
|
||||||
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
||||||
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
||||||
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
||||||
@ -6006,6 +6002,7 @@ class Pages extends Controller
|
|||||||
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
||||||
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
||||||
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
|
'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-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
|
||||||
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
||||||
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
||||||
@ -8811,6 +8808,7 @@ class Pages extends Controller
|
|||||||
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
||||||
$pagePaymentAmount = '0.00';
|
$pagePaymentAmount = '0.00';
|
||||||
$filteredPaymentAmount = '0.00';
|
$filteredPaymentAmount = '0.00';
|
||||||
|
$storePaymentSummary = [];
|
||||||
$shopNames = [];
|
$shopNames = [];
|
||||||
$paymentReasons = [];
|
$paymentReasons = [];
|
||||||
$error = null;
|
$error = null;
|
||||||
@ -8855,6 +8853,9 @@ class Pages extends Controller
|
|||||||
);
|
);
|
||||||
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
||||||
$filteredPaymentAmount = (string) ($result['filtered_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) {
|
} catch (Throwable $exception) {
|
||||||
@ -8869,6 +8870,7 @@ class Pages extends Controller
|
|||||||
'smallPaymentSyncStatus' => $syncStatus,
|
'smallPaymentSyncStatus' => $syncStatus,
|
||||||
'smallPaymentPageAmount' => $pagePaymentAmount,
|
'smallPaymentPageAmount' => $pagePaymentAmount,
|
||||||
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
||||||
|
'smallPaymentStoreSummary' => $storePaymentSummary,
|
||||||
'smallPaymentShops' => $shopNames,
|
'smallPaymentShops' => $shopNames,
|
||||||
'smallPaymentReasons' => $paymentReasons,
|
'smallPaymentReasons' => $paymentReasons,
|
||||||
'smallPaymentStatuses' => [
|
'smallPaymentStatuses' => [
|
||||||
|
|||||||
@ -16,8 +16,7 @@ use RuntimeException;
|
|||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「终版」目录的按表数据:界面与基础页面一致,数据独立存放
|
* 终版页签和快递记账明细的导入、导出及编辑,各入口使用独立数据集。
|
||||||
* (数据集键 final:<目录>:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。
|
|
||||||
*/
|
*/
|
||||||
class PayablesFinalActions extends Controller
|
class PayablesFinalActions extends Controller
|
||||||
{
|
{
|
||||||
@ -171,9 +170,7 @@ class PayablesFinalActions extends Controller
|
|||||||
|
|
||||||
private function storeDataset(Request $request): string
|
private function storeDataset(Request $request): string
|
||||||
{
|
{
|
||||||
$section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier';
|
return $this->registry->storeDataset($this->section($request), $this->dataset($request));
|
||||||
|
|
||||||
return self::DATASET_PREFIX . $section . ':' . $this->dataset($request);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private function csvText(mixed $value): string
|
private function csvText(mixed $value): string
|
||||||
|
|||||||
@ -88,14 +88,21 @@ class PlantingReimbursementWorkbench extends Controller
|
|||||||
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
||||||
'digest_secret' => (string) $request->input('digest_secret', ''),
|
'digest_secret' => (string) $request->input('digest_secret', ''),
|
||||||
'clear_digest' => $request->boolean('clear_digest'),
|
'clear_digest' => $request->boolean('clear_digest'),
|
||||||
|
'cancel_notices_enabled' => $request->has('cancel_notices_enabled')
|
||||||
|
? $request->boolean('cancel_notices_enabled')
|
||||||
|
: $robot->cancelNoticesEnabled(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
|
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */
|
/** 按发起人发送取消 / 待复查通知,须已启用逐单通知且放行检查通过。 */
|
||||||
public function notify(Request $request, PageData $page, Robot $robot)
|
public function notify(Request $request, PageData $page, Robot $robot)
|
||||||
{
|
{
|
||||||
|
if (! $robot->cancelNoticesEnabled()) {
|
||||||
|
return $this->back($request)->with('error', '取消 / 待复查工单通知已暂停,测试完成前不会发送。');
|
||||||
|
}
|
||||||
|
|
||||||
$filters = $page->filters();
|
$filters = $page->filters();
|
||||||
try {
|
try {
|
||||||
$result = $page->build($filters);
|
$result = $page->build($filters);
|
||||||
|
|||||||
88
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
88
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Routing\Controller;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer as Sync;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class ReturnedParcelController extends Controller
|
||||||
|
{
|
||||||
|
public const COLUMNS = [
|
||||||
|
'received_at' => '进仓时间', 'after_sales_id' => '售后单号', 'online_after_sales_no' => '线上售后单号',
|
||||||
|
'waybill' => '退回快递单号', 'courier' => '快递公司', 'shop' => '店铺', 'warehouse' => '收货仓库',
|
||||||
|
'order_id' => '内部订单号', 'online_order_no' => '线上订单号', 'sku' => '商品编码', 'style_code' => '款式编码',
|
||||||
|
'product_name' => '商品名称', 'properties' => '颜色规格', 'applied_qty' => '申请数量',
|
||||||
|
'returned_qty' => '实退数量', 'price' => '商品单价', 'item_amount' => '明细金额',
|
||||||
|
'status' => '售后状态', 'type' => '售后类型', 'goods_status' => '货物状态', 'reason' => '问题类型',
|
||||||
|
'remark' => '备注', 'source_id' => '源明细编号',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function page(Request $request): array
|
||||||
|
{
|
||||||
|
$filters = $this->filters($request);
|
||||||
|
$data = ['view' => 'business.pages.courier-payables.returned-parcels', 'filters' => $filters,
|
||||||
|
'columns' => self::COLUMNS, 'rows' => null, 'summary' => null, 'state' => null, 'error' => null];
|
||||||
|
try {
|
||||||
|
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
if (! Schema::connection($db->getName())->hasTable(Sync::TABLE)) {
|
||||||
|
$data['error'] = '退回件明细尚未完成首次同步,请稍后刷新。';
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
$query = $this->query($filters);
|
||||||
|
$data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COUNT(DISTINCT after_sales_id) AS orders_count, COALESCE(SUM(returned_qty),0) AS quantity')->first();
|
||||||
|
$data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_id')->paginate(50)->withQueryString();
|
||||||
|
$data['state'] = $db->table('business_mirror_table_states')->where('dataset_key', Sync::DATASET)->first();
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$data['error'] = '退回件明细暂时无法读取,请稍后重试。';
|
||||||
|
}
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function export(Request $request)
|
||||||
|
{
|
||||||
|
$query = $this->query($this->filters($request));
|
||||||
|
$selected = array_values(array_intersect(explode(',', (string) $request->query('columns', '')), array_keys(self::COLUMNS)));
|
||||||
|
$selected = $selected ?: array_keys(self::COLUMNS);
|
||||||
|
return response()->streamDownload(function () use ($query, $selected): void {
|
||||||
|
$file = fopen('php://output', 'w');
|
||||||
|
fwrite($file, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($file, array_map(fn ($key) => self::COLUMNS[$key], $selected));
|
||||||
|
foreach ($query->orderBy('source_id')->lazyById(1000, 'source_id') as $row) {
|
||||||
|
fputcsv($file, array_map(function ($key) use ($row) {
|
||||||
|
$value = (string) ($row->$key ?? '');
|
||||||
|
if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value;
|
||||||
|
return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value;
|
||||||
|
}, $selected));
|
||||||
|
}
|
||||||
|
fclose($file);
|
||||||
|
}, '退回件明细.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function filters(Request $request): array
|
||||||
|
{
|
||||||
|
return validator($request->query(), [
|
||||||
|
'from' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:2026-10-01'],
|
||||||
|
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
|
||||||
|
'waybill' => ['nullable', 'string', 'max:255'], 'shop' => ['nullable', 'string', 'max:255'],
|
||||||
|
'warehouse' => ['nullable', 'string', 'max:255'], 'sku' => ['nullable', 'string', 'max:255'],
|
||||||
|
])->validate() + ['from' => Sync::START, 'to' => now('Asia/Shanghai')->toDateString(),
|
||||||
|
'waybill' => '', 'shop' => '', 'warehouse' => '', 'sku' => ''];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function query(array $filters)
|
||||||
|
{
|
||||||
|
$query = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(Sync::TABLE)
|
||||||
|
->where('received_at', '>=', $filters['from'] ?: Sync::START);
|
||||||
|
if ($filters['to']) $query->where('received_at', '<', Carbon::parse($filters['to'])->addDay()->toDateString());
|
||||||
|
foreach (['waybill', 'shop', 'warehouse', 'sku'] as $field) {
|
||||||
|
if (filled($filters[$field])) $query->where($field, trim($filters[$field]));
|
||||||
|
}
|
||||||
|
return $query;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -12,10 +12,11 @@ use Modules\EcommerceFinance\Services\SupplierComparisonCsvExporter;
|
|||||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
|
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierStatementWorkbookExporter;
|
||||||
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
@ -26,6 +27,8 @@ use Throwable;
|
|||||||
*/
|
*/
|
||||||
class SupplierReconciliation extends Controller
|
class SupplierReconciliation extends Controller
|
||||||
{
|
{
|
||||||
|
private const RAW_STATEMENT_PER_PAGE = 50;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly SupplierStatementTemplate $template,
|
private readonly SupplierStatementTemplate $template,
|
||||||
private readonly SupplierStatementStore $statements,
|
private readonly SupplierStatementStore $statements,
|
||||||
@ -36,6 +39,8 @@ class SupplierReconciliation extends Controller
|
|||||||
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
||||||
private readonly SupplierPortalAccess $supplierPortalAccess,
|
private readonly SupplierPortalAccess $supplierPortalAccess,
|
||||||
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
||||||
|
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||||
|
private readonly SupplierStatementWorkbookExporter $statementWorkbookExporter,
|
||||||
) {
|
) {
|
||||||
$this->middleware('auth');
|
$this->middleware('auth');
|
||||||
$this->middleware('company.identify');
|
$this->middleware('company.identify');
|
||||||
@ -69,7 +74,8 @@ class SupplierReconciliation extends Controller
|
|||||||
);
|
);
|
||||||
|
|
||||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||||
$receiptNotice = '';
|
$notices = [];
|
||||||
|
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||||
if ($supplierPortalUpload) {
|
if ($supplierPortalUpload) {
|
||||||
try {
|
try {
|
||||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||||
@ -78,14 +84,30 @@ class SupplierReconciliation extends Controller
|
|||||||
$records,
|
$records,
|
||||||
);
|
);
|
||||||
if ($receiptSent) {
|
if ($receiptSent) {
|
||||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||||
}
|
}
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
report($exception);
|
report($exception);
|
||||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
$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[] = '零差异对账确认自动推送失败,对账单已正常保存';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$message .= $receiptNotice !== '' ? $receiptNotice : '。';
|
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
|
||||||
|
|
||||||
return $request->expectsJson()
|
return $request->expectsJson()
|
||||||
? response()->json(['message' => $message, 'rows' => $rows])
|
? response()->json(['message' => $message, 'rows' => $rows])
|
||||||
@ -145,6 +167,66 @@ 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 rawStatementRows(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'page' => ['nullable', 'integer', 'min:1', 'max:100000'],
|
||||||
|
'keyword' => ['nullable', 'string', 'max:100'],
|
||||||
|
'barcode' => ['nullable', 'string', 'max:191'],
|
||||||
|
'purchase_no' => ['nullable', 'string', 'max:191'],
|
||||||
|
]);
|
||||||
|
[$supplier, $companyId] = $this->returnTarget($request);
|
||||||
|
$page = max((int) $request->query('page', 1), 1);
|
||||||
|
$keyword = trim((string) $request->query('keyword', ''));
|
||||||
|
$exactFilters = array_filter([
|
||||||
|
'barcode' => trim((string) $request->query('barcode', '')),
|
||||||
|
'purchaseNo' => trim((string) $request->query('purchase_no', '')),
|
||||||
|
], static fn (string $value): bool => $value !== '');
|
||||||
|
$result = $this->statements->paginateFiltered(
|
||||||
|
$supplier,
|
||||||
|
$companyId,
|
||||||
|
self::RAW_STATEMENT_PER_PAGE,
|
||||||
|
$page,
|
||||||
|
$keyword,
|
||||||
|
$exactFilters,
|
||||||
|
);
|
||||||
|
$total = (int) ($result['total'] ?? 0);
|
||||||
|
$pages = max((int) ceil($total / self::RAW_STATEMENT_PER_PAGE), 1);
|
||||||
|
$page = min($page, $pages);
|
||||||
|
$latestUpload = $this->statements->uploads($supplier, $companyId, 1)[0] ?? null;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'supplier' => $supplier,
|
||||||
|
'rows' => array_values((array) ($result['rows'] ?? [])),
|
||||||
|
'total' => $total,
|
||||||
|
'page' => $page,
|
||||||
|
'pages' => $pages,
|
||||||
|
'per_page' => self::RAW_STATEMENT_PER_PAGE,
|
||||||
|
'upload' => $latestUpload === null ? null : [
|
||||||
|
'uploaded_at' => (string) ($latestUpload['uploaded_at'] ?? ''),
|
||||||
|
'filename' => (string) ($latestUpload['filename'] ?? ''),
|
||||||
|
'rows' => (int) ($latestUpload['rows'] ?? 0),
|
||||||
|
],
|
||||||
|
])->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
public function saveDingTalkRobot(Request $request): RedirectResponse
|
public function saveDingTalkRobot(Request $request): RedirectResponse
|
||||||
{
|
{
|
||||||
$request->validate([
|
$request->validate([
|
||||||
@ -283,7 +365,7 @@ class SupplierReconciliation extends Controller
|
|||||||
}
|
}
|
||||||
$differences = array_values(array_filter(
|
$differences = array_values(array_filter(
|
||||||
$detail['rows'],
|
$detail['rows'],
|
||||||
static fn (array $row): bool => ($row['type'] ?? '') !== SupplierStatementMatcher::TYPE_MATCH,
|
fn (array $row): bool => $this->pageData->requiresSupplierCorrection($row),
|
||||||
));
|
));
|
||||||
|
|
||||||
if ($request->input('scope') === 'row') {
|
if ($request->input('scope') === 'row') {
|
||||||
|
|||||||
@ -13,6 +13,7 @@ use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
|||||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
@ -30,6 +31,7 @@ class SupplierReconciliation extends Controller
|
|||||||
private readonly SupplierReconciliationPageData $pageData,
|
private readonly SupplierReconciliationPageData $pageData,
|
||||||
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
||||||
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
||||||
|
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +76,7 @@ class SupplierReconciliation extends Controller
|
|||||||
user_id() ? (int) user_id() : null,
|
user_id() ? (int) user_id() : null,
|
||||||
);
|
);
|
||||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||||
$receiptNotice = '';
|
$notices = [];
|
||||||
try {
|
try {
|
||||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||||
$supplier,
|
$supplier,
|
||||||
@ -82,13 +84,30 @@ class SupplierReconciliation extends Controller
|
|||||||
$records,
|
$records,
|
||||||
);
|
);
|
||||||
if ($receiptSent) {
|
if ($receiptSent) {
|
||||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||||
}
|
}
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
report($exception);
|
report($exception);
|
||||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||||
}
|
}
|
||||||
$message .= $receiptNotice !== '' ? $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) . '。';
|
||||||
|
|
||||||
return $request->expectsJson()
|
return $request->expectsJson()
|
||||||
? response()->json(['message' => $message, 'rows' => $rows])
|
? response()->json(['message' => $message, 'rows' => $rows])
|
||||||
|
|||||||
@ -169,7 +169,7 @@ final class BillParser
|
|||||||
}
|
}
|
||||||
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||||
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
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'] ?? '')) !== '') {
|
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
||||||
$freight[] = $sheet;
|
$freight[] = $sheet;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
282
app/Support/CourierBills/BillSurchargeQuoteCalculator.php
Normal file
282
app/Support/CourierBills/BillSurchargeQuoteCalculator.php
Normal file
@ -0,0 +1,282 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees;
|
||||||
|
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||||
|
|
||||||
|
/** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */
|
||||||
|
final class BillSurchargeQuoteCalculator
|
||||||
|
{
|
||||||
|
public const BUYER_CONFIRMATIONS = 'courier-surcharge-buyer-confirmations';
|
||||||
|
|
||||||
|
public static function buyerConfirmationKey(int $ruleId, string $month, string $waybill, string $workOrder): string
|
||||||
|
{
|
||||||
|
return implode('|', [$ruleId, $month, strtoupper(trim($waybill)), $workOrder]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 所有附加费均按自然月含账单当月,匹配最近3个月。 */
|
||||||
|
public static function window(string $month): array
|
||||||
|
{
|
||||||
|
$start = Carbon::parse($month . '-01')->startOfMonth();
|
||||||
|
$months = 3;
|
||||||
|
return ['from' => $start->copy()->subMonthsNoOverflow($months - 1)->toDateString(),
|
||||||
|
'until' => $start->copy()->addMonth()->toDateString(), 'months' => $months];
|
||||||
|
}
|
||||||
|
|
||||||
|
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, $allowedCouriers);
|
||||||
|
$freights = $shipping->summaries($waybills, $allowedCouriers);
|
||||||
|
$needsService = $rules->contains(fn ($r) => in_array($r->mode, ['聚工单客服核实', '固定单价'], true)
|
||||||
|
|| ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因'));
|
||||||
|
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
|
||||||
|
$returns = $rules->contains(fn ($r) => $r->mode === '固定单价' && str_contains($r->condition, '已退回'))
|
||||||
|
? $this->receivedReturns($workOrders, $month) : [];
|
||||||
|
$confirmations = $this->buyerConfirmations($rules, $workOrders, $month);
|
||||||
|
$rows = $notes = $metadata = [];
|
||||||
|
$window = self::window($month);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
// 买家原因必须按当前工单核验,缺少依据时不能回退到旧结算金额。
|
||||||
|
if ($rule->mode === '固定单价'
|
||||||
|
|| ($rule->mode === '取发出运费' && trim($rule->condition) === '查件扣单并且买家原因')) $rows[$wb][$type] = [];
|
||||||
|
if ($date < $window['from']) {
|
||||||
|
$notes[$wb][$type] = '发货日期超出匹配范围:' . $window['from'] . ' 至 ' . Carbon::parse($window['until'])->subDay()->toDateString();
|
||||||
|
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] ?? [],
|
||||||
|
$confirmations[$rule->id][$wb] ?? [], $returns);
|
||||||
|
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 $confirmations, array $returns): array|string
|
||||||
|
{
|
||||||
|
if ($rule->mode === '固定单价') return $this->fixedPrice($rule, $type, $orders, $returns);
|
||||||
|
if ($rule->mode === '取发出运费') {
|
||||||
|
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费', '查件扣单并且买家原因'], true)) return '计费条件尚未支持自动核验';
|
||||||
|
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
|
||||||
|
$evidence = '';
|
||||||
|
if (trim($rule->condition) === '查件扣单并且买家原因') {
|
||||||
|
$reason = $this->buyerReason($rule, $orders, $confirmations);
|
||||||
|
if (is_string($reason)) return $reason;
|
||||||
|
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
|
||||||
|
$evidence = $reason['evidence'] . ';';
|
||||||
|
}
|
||||||
|
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
|
||||||
|
$amount = round($freight['calc_freight'], 2);
|
||||||
|
return [['settlement_amount' => $amount, 'evidence' => $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 = 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 buyerReason(object $rule, array $orders, array $confirmations, bool $requireBuyer = true, bool $allowDamage = false): array|string
|
||||||
|
{
|
||||||
|
$reasons = [];
|
||||||
|
foreach ($orders as $order) {
|
||||||
|
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
|
||||||
|
if (($fields['logisticsField'] ?? '') !== $rule->courier
|
||||||
|
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|
||||||
|
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
|
||||||
|
$reasons[] = ['order' => $order, 'order_id' => (string) ($fields['o_id'] ?? ''),
|
||||||
|
'reason' => trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''))];
|
||||||
|
}
|
||||||
|
if ($reasons === []) return '未找到有效的同快递查件工单,无法核实买家原因';
|
||||||
|
// 同票多工单以最新扣单原因核验;其他查件操作不覆盖扣单原因,费用仍按票只计一次。
|
||||||
|
usort($reasons, fn ($a, $b) => [$b['order']->created, $b['order']->source_id] <=> [$a['order']->created, $a['order']->source_id]);
|
||||||
|
$deductions = array_values(array_filter($reasons, fn ($r) => trim(explode('/', $r['reason'], 2)[0]) === '扣单'));
|
||||||
|
$latest = $deductions[0] ?? $reasons[0];
|
||||||
|
[$operation, $cause] = array_map('trim', array_pad(explode('/', $latest['reason'], 2), 2, ''));
|
||||||
|
if ($operation === '' || ($requireBuyer && ($cause === '' || $cause === '买家-'))) return '查件工单原因不完整,无法核实买家原因';
|
||||||
|
$eligible = $operation === '扣单' && (! $requireBuyer || str_starts_with($cause, '买家-')
|
||||||
|
|| ($allowDamage && in_array($cause, ['快递-破损', '破损'], true)));
|
||||||
|
$confirmation = $confirmations[$latest['order']->woNo] ?? [];
|
||||||
|
if (! $eligible && $operation === '扣单' && ($confirmation['buyer_reason_confirmed'] ?? false) === true
|
||||||
|
&& ($confirmation['original_reason'] ?? '') === $latest['reason'] && trim($confirmation['evidence'] ?? '') !== '') {
|
||||||
|
return ['eligible' => true, 'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
|
||||||
|
. ';人工确认买家原因:' . $confirmation['evidence']];
|
||||||
|
}
|
||||||
|
return ['eligible' => $eligible, 'order_id' => $latest['order_id'], 'operation' => $operation,
|
||||||
|
'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
|
||||||
|
. ($eligible ? ($requireBuyer ? ($allowDamage ? ',符合买家原因或破损条件' : ',符合买家原因条件') : ',符合扣单条件')
|
||||||
|
: ($allowDamage ? ',不符合买家原因或破损条件,不计费' : ',不符合扣单且买家原因条件,不计费'))];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function fixedPrice(object $rule, string $type, array $orders, array $returns): array|string
|
||||||
|
{
|
||||||
|
if (! preg_match('/^(\d{1,9}(?:\.\d{1,2})?)\s*元?\s*\/\s*(?:单|票)$/u', trim($rule->standard), $price)) {
|
||||||
|
return '固定单价格式不支持,请填写如30元/单';
|
||||||
|
}
|
||||||
|
$condition = trim($rule->condition);
|
||||||
|
$evidence = '';
|
||||||
|
if (in_array($condition, ['查件扣单', '查件扣单并且买家原因', '查件扣单并且买家原因或破损', '查件扣单并且买家原因已退回', '查件扣单并且买家原因已退回的'], true)) {
|
||||||
|
$reason = $this->buyerReason($rule, $orders, [], $condition !== '查件扣单', $condition === '查件扣单并且买家原因或破损');
|
||||||
|
if (is_string($reason)) return $reason;
|
||||||
|
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
|
||||||
|
$evidence = $reason['evidence'];
|
||||||
|
if (str_contains($condition, '已退回')) {
|
||||||
|
$received = $returns[$reason['order_id']] ?? null;
|
||||||
|
if ($received === null) return '未找到对应订单在匹配范围内的有效退回进仓明细,待核实';
|
||||||
|
$evidence .= ';退回进仓 ' . $received;
|
||||||
|
}
|
||||||
|
} elseif (in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) {
|
||||||
|
$approved = false;
|
||||||
|
foreach ($orders as $order) {
|
||||||
|
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], null, 'fieldId');
|
||||||
|
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;
|
||||||
|
// 改地址固定报价也接受工单中明确的客服通过回复,不把“已联系快递修改”视作通过。
|
||||||
|
$reason = (string) ($fields['SELECT_CASCADEField1413856620250813172526']['value'] ?? '');
|
||||||
|
if ($type === '改地址' && str_starts_with($reason, '改地址')
|
||||||
|
&& (in_array(trim((string) ($fields['SELECT_CASCADEField1413856620250814100750']['value'] ?? '')), ['通过', '已通过'], true)
|
||||||
|
|| in_array(trim((string) ($fields['TEXTField1413856620250902151101']['value'] ?? '')), ['通过', '已通过', '客服回复已通过'], true))) {
|
||||||
|
$approved = true;
|
||||||
|
$evidence = '聚工单 ' . $order->woNo . ' 改地址客服明确回复已通过';
|
||||||
|
}
|
||||||
|
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
|
||||||
|
$values = array_column($line, 'value', 'fieldId');
|
||||||
|
if (SurchargeSettlementMatcher::type((string) ($values[ServiceFees::FEE_TYPE] ?? '')) === $type
|
||||||
|
&& ($values[ServiceFees::FEE_APPROVAL] ?? '') === '通过') {
|
||||||
|
$approved = true;
|
||||||
|
$evidence = '聚工单 ' . $order->woNo . ' 对应费用客服审核通过';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! $approved) return '未找到同快递、同费用类型的客服审核通过明细';
|
||||||
|
} elseif (! in_array($condition, ['', '固定单价', '按单收取', '每单收取'], true)) {
|
||||||
|
return '固定单价的计费条件尚未支持自动核验';
|
||||||
|
}
|
||||||
|
$amount = (float) $price[1];
|
||||||
|
return [['settlement_amount' => $amount, 'evidence' => ($evidence === '' ? '' : $evidence . ';')
|
||||||
|
. '固定单价 ' . number_format($amount, 2, '.', '') . ' 元/单,按票计一次']];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只按本批工单订单ID关联已有售后镜像,使用o_id/as_id索引,不扫描退回件全表。 */
|
||||||
|
private function receivedReturns(array $orders, string $month): array
|
||||||
|
{
|
||||||
|
$ids = [];
|
||||||
|
foreach ($orders as $records) foreach ($records as $order) {
|
||||||
|
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
|
||||||
|
$id = trim((string) ($fields['o_id'] ?? ''));
|
||||||
|
if (ctype_digit($id) && $id !== '0') $ids[$id] = true;
|
||||||
|
}
|
||||||
|
if ($ids === []) return [];
|
||||||
|
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
if (! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_info') || ! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_item')) return [];
|
||||||
|
$result = [];
|
||||||
|
foreach (array_chunk(array_keys($ids), 300) as $chunk) {
|
||||||
|
$rows = $db->table('ops_jst_return_refund_info as h')->join('ops_jst_return_refund_item as i', 'i.as_id', '=', 'h.as_id')
|
||||||
|
->whereIn('h.o_id', $chunk)->where('i.r_qty', '>', 0)
|
||||||
|
->where('i.receive_date', '>=', self::window($month)['from'])->where('i.receive_date', '<', self::window($month)['until'])
|
||||||
|
->select('h.o_id')->selectRaw('MIN(' . $db->getQueryGrammar()->wrap('i.receive_date') . ') AS received_at')->groupBy('h.o_id')->get();
|
||||||
|
foreach ($rows as $row) $result[(string) $row->o_id] = $row->received_at;
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buyerConfirmations(iterable $rules, array $orders, string $month): array
|
||||||
|
{
|
||||||
|
$rows = [];
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
if ($rule->mode !== '取发出运费' || trim($rule->condition) !== '查件扣单并且买家原因') continue;
|
||||||
|
foreach ($orders as $waybill => $records) foreach ($records as $order) {
|
||||||
|
$rows[] = ['id' => self::buyerConfirmationKey((int) $rule->id, $month, $waybill, $order->woNo),
|
||||||
|
'rule_id' => $rule->id, 'waybill' => $waybill, 'work_order' => $order->woNo];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($rows === []) return [];
|
||||||
|
$result = [];
|
||||||
|
foreach (app(SupplierPayableOverrideStore::class)->decorate(self::BUYER_CONFIRMATIONS, $rows, (int) (company_id() ?: 1)) as $row) {
|
||||||
|
if ($row['_overridden']) $result[$row['rule_id']][$row['waybill']][$row['work_order']] = $row;
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
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', '>=', self::window($month)['from'])
|
||||||
|
->where('w.created', '<', self::window($month)['until'])
|
||||||
|
->orderBy('w.Id')->get(['l.waybill', 'w.Id as source_id', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
|
||||||
|
$result = [];
|
||||||
|
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -52,7 +52,12 @@ final class CourierBillMatcher
|
|||||||
}
|
}
|
||||||
$unshipped = $this->unshipped->unshippedSources($waybills);
|
$unshipped = $this->unshipped->unshippedSources($waybills);
|
||||||
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
|
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
|
||||||
$shipping = $this->shipping->summaries($waybills);
|
$shipping = $this->shipping->summaries($waybills, $names);
|
||||||
|
foreach ($shipping as $key => $ship) {
|
||||||
|
if (($ship['data_source'] ?? null) !== '退件取件管理') continue;
|
||||||
|
unset($unshipped[$key]);
|
||||||
|
if (filled($ship['unshipped_source'] ?? null)) $unshipped[$key] = [$ship['unshipped_source']];
|
||||||
|
}
|
||||||
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
|
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
|
||||||
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
|
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
|
||||||
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
||||||
@ -89,7 +94,7 @@ final class CourierBillMatcher
|
|||||||
$unprovided[$row['waybill']] = $row;
|
$unprovided[$row['waybill']] = $row;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided));
|
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided), $names);
|
||||||
|
|
||||||
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
|
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
|
||||||
foreach ($updates as $id => $values) {
|
foreach ($updates as $id => $values) {
|
||||||
@ -254,13 +259,17 @@ final class CourierBillMatcher
|
|||||||
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
$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();
|
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
||||||
$kinds['配件补发扣款'] = 'accessory';
|
$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);
|
$fees = $this->surchargeItems($statementId);
|
||||||
$template = $this->templateFor($statementId);
|
$template = $this->templateFor($statementId);
|
||||||
|
$this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
|
||||||
$sort = 8000;
|
$sort = 8000;
|
||||||
foreach ($fees as $item => $sum) {
|
foreach ($fees as $item => $sum) {
|
||||||
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
||||||
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填
|
$items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
|
||||||
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
|
|
||||||
$kinds[$item] = 'fee';
|
$kinds[$item] = 'fee';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -302,6 +311,34 @@ final class CourierBillMatcher
|
|||||||
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
'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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
||||||
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
||||||
@ -329,6 +366,38 @@ final class CourierBillMatcher
|
|||||||
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
$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;
|
||||||
|
}
|
||||||
|
$totals = Rebooks::totals($plan['rows']);
|
||||||
|
foreach (array_unique(array_column($plan['rows'], 'deduct_month')) as $deductMonth) {
|
||||||
|
$amount = $totals[$deductMonth] ?? 0.0;
|
||||||
|
$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> */
|
/** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */
|
||||||
public function feeLabels(int $statementId): array
|
public function feeLabels(int $statementId): array
|
||||||
{
|
{
|
||||||
@ -380,7 +449,7 @@ final class CourierBillMatcher
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
||||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。
|
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
|
||||||
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
||||||
*
|
*
|
||||||
* @return array<string,float>
|
* @return array<string,float>
|
||||||
@ -395,9 +464,11 @@ final class CourierBillMatcher
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
$result = [];
|
$result = [];
|
||||||
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
|
$files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
|
||||||
foreach ($primaryIds as $fileId => $primaryId) {
|
foreach ($files as $file) {
|
||||||
$primary = (int) $primaryId;
|
$fileId = (int) $file->id;
|
||||||
|
$primary = (int) $file->statement_id;
|
||||||
|
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
|
||||||
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
||||||
if (! (clone $rows)->exists()) {
|
if (! (clone $rows)->exists()) {
|
||||||
continue;
|
continue;
|
||||||
@ -415,11 +486,14 @@ final class CourierBillMatcher
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void {
|
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
|
||||||
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
$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(), array_keys($names));
|
||||||
foreach ($chunk as $row) {
|
foreach ($chunk as $row) {
|
||||||
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
||||||
if (($names[$express] ?? $primary) !== $statementId) {
|
$owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary);
|
||||||
|
if ($owner !== $statementId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;
|
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;
|
||||||
|
|||||||
@ -54,6 +54,10 @@ final class CourierBillStore
|
|||||||
'weight_header' => self::blank($data['weight_header'] ?? null),
|
'weight_header' => self::blank($data['weight_header'] ?? null),
|
||||||
'updated_at' => now(),
|
'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) {
|
if ($id === null) {
|
||||||
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
||||||
}
|
}
|
||||||
@ -362,6 +366,31 @@ final class CourierBillStore
|
|||||||
return $id;
|
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
|
public function assign(int $fileId, int $groupId): void
|
||||||
{
|
{
|
||||||
@ -394,6 +423,7 @@ final class CourierBillStore
|
|||||||
$db->transaction(function () use ($db, $file): void {
|
$db->transaction(function () use ($db, $file): void {
|
||||||
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
||||||
$db->table('courier_bill_surcharges')->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();
|
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
||||||
});
|
});
|
||||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||||
@ -423,7 +453,7 @@ final class CourierBillStore
|
|||||||
* @param list<int> $groupIds
|
* @param list<int> $groupIds
|
||||||
* @param list<object> $groups
|
* @param list<object> $groups
|
||||||
*/
|
*/
|
||||||
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int
|
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false, ?array $joint = null): int
|
||||||
{
|
{
|
||||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||||
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||||
@ -436,7 +466,7 @@ final class CourierBillStore
|
|||||||
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
|
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
|
||||||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
|
'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(),
|
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
||||||
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
|
'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
|
||||||
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
||||||
]);
|
]);
|
||||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||||
@ -456,6 +486,12 @@ final class CourierBillStore
|
|||||||
{
|
{
|
||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
$file = $db->table('courier_bill_files')->find($fileId);
|
$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();
|
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
|
||||||
if ($statement !== null && $statement->status === 'confirmed') {
|
if ($statement !== null && $statement->status === 'confirmed') {
|
||||||
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
||||||
@ -481,7 +517,7 @@ final class CourierBillStore
|
|||||||
$feeCount = 0;
|
$feeCount = 0;
|
||||||
$overlap = null;
|
$overlap = null;
|
||||||
try {
|
try {
|
||||||
$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 {
|
$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 {
|
||||||
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
||||||
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
||||||
}
|
}
|
||||||
@ -562,7 +598,7 @@ final class CourierBillStore
|
|||||||
$db->table('courier_bill_surcharges')->insert($fees);
|
$db->table('courier_bill_surcharges')->insert($fees);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
|
return $portal && $joint === null ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
|
||||||
});
|
});
|
||||||
} catch (Throwable $error) {
|
} catch (Throwable $error) {
|
||||||
if ($reread) {
|
if ($reread) {
|
||||||
@ -593,7 +629,7 @@ final class CourierBillStore
|
|||||||
$notes[] = '没有找到含单号和运费列的工作表';
|
$notes[] = '没有找到含单号和运费列的工作表';
|
||||||
}
|
}
|
||||||
if ($feeCount > 0) {
|
if ($feeCount > 0) {
|
||||||
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
|
$notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
|
||||||
}
|
}
|
||||||
$unread = [];
|
$unread = [];
|
||||||
foreach ($sheets as $sheet) {
|
foreach ($sheets as $sheet) {
|
||||||
@ -641,6 +677,8 @@ final class CourierBillStore
|
|||||||
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
||||||
{
|
{
|
||||||
$db = $this->db();
|
$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());
|
$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));
|
$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 ?? ''));
|
$bundle = trim((string) ($primary->bundle ?? ''));
|
||||||
@ -663,7 +701,8 @@ final class CourierBillStore
|
|||||||
}
|
}
|
||||||
|
|
||||||
$lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']);
|
$lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']);
|
||||||
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all());
|
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all(),
|
||||||
|
array_values(array_unique([...array_keys($own), ...array_keys($byName)])));
|
||||||
$moves = [];
|
$moves = [];
|
||||||
$strangers = [];
|
$strangers = [];
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
@ -721,6 +760,56 @@ final class CourierBillStore
|
|||||||
return implode(';', $parts);
|
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(), array_keys($owners));
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
||||||
* 涉及的对账单有已确认结算的就不动。
|
* 涉及的对账单有已确认结算的就不动。
|
||||||
@ -926,7 +1015,7 @@ final class CourierBillStore
|
|||||||
return $files;
|
return $files;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 确认结算:锁定对账单,结算台账记下这批单号。 */
|
/** 确认结算:锁定对账单,结算台账记下这批单号;这期补记账补的单记进补记账台账(补过的不再补)。 */
|
||||||
public function confirm(int $statementId, string $user): void
|
public function confirm(int $statementId, string $user): void
|
||||||
{
|
{
|
||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
@ -959,6 +1048,9 @@ final class CourierBillStore
|
|||||||
if ($buffer !== []) {
|
if ($buffer !== []) {
|
||||||
$db->table('courier_bill_ledger')->insertOrIgnore($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([
|
$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(),
|
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
@ -970,6 +1062,7 @@ final class CourierBillStore
|
|||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
$db->transaction(function () use ($db, $statementId): void {
|
$db->transaction(function () use ($db, $statementId): void {
|
||||||
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
||||||
|
app(Rebooks::class)->forget($statementId);
|
||||||
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
||||||
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
|
|||||||
50
app/Support/CourierBills/CourierFreightLink.php
Normal file
50
app/Support/CourierBills/CourierFreightLink.php
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use DateTimeInterface;
|
||||||
|
use Illuminate\Support\Facades\Crypt;
|
||||||
|
use Illuminate\Support\Facades\URL;
|
||||||
|
use Throwable;
|
||||||
|
/**
|
||||||
|
* 快递账单确认链接。factory_id 保留共享令牌结构,表示对账单 ID;
|
||||||
|
* 公司、对账单、账期和推送版本均被加密签名约束,不沿用联合上传链接的范围。
|
||||||
|
*/
|
||||||
|
final class CourierFreightLink
|
||||||
|
{
|
||||||
|
public const TTL_DAYS = 30;
|
||||||
|
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
|
||||||
|
{
|
||||||
|
return $this->signedRoute('signed.courier-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null, array $query = []): string
|
||||||
|
{
|
||||||
|
$url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
|
||||||
|
return $query === [] ? $url : $url . '&' . http_build_query($query);
|
||||||
|
}
|
||||||
|
/** @return array{factory_id:int,month:string,version:int}|null */
|
||||||
|
public function resolveToken(string $token, int $companyId): ?array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$padding = (4 - strlen($token) % 4) % 4;
|
||||||
|
$encrypted = base64_decode(strtr($token . str_repeat('=', $padding), '-_', '+/'), true);
|
||||||
|
if ($encrypted === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$payload = json_decode(Crypt::decryptString($encrypted), true, flags: JSON_THROW_ON_ERROR);
|
||||||
|
} catch (Throwable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!is_array($payload) || (int) ($payload['company_id'] ?? 0) !== $companyId || (int) ($payload['factory_id'] ?? 0) <= 0 || preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1 || (int) ($payload['version'] ?? 0) <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ['factory_id' => (int) $payload['factory_id'], 'month' => (string) $payload['month'], 'version' => (int) $payload['version']];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function token(int $companyId, int $factoryId, string $month, int $version): string
|
||||||
|
{
|
||||||
|
$payload = json_encode(['company_id' => $companyId, 'factory_id' => $factoryId, 'month' => $month, 'version' => $version], JSON_THROW_ON_ERROR);
|
||||||
|
return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '=');
|
||||||
|
}
|
||||||
|
}
|
||||||
57
app/Support/CourierBills/CourierJointUploads.php
Normal file
57
app/Support/CourierBills/CourierJointUploads.php
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
<?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,12 +19,21 @@ final class CourierUploadLink
|
|||||||
return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId);
|
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
|
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 URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{group_id:int,month:string}|null */
|
/** @return array{group_id:int,month:string,joint:?array}|null */
|
||||||
public function resolveToken(string $token, int $companyId): ?array
|
public function resolveToken(string $token, int $companyId): ?array
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
@ -42,7 +51,7 @@ final class CourierUploadLink
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']];
|
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month'], 'joint' => $payload['joint'] ?? null];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function token(int $companyId, int $groupId, string $month): string
|
private function token(int $companyId, int $groupId, string $month): string
|
||||||
|
|||||||
@ -112,6 +112,27 @@ final class FreightBillTemplate
|
|||||||
return $result;
|
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} */
|
/** @return array{rows:int,waybills:int,amount:float} */
|
||||||
private function validateBill(?iterable $rows): array
|
private function validateBill(?iterable $rows): array
|
||||||
{
|
{
|
||||||
|
|||||||
289
app/Support/CourierBills/FreightConfirmation.php
Normal file
289
app/Support/CourierBills/FreightConfirmation.php
Normal file
@ -0,0 +1,289 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||||
|
use RuntimeException;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
/**
|
||||||
|
* 快递与代发共用的对方确认流程,财务结算台账仍由原业务负责。
|
||||||
|
*
|
||||||
|
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
|
||||||
|
* 状态、版本快照、逐单异议与处理记录分别存储,每次读写限定公司、合作方和账期。
|
||||||
|
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
|
||||||
|
*/
|
||||||
|
class FreightConfirmation
|
||||||
|
{
|
||||||
|
public const DATASET = 'courier-freight-confirm';
|
||||||
|
public const DISPUTES = 'courier-freight-dispute:';
|
||||||
|
public const OPEN = 'open';
|
||||||
|
public const CHECKED = 'checked';
|
||||||
|
public const SENDING = 'sending';
|
||||||
|
public const PUSHED = 'pushed';
|
||||||
|
public const FAILED = 'failed';
|
||||||
|
public const CONFIRMED = 'confirmed';
|
||||||
|
public const DISPUTED = 'disputed';
|
||||||
|
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待快递确认', self::FAILED => '推送失败', self::CONFIRMED => '快递已确认', self::DISPUTED => '快递有异议'];
|
||||||
|
public function __construct(private readonly SupplierPayableOverrideStore $store)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
public static function key(string $month, int $factoryId): string
|
||||||
|
{
|
||||||
|
return $month . '|' . $factoryId;
|
||||||
|
}
|
||||||
|
public static function label(?array $state): string
|
||||||
|
{
|
||||||
|
return static::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? static::LABELS[self::OPEN];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function state(string $month, int $factoryId, int $companyId): ?array
|
||||||
|
{
|
||||||
|
return $this->store->findRow(static::DATASET, self::key($month, $factoryId), $companyId);
|
||||||
|
}
|
||||||
|
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
|
||||||
|
public function states(string $month, int $companyId): array
|
||||||
|
{
|
||||||
|
$out = [];
|
||||||
|
foreach ($this->query(static::DATASET, $companyId)->where('record_key', 'like', $month . '|%')->get(['values'])->map(fn ($r) => json_decode($r->values, true)) as $row) {
|
||||||
|
if (($row['month'] ?? '') === $month) {
|
||||||
|
$out[(int) ($row['factory_id'] ?? 0)] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $out;
|
||||||
|
}
|
||||||
|
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
|
||||||
|
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
|
||||||
|
{
|
||||||
|
return $this->locked($month, (int) $factory->id, $companyId, fn () => $this->checkLocked($month, $factory, $summary, $checked, $companyId, $userId, $by));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function checkLocked(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
|
||||||
|
{
|
||||||
|
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
|
||||||
|
$status = (string) ($state['status'] ?? self::OPEN);
|
||||||
|
if ($checked && !in_array($status, [self::OPEN, self::CHECKED, self::FAILED], true)) {
|
||||||
|
throw new RuntimeException('账单已经推送,请通过重新推送更新版本。');
|
||||||
|
}
|
||||||
|
if (!$checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
|
||||||
|
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
|
||||||
|
}
|
||||||
|
$values = array_merge($this->base($state, $month, $factory), ['status' => $checked ? $status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status : self::OPEN, 'checked_at' => $checked ? now()->toDateTimeString() : null, 'checked_by' => $checked ? $by : null, 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff']]);
|
||||||
|
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
|
||||||
|
return $values;
|
||||||
|
}
|
||||||
|
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
|
||||||
|
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by, ?iterable $rows = null, array $fees = []): int
|
||||||
|
{
|
||||||
|
return $this->locked($month, (int) $factory->id, $companyId, function () use ($month, $factory, $summary, $attention, $companyId, $userId, $by, $rows, $fees) {
|
||||||
|
$version = $this->beginPush($month, $factory, $summary, $attention, $companyId, $userId, $by);
|
||||||
|
if ($rows !== null) {
|
||||||
|
$dataset = $this->snapshotDataset($month, (int) $factory->id, $version);
|
||||||
|
$batch = [];
|
||||||
|
$count = 0;
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if ($row['bill'] === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$batch['line:' . str_pad((string) ++$count, 10, '0', STR_PAD_LEFT)] = array_intersect_key($row, array_flip(['waybill', 'ship_time', 'express', 'bill', 'final', 'status', 'label', 'note']));
|
||||||
|
if (count($batch) === 500) {
|
||||||
|
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
|
||||||
|
$batch = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
|
||||||
|
$this->store->save($dataset, 'meta', ['summary' => $summary, 'fees' => $fees, 'rows' => $count], $companyId, $userId, 'freight_snapshot');
|
||||||
|
}
|
||||||
|
return $version;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function beginPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
|
||||||
|
{
|
||||||
|
if ((int) ($summary['billed'] ?? 0) === 0) {
|
||||||
|
throw new RuntimeException('本期没有可推送的账单明细。');
|
||||||
|
}
|
||||||
|
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
|
||||||
|
if (($state['status'] ?? self::OPEN) === self::OPEN) {
|
||||||
|
throw new RuntimeException('先点「核对完成」再推送给厂家。');
|
||||||
|
}
|
||||||
|
if (($state['status'] ?? '') === self::SENDING) {
|
||||||
|
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
|
||||||
|
}
|
||||||
|
$version = (int) ($state['version'] ?? 0) + 1;
|
||||||
|
$values = array_merge($this->base($state, $month, $factory), ['status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(), 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'], 'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null, 'receipt_error' => null, 'receipt_status' => null, 'pushed_at' => null]);
|
||||||
|
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
|
||||||
|
return $version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function markPushed(string $month, int $factoryId, int $companyId): void
|
||||||
|
{
|
||||||
|
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
|
||||||
|
{
|
||||||
|
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
|
||||||
|
*
|
||||||
|
* @param array<string,string> $disputes 快递单号 => 原因
|
||||||
|
* @return array<string,mixed> 提交后的状态
|
||||||
|
*/
|
||||||
|
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
|
||||||
|
{
|
||||||
|
return $this->locked($month, $factoryId, $companyId, fn () => $this->submitLocked($month, $factoryId, $version, $disputes, $companyId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function submitLocked(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
|
||||||
|
{
|
||||||
|
$state = $this->state($month, $factoryId, $companyId);
|
||||||
|
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
|
||||||
|
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
|
||||||
|
}
|
||||||
|
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
|
||||||
|
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
|
||||||
|
}
|
||||||
|
if (($state['status'] ?? '') !== self::PUSHED) {
|
||||||
|
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
|
||||||
|
}
|
||||||
|
if (count($disputes) > 500) {
|
||||||
|
throw new RuntimeException('一次最多提交 500 单异议。');
|
||||||
|
}
|
||||||
|
foreach ($disputes as $reason) {
|
||||||
|
if (trim((string) $reason) === '') {
|
||||||
|
throw new RuntimeException('请填写每单异议原因。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($this->snapshot($month, $factoryId, $version, $companyId)) {
|
||||||
|
$query = $this->snapshotQuery($month, $factoryId, $version, $companyId);
|
||||||
|
$field = $query->getGrammar()->wrap('values->waybill');
|
||||||
|
$keys = array_map(fn ($w) => strtoupper((string)$w), array_keys($disputes));
|
||||||
|
$found = $keys === [] ? collect() : $query->whereRaw('UPPER('.$field.') IN ('.implode(',',array_fill(0,count($keys),'?')).')',$keys)
|
||||||
|
->get(['values'])->mapWithKeys(fn ($r) => [strtoupper((string)json_decode($r->values,true)['waybill']) => (string)json_decode($r->values,true)['waybill']]);
|
||||||
|
if ($found->count() !== count($disputes)) {
|
||||||
|
throw new RuntimeException('单号不在本次推送账单中。');
|
||||||
|
}
|
||||||
|
$canonical = [];
|
||||||
|
foreach ($disputes as $waybill => $reason) $canonical[$found[strtoupper((string)$waybill)]] = $reason;
|
||||||
|
$disputes = $canonical;
|
||||||
|
}
|
||||||
|
$now = now()->toDateTimeString();
|
||||||
|
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
|
||||||
|
foreach ($disputes as $waybill => $reason) {
|
||||||
|
$this->store->save(static::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill, ['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now], $companyId, null, 'manufacturer_link');
|
||||||
|
}
|
||||||
|
$this->merge($month, $factoryId, $companyId, ['status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED, 'confirmed_at' => $now, 'disputed_count' => count($disputes)], 'manufacturer_link');
|
||||||
|
});
|
||||||
|
return $this->state($month, $factoryId, $companyId) ?? [];
|
||||||
|
}
|
||||||
|
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
|
||||||
|
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
|
||||||
|
{
|
||||||
|
$q = $this->query(static::DISPUTES . self::key($month, $factoryId), $companyId);
|
||||||
|
if ($version !== null) {
|
||||||
|
$q->where('record_key', 'like', $version . '|%');
|
||||||
|
}
|
||||||
|
$rows = $q->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
|
||||||
|
if ($version !== null) {
|
||||||
|
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
|
||||||
|
}
|
||||||
|
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')] <=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
|
||||||
|
return $rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function base(array $state, string $month, object $factory): array
|
||||||
|
{
|
||||||
|
$keep = array_diff_key($state, array_flip(['_action_key']));
|
||||||
|
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name, 'supplier' => (string) $factory->name, 'month' => $month]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
|
||||||
|
{
|
||||||
|
$state = $this->state($month, $factoryId, $companyId) ?? [];
|
||||||
|
unset($state['_action_key']);
|
||||||
|
$this->store->save(static::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
|
||||||
|
if (($state['version'] ?? 0) > 0) {
|
||||||
|
$this->store->save(static::DATASET . ':history:' . self::key($month, $factoryId), (string) $state['version'], array_merge($state, $values), $companyId, null, $source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function locked(string $month, int $owner, int $company, callable $action): mixed
|
||||||
|
{
|
||||||
|
return $this->store->transaction(function () use ($month, $owner, $company, $action) {
|
||||||
|
$this->query(static::DATASET, $company)->where('record_key', self::key($month, $owner))->lockForUpdate()->first();
|
||||||
|
return $action();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function query(string $dataset, int $company): Builder
|
||||||
|
{
|
||||||
|
return DB::connection(config('database.supplier_payable_maintenance_connection'))->table('supplier_payable_overrides')->where('company_id', $company)->where('dataset', $dataset);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function snapshotDataset(string $month, int $owner, int $version): string
|
||||||
|
{
|
||||||
|
return static::DATASET . ':snapshot:' . self::key($month, $owner) . ':' . $version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function snapshot(string $month, int $owner, int $version, int $company): ?array
|
||||||
|
{
|
||||||
|
return $this->store->findRow($this->snapshotDataset($month, $owner, $version), 'meta', $company);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function snapshotQuery(string $month, int $owner, int $version, int $company): Builder
|
||||||
|
{
|
||||||
|
return $this->query($this->snapshotDataset($month, $owner, $version), $company)->where('record_key', 'like', 'line:%');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function history(string $month, int $owner, int $company): array
|
||||||
|
{
|
||||||
|
return $this->query(static::DATASET . ':history:' . self::key($month, $owner), $company)->orderByDesc('id')->limit(20)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function review(string $month, int $owner, int $version, string $waybill, string $decision, string $reply, ?float $amount, int $company, ?int $user, string $by): array
|
||||||
|
{
|
||||||
|
return $this->locked($month, $owner, $company, function () use ($month, $owner, $version, $waybill, $decision, $reply, $amount, $company, $user, $by) {
|
||||||
|
$state = $this->state($month, $owner, $company);
|
||||||
|
if ((int) ($state['version'] ?? 0) !== $version || ($state['status'] ?? '') !== self::DISPUTED) {
|
||||||
|
throw new RuntimeException('账单版本或状态已变化,请刷新后处理。');
|
||||||
|
}
|
||||||
|
$dataset = static::DISPUTES . self::key($month, $owner);
|
||||||
|
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
|
||||||
|
if (!$row) {
|
||||||
|
throw new RuntimeException('没有这条异议。');
|
||||||
|
}
|
||||||
|
if (isset($row['decision'])) {
|
||||||
|
throw new RuntimeException('这条异议已经处理,请勿重复提交。');
|
||||||
|
}
|
||||||
|
if (!in_array($decision, ['accept', 'reject'], true) || trim($reply) === '') {
|
||||||
|
throw new RuntimeException('请选择处理结果并填写核实依据。');
|
||||||
|
}
|
||||||
|
unset($row['_action_key']);
|
||||||
|
$row += ['decision' => $decision, 'reply' => trim($reply), 'reviewed_at' => now()->toDateTimeString(), 'reviewed_by' => $by, 'review_amount' => $amount, 'receipt_status' => 'pending'];
|
||||||
|
$this->store->save($dataset, $version . '|' . $waybill, $row, $company, $user, 'freight_review');
|
||||||
|
return $row;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function markReceipt(string $month, int $owner, int $version, int $company, ?string $error, ?string $waybill = null): void
|
||||||
|
{
|
||||||
|
$this->locked($month, $owner, $company, function () use ($month, $owner, $version, $company, $error, $waybill) {
|
||||||
|
if ((int) ($this->state($month, $owner, $company)['version'] ?? 0) !== $version) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$values = ['receipt_status' => $error === null ? 'sent' : 'failed', 'receipt_error' => $error === null ? null : mb_substr($error, 0, 200)];
|
||||||
|
if ($waybill === null) {
|
||||||
|
$this->merge($month, $owner, $company, $values, 'freight_receipt');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$dataset = static::DISPUTES . self::key($month, $owner);
|
||||||
|
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
|
||||||
|
if ($row) {
|
||||||
|
unset($row['_action_key']);
|
||||||
|
$this->store->save($dataset, $version . '|' . $waybill, array_merge($row, $values), $company, null, 'freight_receipt');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -32,7 +32,7 @@ final class PortalFreightBillImports
|
|||||||
touch($queue . '/' . $token);
|
touch($queue . '/' . $token);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array
|
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null, ?string $jointKey = null): array
|
||||||
{
|
{
|
||||||
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
|
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
|
||||||
rsort($files);
|
rsort($files);
|
||||||
@ -42,6 +42,7 @@ final class PortalFreightBillImports
|
|||||||
if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue;
|
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 ($targetId !== null && (int) $task['target_id'] !== $targetId) continue;
|
||||||
if ($month !== null && $task['month'] !== $month) continue;
|
if ($month !== null && $task['month'] !== $month) continue;
|
||||||
|
if (($task['joint']['key'] ?? null) !== $jointKey) continue;
|
||||||
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
|
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
|
||||||
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
|
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
|
||||||
'message' => $task['message'], 'at' => $task['created_at']];
|
'message' => $task['message'], 'at' => $task['created_at']];
|
||||||
@ -89,7 +90,8 @@ final class PortalFreightBillImports
|
|||||||
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
|
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
|
||||||
if (($task['source'] ?? null) === 'courier_upload_link') {
|
if (($task['source'] ?? null) === 'courier_upload_link') {
|
||||||
if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。');
|
if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。');
|
||||||
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->where('group_id', $task['target_id'])
|
$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']])
|
||||||
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
|
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
|
||||||
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
|
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
|
||||||
}
|
}
|
||||||
@ -110,7 +112,9 @@ final class PortalFreightBillImports
|
|||||||
} else {
|
} else {
|
||||||
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
|
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
|
||||||
$store = app(CourierBillStore::class);
|
$store = app(CourierBillStore::class);
|
||||||
$id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']);
|
$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']);
|
||||||
$row = $store->db()->table('courier_bill_files')->find($id);
|
$row = $store->db()->table('courier_bill_files')->find($id);
|
||||||
}
|
}
|
||||||
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));
|
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));
|
||||||
|
|||||||
80
app/Support/CourierBills/RebookReturns.php
Normal file
80
app/Support/CourierBills/RebookReturns.php
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
/** 仅用于补记账复核;原始退回和记账记录均保持不变。 */
|
||||||
|
final class RebookReturns
|
||||||
|
{
|
||||||
|
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
|
||||||
|
public function annotate(array $rows): array
|
||||||
|
{
|
||||||
|
$wanted = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
foreach (self::numbers($row) as $number) {
|
||||||
|
$wanted[self::key($number)] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$db = Rebooks::db();
|
||||||
|
$available = $wanted !== [] && Schema::connection($db->getName())->hasTable('courier_returned_parcels');
|
||||||
|
$found = [];
|
||||||
|
if ($available) {
|
||||||
|
// 按主键分批读取窄列,一次遍历,不能对每个工单循环模糊扫全表。
|
||||||
|
foreach ($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
|
||||||
|
->select(['source_id', 'waybill', 'received_at'])->lazyById(1000, 'source_id') as $record) {
|
||||||
|
$key = self::key((string) $record->waybill);
|
||||||
|
if ($key !== null && isset($wanted[$key])) {
|
||||||
|
$found[$key][] = ['waybill' => trim((string) $record->waybill), 'received_at' => (string) $record->received_at];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($rows as &$row) {
|
||||||
|
$exact = $fuzzy = [];
|
||||||
|
foreach (self::numbers($row) as $number) {
|
||||||
|
foreach ($found[self::key($number)] ?? [] as $record) {
|
||||||
|
$fuzzy[] = $record;
|
||||||
|
if ($number === $record['waybill']) {
|
||||||
|
$exact[] = $record;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$matches = $exact ?: $fuzzy;
|
||||||
|
$analysis = trim((string) ($row['analysis'] ?? ''));
|
||||||
|
$historicReturn = str_contains($analysis, '已退回') || str_contains($analysis, '原单退回改0') || str_contains($analysis, '换单退回');
|
||||||
|
$row['_return_status'] = $matches !== [] ? '已退回' : ($historicReturn ? '历史记账已记退回' : ($available ? '未匹配退回记录' : '退回数据未就绪'));
|
||||||
|
$row['_return_method'] = $exact !== [] ? '精确匹配' : ($fuzzy !== [] ? '模糊匹配(格式或T前缀)' : '');
|
||||||
|
$row['_matched_return_no'] = implode('、', array_unique(array_column($matches, 'waybill')));
|
||||||
|
$row['_return_received_at'] = $matches === [] ? '' : max(array_column($matches, 'received_at'));
|
||||||
|
// 只重判此前“未退回”的行,不覆盖未发出、取消记账等已有财务判定。
|
||||||
|
if ($analysis === '未退回' && $matches !== []) {
|
||||||
|
$lossFreight = preg_match('/丢件|双面单|违规件|站点异常/u', (string) ($row['bookkeeping_reason'] ?? '')) === 1;
|
||||||
|
$cost = $row['cost'] ?? null;
|
||||||
|
$freight = $row['settle_freight'] ?? null;
|
||||||
|
if (! $lossFreight || (is_numeric($cost) && is_numeric($freight))) {
|
||||||
|
$row['_return_current'] = $lossFreight ? round((float) $freight + round((float) $cost * .2, 2), 2) : 0.0;
|
||||||
|
$row['_return_analysis'] = $lossFreight ? '记账损耗+运费' : '原单退回改0';
|
||||||
|
} else {
|
||||||
|
$row['_return_status'] = '已退回,成本或结算运费缺失待核对';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($row);
|
||||||
|
|
||||||
|
return $rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return list<string> */
|
||||||
|
private static function numbers(array $row): array
|
||||||
|
{
|
||||||
|
return array_values(array_unique(array_filter(array_map(static fn ($v): string => trim((string) $v),
|
||||||
|
[$row['tracking_no_clean'] ?? '', $row['tracking_no'] ?? '', $row['return_no'] ?? '']), static fn (string $v): bool => self::key($v) !== null)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function key(string $number): ?string
|
||||||
|
{
|
||||||
|
$number = Waybill::normalize(mb_convert_kana($number, 'as'));
|
||||||
|
|
||||||
|
return $number === null ? null : (preg_match('/^T\d{10,30}$/', $number) ? substr($number, 1) : $number);
|
||||||
|
}
|
||||||
|
}
|
||||||
548
app/Support/CourierBills/Rebooks.php
Normal file
548
app/Support/CourierBills/Rebooks.php
Normal file
@ -0,0 +1,548 @@
|
|||||||
|
<?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 = [];
|
||||||
|
$sourceRows = [];
|
||||||
|
foreach ($this->bookkeeping($window) as $row) {
|
||||||
|
$carrier = trim((string) ($row['carrier'] ?? ''));
|
||||||
|
if (! isset($names[$carrier])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$sourceRows[] = $row;
|
||||||
|
}
|
||||||
|
$sourceRows = app(RebookReturns::class)->annotate($sourceRows);
|
||||||
|
foreach ($sourceRows as $row) {
|
||||||
|
$carrier = trim((string) ($row['carrier'] ?? ''));
|
||||||
|
$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, 'sources' => []];
|
||||||
|
$deductions[$key]['sources'][] = $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;
|
||||||
|
$automatic = false;
|
||||||
|
$missingData = false;
|
||||||
|
foreach ($d['sources'] as $source) {
|
||||||
|
$missingData = $missingData || str_contains((string) ($source['_return_status'] ?? ''), '缺失');
|
||||||
|
}
|
||||||
|
if ($current === null) {
|
||||||
|
$current = self::returnedAmount($d['sources']);
|
||||||
|
$automatic = $current !== null;
|
||||||
|
}
|
||||||
|
$done = $refunded[$k] ?? null;
|
||||||
|
[$status, $amount] = match (true) {
|
||||||
|
$done !== null => ['已补(' . $done['month'] . ')', 0.0],
|
||||||
|
$deducted <= 0 => ['没扣', 0.0],
|
||||||
|
$current === null && $missingData => ['资料缺失待核对', 0.0],
|
||||||
|
$current === null => ['无新增退回,不补', 0.0],
|
||||||
|
$current >= $deducted => ['仍应扣,不补', 0.0],
|
||||||
|
default => ['本期补款', round($deducted - $current, 2)],
|
||||||
|
};
|
||||||
|
$d['info']['_rebook_sources'] = $d['sources'];
|
||||||
|
$d['info']['_automatic_current'] = $automatic;
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只重算有退回证据的原未退回行;同单其他行沿用原应扣,缺少任一行金额则整单暂缓。 */
|
||||||
|
private static function returnedAmount(array $sources): ?float
|
||||||
|
{
|
||||||
|
$matched = false;
|
||||||
|
$amount = '0';
|
||||||
|
foreach ($sources as $source) {
|
||||||
|
if (str_contains((string) ($source['_return_status'] ?? ''), '缺失')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$matched = $matched || isset($source['_return_current']);
|
||||||
|
$amount = bcadd($amount, (string) ($source['_return_current'] ?? (($source['settle_bookkeeping'] ?? '') ?: '0')), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $matched ? round((float) $amount, 2) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 页面、导出共用自动补款金额;人工填写的小汇总不覆盖,已确认账单不重算。 */
|
||||||
|
public function summaryItems(int $statementId, iterable $items, ?array $plan = null): \Illuminate\Support\Collection
|
||||||
|
{
|
||||||
|
$items = collect($items);
|
||||||
|
$plan ??= $this->forStatement($statementId);
|
||||||
|
if ($plan['source'] === 'confirmed') return $items;
|
||||||
|
$automaticMonths = [];
|
||||||
|
foreach ($plan['rows'] as $row) {
|
||||||
|
if ($row['info']['_automatic_current'] ?? false) $automaticMonths[$row['deduct_month']] = true;
|
||||||
|
}
|
||||||
|
if ($automaticMonths === []) return $items;
|
||||||
|
$totals = self::totals($plan['rows']);
|
||||||
|
$allocated = [];
|
||||||
|
$affected = [];
|
||||||
|
foreach ($plan['window'] as $month) {
|
||||||
|
$item = $items->first(fn ($item) => SummaryTemplate::normalize($item->label) === self::label($month))
|
||||||
|
?? $items->first(fn ($item) => self::labelCovers($item->label, (int) substr($month, 5, 2)));
|
||||||
|
if ($item === null || $item->manual) continue;
|
||||||
|
$allocated[$item->id] = round(($allocated[$item->id] ?? 0) + ($totals[$month] ?? 0), 2);
|
||||||
|
if (isset($automaticMonths[$month])) $affected[$item->id] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $items->map(function ($item) use ($allocated, $affected) {
|
||||||
|
$copy = clone $item;
|
||||||
|
if (isset($affected[$item->id])) $copy->self_amount = $allocated[$item->id];
|
||||||
|
return $copy;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 各扣款月份本期补款合计(只算要补的)。 @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);
|
||||||
|
$items = self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')->get();
|
||||||
|
foreach ($this->summaryItems($statementId, $items, $plan) as $item) {
|
||||||
|
if ($item->self_amount !== $items->firstWhere('id', $item->id)->self_amount) {
|
||||||
|
self::db()->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
236
app/Support/CourierBills/ReturnPickupLookup.php
Normal file
236
app/Support/CourierBills/ReturnPickupLookup.php
Normal file
@ -0,0 +1,236 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use App\Models\Business\CourierQuoteVersion;
|
||||||
|
use App\Support\CourierRequoteService;
|
||||||
|
use App\Support\ReturnPickupFreightCalculator;
|
||||||
|
use Illuminate\Database\ConnectionInterface;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\QuoteSheet;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\ShippingFreightCalculator;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
/** 逆向账单只读退件镜像;原退货单号和实退单号指向同一票,不能重复计费。 */
|
||||||
|
final class ReturnPickupLookup
|
||||||
|
{
|
||||||
|
public const CARRIERS = [
|
||||||
|
'中通快运' => '中通快运逆向', '中通快运逆向' => '中通快运逆向',
|
||||||
|
'德邦' => '常州德邦逆向', '常州德邦逆向' => '常州德邦逆向',
|
||||||
|
'速寄递' => '申通退货', '申通' => '申通退货', '申通退货' => '申通退货',
|
||||||
|
'好省邮' => '好省邮快递', '好省邮快递' => '好省邮快递',
|
||||||
|
'百世' => '好省邮快递', '顺心捷达' => '好省邮快递', '顺丰' => '好省邮快递',
|
||||||
|
];
|
||||||
|
|
||||||
|
private const HAO_QUOTES = ['百世' => '好省邮百世', '顺心捷达' => '好省邮顺心捷达', '顺丰' => '好省邮顺丰'];
|
||||||
|
private array $versions = [];
|
||||||
|
|
||||||
|
private const MAIN = 'js_ekf_return_pickup_management';
|
||||||
|
private const ITEMS = 'js_ekf_return_pickup_management_item';
|
||||||
|
private const TRUTH = 'js_ekf_return_pickup_truth_express';
|
||||||
|
private const CHUNK = 500;
|
||||||
|
|
||||||
|
public function __construct(private readonly ReturnPickupFreightCalculator $calculator) {}
|
||||||
|
|
||||||
|
public static function supports(array $names): bool
|
||||||
|
{
|
||||||
|
return array_intersect($names, array_values(self::CARRIERS)) !== [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function connection(): ConnectionInterface
|
||||||
|
{
|
||||||
|
return DB::connection('business_mirror');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function assertReady(): void
|
||||||
|
{
|
||||||
|
$schema = Schema::connection('business_mirror');
|
||||||
|
foreach ([self::MAIN, self::ITEMS, self::TRUTH] as $table) {
|
||||||
|
if (! $schema->hasTable($table)) {
|
||||||
|
throw new RuntimeException('退件取件镜像未就绪,未更新逆向账单。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! $schema->hasTable('business_mirror_table_states') || $this->connection()->table('business_mirror_table_states')
|
||||||
|
->whereIn('target_table', [self::MAIN, self::ITEMS, self::TRUTH])->whereNotNull('initial_completed_at')->count() !== 3) {
|
||||||
|
throw new RuntimeException('退件取件镜像首次同步未完成,未更新逆向账单。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,array<string,mixed>> 大写单号 => 与发货明细相同的导出字段 */
|
||||||
|
public function details(array $waybills, array $names): array
|
||||||
|
{
|
||||||
|
if ($waybills === [] || ! self::supports($names)) return [];
|
||||||
|
$this->assertReady();
|
||||||
|
$db = $this->connection();
|
||||||
|
$result = [];
|
||||||
|
foreach (array_chunk(array_values(array_unique(array_map([self::class, 'number'], $waybills))), self::CHUNK) as $chunk) {
|
||||||
|
$links = [];
|
||||||
|
$direct = $db->table(self::MAIN)->whereIn('returnExpressNo', $chunk)->get();
|
||||||
|
foreach ($direct as $main) $links[self::number($main->returnExpressNo)][(int) $main->Id] = true;
|
||||||
|
foreach ($db->table(self::TRUTH)->whereIn('truthExpressNumber', $chunk)->get(['mId', 'truthExpressNumber']) as $link) {
|
||||||
|
$links[self::number($link->truthExpressNumber)][(int) $link->mId] = true;
|
||||||
|
}
|
||||||
|
$ids = [];
|
||||||
|
foreach ($links as $set) $ids += $set;
|
||||||
|
if ($ids === []) continue;
|
||||||
|
$mains = $db->table(self::MAIN)->whereIn('Id', array_keys($ids))->get()->keyBy('Id');
|
||||||
|
$items = $db->table(self::ITEMS)->whereIn('mainTableId', array_keys($ids))->orderBy('id')->get()->groupBy('mainTableId');
|
||||||
|
$truth = $db->table(self::TRUTH)->whereIn('mId', array_keys($ids))->get(['mId', 'truthExpressNumber'])->groupBy('mId');
|
||||||
|
foreach ($links as $number => $set) {
|
||||||
|
$number = (string) $number;
|
||||||
|
$candidates = $mains->only(array_keys($set))->filter(fn ($m) => isset(self::CARRIERS[trim((string) $m->express_company)]));
|
||||||
|
if ($candidates->isEmpty()) continue;
|
||||||
|
$main = $candidates->first();
|
||||||
|
$actual = array_values(array_unique(array_filter(array_map([self::class, 'number'], ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all()))));
|
||||||
|
$row = $this->row($main, ($items[$main->Id] ?? collect())->all(), $number);
|
||||||
|
if ($candidates->count() !== 1 || count($actual) > 1) {
|
||||||
|
$row = $this->uncalculated($row, '同号多张取件单或一单多个实退单号,需核实包裹归属');
|
||||||
|
} elseif ($actual !== [] && ! in_array($number, $actual, true)) {
|
||||||
|
$row = $this->uncalculated($row, '退件已换单:' . implode('、', $actual));
|
||||||
|
$row['_unshipped'] = $row['qc_status'];
|
||||||
|
}
|
||||||
|
$result[$number] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅实际取件月份内的有效单号;分批读取,不加载整张退件表。 */
|
||||||
|
public function monthWaybills(array $names, string $month): \Generator
|
||||||
|
{
|
||||||
|
if (! self::supports($names)) return;
|
||||||
|
$this->assertReady();
|
||||||
|
$sources = array_keys(array_filter(self::CARRIERS, fn ($name) => in_array($name, $names, true)));
|
||||||
|
$query = $this->connection()->table(self::MAIN)->whereIn('express_company', $sources)
|
||||||
|
->where('expressPickupTime', '>=', $month . '-01')
|
||||||
|
->where('expressPickupTime', '<', date('Y-m-d', strtotime($month . '-01 +1 month')))
|
||||||
|
->whereNotIn('orderStatus', ['ExpCanceled', 'TicketTimeoutClose'])->orderBy('Id');
|
||||||
|
$lastId = 0;
|
||||||
|
do {
|
||||||
|
$mains = (clone $query)->where('Id', '>', $lastId)->limit(self::CHUNK)->get();
|
||||||
|
if ($mains->isEmpty()) break;
|
||||||
|
$truth = $this->connection()->table(self::TRUTH)->whereIn('mId', $mains->pluck('Id'))->get(['mId', 'truthExpressNumber'])->groupBy('mId');
|
||||||
|
foreach ($mains as $main) {
|
||||||
|
$actual = ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all();
|
||||||
|
$numbers = array_values(array_unique(array_filter(array_map([self::class, 'number'], $actual))));
|
||||||
|
if ($numbers === []) $numbers = array_filter([self::number($main->returnExpressNo)]);
|
||||||
|
foreach ($numbers as $number) yield ['waybill' => $number, 'ship_time' => (string) $main->expressPickupTime,
|
||||||
|
'express_name' => self::CARRIERS[$main->express_company]];
|
||||||
|
}
|
||||||
|
$lastId = (int) $mains->last()->Id;
|
||||||
|
} while ($mains->count() === self::CHUNK);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function row(object $main, array $items, string $number): array
|
||||||
|
{
|
||||||
|
$carrier = self::CARRIERS[trim((string) $main->express_company)];
|
||||||
|
$package = $items === [] ? null : clone $items[0];
|
||||||
|
if ($package !== null) {
|
||||||
|
$package->grossWeight = $package->packageVolume = 0.0;
|
||||||
|
$package->length = $package->width = $package->height = 0.0;
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$quantity = max(0, (float) ($item->returnQuantity ?? 0));
|
||||||
|
$package->grossWeight += (float) $item->grossWeight * $quantity;
|
||||||
|
$package->packageVolume += (float) $item->length * (float) $item->width * (float) $item->height * $quantity;
|
||||||
|
foreach (['length', 'width', 'height'] as $dimension) $package->$dimension = max($package->$dimension, (float) $item->$dimension);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$row = ['express_no' => $number, 'express_name1' => $carrier, 'ship_time' => $main->expressPickupTime,
|
||||||
|
'trade_no' => $main->transactionNo ?? null, 'shop_name' => $main->shopName ?? null,
|
||||||
|
'origin_state' => $main->province, 'origin_city' => $main->city ?? null,
|
||||||
|
'data_source' => '退件取件管理', 'qc_freight' => 0.0, 'qc_charge_weight' => 0.0,
|
||||||
|
'qc_settle_weight' => 0.0, 'qc_miandan' => 0.0, 'qc_extra_fee' => 0.0, 'qty' => 0.0,
|
||||||
|
'weight_kg' => 0.0, 'qc_status' => 'OK', 'qc_quote_version' => '逆向物流报价/' . $carrier];
|
||||||
|
$formulas = $products = $barcodes = [];
|
||||||
|
$reason = $items === [] ? '退件缺少商品重量尺寸明细' : null;
|
||||||
|
$rate = $package === null ? null : $this->calculate($main, $package, $carrier);
|
||||||
|
if ($rate !== null) {
|
||||||
|
if (! $rate['covered']) $reason = $rate['reason'];
|
||||||
|
$row['qc_freight'] += (float) $rate['total'];
|
||||||
|
$row['qc_charge_weight'] += (float) $rate['billable'];
|
||||||
|
$row['qc_settle_weight'] += (float) $rate['settlement'];
|
||||||
|
$row['qc_miandan'] += (float) $rate['base_amount'];
|
||||||
|
$row['qc_extra_fee'] += (float) $rate['surcharge'];
|
||||||
|
$row['qc_rate'] = $rate['increment_amount'];
|
||||||
|
if (isset($rate['quote_version'])) $row['qc_quote_version'] = $rate['quote_version'];
|
||||||
|
$formulas[] = '整票商品重量/体积合计,面单只计一次;' . ($rate['process'] ?? $rate['reason']);
|
||||||
|
}
|
||||||
|
$destinations = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$quantity = max(0, (float) ($item->returnQuantity ?? 0));
|
||||||
|
if ($quantity <= 0 || ((float) $item->grossWeight <= 0 && (float) $item->length * (float) $item->width * (float) $item->height <= 0)) {
|
||||||
|
$reason = '退件商品缺少有效数量或重量';
|
||||||
|
}
|
||||||
|
$row['qty'] += $quantity;
|
||||||
|
$row['weight_kg'] += (float) $item->grossWeight * $quantity;
|
||||||
|
$destinations[trim((string) $item->receiverAddress)] = true;
|
||||||
|
$row['receiver_address'] ??= $item->receiverAddress;
|
||||||
|
$row['receiver_state'] ??= ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress);
|
||||||
|
$row['receiver_name'] ??= $item->receiverName ?? null;
|
||||||
|
$row['warehouse_name'] ??= $item->warehouse ?? null;
|
||||||
|
foreach (['length_cm' => 'length', 'width_cm' => 'width', 'height_cm' => 'height'] as $field => $source) {
|
||||||
|
$row[$field] = max((float) ($row[$field] ?? 0), (float) $item->$source);
|
||||||
|
}
|
||||||
|
$products[] = $item->productName ?? '';
|
||||||
|
$barcodes[] = $item->barcode ?? '';
|
||||||
|
}
|
||||||
|
$row['volume_cm3'] = $package?->packageVolume;
|
||||||
|
if (count($destinations) > 1) $reason = '同一运单存在不同收件地址,需核实';
|
||||||
|
$row['qc_freight'] = round($row['qc_freight'], 2);
|
||||||
|
$row['product_name'] = implode(',', array_unique(array_filter($products)));
|
||||||
|
$row['barcode'] = implode(',', array_unique(array_filter($barcodes)));
|
||||||
|
$row['qc_formula'] = implode(';', array_filter($formulas));
|
||||||
|
if (in_array($main->orderStatus, ['ExpCanceled', 'TicketTimeoutClose'], true) || empty($main->expressPickupTime)) {
|
||||||
|
$row['_unshipped'] = '退件已取消、关闭或尚无实际取件时间';
|
||||||
|
$reason = $row['_unshipped'];
|
||||||
|
}
|
||||||
|
return $reason === null ? $row : $this->uncalculated($row, $reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function calculate(object $main, object $item, string $carrier): array
|
||||||
|
{
|
||||||
|
if ($carrier !== '好省邮快递') {
|
||||||
|
return $this->calculator->calculate($carrier, $main->province, $item->receiverAddress,
|
||||||
|
(float) $item->grossWeight, $item->length, $item->width, $item->height,
|
||||||
|
$main->expressPickupTime ? substr($main->expressPickupTime, 0, 10) : null, $item->packageVolume);
|
||||||
|
}
|
||||||
|
$name = self::HAO_QUOTES[trim((string) $main->express_company)] ?? null;
|
||||||
|
$empty = ['covered' => false, 'total' => null, 'billable' => null, 'settlement' => null,
|
||||||
|
'base_amount' => null, 'surcharge' => null, 'increment_amount' => null, 'process' => null];
|
||||||
|
if ($name === null || empty($main->expressPickupTime)) return $empty + ['reason' => '好省邮缺少实际承运快递或取件日期'];
|
||||||
|
$versions = $this->versions[$name] ??= CourierQuoteVersion::query()->with(['signature', 'change'])->where('company_name', $name)->get();
|
||||||
|
$version = CourierRequoteService::resolveAt($versions, Carbon::parse($main->expressPickupTime));
|
||||||
|
if ($version === null) return $empty + ['reason' => '取件日期没有生效的' . $name . '报价'];
|
||||||
|
$values = json_decode((string) $version->values_json, true) ?: [];
|
||||||
|
$destination = ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress);
|
||||||
|
$city = null;
|
||||||
|
if (preg_match('/^(?:.+?省|.+?自治区)(.+?(?:市|自治州|地区|盟))/u', (string) $item->receiverAddress, $m)) $city = $m[1];
|
||||||
|
elseif (in_array($destination, ['北京', '上海', '天津', '重庆'], true)) $city = $destination;
|
||||||
|
$cfg = FreightCarrierRules::for($name) + ['_name' => $name];
|
||||||
|
$result = app(ShippingFreightCalculator::class)->calculate([
|
||||||
|
'express_name1' => $name, 'sender_state' => $main->province, 'sender_city' => $main->city ?? null,
|
||||||
|
'receiver_state' => $destination, 'receiver_city' => $city, 'weight_kg' => (float) $item->grossWeight,
|
||||||
|
'volume_cm3' => $item->packageVolume,
|
||||||
|
], ['id' => $version->version_code, 'p' => QuoteSheet::parse($values), 'vals' => $values,
|
||||||
|
'rules' => (string) $version->billing_rules], $cfg);
|
||||||
|
return ['covered' => $result['status'] === 'OK', 'reason' => $result['status'], 'total' => $result['fee'],
|
||||||
|
'billable' => $result['charge_w'], 'settlement' => $result['settle_w'],
|
||||||
|
'base_amount' => $result['first_price'] ?? $result['miandan'], 'surcharge' => $result['extra'],
|
||||||
|
'increment_amount' => $result['rate'], 'process' => $result['formula'], 'quote_version' => $version->version_code];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function uncalculated(array $row, string $reason): array
|
||||||
|
{
|
||||||
|
$row['qc_freight'] = $row['qc_charge_weight'] = null;
|
||||||
|
$row['qc_status'] = $reason;
|
||||||
|
return $row;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function number(mixed $value): string
|
||||||
|
{
|
||||||
|
return strtoupper(trim((string) $value));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -34,6 +34,8 @@ final class ShippingLookup
|
|||||||
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
|
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
|
||||||
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
|
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
|
||||||
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
|
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
|
||||||
|
'data_source' => '数据来源',
|
||||||
|
'origin_state' => '始发省', 'origin_city' => '始发市',
|
||||||
];
|
];
|
||||||
|
|
||||||
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
|
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
|
||||||
@ -56,7 +58,7 @@ final class ShippingLookup
|
|||||||
* @param list<string> $waybills
|
* @param list<string> $waybills
|
||||||
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
|
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
|
||||||
*/
|
*/
|
||||||
public function summaries(array $waybills): array
|
public function summaries(array $waybills, array $expressNames = []): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
||||||
@ -100,6 +102,11 @@ final class ShippingLookup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (app(ReturnPickupLookup::class)->details($waybills, $expressNames) as $key => $row) {
|
||||||
|
$result[$key] = ['ship_time' => $row['ship_time'], 'express_name' => $row['express_name1'],
|
||||||
|
'calc_freight' => $row['qc_freight'], 'charge_weight' => $row['qc_charge_weight'],
|
||||||
|
'data_source' => $row['data_source'], 'unshipped_source' => $row['_unshipped'] ?? null];
|
||||||
|
}
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,7 +116,7 @@ final class ShippingLookup
|
|||||||
* @param list<string> $waybills
|
* @param list<string> $waybills
|
||||||
* @return array<string,array<string,mixed>> 键为大写单号
|
* @return array<string,array<string,mixed>> 键为大写单号
|
||||||
*/
|
*/
|
||||||
public function details(array $waybills): array
|
public function details(array $waybills, array $expressNames = []): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
||||||
@ -189,7 +196,7 @@ final class ShippingLookup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $result;
|
return array_replace($result, app(ReturnPickupLookup::class)->details($waybills, $expressNames));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -203,6 +210,9 @@ final class ShippingLookup
|
|||||||
if ($expressNames === []) {
|
if ($expressNames === []) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
yield from app(ReturnPickupLookup::class)->monthWaybills($expressNames, $month);
|
||||||
|
$expressNames = array_values(array_diff($expressNames, array_values(ReturnPickupLookup::CARRIERS)));
|
||||||
|
if ($expressNames === []) return;
|
||||||
// 按天走 ship_time 索引,单次只扫一天的发货行。
|
// 按天走 ship_time 索引,单次只扫一天的发货行。
|
||||||
$day = strtotime($month . '-01');
|
$day = strtotime($month . '-01');
|
||||||
$end = strtotime($month . '-01 +1 month');
|
$end = strtotime($month . '-01 +1 month');
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
namespace App\Support\CourierBills;
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Modules\EcommerceFinance\Services\CourierBookkeepingRegistry;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
||||||
@ -64,6 +65,8 @@ final class StatementExporter
|
|||||||
{
|
{
|
||||||
$db = CourierBillMatcher::db();
|
$db = CourierBillMatcher::db();
|
||||||
$ids = $this->related($statementId);
|
$ids = $this->related($statementId);
|
||||||
|
$expressNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||||
|
->whereIn('s.id', $ids)->pluck('g.express_names')->flatMap(fn ($value) => (array) json_decode((string) $value, true))->unique()->values()->all();
|
||||||
$multi = count($ids) > 1;
|
$multi = count($ids) > 1;
|
||||||
$groupNames = [];
|
$groupNames = [];
|
||||||
$book = new StreamingWorkbook();
|
$book = new StreamingWorkbook();
|
||||||
@ -91,7 +94,8 @@ final class StatementExporter
|
|||||||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||||||
$bill = 0.0;
|
$bill = 0.0;
|
||||||
$self = 0.0;
|
$self = 0.0;
|
||||||
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
|
$items = app(SurchargeSettlementMatcher::class)->summaryItems($id,$db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get());
|
||||||
|
foreach (app(Rebooks::class)->summaryItems($id, $items) as $item) {
|
||||||
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
||||||
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
||||||
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
||||||
@ -119,12 +123,12 @@ final class StatementExporter
|
|||||||
}
|
}
|
||||||
foreach ($sheets as $name => $filter) {
|
foreach ($sheets as $name => $filter) {
|
||||||
$headerWritten = false;
|
$headerWritten = false;
|
||||||
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void {
|
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void {
|
||||||
if (! $headerWritten) {
|
if (! $headerWritten) {
|
||||||
$book->row($name, $fullHeader, true);
|
$book->row($name, $fullHeader, true);
|
||||||
$headerWritten = true;
|
$headerWritten = true;
|
||||||
}
|
}
|
||||||
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines));
|
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines), $expressNames);
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
||||||
$cells = $this->originalCells($line, $sources, $original);
|
$cells = $this->originalCells($line, $sources, $original);
|
||||||
@ -163,22 +167,143 @@ final class StatementExporter
|
|||||||
// 未提供:发货数据有、账单没有
|
// 未提供:发货数据有、账单没有
|
||||||
$headerWritten = false;
|
$headerWritten = false;
|
||||||
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
|
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
|
||||||
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void {
|
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, $expressNames, &$headerWritten): void {
|
||||||
if (! $headerWritten) {
|
if (! $headerWritten) {
|
||||||
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
|
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
|
||||||
$headerWritten = true;
|
$headerWritten = true;
|
||||||
}
|
}
|
||||||
$details = $this->shipping->details($rows->pluck('waybill_no')->all());
|
$details = $this->shipping->details($rows->pluck('waybill_no')->all(), $expressNames);
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
|
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
|
||||||
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
|
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
|
||||||
|
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
|
||||||
$this->writeNotes($book, $ids, $originals);
|
$this->writeNotes($book, $ids, $originals);
|
||||||
$book->writeTo($output);
|
$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
|
||||||
|
{
|
||||||
|
$plans = [];
|
||||||
|
$window = [];
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
try {
|
||||||
|
$plan = app(Rebooks::class)->forStatement($id);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($plan['window'] !== []) {
|
||||||
|
// 全部历史记账都展示,已补、未退回等仅供核对,不重复计入本期金额。
|
||||||
|
$plans[$id] = $plan['rows'];
|
||||||
|
$window = array_values(array_unique([...$window, ...$plan['window']]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($plans === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sort($window);
|
||||||
|
$name = Rebooks::sheetName($window);
|
||||||
|
$fields = ['summary_month' => ['label' => '月份', 'type' => 'text']];
|
||||||
|
foreach (app(CourierBookkeepingRegistry::class)->fields() as $field => $definition) {
|
||||||
|
$fields[$field] = $definition;
|
||||||
|
if ($field === 'settle_bookkeeping') {
|
||||||
|
$fields['current_bookkeeping'] = ['label' => '现结算记账金额', 'type' => 'number'];
|
||||||
|
$fields['rebook_amount'] = ['label' => '需补款记账金额', 'type' => 'number'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (['return_status' => '退回核对状态', 'return_match' => '退回匹配方式', 'matched_return' => '匹配退回单号',
|
||||||
|
'received_at' => '退回进仓时间', 'refund_status' => '补款状态'] as $field => $label) {
|
||||||
|
$fields[$field] = ['label' => $label, 'type' => 'text'];
|
||||||
|
}
|
||||||
|
$fields['refunded'] = ['label' => '历史已补金额', 'type' => 'number'];
|
||||||
|
$fields['payable_refund'] = ['label' => '本期补款金额', 'type' => 'number'];
|
||||||
|
$book->row($name, [...array_column($fields, 'label'), ...$tail], true);
|
||||||
|
$rowNumber = 1;
|
||||||
|
$settleColumn = array_search('settle_bookkeeping', array_keys($fields), true) + 1;
|
||||||
|
$currentColumn = $settleColumn + 1;
|
||||||
|
foreach ($plans as $id => $rows) {
|
||||||
|
foreach ($rows as $r) {
|
||||||
|
$sources = $r['info']['_rebook_sources'] ?? [$r['info']];
|
||||||
|
$remainingCurrent = (float) ($r['current'] ?? $r['deducted']);
|
||||||
|
$remainingRefund = (float) $r['amount'];
|
||||||
|
$last = array_key_last($sources);
|
||||||
|
$automatic = $r['info']['_automatic_current'] ?? false;
|
||||||
|
$weights = [];
|
||||||
|
foreach ($sources as $index => $source) {
|
||||||
|
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
|
||||||
|
$weights[$index] = $automatic ? max(0, round($old - (float) ($source['_return_current'] ?? $old), 2)) : max(0, $old);
|
||||||
|
}
|
||||||
|
$totalWeight = array_sum($weights);
|
||||||
|
$lastRefund = array_key_last(array_filter($weights, static fn ($weight) => $weight > 0));
|
||||||
|
$historyWritten = false;
|
||||||
|
foreach ($sources as $index => $source) {
|
||||||
|
$rowNumber++;
|
||||||
|
$values = $source;
|
||||||
|
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
|
||||||
|
$share = $r['deducted'] > 0 ? $old / $r['deducted'] : 0;
|
||||||
|
$current = $automatic || $r['current'] === null ? (float) ($source['_return_current'] ?? $old)
|
||||||
|
: ($index === $last ? $remainingCurrent : round((float) $r['current'] * $share, 2));
|
||||||
|
$payable = $weights[$index] <= 0 || $totalWeight <= 0 ? 0.0
|
||||||
|
: ($index === $lastRefund ? $remainingRefund : round((float) $r['amount'] * $weights[$index] / $totalWeight, 2));
|
||||||
|
$remainingCurrent = round($remainingCurrent - $current, 2);
|
||||||
|
$remainingRefund = round($remainingRefund - $payable, 2);
|
||||||
|
$values['summary_month'] = $r['deduct_month'];
|
||||||
|
$values['tracking_no'] = $values['tracking_no'] ?? $r['waybill'];
|
||||||
|
$values['tracking_no_clean'] = $r['waybill'];
|
||||||
|
$values['carrier'] = $source['carrier'] ?? $r['carrier'];
|
||||||
|
$values['settle_bookkeeping'] = $old;
|
||||||
|
$values['current_bookkeeping'] = $current;
|
||||||
|
if (isset($source['_return_analysis'])) {
|
||||||
|
$values['analysis'] = $source['_return_analysis'];
|
||||||
|
}
|
||||||
|
$values['rebook_amount'] = new XlsxFormula(
|
||||||
|
self::columnName($settleColumn) . $rowNumber . '-' . self::columnName($currentColumn) . $rowNumber,
|
||||||
|
round($old - $current, 2),
|
||||||
|
);
|
||||||
|
$values['return_status'] = $source['_return_status'] ?? '';
|
||||||
|
$values['return_match'] = $source['_return_method'] ?? '';
|
||||||
|
$values['matched_return'] = $source['_matched_return_no'] ?? '';
|
||||||
|
$values['received_at'] = $source['_return_received_at'] ?? '';
|
||||||
|
$values['refund_status'] = $r['status'];
|
||||||
|
$values['refunded'] = $historyWritten ? null : $r['refunded'];
|
||||||
|
$historyWritten = true;
|
||||||
|
$values['payable_refund'] = $payable;
|
||||||
|
$cells = [];
|
||||||
|
foreach ($fields as $field => $definition) {
|
||||||
|
$value = $values[$field] ?? null;
|
||||||
|
$cells[] = $value instanceof XlsxFormula ? $value : ($definition['type'] === 'number'
|
||||||
|
? ($value === null || $value === '' ? null : (float) $value)
|
||||||
|
: ($value === null || $value === '' ? null : (string) $value));
|
||||||
|
}
|
||||||
|
$book->row($name, [...$cells, ...($multi ? [$groupNames[$id] ?? ''] : [])]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function columnName(int $column): string
|
||||||
|
{
|
||||||
|
$name = '';
|
||||||
|
while ($column > 0) {
|
||||||
|
$column--;
|
||||||
|
$name = chr(65 + $column % 26) . $name;
|
||||||
|
$column = intdiv($column, 26);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $name;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
||||||
*
|
*
|
||||||
|
|||||||
@ -187,6 +187,7 @@ final class SummaryTemplate
|
|||||||
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
|
$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 === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
|
||||||
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
|
$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),
|
$kind === 'fee' => self::feeSlot($key, $find),
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
|
|||||||
237
app/Support/CourierBills/SurchargeSettlementMatcher.php
Normal file
237
app/Support/CourierBills/SurchargeSettlementMatcher.php
Normal file
@ -0,0 +1,237 @@
|
|||||||
|
<?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) ?? '';
|
||||||
|
if (str_contains($type, '拦截费')) return '拦截费';
|
||||||
|
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','已计算');
|
||||||
|
$window=BillSurchargeQuoteCalculator::window($month);$end=$window['until'];
|
||||||
|
if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){
|
||||||
|
$sourceQuery->whereRaw('COALESCE(source_created_at,shipped_at) >= ?',[$window['from']])->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end]);
|
||||||
|
}else{$sourceQuery->where('shipped_at','>=',$window['from'])->where('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;
|
||||||
|
}
|
||||||
|
$calculated=app(BillSurchargeQuoteCalculator::class)->calculate($input,$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']='无法确认该单属于本厂家代发快递及仓库';
|
||||||
|
}
|
||||||
|
$window=BillSurchargeQuoteCalculator::window($month);
|
||||||
|
$rows=array_values(array_filter($rows,function($r)use($allowed,$window){
|
||||||
|
$date=substr((string)($r->source_created_at??$r->shipped_at??''),0,10);
|
||||||
|
$shipped=substr((string)($r->shipped_at??''),0,10);
|
||||||
|
return in_array($r->courier_name,$allowed,true)&&$date!==''&&$date>=$window['from']&&$date<$window['until']
|
||||||
|
&&($shipped===''||($shipped>=$window['from']&&$shipped<$window['until']));
|
||||||
|
}));
|
||||||
|
$priced=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true)));
|
||||||
|
// 已支持的报价按票核价优先,避免同单号多张出库记录把每票费用重复累加。
|
||||||
|
if(array_key_exists($type,$calculated['rows'][$wb]??[]))$rows=$priced;
|
||||||
|
if($rows===[]){
|
||||||
|
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]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,174 +2,12 @@
|
|||||||
|
|
||||||
namespace App\Support\DropshipFreight;
|
namespace App\Support\DropshipFreight;
|
||||||
|
|
||||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
use App\Support\CourierBills\FreightConfirmation;
|
||||||
use RuntimeException;
|
|
||||||
|
|
||||||
/**
|
final class DropshipConfirmation extends FreightConfirmation
|
||||||
* 代发运费对账的「核对完成 → 推送厂家确认 → 厂家确认 / 逐单异议」状态。
|
|
||||||
*
|
|
||||||
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
|
|
||||||
* - 数据集 dropship-freight-confirm,记录键「月份|厂家ID」:这家这个月的状态、推送版本、推送时的金额快照;
|
|
||||||
* - 数据集 dropship-freight-dispute:月份|厂家ID,记录键是快递单号:厂家对这一单的异议原因(带推送版本)。
|
|
||||||
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
|
|
||||||
*/
|
|
||||||
final class DropshipConfirmation
|
|
||||||
{
|
{
|
||||||
public const DATASET = 'dropship-freight-confirm';
|
public const DATASET = 'dropship-freight-confirm';
|
||||||
public const DISPUTES = 'dropship-freight-dispute:';
|
public const DISPUTES = 'dropship-freight-dispute:';
|
||||||
|
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中',
|
||||||
public const OPEN = 'open';
|
self::PUSHED => '已推送,待厂家确认', self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议'];
|
||||||
public const CHECKED = 'checked';
|
|
||||||
public const SENDING = 'sending';
|
|
||||||
public const PUSHED = 'pushed';
|
|
||||||
public const FAILED = 'failed';
|
|
||||||
public const CONFIRMED = 'confirmed';
|
|
||||||
public const DISPUTED = 'disputed';
|
|
||||||
|
|
||||||
public const LABELS = [
|
|
||||||
self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待厂家确认',
|
|
||||||
self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议',
|
|
||||||
];
|
|
||||||
|
|
||||||
public function __construct(private readonly SupplierPayableOverrideStore $store) {}
|
|
||||||
|
|
||||||
public static function key(string $month, int $factoryId): string
|
|
||||||
{
|
|
||||||
return $month . '|' . $factoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function label(?array $state): string
|
|
||||||
{
|
|
||||||
return self::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? self::LABELS[self::OPEN];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function state(string $month, int $factoryId, int $companyId): ?array
|
|
||||||
{
|
|
||||||
return $this->store->findRow(self::DATASET, self::key($month, $factoryId), $companyId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
|
|
||||||
public function states(string $month, int $companyId): array
|
|
||||||
{
|
|
||||||
$out = [];
|
|
||||||
foreach ($this->store->listRows(self::DATASET, $companyId) as $row) {
|
|
||||||
if (($row['month'] ?? '') === $month) {
|
|
||||||
$out[(int) ($row['factory_id'] ?? 0)] = $row;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
|
|
||||||
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
|
|
||||||
{
|
|
||||||
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
|
|
||||||
$status = (string) ($state['status'] ?? self::OPEN);
|
|
||||||
if (! $checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
|
|
||||||
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
|
|
||||||
}
|
|
||||||
$values = array_merge($this->base($state, $month, $factory), [
|
|
||||||
'status' => $checked ? ($status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status) : self::OPEN,
|
|
||||||
'checked_at' => $checked ? now()->toDateTimeString() : null,
|
|
||||||
'checked_by' => $checked ? $by : null,
|
|
||||||
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'],
|
|
||||||
]);
|
|
||||||
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
|
|
||||||
|
|
||||||
return $values;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
|
|
||||||
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
|
|
||||||
{
|
|
||||||
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
|
|
||||||
if (($state['status'] ?? self::OPEN) === self::OPEN) {
|
|
||||||
throw new RuntimeException('先点「核对完成」再推送给厂家。');
|
|
||||||
}
|
|
||||||
if (($state['status'] ?? '') === self::SENDING) {
|
|
||||||
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
|
|
||||||
}
|
|
||||||
$version = (int) ($state['version'] ?? 0) + 1;
|
|
||||||
$values = array_merge($this->base($state, $month, $factory), [
|
|
||||||
'status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(),
|
|
||||||
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'],
|
|
||||||
'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null,
|
|
||||||
]);
|
|
||||||
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
|
|
||||||
|
|
||||||
return $version;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function markPushed(string $month, int $factoryId, int $companyId): void
|
|
||||||
{
|
|
||||||
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
|
|
||||||
{
|
|
||||||
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
|
|
||||||
*
|
|
||||||
* @param array<string,string> $disputes 快递单号 => 原因
|
|
||||||
* @return array<string,mixed> 提交后的状态
|
|
||||||
*/
|
|
||||||
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
|
|
||||||
{
|
|
||||||
$state = $this->state($month, $factoryId, $companyId);
|
|
||||||
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
|
|
||||||
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
|
|
||||||
}
|
|
||||||
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
|
|
||||||
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
|
|
||||||
}
|
|
||||||
if (($state['status'] ?? '') !== self::PUSHED) {
|
|
||||||
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
|
|
||||||
}
|
|
||||||
$now = now()->toDateTimeString();
|
|
||||||
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
|
|
||||||
foreach ($disputes as $waybill => $reason) {
|
|
||||||
$this->store->save(self::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill,
|
|
||||||
['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now],
|
|
||||||
$companyId, null, 'manufacturer_link');
|
|
||||||
}
|
|
||||||
$this->merge($month, $factoryId, $companyId, [
|
|
||||||
'status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED,
|
|
||||||
'confirmed_at' => $now, 'disputed_count' => count($disputes),
|
|
||||||
], 'manufacturer_link');
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this->state($month, $factoryId, $companyId) ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
|
|
||||||
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
|
|
||||||
{
|
|
||||||
$rows = $this->store->listRows(self::DISPUTES . self::key($month, $factoryId), $companyId);
|
|
||||||
if ($version !== null) {
|
|
||||||
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
|
|
||||||
}
|
|
||||||
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')]
|
|
||||||
<=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
|
|
||||||
|
|
||||||
return $rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function base(array $state, string $month, object $factory): array
|
|
||||||
{
|
|
||||||
$keep = array_diff_key($state, array_flip(['_action_key']));
|
|
||||||
|
|
||||||
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name,
|
|
||||||
'supplier' => (string) $factory->name, 'month' => $month]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
|
|
||||||
{
|
|
||||||
$state = $this->state($month, $factoryId, $companyId) ?? [];
|
|
||||||
unset($state['_action_key']);
|
|
||||||
$this->store->save(self::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -138,6 +138,7 @@ final class DropshipExporter
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->writeNotes($book, $rows, $originals);
|
$this->writeNotes($book, $rows, $originals);
|
||||||
|
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
|
||||||
$book->writeTo($output);
|
$book->writeTo($output);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,7 +175,7 @@ final class DropshipExporter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
|
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
|
||||||
// 厂家按模板填的「附加费」表:金额合计放一行(不逐单核对,简尚核对空着手工填)
|
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
|
||||||
$fee = 0.0;
|
$fee = 0.0;
|
||||||
$hasFee = false;
|
$hasFee = false;
|
||||||
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
|
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
|
||||||
@ -213,7 +214,7 @@ final class DropshipExporter
|
|||||||
[$bill, $settle] = match (true) {
|
[$bill, $settle] = match (true) {
|
||||||
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
|
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],
|
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
|
||||||
$label === $feeLabel => [round($fee, 2), null],
|
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int)$factory->id,$month)],
|
||||||
default => [null, null],
|
default => [null, null],
|
||||||
};
|
};
|
||||||
$sums[0] += (float) $bill;
|
$sums[0] += (float) $bill;
|
||||||
@ -232,6 +233,17 @@ final class DropshipExporter
|
|||||||
$bill === null && $settle === null ? '' : round((float) $bill - (float) $settle, 2));
|
$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」;一个文件几张表的加「-原表名」。 */
|
/** 原账单的表名:「厂家账单」;第 2 个文件起「厂家账单2」;一个文件几张表的加「-原表名」。 */
|
||||||
private static function originalName(int $fileIndex, string $sheet, int $sheetCount): string
|
private static function originalName(int $fileIndex, string $sheet, int $sheetCount): string
|
||||||
{
|
{
|
||||||
|
|||||||
@ -112,6 +112,33 @@ final class DropshipFees
|
|||||||
public function auto(string $month): array
|
public function auto(string $month): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$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')
|
$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']);
|
->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']);
|
||||||
foreach ($files as $file) {
|
foreach ($files as $file) {
|
||||||
|
|||||||
@ -6,6 +6,7 @@ use App\Support\CourierBills\BillWorkbookReader;
|
|||||||
use App\Support\CourierBills\CourierBillStore;
|
use App\Support\CourierBills\CourierBillStore;
|
||||||
use App\Support\CourierBills\FreightBillTemplate;
|
use App\Support\CourierBills\FreightBillTemplate;
|
||||||
use App\Support\CourierBills\ShippingLookup;
|
use App\Support\CourierBills\ShippingLookup;
|
||||||
|
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||||
use Illuminate\Database\ConnectionInterface;
|
use Illuminate\Database\ConnectionInterface;
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@ -84,6 +85,21 @@ final class DropshipFreightStore
|
|||||||
return $sheets;
|
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
|
public function db(): ConnectionInterface
|
||||||
{
|
{
|
||||||
return DB::connection('business_mirror');
|
return DB::connection('business_mirror');
|
||||||
@ -258,9 +274,14 @@ final class DropshipFreightStore
|
|||||||
}
|
}
|
||||||
$this->db()->transaction(function () use ($file): void {
|
$this->db()->transaction(function () use ($file): void {
|
||||||
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
$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();
|
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
||||||
});
|
});
|
||||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||||
|
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -409,6 +430,7 @@ final class DropshipFreightStore
|
|||||||
$lines = array_diff_key($lines, array_flip($others));
|
$lines = array_diff_key($lines, array_flip($others));
|
||||||
}
|
}
|
||||||
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
$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();
|
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
||||||
foreach (array_chunk($lines, 500, true) as $chunk) {
|
foreach (array_chunk($lines, 500, true) as $chunk) {
|
||||||
$insert = [];
|
$insert = [];
|
||||||
@ -427,6 +449,7 @@ final class DropshipFreightStore
|
|||||||
'updated_at' => now(),
|
'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
||||||
|
|||||||
@ -20,11 +20,13 @@ final class DropshipShareLink
|
|||||||
return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
|
return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null): string
|
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null, array $query = []): string
|
||||||
{
|
{
|
||||||
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [
|
$url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [
|
||||||
'company_id' => $companyId, 'token' => $token,
|
'company_id' => $companyId, 'token' => $token,
|
||||||
]);
|
]);
|
||||||
|
// The project's signature middleware signs the resource and expiry, not view filters.
|
||||||
|
return $query === [] ? $url : $url . '&' . http_build_query($query);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{factory_id:int,month:string,version:int}|null */
|
/** @return array{factory_id:int,month:string,version:int}|null */
|
||||||
|
|||||||
@ -53,6 +53,8 @@ class ReturnPickupFreightCalculator
|
|||||||
?float $length = null,
|
?float $length = null,
|
||||||
?float $width = null,
|
?float $width = null,
|
||||||
?float $height = null,
|
?float $height = null,
|
||||||
|
?string $pickupDate = null,
|
||||||
|
?float $volumeCm3 = null,
|
||||||
): array {
|
): array {
|
||||||
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
|
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
|
||||||
|
|
||||||
@ -63,8 +65,8 @@ class ReturnPickupFreightCalculator
|
|||||||
$length = max((float) $length, 0);
|
$length = max((float) $length, 0);
|
||||||
$width = max((float) $width, 0);
|
$width = max((float) $width, 0);
|
||||||
$height = max((float) $height, 0);
|
$height = max((float) $height, 0);
|
||||||
$volumeWeight = ($length > 0 && $width > 0 && $height > 0)
|
$volumeWeight = ($volumeCm3 !== null || ($length > 0 && $width > 0 && $height > 0))
|
||||||
? round($length * $width * $height / 6000, 4)
|
? round(max(0, $volumeCm3 ?? ($length * $width * $height)) / 6000, 4)
|
||||||
: 0.0;
|
: 0.0;
|
||||||
$settlement = round(max($grossWeight, $volumeWeight), 4);
|
$settlement = round(max($grossWeight, $volumeWeight), 4);
|
||||||
|
|
||||||
@ -82,6 +84,9 @@ class ReturnPickupFreightCalculator
|
|||||||
}
|
}
|
||||||
|
|
||||||
$rule = $this->rules[$carrier] ?? [];
|
$rule = $this->rules[$carrier] ?? [];
|
||||||
|
if ($pickupDate !== null && ! empty($rule['effective_date']) && $pickupDate < $rule['effective_date']) {
|
||||||
|
return $this->missing('取件日期早于该逆向物流报价执行日期');
|
||||||
|
}
|
||||||
$mode = (string) ($rule['pricing_mode'] ?? '');
|
$mode = (string) ($rule['pricing_mode'] ?? '');
|
||||||
$maxSide = max($length, $width, $height);
|
$maxSide = max($length, $width, $height);
|
||||||
$sideSum = $length + $width + $height;
|
$sideSum = $length + $width + $height;
|
||||||
|
|||||||
@ -127,6 +127,14 @@ class SidebarPermissions
|
|||||||
$allowed[] = 'process-data/invoice-data';
|
$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));
|
return array_values(array_unique($allowed));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -43,6 +43,7 @@ return [
|
|||||||
* existing table, but do not keep querying the upstream source.
|
* existing table, but do not keep querying the upstream source.
|
||||||
*/
|
*/
|
||||||
'datasets' => [
|
'datasets' => [
|
||||||
|
'jiansun.dbo.jst_shipFreight_view' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货数据专线核算运费'],
|
||||||
// Small organization and catalog dimensions stay in MariaDB.
|
// Small organization and catalog dimensions stay in MariaDB.
|
||||||
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
|
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
|
||||||
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],
|
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],
|
||||||
|
|||||||
@ -813,6 +813,7 @@ $navigation = [
|
|||||||
'icon' => 'fact_check',
|
'icon' => 'fact_check',
|
||||||
'pages' => [
|
'pages' => [
|
||||||
['slug' => 'finance-data', 'title' => '财务端数据'],
|
['slug' => 'finance-data', 'title' => '财务端数据'],
|
||||||
|
['slug' => 'raw-statements', 'title' => '原始账单'],
|
||||||
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@ -10,6 +10,9 @@ return [
|
|||||||
| Entries are appended to an existing section in configuration order.
|
| Entries are appended to an existing section in configuration order.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
'courier-payables' => [
|
||||||
|
['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'],
|
||||||
|
],
|
||||||
'module_sections' => [
|
'module_sections' => [
|
||||||
[
|
[
|
||||||
'position_after' => 'inventory-management',
|
'position_after' => 'inventory-management',
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'dataset_key' => 'operations_replica.rpt.ding_invoices',
|
'dataset_key' => 'operations_replica.rpt.ding_invoices',
|
||||||
|
'first_supported_month' => '2026-10',
|
||||||
'document_types' => [
|
'document_types' => [
|
||||||
'公摊日常报销',
|
'公摊日常报销',
|
||||||
'店铺日常报销',
|
'店铺日常报销',
|
||||||
|
|||||||
@ -6,6 +6,37 @@ return [
|
|||||||
'final_version_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_FINAL_VERSION_DAY', 15))),
|
'final_version_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_FINAL_VERSION_DAY', 15))),
|
||||||
'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))),
|
'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))),
|
||||||
|
|
||||||
|
// 这些结算方式不依赖月度对账单,不进入未上传统计,也不发送群催办。
|
||||||
|
'statement_upload_exempt_settlement_methods' => ['订单合同', '现结'],
|
||||||
|
|
||||||
|
// 应付汇总镜像尚未覆盖完整,保留已确认的无需上传厂家作为兜底。
|
||||||
|
'statement_upload_exempt_suppliers' => [
|
||||||
|
'博曼特',
|
||||||
|
'常州安裕',
|
||||||
|
'格林家具',
|
||||||
|
'公牛电器',
|
||||||
|
'河北星沐橡胶制品',
|
||||||
|
'恒菏',
|
||||||
|
'简尚',
|
||||||
|
'兰考华兰家具',
|
||||||
|
'木町工艺品',
|
||||||
|
'青岛弢森',
|
||||||
|
'三环',
|
||||||
|
'三洋木业',
|
||||||
|
'沐野竹木',
|
||||||
|
'沭阳简华家具有限公司',
|
||||||
|
'沭阳勋雅泡沫',
|
||||||
|
'双爱家私',
|
||||||
|
'顺兴木业',
|
||||||
|
'苏州贝格迪派',
|
||||||
|
'腾云',
|
||||||
|
'橡润家',
|
||||||
|
'新奇维木艺',
|
||||||
|
'优创包装',
|
||||||
|
'众隆包装',
|
||||||
|
'帝富尼',
|
||||||
|
],
|
||||||
|
|
||||||
'reminder' => [
|
'reminder' => [
|
||||||
// 1-14 日每天 10:00、16:00 运行,15 日不得再催办。
|
// 1-14 日每天 10:00、16:00 运行,15 日不得再催办。
|
||||||
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
||||||
|
|||||||
@ -342,6 +342,17 @@ return [
|
|||||||
],
|
],
|
||||||
|
|
||||||
'datasets' => [
|
'datasets' => [
|
||||||
|
// 专线页 FreightNew 已按包裹分摊;totalFreight 是组合总额,不能逐包复制。
|
||||||
|
// 视图没有可靠更新时间,按稳定出库键追加,并每小时全量校准历史改价/反审核。
|
||||||
|
'jiansun.dbo.jst_shipFreight_view' => [
|
||||||
|
'source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'jst_shipFreight_view',
|
||||||
|
'target' => 'js_jst_ship_freight', 'keys' => ['Id'],
|
||||||
|
'full_reconcile_hours' => 1,
|
||||||
|
'minimum_datetime' => ['column' => 'Shiptime', 'value' => '2026-09-01 00:00:00'],
|
||||||
|
'fixed_filters' => ['ExName' => ['中铁物流', '武进安能', '壹米滴答专线']],
|
||||||
|
'columns' => ['Id', 'Shiptime', 'ExName', 'Expressno', 'FreightNew', 'totalFreight', 'checksgn', 'status', 'combsgn'],
|
||||||
|
'indexes' => [['Expressno(64)', 'ExName', 'Shiptime'], ['Id']],
|
||||||
|
],
|
||||||
// 工作平台供应商管理(简尚版):列表和详情只读共享镜像。
|
// 工作平台供应商管理(简尚版):列表和详情只读共享镜像。
|
||||||
// 供应商视图含关联资料变化,无可靠视图更新时间,按稳定键追加并周期全量校准。
|
// 供应商视图含关联资料变化,无可靠视图更新时间,按稳定键追加并周期全量校准。
|
||||||
'jiansun.dbo.js_supplier_View' => [
|
'jiansun.dbo.js_supplier_View' => [
|
||||||
@ -544,10 +555,12 @@ return [
|
|||||||
|
|
||||||
// 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里,
|
// 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里,
|
||||||
// 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。
|
// 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。
|
||||||
// 订单售后费用明细等页面需要把两套来源合并展示。
|
// operations_replica 中的同名对象是无索引报表视图,按更新时间读取会在
|
||||||
|
// 上游超时;订单和明细改读 jiansun 中带主键/时间索引的实体表。数据集键
|
||||||
|
// 保留原值,以续用既有镜像状态和目标表。
|
||||||
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
||||||
'source_key' => 'operations_replica',
|
'source_key' => 'jiansun',
|
||||||
'schema' => 'rpt',
|
'schema' => 'dbo',
|
||||||
'object' => 'jst_qmcust_orderlist',
|
'object' => 'jst_qmcust_orderlist',
|
||||||
'target' => 'ops_jst_qmcust_orders',
|
'target' => 'ops_jst_qmcust_orders',
|
||||||
'keys' => ['Id'],
|
'keys' => ['Id'],
|
||||||
@ -560,8 +573,8 @@ return [
|
|||||||
],
|
],
|
||||||
],
|
],
|
||||||
'operations_replica.rpt.jst_qmcust_orderlist_item' => [
|
'operations_replica.rpt.jst_qmcust_orderlist_item' => [
|
||||||
'source_key' => 'operations_replica',
|
'source_key' => 'jiansun',
|
||||||
'schema' => 'rpt',
|
'schema' => 'dbo',
|
||||||
'object' => 'jst_qmcust_orderlist_item',
|
'object' => 'jst_qmcust_orderlist_item',
|
||||||
'target' => 'ops_jst_qmcust_order_items',
|
'target' => 'ops_jst_qmcust_order_items',
|
||||||
'keys' => ['Id'],
|
'keys' => ['Id'],
|
||||||
@ -1101,6 +1114,9 @@ return [
|
|||||||
['updateTime', 'Id'],
|
['updateTime', 'Id'],
|
||||||
['express_company', 'createTime', 'Id'],
|
['express_company', 'createTime', 'Id'],
|
||||||
['transactionNo', 'Id'],
|
['transactionNo', 'Id'],
|
||||||
|
['Id'],
|
||||||
|
['returnExpressNo(191)', 'Id'],
|
||||||
|
['express_company', 'expressPickupTime', 'Id'],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [
|
'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [
|
||||||
|
|||||||
@ -0,0 +1,58 @@
|
|||||||
|
<?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');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
if (! app()->environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) {
|
||||||
|
if ($schema->hasTable($name)) continue;
|
||||||
|
$schema->create($name, function (Blueprint $table): void {
|
||||||
|
$table->unsignedBigInteger('source_id')->primary();
|
||||||
|
$table->unsignedBigInteger('after_sales_id')->nullable()->index();
|
||||||
|
$table->unsignedBigInteger('item_id')->nullable();
|
||||||
|
$table->dateTime('received_at', 6)->index();
|
||||||
|
$table->string('online_after_sales_no', 255)->nullable();
|
||||||
|
$table->string('order_id', 64)->nullable();
|
||||||
|
$table->string('online_order_no', 255)->nullable();
|
||||||
|
$table->string('waybill', 255)->nullable()->index();
|
||||||
|
$table->string('courier', 255)->nullable();
|
||||||
|
$table->string('shop', 255)->nullable();
|
||||||
|
$table->string('warehouse', 255)->nullable();
|
||||||
|
$table->string('sku', 255)->nullable()->index();
|
||||||
|
$table->string('style_code', 255)->nullable();
|
||||||
|
$table->text('product_name')->nullable();
|
||||||
|
$table->text('properties')->nullable();
|
||||||
|
$table->decimal('applied_qty', 20, 4)->nullable();
|
||||||
|
$table->decimal('returned_qty', 20, 4)->nullable();
|
||||||
|
$table->decimal('price', 20, 4)->nullable();
|
||||||
|
$table->decimal('item_amount', 20, 4)->nullable();
|
||||||
|
$table->decimal('order_refund', 20, 4)->nullable();
|
||||||
|
$table->string('status', 64)->nullable();
|
||||||
|
$table->string('type', 64)->nullable();
|
||||||
|
$table->string('goods_status', 64)->nullable();
|
||||||
|
$table->text('reason')->nullable();
|
||||||
|
$table->text('remark')->nullable();
|
||||||
|
$table->dateTime('source_updated_at', 6)->nullable();
|
||||||
|
$table->uuid('generation')->index();
|
||||||
|
$table->dateTime('synced_at', 6);
|
||||||
|
$table->index(['received_at', 'source_id'], 'returned_parcel_date_id_' . (str_ends_with($table->getTable(), '_stage') ? 'stage' : 'live'));
|
||||||
|
$table->index(['shop', 'received_at']);
|
||||||
|
$table->index(['warehouse', 'received_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
$schema->dropIfExists('courier_returned_parcels_stage');
|
||||||
|
$schema->dropIfExists('courier_returned_parcels');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,60 @@
|
|||||||
|
<?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']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
<?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');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const TABLE = 'js_ekf_return_pickup_management';
|
||||||
|
private const INDEXES = [
|
||||||
|
'return_pickup_bill_id' => ['Id'],
|
||||||
|
'return_pickup_bill_number' => ['returnExpressNo', 'Id'],
|
||||||
|
'return_pickup_bill_month' => ['express_company', 'expressPickupTime', 'Id'],
|
||||||
|
];
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$schema = Schema::connection('business_mirror');
|
||||||
|
if (! $schema->hasTable(self::TABLE)) return;
|
||||||
|
$existing = array_column($schema->getIndexes(self::TABLE), 'columns');
|
||||||
|
foreach (self::INDEXES as $name => $columns) {
|
||||||
|
if (! in_array(array_map('strtolower', $columns), array_map(fn ($v) => array_map('strtolower', $v), $existing), true)) {
|
||||||
|
if ($name === 'return_pickup_bill_number' && $schema->getConnection()->getDriverName() === 'mysql') {
|
||||||
|
$schema->getConnection()->statement('ALTER TABLE `js_ekf_return_pickup_management` ADD INDEX `return_pickup_bill_number` (`returnExpressNo`(191), `Id`)');
|
||||||
|
} else {
|
||||||
|
$schema->table(self::TABLE, fn (Blueprint $table) => $table->index($columns, $name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$schema = Schema::connection('business_mirror');
|
||||||
|
if (! $schema->hasTable(self::TABLE)) return;
|
||||||
|
$existing = array_column($schema->getIndexes(self::TABLE), 'name');
|
||||||
|
foreach (array_keys(self::INDEXES) as $name) {
|
||||||
|
if (in_array($name, $existing, true)) $schema->table(self::TABLE, fn (Blueprint $table) => $table->dropIndex($name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -248,6 +248,7 @@ CRON_TZ=Asia/Shanghai
|
|||||||
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
|
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 前完成。
|
# 退款待确认四张副本库镜像每天 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 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
|
*/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秒。
|
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多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
|
*/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
|
||||||
@ -267,7 +268,8 @@ 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
|
*/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
|
* * * * * 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-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-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
|
* * * * * 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
|
||||||
@ -282,6 +284,9 @@ 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
|
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
|
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
|
EOF
|
||||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||||
|
|
||||||
|
|||||||
@ -252,6 +252,7 @@ CRON_TZ=Asia/Shanghai
|
|||||||
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
|
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 前完成。
|
# 退款待确认四张副本库镜像每天 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 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
|
*/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秒。
|
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多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
|
*/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
|
||||||
@ -271,7 +272,8 @@ 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
|
*/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
|
* * * * * 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-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-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
|
* * * * * 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
|
||||||
@ -286,6 +288,9 @@ 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
|
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
|
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
|
EOF
|
||||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||||
|
|
||||||
|
|||||||
@ -1,5 +1,7 @@
|
|||||||
[
|
[
|
||||||
|
"courier-bills:match-reverse",
|
||||||
"portal-freight:import-pending",
|
"portal-freight:import-pending",
|
||||||
|
"courier-surcharge:match-bills",
|
||||||
"planting-reimbursement:auto-confirm",
|
"planting-reimbursement:auto-confirm",
|
||||||
"jushuitan:apply-shipping-corrections",
|
"jushuitan:apply-shipping-corrections",
|
||||||
"actual-tax:import",
|
"actual-tax:import",
|
||||||
|
|||||||
@ -8,10 +8,10 @@ is_import=0
|
|||||||
CAIWU_BATCH_CALLER_DIR="$PWD"
|
CAIWU_BATCH_CALLER_DIR="$PWD"
|
||||||
export CAIWU_BATCH_CALLER_DIR
|
export CAIWU_BATCH_CALLER_DIR
|
||||||
case "${1:-}" in
|
case "${1:-}" in
|
||||||
portal-freight:import-pending) is_import=1 ;;
|
portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse) is_import=1 ;;
|
||||||
planting-reimbursement:auto-confirm) 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:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
|
||||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
|
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;
|
||||||
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) ;;
|
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 ;;
|
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
|
||||||
esac
|
esac
|
||||||
@ -67,6 +67,34 @@ if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ];
|
|||||||
fi
|
fi
|
||||||
[ -n "$pending_request" ] || exit 0
|
[ -n "$pending_request" ] || exit 0
|
||||||
fi
|
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
|
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}}')"
|
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
|
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
|
||||||
@ -125,4 +153,15 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then
|
|||||||
--name "$container_name" batch "$@"
|
--name "$container_name" batch "$@"
|
||||||
exit $?
|
exit $?
|
||||||
fi
|
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 "$@"
|
docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@"
|
||||||
|
|||||||
@ -1,5 +1,17 @@
|
|||||||
# 上游业务镜像清单
|
# 上游业务镜像清单
|
||||||
|
|
||||||
|
## 发货数据专线运费
|
||||||
|
|
||||||
|
中铁物流、武进安能、壹米滴答专线的核算运费读取工作平台「专线运费」视图 `jiansun.dbo.jst_shipFreight_view`,镜像为 `js_jst_ship_freight`。只接入这三个快递自 2026-09-01 起的记录;按稳定出库键 `Id` 断点同步,无可靠更新时间,因此每小时全量校准。复用 `business-mirror:sync-tables`、生产批容器及现有同步锁,镜像完成后仅重算这三个快递。首次全量完成前显示待同步。
|
||||||
|
|
||||||
|
采用视图逐包分摊后的 `FreightNew`,不把组合总额 `totalFreight` 重复计入每包;0 元保留为有效金额。按快递、运单及出库单/发货时间匹配,同单号重复出库不借用其他批次金额;未匹配、金额为空或匹配不唯一时保留待核对,不回退报价。核算只写 `jst_oms_shipping_freight`,不修改聚水潭原始运费、结算重量或其他快递计费规则。
|
||||||
|
|
||||||
|
## 客服核实附加费
|
||||||
|
|
||||||
|
`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 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。
|
`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 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。
|
||||||
@ -10,7 +22,7 @@
|
|||||||
|
|
||||||
厂家记账核价使用工作平台月度导出的受控镜像,2026年10月账期覆盖5—10月,不借用年份不符或覆盖不足的现有发货来源。`supplier_bookkeeping_shipping_months` 保存月覆盖、摘要、可见代次及断点;`supplier_bookkeeping_shipping_rows` 保存最少核价字段和来源行号;`supplier_bookkeeping_shipping_refs` 保存快递号、换单前单号和订单号索引。原件只读,不接入收件人等个人字段。
|
厂家记账核价使用工作平台月度导出的受控镜像,2026年10月账期覆盖5—10月,不借用年份不符或覆盖不足的现有发货来源。`supplier_bookkeeping_shipping_months` 保存月覆盖、摘要、可见代次及断点;`supplier_bookkeeping_shipping_rows` 保存最少核价字段和来源行号;`supplier_bookkeeping_shipping_refs` 保存快递号、换单前单号和订单号索引。原件只读,不接入收件人等个人字段。
|
||||||
|
|
||||||
预处理脚本为 `scripts/prepare-supplier-bookkeeping-shipping.py`,导入命令为受限批入口下的 `supplier-bookkeeping:import-shipments`。完整月导入成功后原子切换代次,失败保留旧版,可续传。运费取“运费”,5月取经用户确认的“系统运费”,不使用“结算运费”。普通商品当前成本读取既有商品资料镜像。规则和验收范围见 [厂家记账金额规则](厂家记账金额规则.md)。
|
预处理脚本为 `scripts/prepare-supplier-bookkeeping-shipping.py`,导入命令为受限批入口下的 `supplier-bookkeeping:import-shipments`。完整月导入成功后原子切换代次,失败保留旧版,可续传。运费取“运费”,5月取经用户确认的“系统运费”,不使用“结算运费”。普通商品当前成本读取既有商品资料镜像。缺月度文件且工单带明确快递号时,可从现有自动同步表 `jst_oms_shipping` 按索引匹配全部指定包裹,使用商品明细数量及原始 `freight`,不取核算运费或结算运费、不改重量逻辑;无快递号仍要求完整月度文件。规则和验收范围见 [厂家记账金额规则](厂家记账金额规则.md)。
|
||||||
|
|
||||||
## 结论
|
## 结论
|
||||||
|
|
||||||
@ -20,6 +32,10 @@
|
|||||||
|
|
||||||
## 当前迁移状态
|
## 当前迁移状态
|
||||||
|
|
||||||
|
“快递应付 → 退回件明细”按 `operations_replica/rpt.jst_returnAndRefundItem.receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 关联 `rpt.jst_returnAndRefundInfo` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,源明细 `Id` 为稳定键;分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存游标。完整核对来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。
|
||||||
|
|
||||||
|
生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每批最多 2,000 条商品,按所选商品关联售后主表。命令不会写聚水潭或其他财务台账。
|
||||||
|
|
||||||
| 状态 | 说明 |
|
| 状态 | 说明 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 |
|
| 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 |
|
||||||
@ -86,6 +102,7 @@
|
|||||||
| 店铺资料 | `rpt.fys_shopInfo` | `ops_fys_shop_info` |
|
| 店铺资料 | `rpt.fys_shopInfo` | `ops_fys_shop_info` |
|
||||||
| 商标资料 | `rpt.fys_TrademarkInfo` | `ops_fys_trademark_info` |
|
| 商标资料 | `rpt.fys_TrademarkInfo` | `ops_fys_trademark_info` |
|
||||||
| 订单 | `rpt.jst_Orders`、`rpt.jst_OrderItem` | `ops_jst_orders`、`ops_jst_order_item` |
|
| 订单 | `rpt.jst_Orders`、`rpt.jst_OrderItem` | `ops_jst_orders`、`ops_jst_order_item` |
|
||||||
|
| 淘系订单与明细 | `jiansun/dbo.jst_qmcust_orderlist`、`jiansun/dbo.jst_qmcust_orderlist_item` | `ops_jst_qmcust_orders`、`ops_jst_qmcust_order_items`。数据集键沿用历史上的 `operations_replica.rpt.*` 名称以续用镜像状态;实际来源使用原业务库实体表,避免报表库无索引视图超时 |
|
||||||
| 商品与仓库 | `rpt.jst_sku`、`rpt.jst_warehouseInfo`、`rpt.jst_skumap` | `ops_jst_*`(普通商品资料已切换) |
|
| 商品与仓库 | `rpt.jst_sku`、`rpt.jst_warehouseInfo`、`rpt.jst_skumap` | `ops_jst_*`(普通商品资料已切换) |
|
||||||
| 推广费用 | `rpt.ads_itemid_sales_cost_ratio_v2_di` | `ops_item_sales_cost_ratio` |
|
| 推广费用 | `rpt.ads_itemid_sales_cost_ratio_v2_di` | `ops_item_sales_cost_ratio` |
|
||||||
| 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem`、`rpt.jst_qmcust_refundlist`、`rpt.jst_qmcust_refundlist_item` | `ops_jst_return_refund_*`、`ops_jst_qmcust_refunds`、`ops_jst_qmcust_refund_items` |
|
| 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem`、`rpt.jst_qmcust_refundlist`、`rpt.jst_qmcust_refundlist_item` | `ops_jst_return_refund_*`、`ops_jst_qmcust_refunds`、`ops_jst_qmcust_refund_items` |
|
||||||
|
|||||||
@ -8,7 +8,7 @@
|
|||||||
2. 未命中的,再用工单 `actual_paid_amount`(页面“实付金额”)作分母,独立判断同样的严格边界。任一轮实付缺失、无效或为0时,只跳过该轮;另一轮仍可正常判断。多商品买家实付缺一项时,不把部分金额当作完整合计。
|
2. 未命中的,再用工单 `actual_paid_amount`(页面“实付金额”)作分母,独立判断同样的严格边界。任一轮实付缺失、无效或为0时,只跳过该轮;另一轮仍可正常判断。多商品买家实付缺一项时,不把部分金额当作完整合计。
|
||||||
3. 保留厂家记账配置、代发仓发错货限制和多供应商待确认规则。只有已判定可扣款的剩余工单进入核价,不用核价推翻“不扣款”或“待确认”。
|
3. 保留厂家记账配置、代发仓发错货限制和多供应商待确认规则。只有已判定可扣款的剩余工单进入核价,不用核价推翻“不扣款”或“待确认”。
|
||||||
工单供应商为空时,先按普通商品编码匹配商品资料;完整的 `ZH-/MKH-商品编码-数量-商品编码-数量` 组合编码拆出组件后逐个精确匹配,普通商品精确命中优先。运营组合套装从六个月内原单发货明细拆出实际商品编码,必须覆盖全部指定单号并核对订单;未发出或未完整匹配时不采用部分明细。每个组件都查到商品资料供应商后,才按当前配置、小额归零和核价规则继续处理。保留原编码,展示实际商品编码、逐编码供应商匹配说明;任一组件缺供应商或多供应商判定不一致仍待确认,不使用部分供应商扣款。不覆盖工单已有供应商。
|
工单供应商为空时,先按普通商品编码匹配商品资料;完整的 `ZH-/MKH-商品编码-数量-商品编码-数量` 组合编码拆出组件后逐个精确匹配,普通商品精确命中优先。运营组合套装从六个月内原单发货明细拆出实际商品编码,必须覆盖全部指定单号并核对订单;未发出或未完整匹配时不采用部分明细。每个组件都查到商品资料供应商后,才按当前配置、小额归零和核价规则继续处理。保留原编码,展示实际商品编码、逐编码供应商匹配说明;任一组件缺供应商或多供应商判定不一致仍待确认,不使用部分供应商扣款。不覆盖工单已有供应商。
|
||||||
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
|
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值;原单运费为空或0时,按对应商品成本×0.2替代,并注明“原单运费缺失或为0,按商品成本×0.2替代运费”。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
|
||||||
5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。
|
5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。
|
||||||
|
|
||||||
6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。
|
6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。
|
||||||
@ -18,14 +18,15 @@
|
|||||||
## 发货匹配
|
## 发货匹配
|
||||||
|
|
||||||
- 运费取工作平台月度导出“运费”;5月“系统运费”经用户确认是相同口径。不使用“结算运费”,不借用覆盖不足的现有发货表或其他年份数据。
|
- 运费取工作平台月度导出“运费”;5月“系统运费”经用户确认是相同口径。不使用“结算运费”,不借用覆盖不足的现有发货表或其他年份数据。
|
||||||
- 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月未完整导入时待确认。
|
- 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月月度文件完整时保持原导出核价路径;缺文件且工单有明确快递号时,改为只读现有 `jst_oms_shipping` 自动同步明细,所有指定快递号和工单商品都匹配后,按同一金额规则核价,并注明“按系统同步发货明细核价(原快递单号完整匹配)”。无快递号、只有订单号时,仍须六个月月度文件完整,不按局部订单包裹核价。
|
||||||
|
- 自动同步来源须有成功同步记录,按现有快递号/订单号索引定点读取,换单前号仅在订单候选内精确核对;不直连上游、不改写发货数据。包裹行数须与 `pkg_count` 一致,沿用未发出名单排除,缺发货、部分单号、缺数量/商品/成本和冲突值仍待确认;自动同步来源不可用不影响文件完整的账期。
|
||||||
- 有物流单号时精确匹配该单号或换单前单号,同时核对工单提供的线上订单号;无物流单号时按线上订单号匹配全部相关包裹。合并订单按拆分后的完整单号建立索引。
|
- 有物流单号时精确匹配该单号或换单前单号,同时核对工单提供的线上订单号;无物流单号时按线上订单号匹配全部相关包裹。合并订单按拆分后的完整单号建立索引。
|
||||||
- 单号及商品编码匹配前清理前后空白、不可见复制符、单引号、引号、`@` 及其全角形式;保留原始展示值及单号前导0,保留编码内部的 `-`、`+` 等合法内容,不做模糊匹配。
|
- 单号及商品编码匹配前清理前后空白、不可见复制符、单引号、引号、`@` 及其全角形式;保留原始展示值及单号前导0,保留编码内部的 `-`、`+` 等合法内容,不做模糊匹配。
|
||||||
- 不以平均运费替代原单运费,不借同订单其他快递单的运费;多个单号只匹配部分时待确认。
|
- 不以平均运费替代原单运费,不借同订单其他快递单的运费;多个单号只匹配部分时待确认。
|
||||||
- “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出或工单明确列出的单号被部分排除时待确认、不计扣款,保留原金额。其他辅助列错误待确认。
|
- “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出或工单明确列出的单号被部分排除时待确认、不计扣款,保留原金额。其他辅助列错误待确认。
|
||||||
- 工单商品须全部匹配。一个单元格合并多个商品编码、仅有总数量时,不推测每个商品的数量,标为待确认。
|
- 工单商品须全部匹配。组合装一个单元格合并多个商品编码、仅有总数量时,沿用财务已确认的各条码1件口径,并注明“组合装按各条码1件计”;沐野竹木只记成本价的特殊规则仍要求逐商品实际数量。
|
||||||
- 包裹运费只取一次;同包裹同商品的重复行不重复累计数量。运费或数量冲突时待确认,不相加、不擅自选值。
|
- 包裹运费只取一次;同包裹同商品的重复行不重复累计数量。运费或数量冲突时待确认,不相加、不擅自选值。
|
||||||
- 缺发货、有效数量、成本价或运费时待确认,保留原金额,不计扣款合计;运费损耗的空/0运费按第5条替代,判定说明及备注明确记录“按对应商品成本合计×0.2替代运费”,成本与数量列展示替代部分的依据。补偿/全款仍将明确0运费视为有效,空运费待确认。
|
- 缺发货、有效数量或成本价时待确认,保留原金额,不计扣款合计;空/0运费按第4、5条替代,成本与数量列展示替代部分的依据,不把缺失运费直接按0记账。
|
||||||
- 原记账金额、匹配成本/运费/数量/快递号/期间供页面核对与导出。
|
- 原记账金额、匹配成本/运费/数量/快递号/期间供页面核对与导出。
|
||||||
|
|
||||||
## 月度发货导出镜像
|
## 月度发货导出镜像
|
||||||
|
|||||||
35
docs/快递联合上传验收.md
Normal file
35
docs/快递联合上传验收.md
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
# 快递联合上传
|
||||||
|
|
||||||
|
入口:快递应付(及终版)→ 快递账单对账 → 上传账单 → 联合上传链接。
|
||||||
|
选择月份、打开页面后复制地址给快递。仍使用统一逐单模板及 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 小时超时继续生效。
|
||||||
|
中断任务标记失败,联系财务核对后重传,不自动重复导入。
|
||||||
33
docs/运费账单确认.md
Normal file
33
docs/运费账单确认.md
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
# 运费账单确认
|
||||||
|
|
||||||
|
代发运费对账的厂家明细页提供厂家切换、费用小汇总、逐单查询、异议处理和推送历史;快递账单对账在对账单内提供同样的对方确认入口。
|
||||||
|
|
||||||
|
## 操作顺序
|
||||||
|
|
||||||
|
1. 按原有规则完成核对。代发点“核对完成”;自有快递先完成“确认结算”。
|
||||||
|
2. 点“推送厂家确认”或“推送快递确认”。使用该厂家或对账分组已配置的钉钉机器人。
|
||||||
|
3. 对方打开免登录链接,查看本版本汇总、费用和逐单明细,也可下载 Excel。可跨页勾选异议并填写原因;未提出异议的单据按本版结果确认。
|
||||||
|
4. 提交后显示确认状态或逐单异议,同时发送群回执。财务在右侧记录采纳复核结果或不采纳,并填写依据,处理结果回到群内。
|
||||||
|
5. 需要调整金额时,先修正原有核算来源或费用,再重新推送。新推送生成新版本;旧链接不可再次提交,历史异议保留。
|
||||||
|
|
||||||
|
采纳反馈不会直接把对方提出的金额写入财务数据。财务内部的确认结算、台账和原有核算规则保持独立。群消息失败不会丢失确认或异议,财务页提供重发回执入口。
|
||||||
|
|
||||||
|
## 数据与权限
|
||||||
|
|
||||||
|
- 不新增数据库表或迁移。状态与审计继续使用 `supplier_payable_overrides` 和对应事件表。
|
||||||
|
- 代发状态 dataset 为 `dropship-freight-confirm`,快递为 `courier-freight-confirm`,record key 均为 `月份|ID`。代发 ID 是厂家 ID,快递 ID 是对账单 ID。
|
||||||
|
- 逐行版本账单 dataset 为 `<状态dataset>:snapshot:月份|ID:版本`;`meta` 保存汇总和费用,`line:序号` 保存对外明细。批量写入每批 500 行。
|
||||||
|
- 异议 dataset 为 `dropship-freight-dispute:月份|ID` 或 `courier-freight-dispute:月份|ID`,record key 为 `版本|单号`。保存原始原因、财务决定、依据、复核金额、处理人及时间、回执结果。
|
||||||
|
- 历史状态 dataset 为 `<状态dataset>:history:月份|ID`,record key 为版本号。
|
||||||
|
- 外部链接绑定公司、对账单或厂家、账期和版本,有效期 30 天。对外明细只包括单号、发货时间、快递、账单金额、应结金额、分类和说明,不包含内部公式、原始导入列或其他合作方数据。
|
||||||
|
- 已存在的旧代发链接继续兼容;历史版本未保存逐行快照的页面明确标注当前核算结果,需重新推送后才能固定版本。
|
||||||
|
|
||||||
|
## 验证边界
|
||||||
|
|
||||||
|
生产只读规模盘点:2026 年 11 月代发账单 15,119 行、最大一家 9,730 行;快递账单 71,650 行、最大一组 24,566 行。性能验证使用隔离 SQLite 和模拟数据,不向真实群发送测试消息,不运行生产压测。
|
||||||
|
|
||||||
|
界面每页 50 行对外明细、100 行代发内部明细、20 条财务异议。导出使用现有流式工作簿写入器;版本账单按固定范围分批读取。
|
||||||
|
|
||||||
|
2026-12-05 本地 PHP 8.3、2 核/2 GiB、内存 SQLite 验证:相关回归 48 项、767 条断言通过;随后补充大小写规范化、跨页异议提交和并发版本保护,专项 3 项、62 条断言通过。9,730 行代发账单的首页、第二页、筛选合计 1.44 秒,284 次查询累计 241 毫秒;24,566 行快递版本账单保存 1.08 秒,首页/第二页/筛选合计 0.31 秒,导出 1.68 秒,文件 683,504 字节,该专项 254 次查询累计 919 毫秒。整进程峰值 RSS 266.3 MiB,PHP 峰值 195 MiB。包含框架与测试初始化开销;没有在生产压测,也没有实测生产数据库写入耗时。
|
||||||
|
|
||||||
|
2026-12-05 发布前补验:合入最新主线后,相关 32 项测试、500 条断言通过。Chrome 已检查真实模板渲染的厂家明细、待确认页、异议表单、填写后自动勾选、刷新保留草稿与清空勾选;修复反馈链接在含 base 地址的页面跳离当前账单的问题,并支持定位到对应异议分页。真实钉钉发送不作为验收动作。手机尺寸及真实设备交互尚未实测。
|
||||||
18
docs/逆向快递账单核算.md
Normal file
18
docs/逆向快递账单核算.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
# 逆向快递账单核算
|
||||||
|
|
||||||
|
快递账单对账中的中通快运逆向、常州德邦逆向、申通退货、好省邮快递读取退件取件管理共享镜像。按退货单号和实退单号匹配,原单号已换单时不重复付款;同号多张取件单或一单多个实退单号保留待核实,不重复分配整单运费。普通快递仍按发货数据核对,常州德邦与常州德邦逆向分别处理。
|
||||||
|
|
||||||
|
以实际取件时间归属月份;取消、关闭或没有实际取件时间的记录列为未发出。中通、德邦、申通复用逆向报价试算规则。按用户确认口径,同一运单各商品的毛重×退货数量、长×宽×高×退货数量分别合计,整票计费,面单只收一次;基础运费与附加费分别保留。缺少重量、路线、报价或报价尚未生效时不填零价,显示系统未核算。导出保留退件商品、重量、计算公式、报价来源。
|
||||||
|
|
||||||
|
好省邮按取件记录的实际承运快递选择报价管理里的好省邮百世、好省邮顺心捷达或好省邮顺丰,复用现有源目省份及城市报价计算器,以取件日选择有效版本。
|
||||||
|
|
||||||
|
原始账单、人工处理结果及手工小汇总保留。仅对明确指定且未确认的账单重算,确认后的账单拒绝自动重算。服务器使用独立批处理入口(既有内存、超时和互斥限制):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1
|
||||||
|
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1 --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
不带 `--apply` 只预演;实际执行前自动备份该账单的行、未提供明细和小汇总到私有目录。失败后可在核对备份与最新状态后重新运行;不批量处理其他账单。
|
||||||
|
|
||||||
|
退件主表约 31 万行、明细约 40 万行、实退单号约 19 万行;查询按单号分批,月份按快递和取件时间索引,关联按取件主键。迁移仅增加共享镜像索引,不写上游业务数据。
|
||||||
25
docs/附加费账单匹配.md
Normal file
25
docs/附加费账单匹配.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# 附加费账单匹配
|
||||||
|
|
||||||
|
快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;统一匹配包含账单当月在内最近3个自然月,不把账单金额当自算金额。例如11月账单匹配9月1日(含)至12月1日(不含)的数据,跨年同样按自然月计算。发货记录、客服工单和来源结算均受此时间范围限制;无日期记录不自动计费。已计入其他账单的费用仍去重,不因跨月重复结算。
|
||||||
|
|
||||||
|
新文件导入时自动匹配,已有账单可用 `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 忽略的私有目录。
|
||||||
|
|
||||||
|
结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单及客服明细中包含“拦截费”的名称(如“拦截费用”“待拦截费”“包裹拦截费用”,忽略空格)统一对应“拦截费”;“拦截”“拦截退回”“拦截退回运费”也按同一类型处理,同票同类费用仍去重。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。
|
||||||
|
|
||||||
|
“取发出运费”的“查件扣单并且买家原因”条件,按同一单号、同一快递、匹配时间范围内的有效查件工单核验原因分类,要求为“扣单/买家-具体原因”,不要求退回进仓。多个扣单工单采用最新有效工单(创建时间、来源ID排序),取消工单不参与;明确非买家原因计0,缺工单或原因不完整保持未匹配。核对说明保留工单号和原始原因,每票发出运费只计一次。
|
||||||
|
|
||||||
|
负责人逐票确认的买家原因,复用 `supplier_payable_overrides` 的 `courier-surcharge-buyer-confirmations` 数据集及其事件审计保存,不修改上游工单。确认绑定报价、账单月份、完整单号、工单号及原始原因,并保留确认依据;重新匹配继续使用同一确认。换工单、换报价或原因变更后需重新核实,其他破损单不自动视为买家原因。真实单号和确认记录不得进入 Git。
|
||||||
|
|
||||||
|
固定单价自动核价读取报价中的金额(如30元/单、30/单),每票同类费用只计一次,不乘商品数量。空条件或“按单收取”按票计费;“查件扣单”核对同快递有效工单;带“买家原因”的条件核对扣单原因;带“已退回”的条件还要求该工单订单在最近三个自然月有实退数量大于0的进仓记录。退回状态通过已接入售后镜像的订单和售后单索引关联读取,无需全表扫描;缺少进仓依据保持未匹配,不推测已退回。客服通过类条件仍要求同单号、同快递、同费用类型的审核通过明细,金额取报价固定单价,不取客服填写的金额。暂不支持的条件或金额格式保留未匹配原因,不能回退到旧结算金额绕过条件。
|
||||||
|
|
||||||
|
固定单价条件“查件扣单并且买家原因或破损”接受扣单原因的“买家-*”“快递-破损”或“破损”,无需退回进仓;仅报价明确采用该条件时适用,不扩大其他报价的范围。改地址固定单价也接受同快递改地址工单中客服结果字段明确为“通过/已通过”,或客服回复字段明确为“通过/已通过/客服回复已通过”;“已联系快递修改”、待跟进及未通过均不是审核通过。
|
||||||
|
|
||||||
|
用户要求保留某厂家某月现有金额时,在既有覆盖值表的 `bill-surcharge-auto-match-holds` 数据集记录 `dropship|厂家ID|月份`、`enabled=true` 及原因,并写审计;`--existing-only` 的每日自动重匹配跳过该账期。新账单导入、其他厂家或月份不受影响,后续获授权的指定账期重算仍可正常执行。
|
||||||
|
|
||||||
|
客服费用通过现有单号索引读取共享工单,要求同一快递、费用类型一致、逐项审核通过且工单在账单月份结束前创建;按工单归集,不按商品数重复计费。“重量60kg以上”先检查本票已核算计费重量,低于门槛计0;缺重量、缺审核、无报价分别显示原因。原始账单、报价和发货运费均不改写。
|
||||||
@ -63,7 +63,7 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
public function state(): array
|
public function state(array $filters = []): array
|
||||||
{
|
{
|
||||||
if (! $this->available()) {
|
if (! $this->available()) {
|
||||||
return [
|
return [
|
||||||
@ -75,8 +75,15 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$lastPulledAt = $this->connection->table(self::TABLE)->max('pulled_at');
|
$query = $this->filteredQuery($filters);
|
||||||
$rowCount = (int) $this->connection->table(self::TABLE)->count();
|
$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();
|
||||||
|
}
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
return [
|
return [
|
||||||
'code' => 'pending',
|
'code' => 'pending',
|
||||||
@ -87,9 +94,9 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'code' => $lastPulledAt === null ? 'pending' : 'fresh',
|
'code' => $serviceState ? ($serviceState->status === 'succeeded' ? 'fresh' : ($serviceState->status === 'failed' ? 'failed' : 'syncing')) : ($lastPulledAt === null ? 'pending' : 'fresh'),
|
||||||
'status' => $lastPulledAt === null ? 'pending' : 'succeeded',
|
'status' => $serviceState->status ?? ($lastPulledAt === null ? 'pending' : 'succeeded'),
|
||||||
'last_succeeded_at' => $lastPulledAt,
|
'last_succeeded_at' => $serviceState->last_succeeded_at ?? $lastPulledAt,
|
||||||
'mirror_row_count' => $rowCount,
|
'mirror_row_count' => $rowCount,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@ -141,7 +148,7 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
$data[] = $mapped;
|
$data[] = $mapped;
|
||||||
}
|
}
|
||||||
|
|
||||||
$state = $this->state();
|
$state = $this->state($filters);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'data' => $data,
|
'data' => $data,
|
||||||
@ -370,6 +377,7 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
private function normalizeImportType(string $type): string
|
private function normalizeImportType(string $type): string
|
||||||
{
|
{
|
||||||
$type = trim($type);
|
$type = trim($type);
|
||||||
|
if (str_contains(preg_replace('/\s+/u', '', $type) ?? '', '拦截费')) return '拦截费';
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'退回件' => '退回费',
|
'退回件' => '退回费',
|
||||||
@ -377,6 +385,9 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
'退货件' => '退回费',
|
'退货件' => '退回费',
|
||||||
'超长' => '超长费',
|
'超长' => '超长费',
|
||||||
'改地址费' => '改地址',
|
'改地址费' => '改地址',
|
||||||
|
'拦截' => '拦截费',
|
||||||
|
'拦截退回' => '拦截费',
|
||||||
|
'拦截退回运费' => '拦截费',
|
||||||
][$type] ?? $type;
|
][$type] ?? $type;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -386,6 +397,18 @@ class CourierSurchargeSettlementMirrorRepository
|
|||||||
private function matchImportRow(iterable $rows, string $type, string $courier = ''): ?object
|
private function matchImportRow(iterable $rows, string $type, string $courier = ''): ?object
|
||||||
{
|
{
|
||||||
$fallback = null;
|
$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) {
|
foreach ($rows as $row) {
|
||||||
if (trim((string) $row->surcharge_type) !== $type) {
|
if (trim((string) $row->surcharge_type) !== $type) {
|
||||||
|
|||||||
@ -23,10 +23,10 @@ class DingInvoiceDataMirrorRepository
|
|||||||
public const VIEW_ATTACHMENTS = 'attachments';
|
public const VIEW_ATTACHMENTS = 'attachments';
|
||||||
|
|
||||||
public const INVOICE_STATES = [
|
public const INVOICE_STATES = [
|
||||||
'all' => '全部状态',
|
'all' => '全部流程',
|
||||||
'has_invoice' => '有发票',
|
'has_invoice' => '有票流程',
|
||||||
'no_invoice' => '无票',
|
'no_invoice' => '无票流程',
|
||||||
'needs_review' => '待复核',
|
'needs_review' => '待复核流程',
|
||||||
];
|
];
|
||||||
|
|
||||||
private ConnectionInterface $connection;
|
private ConnectionInterface $connection;
|
||||||
@ -381,13 +381,14 @@ class DingInvoiceDataMirrorRepository
|
|||||||
'has_invoice' => $query->where("{$alias}.invoice_count", '>', 0),
|
'has_invoice' => $query->where("{$alias}.invoice_count", '>', 0),
|
||||||
'no_invoice' => $query
|
'no_invoice' => $query
|
||||||
->where("{$alias}.invoice_count", '=', 0)
|
->where("{$alias}.invoice_count", '=', 0)
|
||||||
|
->whereIn("{$alias}.scan_status", ['no_invoice', 'recognized', 'imported'])
|
||||||
->where(function (Builder $nested) use ($alias): void {
|
->where(function (Builder $nested) use ($alias): void {
|
||||||
$nested->whereNull("{$alias}.last_error")
|
$nested->whereNull("{$alias}.last_error")
|
||||||
->orWhere("{$alias}.last_error", '=', '');
|
->orWhere("{$alias}.last_error", '=', '');
|
||||||
}),
|
}),
|
||||||
'needs_review' => $query
|
'needs_review' => $query
|
||||||
->where(function (Builder $nested) use ($alias): void {
|
->where(function (Builder $nested) use ($alias): void {
|
||||||
$nested->whereIn("{$alias}.scan_status", ['partial', 'failed'])
|
$nested->whereIn("{$alias}.scan_status", ['pending', 'partial', 'failed'])
|
||||||
->orWhere(function (Builder $failed) use ($alias): void {
|
->orWhere(function (Builder $failed) use ($alias): void {
|
||||||
$failed->whereNotNull("{$alias}.last_error")
|
$failed->whereNotNull("{$alias}.last_error")
|
||||||
->where("{$alias}.last_error", '!=', '');
|
->where("{$alias}.last_error", '!=', '');
|
||||||
@ -457,12 +458,13 @@ class DingInvoiceDataMirrorRepository
|
|||||||
$query->where('invoice_count', '>', 0);
|
$query->where('invoice_count', '>', 0);
|
||||||
} elseif (($filters['invoice_state'] ?? 'all') === 'no_invoice') {
|
} elseif (($filters['invoice_state'] ?? 'all') === 'no_invoice') {
|
||||||
$query->where('invoice_count', 0)
|
$query->where('invoice_count', 0)
|
||||||
|
->whereIn('scan_status', ['no_invoice', 'recognized', 'imported'])
|
||||||
->where(function (Builder $nested): void {
|
->where(function (Builder $nested): void {
|
||||||
$nested->whereNull('last_error')->orWhere('last_error', '');
|
$nested->whereNull('last_error')->orWhere('last_error', '');
|
||||||
});
|
});
|
||||||
} elseif (($filters['invoice_state'] ?? 'all') === 'needs_review') {
|
} elseif (($filters['invoice_state'] ?? 'all') === 'needs_review') {
|
||||||
$query->where(function (Builder $nested): void {
|
$query->where(function (Builder $nested): void {
|
||||||
$nested->whereIn('scan_status', ['partial', 'failed'])
|
$nested->whereIn('scan_status', ['pending', 'partial', 'failed'])
|
||||||
->orWhere(function (Builder $failed): void {
|
->orWhere(function (Builder $failed): void {
|
||||||
$failed->whereNotNull('last_error')->where('last_error', '!=', '');
|
$failed->whereNotNull('last_error')->where('last_error', '!=', '');
|
||||||
});
|
});
|
||||||
@ -546,10 +548,15 @@ class DingInvoiceDataMirrorRepository
|
|||||||
'invoice_total' => $invoice,
|
'invoice_total' => $invoice,
|
||||||
'no_invoice_flows' => $rows->filter(
|
'no_invoice_flows' => $rows->filter(
|
||||||
static fn (object $row): bool => (int) $row->invoice_count === 0
|
static fn (object $row): bool => (int) $row->invoice_count === 0
|
||||||
|
&& in_array((string) $row->scan_status, ['no_invoice', 'recognized', 'imported'], true)
|
||||||
&& ($row->last_error === null || $row->last_error === ''),
|
&& ($row->last_error === null || $row->last_error === ''),
|
||||||
)->count(),
|
)->count(),
|
||||||
'needs_review_flows' => $rows->filter(
|
'needs_review_flows' => $rows->filter(
|
||||||
static fn (object $row): bool => in_array((string) $row->scan_status, ['partial', 'failed'], true)
|
static fn (object $row): bool => in_array(
|
||||||
|
(string) $row->scan_status,
|
||||||
|
['pending', 'partial', 'failed'],
|
||||||
|
true,
|
||||||
|
)
|
||||||
|| ($row->last_error !== null && $row->last_error !== ''),
|
|| ($row->last_error !== null && $row->last_error !== ''),
|
||||||
)->count(),
|
)->count(),
|
||||||
'invoice_rate' => $payment > 0 ? $invoice / $payment : 0,
|
'invoice_rate' => $payment > 0 ? $invoice / $payment : 0,
|
||||||
|
|||||||
@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\EcommerceFinance\Repositories;
|
||||||
|
|
||||||
|
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
||||||
|
|
||||||
|
/** 工作平台「专线运费」的逐出库单金额;页面和核算只读共享镜像。 */
|
||||||
|
class LinehaulFreightRepository
|
||||||
|
{
|
||||||
|
public const DATASET = 'jiansun.dbo.jst_shipFreight_view';
|
||||||
|
public const TABLE = 'js_jst_ship_freight';
|
||||||
|
public const CARRIERS = ['中铁物流', '武进安能', '壹米滴答专线'];
|
||||||
|
|
||||||
|
public static function supports(string $carrier): bool
|
||||||
|
{
|
||||||
|
return in_array(trim($carrier), self::CARRIERS, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int,array{error:?string,row:?array}> */
|
||||||
|
public function forPackages(array $packages): array
|
||||||
|
{
|
||||||
|
$packages = array_filter($packages, static fn (array $p): bool => self::supports((string) ($p['express_name1'] ?? '')));
|
||||||
|
if ($packages === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$mirror = app(GenericBusinessMirrorRepository::class);
|
||||||
|
$dataset = app(BusinessMirrorDatasetRegistry::class)->get(self::DATASET);
|
||||||
|
if (! $mirror->ready($dataset)) {
|
||||||
|
return array_fill_keys(array_column($packages, 'source_id'), ['error' => '工作平台专线运费尚未完成同步', 'row' => null]);
|
||||||
|
}
|
||||||
|
$variants = [];
|
||||||
|
foreach ($packages as $package) {
|
||||||
|
$number = self::number($package['express_no'] ?? '');
|
||||||
|
if ($number !== '') {
|
||||||
|
$variants[] = $number;
|
||||||
|
$variants[] = '@' . $number;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$byNumber = [];
|
||||||
|
foreach (array_chunk(array_values(array_unique($variants)), 800) as $chunk) {
|
||||||
|
foreach ($mirror->connection()->table(self::TABLE)->whereIn('Expressno', $chunk)
|
||||||
|
->get(['Id', 'Shiptime', 'ExName', 'Expressno', 'FreightNew', 'checksgn', 'status', 'combsgn']) as $row) {
|
||||||
|
$byNumber[self::number($row->Expressno)][] = (array) $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$result = [];
|
||||||
|
foreach ($packages as $package) {
|
||||||
|
$result[(int) $package['source_id']] = $this->match($package, $byNumber[self::number($package['express_no'] ?? '')] ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function number(mixed $value): string
|
||||||
|
{
|
||||||
|
return ltrim(trim((string) $value), '@');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{error:?string,row:?array} */
|
||||||
|
private function match(array $package, array $rows): array
|
||||||
|
{
|
||||||
|
$carrier = trim((string) $package['express_name1']);
|
||||||
|
$rows = array_values(array_filter($rows, static fn (array $row): bool => trim((string) $row['ExName']) === $carrier));
|
||||||
|
$sourceId = (int) $package['source_id'];
|
||||||
|
if ($sourceId >= 2000000000 && $sourceId < 3000000000) {
|
||||||
|
// 出库补漏的来源键直接包含 io_id,不能拿同单号另一次出库的金额。
|
||||||
|
$rows = array_values(array_filter($rows, static fn (array $row): bool => (int) $row['Id'] === $sourceId - 2000000000));
|
||||||
|
} else {
|
||||||
|
$time = substr((string) ($package['ship_time'] ?? ''), 0, 19);
|
||||||
|
$exact = array_values(array_filter($rows, static fn (array $row): bool => substr((string) $row['Shiptime'], 0, 19) === $time));
|
||||||
|
$rows = $exact !== [] ? $exact : array_values(array_filter($rows,
|
||||||
|
static fn (array $row): bool => substr((string) $row['Shiptime'], 0, 10) === substr($time, 0, 10)));
|
||||||
|
}
|
||||||
|
if ($rows === []) {
|
||||||
|
return ['error' => '工作平台专线运费未找到对应出库记录', 'row' => null];
|
||||||
|
}
|
||||||
|
if (count($rows) !== 1) {
|
||||||
|
return ['error' => '工作平台专线运费匹配到多条出库记录,待核对', 'row' => null];
|
||||||
|
}
|
||||||
|
$row = $rows[0];
|
||||||
|
if (! is_numeric($row['FreightNew']) || (float) $row['FreightNew'] < 0) {
|
||||||
|
return ['error' => '工作平台专线运费尚未填写有效金额', 'row' => $row];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['error' => null, 'row' => $row];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -163,7 +163,13 @@ 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
|
* @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}
|
* @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}>
|
||||||
|
* }
|
||||||
*/
|
*/
|
||||||
public function paginate(array $filters, int $page, int $perPage): array
|
public function paginate(array $filters, int $page, int $perPage): array
|
||||||
{
|
{
|
||||||
@ -188,6 +194,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
|||||||
'total' => $summary['count'],
|
'total' => $summary['count'],
|
||||||
'page_payment_amount' => $this->sumMoney(array_column($rows, 'payment_amount')),
|
'page_payment_amount' => $this->sumMoney(array_column($rows, 'payment_amount')),
|
||||||
'filtered_payment_amount' => $summary['payment_amount'],
|
'filtered_payment_amount' => $summary['payment_amount'],
|
||||||
|
'store_summary' => $summary['store_summary'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -206,7 +213,11 @@ 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
|
* @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}
|
* @return array{
|
||||||
|
* count:int,
|
||||||
|
* payment_amount:string,
|
||||||
|
* store_summary:list<array{shop_name:string,work_order_count:int,payment_amount:string}>
|
||||||
|
* }
|
||||||
*/
|
*/
|
||||||
private function filteredSummary(array $filters, int $chunkSize = 1000): array
|
private function filteredSummary(array $filters, int $chunkSize = 1000): array
|
||||||
{
|
{
|
||||||
@ -224,7 +235,11 @@ 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
|
* @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}
|
* @return array{
|
||||||
|
* count:int,
|
||||||
|
* payment_amount:string,
|
||||||
|
* store_summary:list<array{shop_name:string,work_order_count:int,payment_amount:string}>
|
||||||
|
* }
|
||||||
*/
|
*/
|
||||||
private function calculateFilteredSummary(array $filters, int $chunkSize): array
|
private function calculateFilteredSummary(array $filters, int $chunkSize): array
|
||||||
{
|
{
|
||||||
@ -237,23 +252,49 @@ class SmallPaymentWorkOrderMirrorRepository
|
|||||||
$cents = 0;
|
$cents = 0;
|
||||||
$count = 0;
|
$count = 0;
|
||||||
$lastId = null;
|
$lastId = null;
|
||||||
|
$shops = [];
|
||||||
|
|
||||||
do {
|
do {
|
||||||
$chunk = $this->boundedGet((clone $query)
|
$chunk = $this->boundedGet((clone $query)
|
||||||
->select(['w.Id AS source_id', 'w.businessFieldList'])
|
->select(['w.Id AS source_id', 'w.businessFieldList', 'p.shop_name'])
|
||||||
->when($lastId !== null, static fn (Builder $q): Builder => $q->where('w.Id', '>', $lastId))
|
->when($lastId !== null, static fn (Builder $q): Builder => $q->where('w.Id', '>', $lastId))
|
||||||
->orderBy('w.Id')
|
->orderBy('w.Id')
|
||||||
->limit($chunkSize));
|
->limit($chunkSize));
|
||||||
|
|
||||||
foreach ($chunk as $row) {
|
foreach ($chunk as $row) {
|
||||||
$cents += $this->centsFromMoney($this->paymentAmountOf($row->businessFieldList ?? null));
|
$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;
|
||||||
}
|
}
|
||||||
|
|
||||||
$count += $chunk->count();
|
$count += $chunk->count();
|
||||||
$lastId = $chunk->isEmpty() ? null : $chunk->last()->source_id;
|
$lastId = $chunk->isEmpty() ? null : $chunk->last()->source_id;
|
||||||
} while ($chunk->count() === $chunkSize);
|
} while ($chunk->count() === $chunkSize);
|
||||||
|
|
||||||
return ['count' => $count, 'payment_amount' => $this->formatCents($cents)];
|
$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,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function paymentAmountOf(mixed $businessFieldList): ?string
|
private function paymentAmountOf(mixed $businessFieldList): ?string
|
||||||
@ -717,7 +758,7 @@ class SmallPaymentWorkOrderMirrorRepository
|
|||||||
$normalized = array_map(static fn (mixed $value): string => trim((string) $value), $filters);
|
$normalized = array_map(static fn (mixed $value): string => trim((string) $value), $filters);
|
||||||
ksort($normalized);
|
ksort($normalized);
|
||||||
|
|
||||||
return 'small-payment-work-orders:summary:v1:' . hash(
|
return 'small-payment-work-orders:summary:v2:' . hash(
|
||||||
'sha256',
|
'sha256',
|
||||||
(string) json_encode($normalized, JSON_UNESCAPED_UNICODE),
|
(string) json_encode($normalized, JSON_UNESCAPED_UNICODE),
|
||||||
);
|
);
|
||||||
|
|||||||
@ -2,13 +2,16 @@
|
|||||||
|
|
||||||
namespace Modules\EcommerceFinance\Repositories;
|
namespace Modules\EcommerceFinance\Repositories;
|
||||||
|
|
||||||
|
use App\Support\UnshippedWaybills;
|
||||||
use Illuminate\Support\Carbon;
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
||||||
use Modules\EcommerceFinance\Services\SupplierBookkeepingShippingImporter as Shipping;
|
use Modules\EcommerceFinance\Services\SupplierBookkeepingShippingImporter as Shipping;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
/** 厂家记账只读核价:工作平台月度导出镜像 + 当前普通商品资料成本。 */
|
/** 厂家记账只读核价:月度导出/原单自动同步明细 + 当前普通商品资料成本。 */
|
||||||
class SupplierBookkeepingValuationRepository
|
class SupplierBookkeepingValuationRepository
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
@ -63,6 +66,73 @@ class SupplierBookkeepingValuationRepository
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
$synced = $this->syncedShipmentsFor($rows);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$synced = [];
|
||||||
|
}
|
||||||
|
return array_merge(array_values($found), $synced);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 缺月度文件时,只为有明确快递号的工单读取现有自动同步明细,不按订单借用其他包裹。 */
|
||||||
|
private function syncedShipmentsFor(array $rows): array
|
||||||
|
{
|
||||||
|
$months = $this->readyMonths();
|
||||||
|
$tracking = $orders = [];
|
||||||
|
$from = $to = null;
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if (self::missingMonth($row, $months) === null) continue;
|
||||||
|
$numbers = self::numbers($row['tracking_no'] ?? '');
|
||||||
|
if ($numbers === []) continue;
|
||||||
|
array_push($tracking, ...$numbers);
|
||||||
|
array_push($orders, ...self::numbers($row['online_order_no'] ?? ''));
|
||||||
|
[$start, $end] = self::window($row);
|
||||||
|
$from = $from === null || $start < $from ? $start : $from;
|
||||||
|
$to = $to === null || $end > $to ? $end : $to;
|
||||||
|
}
|
||||||
|
if ($tracking === []) return [];
|
||||||
|
$db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
||||||
|
$schema = $db->getSchemaBuilder();
|
||||||
|
if (!$schema->hasTable('jst_oms_shipping') || !$schema->hasTable('jst_sync_state')
|
||||||
|
|| !$db->table('jst_sync_state')->where('dataset_key', 'jst.sctrade')->whereNotNull('last_succeeded_at')->exists()
|
||||||
|
|| !app(UnshippedWaybills::class)->connection()->getSchemaBuilder()->hasTable('courier_unshipped_waybills')) return [];
|
||||||
|
|
||||||
|
$wanted = array_fill_keys($tracking, true);
|
||||||
|
$trackingValues = [];
|
||||||
|
foreach (array_keys($wanted) as $number) array_push($trackingValues, (string) $number, '@' . $number);
|
||||||
|
$found = [];
|
||||||
|
// express_no/trade_no 均有现有索引;换单前号只在订单定点候选中核对,避免扫描未索引的 front_no。
|
||||||
|
foreach (['express_no' => $trackingValues, 'trade_no' => $orders] as $column => $values) {
|
||||||
|
foreach (array_chunk(array_values(array_unique($values)), 150) as $chunk) {
|
||||||
|
$query = $db->table('jst_oms_shipping')->whereIn($column, $chunk)
|
||||||
|
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
|
||||||
|
->select(['id', 'source_id', 'express_no', 'front_no', 'trade_no', 'barcode', 'qty', 'freight', 'ship_time', 'pkg_count']);
|
||||||
|
foreach ($query->cursor() as $record) {
|
||||||
|
$references = array_values(array_unique(array_merge(self::numbers($record->express_no), self::numbers($record->front_no))));
|
||||||
|
if (array_intersect($references, array_keys($wanted)) === []) continue;
|
||||||
|
$shipment = (array) $record;
|
||||||
|
$shipment['id'] = 'synced:' . $record->id;
|
||||||
|
$shipment['source_id'] = 'synced:' . $record->source_id;
|
||||||
|
$shipment['valuation_source'] = 'synced';
|
||||||
|
$shipment['tracking_numbers'] = $references;
|
||||||
|
$shipment['order_numbers'] = self::numbers($record->trade_no);
|
||||||
|
$found[$shipment['id']] = $shipment;
|
||||||
|
if (count($found) > 20000) throw new RuntimeException('匹配发货记录过多,须缩小工单范围');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$unshipped = app(UnshippedWaybills::class)->unshippedSources(array_column($found, 'express_no'));
|
||||||
|
$packages = [];
|
||||||
|
foreach ($found as $shipment) $packages[$shipment['source_id']][] = $shipment;
|
||||||
|
foreach ($found as &$shipment) {
|
||||||
|
$shipment['unshipped'] = isset($unshipped[UnshippedWaybills::normalize($shipment['express_no'])]) ? $shipment['express_no'] : '';
|
||||||
|
if (preg_match('/^1\/([1-9]\d*)$/D', (string) $shipment['pkg_count'], $match) !== 1
|
||||||
|
|| count($packages[$shipment['source_id']]) !== (int) $match[1]) {
|
||||||
|
$shipment['valuation_error'] = '同步包裹商品明细尚未齐全,请核对';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($shipment);
|
||||||
return array_values($found);
|
return array_values($found);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -119,6 +189,15 @@ class SupplierBookkeepingValuationRepository
|
|||||||
return [$month->copy()->subMonthsNoOverflow(5)->format('Y-m-d H:i:s'), $month->addMonth()->format('Y-m-d H:i:s')];
|
return [$month->copy()->subMonthsNoOverflow(5)->format('Y-m-d H:i:s'), $month->addMonth()->format('Y-m-d H:i:s')];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static function missingMonth(array $row, array $readyMonths): ?string
|
||||||
|
{
|
||||||
|
[$from, $to] = self::window($row);
|
||||||
|
for ($month = Carbon::parse($from); $month->format('Y-m-d H:i:s') < $to; $month->addMonth()) {
|
||||||
|
if (!in_array($month->format('Y-m'), $readyMonths, true)) return $month->format('Y-m');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
public static function numbers(mixed $value): array
|
public static function numbers(mixed $value): array
|
||||||
{
|
{
|
||||||
return array_values(array_unique(array_filter(array_map(static fn ($v) => self::identifier($v), preg_split('/[\r\n,,、;;]+/u', (string) $value) ?: []), static fn ($v) => $v !== '')));
|
return array_values(array_unique(array_filter(array_map(static fn ($v) => self::identifier($v), preg_split('/[\r\n,,、;;]+/u', (string) $value) ?: []), static fn ($v) => $v !== '')));
|
||||||
|
|||||||
@ -0,0 +1,70 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\EcommerceFinance\Repositories;
|
||||||
|
|
||||||
|
use Illuminate\Database\DatabaseManager;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
class SupplierStatementSettlementRepository
|
||||||
|
{
|
||||||
|
public const TABLE = 'js_supplier_payment_summary';
|
||||||
|
|
||||||
|
private readonly \Illuminate\Database\ConnectionInterface $connection;
|
||||||
|
|
||||||
|
private readonly string $connectionName;
|
||||||
|
|
||||||
|
public function __construct(DatabaseManager $database)
|
||||||
|
{
|
||||||
|
$this->connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||||
|
$this->connection = $database->connection($this->connectionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取每家供应商在目标月份或之前最近一期的结算方式。
|
||||||
|
*
|
||||||
|
* @param list<string> $suppliers
|
||||||
|
* @return array<string,array{settlement_method:string,month:string}>
|
||||||
|
*/
|
||||||
|
public function latestMethods(array $suppliers, string $month): array
|
||||||
|
{
|
||||||
|
$month = trim($month);
|
||||||
|
$suppliers = array_values(array_unique(array_filter(
|
||||||
|
array_map(static fn (mixed $supplier): string => trim((string) $supplier), $suppliers),
|
||||||
|
static fn (string $supplier): bool => $supplier !== '',
|
||||||
|
)));
|
||||||
|
if ($suppliers === []
|
||||||
|
|| preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D', $month) !== 1
|
||||||
|
|| ! Schema::connection($this->connectionName)->hasTable(self::TABLE)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $this->connection->table(self::TABLE)
|
||||||
|
->whereIn('supplier', $suppliers)
|
||||||
|
->where('Month', '<=', $month)
|
||||||
|
->whereNotNull('settleway')
|
||||||
|
->where('settleway', '<>', '')
|
||||||
|
->orderByDesc('Month')
|
||||||
|
->orderByDesc('id')
|
||||||
|
->get(['supplier', 'settleway', 'Month']);
|
||||||
|
|
||||||
|
$methods = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$supplier = trim((string) ($row->supplier ?? ''));
|
||||||
|
if ($supplier === '' || isset($methods[$supplier])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$settlementMethod = trim((string) ($row->settleway ?? ''));
|
||||||
|
if ($settlementMethod === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$methods[$supplier] = [
|
||||||
|
'settlement_method' => $settlementMethod,
|
||||||
|
'month' => trim((string) ($row->Month ?? '')),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $methods;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -31,6 +31,10 @@ class AccountMappingCoverage
|
|||||||
|
|
||||||
private const RETRY_SECONDS = 8;
|
private const RETRY_SECONDS = 8;
|
||||||
|
|
||||||
|
private const ALL_SCOPE = 'all';
|
||||||
|
|
||||||
|
private const ALL_SCOPE_MONTHS = 60;
|
||||||
|
|
||||||
private const SOURCES = [
|
private const SOURCES = [
|
||||||
'淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
'淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||||
'淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
'淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||||
@ -42,8 +46,8 @@ class AccountMappingCoverage
|
|||||||
];
|
];
|
||||||
|
|
||||||
private const PLATFORM_PREFIX = [
|
private const PLATFORM_PREFIX = [
|
||||||
'天猫' => '天猫',
|
'天猫' => AccountMappingPlatform::TAOBAO_TMALL,
|
||||||
'淘宝' => '淘宝',
|
'淘宝' => AccountMappingPlatform::TAOBAO_TMALL,
|
||||||
'京东' => '京东',
|
'京东' => '京东',
|
||||||
'京喜' => '京喜',
|
'京喜' => '京喜',
|
||||||
'京喜小店' => '京喜',
|
'京喜小店' => '京喜',
|
||||||
@ -56,7 +60,6 @@ class AccountMappingCoverage
|
|||||||
'淘工厂' => '阿里巴巴',
|
'淘工厂' => '阿里巴巴',
|
||||||
'唯品会MP' => '唯品会MP',
|
'唯品会MP' => '唯品会MP',
|
||||||
'唯品会JX' => '唯品会JX',
|
'唯品会JX' => '唯品会JX',
|
||||||
'支付宝' => '支付宝',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/** @var array<string,list<string>> */
|
/** @var array<string,list<string>> */
|
||||||
@ -70,15 +73,26 @@ class AccountMappingCoverage
|
|||||||
|
|
||||||
public function defaultMonth(): string
|
public function defaultMonth(): string
|
||||||
{
|
{
|
||||||
$timezone = trim((string) config('app.platform_timezone', ''));
|
try {
|
||||||
if ($timezone === '') {
|
return $this->platformNow()->subMonthNoOverflow()->format('Y-m');
|
||||||
$timezone = (string) config('app.timezone', 'UTC');
|
} 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 {
|
try {
|
||||||
return CarbonImmutable::now($timezone)->subMonthNoOverflow()->format('Y-m');
|
return CarbonImmutable::parse($snapshot['refreshed_at'], $this->platformTimezone())
|
||||||
|
->format('Y-m') !== $this->platformNow()->format('Y-m');
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -173,13 +187,13 @@ class AccountMappingCoverage
|
|||||||
return $lock->block(20, function () use ($period): array {
|
return $lock->block(20, function () use ($period): array {
|
||||||
Cache::put($this->statusCacheKey($period), [
|
Cache::put($this->statusCacheKey($period), [
|
||||||
'status' => 'refreshing',
|
'status' => 'refreshing',
|
||||||
'started_at' => now()->toDateTimeString(),
|
'started_at' => $this->platformNow()->toDateTimeString(),
|
||||||
], now()->addMinutes(self::STATUS_MINUTES));
|
], now()->addMinutes(self::STATUS_MINUTES));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$sourceKey = $this->rawCacheKey($period);
|
$sourceKey = $this->rawCacheKey($period);
|
||||||
$raw = $this->buildSourceCoverage($period);
|
$raw = $this->buildSourceCoverage($period);
|
||||||
$refreshedAt = now()->toDateTimeString();
|
$refreshedAt = $this->platformNow()->toDateTimeString();
|
||||||
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
||||||
$this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt);
|
$this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt);
|
||||||
Cache::put($this->statusCacheKey($period), [
|
Cache::put($this->statusCacheKey($period), [
|
||||||
@ -203,13 +217,106 @@ 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
|
public function markFailed(string $month, string $message): void
|
||||||
{
|
{
|
||||||
$period = $this->parseMonth($month);
|
$period = $this->normalizeRefreshKey($month);
|
||||||
Cache::put($this->statusCacheKey($period), [
|
Cache::put($this->statusCacheKey($period), [
|
||||||
'status' => 'failed',
|
'status' => 'failed',
|
||||||
'message' => $message,
|
'message' => $message,
|
||||||
'failed_at' => now()->toDateTimeString(),
|
'failed_at' => $this->platformNow()->toDateTimeString(),
|
||||||
], now()->addMinutes(self::STATUS_MINUTES));
|
], now()->addMinutes(self::STATUS_MINUTES));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -222,7 +329,12 @@ class AccountMappingCoverage
|
|||||||
$mapping = $this->coverageMappingKeys($this->store->all());
|
$mapping = $this->coverageMappingKeys($this->store->all());
|
||||||
$items = [];
|
$items = [];
|
||||||
$missingRows = 0;
|
$missingRows = 0;
|
||||||
foreach ($raw['pairs'] as $pair) {
|
$excludedRows = 0;
|
||||||
|
foreach ($this->canonicalPairs((array) ($raw['pairs'] ?? [])) as $pair) {
|
||||||
|
if (! $this->isPlatformBill($pair)) {
|
||||||
|
$excludedRows += (int) $pair['source_rows'];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if ($this->isMapped($pair, $mapping)) {
|
if ($this->isMapped($pair, $mapping)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -239,8 +351,9 @@ class AccountMappingCoverage
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'status' => $raw['status'],
|
'status' => $raw['status'],
|
||||||
|
'scope' => 'month',
|
||||||
'month' => $period,
|
'month' => $period,
|
||||||
'source_rows' => $raw['source_rows'],
|
'source_rows' => max(0, $raw['source_rows'] - $excludedRows),
|
||||||
'missing_item_count' => count($items),
|
'missing_item_count' => count($items),
|
||||||
'missing_row_count' => $missingRows,
|
'missing_row_count' => $missingRows,
|
||||||
'pending_sources' => $raw['pending_sources'],
|
'pending_sources' => $raw['pending_sources'],
|
||||||
@ -252,12 +365,65 @@ 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;
|
||||||
|
$excludedRows = 0;
|
||||||
|
|
||||||
|
foreach ($this->canonicalPairs((array) ($raw['pairs'] ?? [])) as $pair) {
|
||||||
|
if (! $this->isPlatformBill($pair)) {
|
||||||
|
$excludedRows += (int) $pair['source_rows'];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
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' => max(0, $raw['source_rows'] - $excludedRows),
|
||||||
|
'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> */
|
/** @return array<string,mixed> */
|
||||||
private function waitingPayload(string $period, string $status, string $message = ''): array
|
private function waitingPayload(string $period, string $status, string $message = ''): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'status' => $status,
|
'status' => $status,
|
||||||
'month' => $period,
|
'scope' => $period === self::ALL_SCOPE ? self::ALL_SCOPE : 'month',
|
||||||
|
'month' => $period === self::ALL_SCOPE ? null : $period,
|
||||||
'source_rows' => 0,
|
'source_rows' => 0,
|
||||||
'missing_item_count' => 0,
|
'missing_item_count' => 0,
|
||||||
'missing_row_count' => 0,
|
'missing_row_count' => 0,
|
||||||
@ -273,9 +439,10 @@ class AccountMappingCoverage
|
|||||||
/** @return array{status:string,message:string} */
|
/** @return array{status:string,message:string} */
|
||||||
private function requestRefresh(string $period): array
|
private function requestRefresh(string $period): array
|
||||||
{
|
{
|
||||||
|
$period = $this->normalizeRefreshKey($period);
|
||||||
Cache::put($this->statusCacheKey($period), [
|
Cache::put($this->statusCacheKey($period), [
|
||||||
'status' => 'refreshing',
|
'status' => 'refreshing',
|
||||||
'started_at' => now()->toDateTimeString(),
|
'started_at' => $this->platformNow()->toDateTimeString(),
|
||||||
], now()->addMinutes(self::STATUS_MINUTES));
|
], now()->addMinutes(self::STATUS_MINUTES));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -285,7 +452,7 @@ class AccountMappingCoverage
|
|||||||
$temporary = $pending . '.' . getmypid() . '.tmp';
|
$temporary = $pending . '.' . getmypid() . '.tmp';
|
||||||
$payload = json_encode([
|
$payload = json_encode([
|
||||||
'month' => $period,
|
'month' => $period,
|
||||||
'requested_at' => now()->toDateTimeString(),
|
'requested_at' => $this->platformNow()->toDateTimeString(),
|
||||||
], JSON_UNESCAPED_UNICODE);
|
], JSON_UNESCAPED_UNICODE);
|
||||||
if ($payload === false || File::put($temporary, $payload, true) === false) {
|
if ($payload === false || File::put($temporary, $payload, true) === false) {
|
||||||
throw new RuntimeException('无法写入未映射清单刷新请求。');
|
throw new RuntimeException('无法写入未映射清单刷新请求。');
|
||||||
@ -315,7 +482,7 @@ class AccountMappingCoverage
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$month = basename((string) $running, '.running');
|
$month = basename((string) $running, '.running');
|
||||||
if ($this->isValidMonth($month)) {
|
if ($this->isValidRefreshKey($month)) {
|
||||||
File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true);
|
File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -324,7 +491,7 @@ class AccountMappingCoverage
|
|||||||
sort($pendingFiles);
|
sort($pendingFiles);
|
||||||
foreach ($pendingFiles as $pending) {
|
foreach ($pendingFiles as $pending) {
|
||||||
$month = basename((string) $pending, '.pending');
|
$month = basename((string) $pending, '.pending');
|
||||||
if (! $this->isValidMonth($month)) {
|
if (! $this->isValidRefreshKey($month)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$running = $directory . DIRECTORY_SEPARATOR . $month . '.running';
|
$running = $directory . DIRECTORY_SEPARATOR . $month . '.running';
|
||||||
@ -357,7 +524,7 @@ class AccountMappingCoverage
|
|||||||
File::move($runningPath, $failed, true);
|
File::move($runningPath, $failed, true);
|
||||||
File::put($failed, json_encode([
|
File::put($failed, json_encode([
|
||||||
'month' => $month,
|
'month' => $month,
|
||||||
'failed_at' => now()->toDateTimeString(),
|
'failed_at' => $this->platformNow()->toDateTimeString(),
|
||||||
'message' => $error,
|
'message' => $error,
|
||||||
], JSON_UNESCAPED_UNICODE), true);
|
], JSON_UNESCAPED_UNICODE), true);
|
||||||
}
|
}
|
||||||
@ -368,7 +535,7 @@ class AccountMappingCoverage
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$month = basename($runningPath, '.running');
|
$month = basename($runningPath, '.running');
|
||||||
if (! $this->isValidMonth($month)) {
|
if (! $this->isValidRefreshKey($month)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
File::move(
|
File::move(
|
||||||
@ -393,7 +560,41 @@ class AccountMappingCoverage
|
|||||||
*/
|
*/
|
||||||
private function readSnapshot(string $period, string $sourceKey): ?array
|
private function readSnapshot(string $period, string $sourceKey): ?array
|
||||||
{
|
{
|
||||||
$path = $this->snapshotPath($period, $sourceKey);
|
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
|
||||||
|
{
|
||||||
if (! File::isFile($path)) {
|
if (! File::isFile($path)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -403,7 +604,7 @@ class AccountMappingCoverage
|
|||||||
if (! is_array($snapshot)
|
if (! is_array($snapshot)
|
||||||
|| (int) ($snapshot['version'] ?? 0) !== self::SNAPSHOT_VERSION
|
|| (int) ($snapshot['version'] ?? 0) !== self::SNAPSHOT_VERSION
|
||||||
|| (string) ($snapshot['month'] ?? '') !== $period
|
|| (string) ($snapshot['month'] ?? '') !== $period
|
||||||
|| (string) ($snapshot['source_key'] ?? '') !== $sourceKey
|
|| ($sourceKey !== null && (string) ($snapshot['source_key'] ?? '') !== $sourceKey)
|
||||||
|| ! is_array($snapshot['raw'] ?? null)) {
|
|| ! is_array($snapshot['raw'] ?? null)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -431,7 +632,7 @@ class AccountMappingCoverage
|
|||||||
'version' => self::SNAPSHOT_VERSION,
|
'version' => self::SNAPSHOT_VERSION,
|
||||||
'month' => $period,
|
'month' => $period,
|
||||||
'source_key' => $sourceKey,
|
'source_key' => $sourceKey,
|
||||||
'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : now()->toDateTimeString(),
|
'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : $this->platformNow()->toDateTimeString(),
|
||||||
'raw' => $raw,
|
'raw' => $raw,
|
||||||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||||
|
|
||||||
@ -472,6 +673,166 @@ class AccountMappingCoverage
|
|||||||
. $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json';
|
. $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;
|
||||||
|
$item = trim((string) $group->item);
|
||||||
|
$displayItem = $item === '' ? '(未填写账单项目)' : $item;
|
||||||
|
$platform = trim((string) $group->platform);
|
||||||
|
if ($platform === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$sourceRows += $rows;
|
||||||
|
$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{
|
* @return array{
|
||||||
* status:string,
|
* status:string,
|
||||||
@ -532,10 +893,13 @@ class AccountMappingCoverage
|
|||||||
|
|
||||||
foreach ($groups as $group) {
|
foreach ($groups as $group) {
|
||||||
$rows = (int) $group->source_rows;
|
$rows = (int) $group->source_rows;
|
||||||
$sourceRows += $rows;
|
|
||||||
$item = trim((string) $group->item);
|
$item = trim((string) $group->item);
|
||||||
$displayItem = $item === '' ? '(未填写账单项目)' : $item;
|
$displayItem = $item === '' ? '(未填写账单项目)' : $item;
|
||||||
$platform = trim((string) $group->platform);
|
$platform = trim((string) $group->platform);
|
||||||
|
if ($platform === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$sourceRows += $rows;
|
||||||
$key = $platform . "\0" . $displayItem;
|
$key = $platform . "\0" . $displayItem;
|
||||||
|
|
||||||
if (! isset($pairs[$key])) {
|
if (! isset($pairs[$key])) {
|
||||||
@ -607,7 +971,7 @@ class AccountMappingCoverage
|
|||||||
{
|
{
|
||||||
$keys = [];
|
$keys = [];
|
||||||
foreach ($rules as $rule) {
|
foreach ($rules as $rule) {
|
||||||
$platform = trim((string) ($rule['platform'] ?? ''));
|
$platform = AccountMappingPlatform::canonical((string) ($rule['platform'] ?? ''));
|
||||||
$item = trim((string) ($rule['item'] ?? ''));
|
$item = trim((string) ($rule['item'] ?? ''));
|
||||||
if ($platform === '' || $item === '') {
|
if ($platform === '' || $item === '') {
|
||||||
continue;
|
continue;
|
||||||
@ -620,7 +984,7 @@ class AccountMappingCoverage
|
|||||||
|
|
||||||
private function isMapped(array $pair, array $mapping): bool
|
private function isMapped(array $pair, array $mapping): bool
|
||||||
{
|
{
|
||||||
$platform = (string) ($pair['platform'] ?? '');
|
$platform = AccountMappingPlatform::canonical((string) ($pair['platform'] ?? ''));
|
||||||
$item = (string) ($pair['item'] ?? '');
|
$item = (string) ($pair['item'] ?? '');
|
||||||
if ($platform === '' || $item === '') {
|
if ($platform === '' || $item === '') {
|
||||||
return false;
|
return false;
|
||||||
@ -629,6 +993,77 @@ class AccountMappingCoverage
|
|||||||
return isset($mapping[$platform . '|' . $item]);
|
return isset($mapping[$platform . '|' . $item]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 清单只维护实际经营平台;资金渠道名和无法识别的店铺不进入平台账单。 */
|
||||||
|
private function isPlatformBill(array $pair): bool
|
||||||
|
{
|
||||||
|
$platform = trim((string) ($pair['platform'] ?? ''));
|
||||||
|
|
||||||
|
return $platform !== '' && $platform !== '支付宝';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 历史快照仍可能保存“淘宝”“天猫”两组;读取时统一口径并合并同名项目。
|
||||||
|
*
|
||||||
|
* @param list<array<string,mixed>> $pairs
|
||||||
|
* @return list<array<string,mixed>>
|
||||||
|
*/
|
||||||
|
private function canonicalPairs(array $pairs): array
|
||||||
|
{
|
||||||
|
$normalized = [];
|
||||||
|
foreach ($pairs as $pair) {
|
||||||
|
if (! is_array($pair)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$platform = AccountMappingPlatform::canonical((string) ($pair['platform'] ?? ''));
|
||||||
|
$item = trim((string) ($pair['item'] ?? ''));
|
||||||
|
if ($platform === '' && $item === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$pair['platform'] = $platform;
|
||||||
|
$pair['platform_label'] = $platform;
|
||||||
|
$key = $platform . "\0" . $item;
|
||||||
|
if (! isset($normalized[$key])) {
|
||||||
|
$normalized[$key] = $pair;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized[$key]['source_rows'] += (int) ($pair['source_rows'] ?? 0);
|
||||||
|
$normalized[$key]['store_count'] += (int) ($pair['store_count'] ?? 0);
|
||||||
|
$normalized[$key]['source_labels'] = array_values(array_unique(array_merge(
|
||||||
|
(array) ($normalized[$key]['source_labels'] ?? []),
|
||||||
|
(array) ($pair['source_labels'] ?? []),
|
||||||
|
)));
|
||||||
|
$normalized[$key]['raw_items'] = array_values(array_unique(array_merge(
|
||||||
|
(array) ($normalized[$key]['raw_items'] ?? []),
|
||||||
|
(array) ($pair['raw_items'] ?? []),
|
||||||
|
)));
|
||||||
|
$normalized[$key]['months'] = array_values(array_unique(array_merge(
|
||||||
|
(array) ($normalized[$key]['months'] ?? []),
|
||||||
|
(array) ($pair['months'] ?? []),
|
||||||
|
)));
|
||||||
|
if (isset($pair['month_rows']) || isset($normalized[$key]['month_rows'])) {
|
||||||
|
$monthRows = (array) ($normalized[$key]['month_rows'] ?? []);
|
||||||
|
foreach ((array) ($pair['month_rows'] ?? []) as $month => $rows) {
|
||||||
|
$monthRows[$month] = (int) ($monthRows[$month] ?? 0) + (int) $rows;
|
||||||
|
}
|
||||||
|
ksort($monthRows);
|
||||||
|
$normalized[$key]['month_rows'] = $monthRows;
|
||||||
|
$normalized[$key]['months'] = array_keys($monthRows);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($normalized as &$pair) {
|
||||||
|
if (isset($pair['months'])) {
|
||||||
|
sort($pair['months']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($pair);
|
||||||
|
|
||||||
|
return array_values($normalized);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return list<string> */
|
/** @return list<string> */
|
||||||
private function generations(string $periodsTable, string $start, string $end): array
|
private function generations(string $periodsTable, string $start, string $end): array
|
||||||
{
|
{
|
||||||
@ -710,6 +1145,21 @@ class AccountMappingCoverage
|
|||||||
return $month;
|
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
|
private function isValidMonth(string $month): bool
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
@ -719,4 +1169,19 @@ class AccountMappingCoverage
|
|||||||
return false;
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -35,7 +35,8 @@ class AccountMappingMatcher
|
|||||||
{
|
{
|
||||||
$candidates = [];
|
$candidates = [];
|
||||||
foreach ($this->store->all() as $rule) {
|
foreach ($this->store->all() as $rule) {
|
||||||
if ($this->sameText((string) $rule['platform'], $platform) && $this->sameText((string) $rule['item'], $item)) {
|
if (AccountMappingPlatform::equivalent((string) $rule['platform'], $platform)
|
||||||
|
&& $this->sameText((string) $rule['item'], $item)) {
|
||||||
$candidates[] = $rule;
|
$candidates[] = $rule;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -45,13 +46,14 @@ class AccountMappingMatcher
|
|||||||
}
|
}
|
||||||
|
|
||||||
$hits = [];
|
$hits = [];
|
||||||
$fallback = null;
|
$fallbacks = [];
|
||||||
foreach ($candidates as $rule) {
|
foreach ($candidates as $rule) {
|
||||||
$memo = trim((string) ($rule['memo'] ?? ''));
|
$memo = trim((string) ($rule['memo'] ?? ''));
|
||||||
$goods = trim((string) ($rule['goods'] ?? ''));
|
$goods = trim((string) ($rule['goods'] ?? ''));
|
||||||
|
|
||||||
if ($memo === '' && $goods === '') {
|
if ($memo === '' && $goods === '') {
|
||||||
$fallback ??= $rule;
|
$rank = AccountMappingPlatform::matchRank((string) $rule['platform'], $platform);
|
||||||
|
$fallbacks[$rank] ??= $rule;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -62,11 +64,21 @@ class AccountMappingMatcher
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$hits[] = ['rule' => $rule, 'score' => ($goods !== '' ? 2 : 0) + ($memo !== '' ? 1 : 0)];
|
$hits[] = [
|
||||||
|
'rule' => $rule,
|
||||||
|
'score' => ($goods !== '' ? 2 : 0) + ($memo !== '' ? 1 : 0),
|
||||||
|
'platform_rank' => AccountMappingPlatform::matchRank((string) $rule['platform'], $platform),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($hits !== []) {
|
if ($hits !== []) {
|
||||||
usort($hits, static fn (array $a, array $b): int => $b['score'] <=> $a['score'] ?: ((int) $a['rule']['id'] <=> (int) $b['rule']['id']));
|
usort($hits, static fn (array $a, array $b): int => (
|
||||||
|
$b['score'] <=> $a['score']
|
||||||
|
) ?: (
|
||||||
|
$a['platform_rank'] <=> $b['platform_rank']
|
||||||
|
) ?: (
|
||||||
|
(int) $a['rule']['id'] <=> (int) $b['rule']['id']
|
||||||
|
));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'rule' => $hits[0]['rule'],
|
'rule' => $hits[0]['rule'],
|
||||||
@ -75,6 +87,8 @@ class AccountMappingMatcher
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ksort($fallbacks);
|
||||||
|
$fallback = reset($fallbacks) ?: null;
|
||||||
$rule = $fallback ?? $candidates[0];
|
$rule = $fallback ?? $candidates[0];
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|||||||
48
modules/EcommerceFinance/Services/AccountMappingPlatform.php
Normal file
48
modules/EcommerceFinance/Services/AccountMappingPlatform.php
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\EcommerceFinance\Services;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 科目映射的业务平台口径。
|
||||||
|
*
|
||||||
|
* 淘宝和天猫在实际经营中按同一平台处理;规则仍保留原始平台名,
|
||||||
|
* 这样历史操作记录和精确规则不会丢失。
|
||||||
|
*/
|
||||||
|
final class AccountMappingPlatform
|
||||||
|
{
|
||||||
|
public const TAOBAO = '淘宝';
|
||||||
|
|
||||||
|
public const TMALL = '天猫';
|
||||||
|
|
||||||
|
public const TAOBAO_TMALL = '淘宝天猫';
|
||||||
|
|
||||||
|
public static function canonical(string $platform): string
|
||||||
|
{
|
||||||
|
$platform = trim($platform);
|
||||||
|
|
||||||
|
return match ($platform) {
|
||||||
|
self::TAOBAO, self::TMALL, self::TAOBAO_TMALL => self::TAOBAO_TMALL,
|
||||||
|
default => $platform,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function equivalent(string $left, string $right): bool
|
||||||
|
{
|
||||||
|
return self::canonical($left) === self::canonical($right);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 排序优先级:原平台精确匹配优先,同口径平台其次,其它平台最后。
|
||||||
|
*/
|
||||||
|
public static function matchRank(string $candidate, string $target): int
|
||||||
|
{
|
||||||
|
$candidate = trim($candidate);
|
||||||
|
$target = trim($target);
|
||||||
|
|
||||||
|
if (mb_strtolower($candidate) === mb_strtolower($target)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::equivalent($candidate, $target) ? 1 : 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
167
modules/EcommerceFinance/Services/AccountMappingSuggestion.php
Normal file
167
modules/EcommerceFinance/Services/AccountMappingSuggestion.php
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
<?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 => (
|
||||||
|
AccountMappingPlatform::matchRank((string) ($left['platform'] ?? ''), $platform)
|
||||||
|
<=> AccountMappingPlatform::matchRank((string) ($right['platform'] ?? ''), $platform)
|
||||||
|
) ?: (((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,6 +63,8 @@ final class BankBillStatementImporter
|
|||||||
$bankName = BankBillTemplateExporter::storageBankName($templateBank);
|
$bankName = BankBillTemplateExporter::storageBankName($templateBank);
|
||||||
$isHuaxiaPersonal = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
$isHuaxiaPersonal = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||||
&& $templateBank === '华夏银行个人卡';
|
&& $templateBank === '华夏银行个人卡';
|
||||||
|
$isCmbPersonal = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||||
|
&& $templateBank === '招商银行个人卡';
|
||||||
$isAgriculturalMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
$isAgriculturalMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||||
&& $templateBank === '农业银行';
|
&& $templateBank === '农业银行';
|
||||||
$isJiangnanMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
$isJiangnanMonthly = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||||||
@ -85,6 +87,8 @@ final class BankBillStatementImporter
|
|||||||
[$headerRow, $headers, $metadata] = $this->huaxiaMonthlyHeaderAndMetadata($reader);
|
[$headerRow, $headers, $metadata] = $this->huaxiaMonthlyHeaderAndMetadata($reader);
|
||||||
} elseif ($templateBank === '华夏银行个人卡') {
|
} elseif ($templateBank === '华夏银行个人卡') {
|
||||||
[$headerRow, $headers, $metadata] = $this->huaxiaPersonalHeaderAndMetadata($reader);
|
[$headerRow, $headers, $metadata] = $this->huaxiaPersonalHeaderAndMetadata($reader);
|
||||||
|
} elseif ($isCmbPersonal) {
|
||||||
|
[$headerRow, $headers, $metadata] = $this->cmbPersonalHeaderAndMetadata($reader);
|
||||||
} elseif ($templateBank === '农业银行') {
|
} elseif ($templateBank === '农业银行') {
|
||||||
[$headerRow, $headers, $metadata] = $this->agriculturalMonthlyHeaderAndMetadata($reader);
|
[$headerRow, $headers, $metadata] = $this->agriculturalMonthlyHeaderAndMetadata($reader);
|
||||||
} elseif ($templateBank === '江南农商行') {
|
} elseif ($templateBank === '江南农商行') {
|
||||||
@ -192,6 +196,10 @@ final class BankBillStatementImporter
|
|||||||
if ($isHuaxiaPersonal && $this->isHuaxiaPersonalFooterRow($cells)) {
|
if ($isHuaxiaPersonal && $this->isHuaxiaPersonalFooterRow($cells)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if ($isCmbPersonal
|
||||||
|
&& str_starts_with($this->normaliseCell($cells[0] ?? null), '#')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
$rawData = [];
|
$rawData = [];
|
||||||
foreach ($sourceIndexByKey as $sourceIndex => $columnKey) {
|
foreach ($sourceIndexByKey as $sourceIndex => $columnKey) {
|
||||||
@ -222,10 +230,11 @@ final class BankBillStatementImporter
|
|||||||
$accountNo = match (true) {
|
$accountNo = match (true) {
|
||||||
$bankName === '网商银行',
|
$bankName === '网商银行',
|
||||||
$isBocMonthly,
|
$isBocMonthly,
|
||||||
$isHuaxiaPersonal,
|
$isCmbPersonal,
|
||||||
$isAgriculturalMonthly,
|
$isAgriculturalMonthly,
|
||||||
$isJiangnanMonthly,
|
$isJiangnanMonthly,
|
||||||
$isAlipayMonthly => (string) ($metadata['account_no'] ?? ''),
|
$isAlipayMonthly => (string) ($metadata['account_no'] ?? ''),
|
||||||
|
$isHuaxiaPersonal => $this->huaxiaPersonalAccountNumber($metadata, $accountsByNumber),
|
||||||
default => $this->accountNumber($valuesByLabel),
|
default => $this->accountNumber($valuesByLabel),
|
||||||
};
|
};
|
||||||
$account = $accountsByNumber[$this->digits($accountNo)] ?? null;
|
$account = $accountsByNumber[$this->digits($accountNo)] ?? null;
|
||||||
@ -243,7 +252,7 @@ final class BankBillStatementImporter
|
|||||||
$companyName = match (true) {
|
$companyName = match (true) {
|
||||||
$bankName === '网商银行' => (string) ($metadata['company_name'] ?? ''),
|
$bankName === '网商银行' => (string) ($metadata['company_name'] ?? ''),
|
||||||
$isBocMonthly => $this->bocAccountHolderName($valuesByLabel),
|
$isBocMonthly => $this->bocAccountHolderName($valuesByLabel),
|
||||||
$isHuaxiaPersonal, $isAgriculturalMonthly => (string) ($metadata['company_name'] ?? ''),
|
$isHuaxiaPersonal, $isCmbPersonal, $isAgriculturalMonthly => (string) ($metadata['company_name'] ?? ''),
|
||||||
$isJiangnanMonthly => (string) ($account->company_name ?? ''),
|
$isJiangnanMonthly => (string) ($account->company_name ?? ''),
|
||||||
default => (string) ($metadata['company_name'] ?? $this->firstValue(
|
default => (string) ($metadata['company_name'] ?? $this->firstValue(
|
||||||
$valuesByLabel,
|
$valuesByLabel,
|
||||||
@ -309,6 +318,10 @@ final class BankBillStatementImporter
|
|||||||
$counterpartyName = $counterparty['name'];
|
$counterpartyName = $counterparty['name'];
|
||||||
$counterpartyAccount = $counterparty['account'];
|
$counterpartyAccount = $counterparty['account'];
|
||||||
$counterpartyBank = $counterparty['bank'];
|
$counterpartyBank = $counterparty['bank'];
|
||||||
|
} elseif ($isCmbPersonal) {
|
||||||
|
$counterpartyName = $this->firstValue($valuesByLabel, ['交易备注']);
|
||||||
|
$counterpartyAccount = '';
|
||||||
|
$counterpartyBank = '';
|
||||||
} else {
|
} else {
|
||||||
$counterpartyName = $this->firstValue(
|
$counterpartyName = $this->firstValue(
|
||||||
$valuesByLabel,
|
$valuesByLabel,
|
||||||
@ -355,6 +368,7 @@ final class BankBillStatementImporter
|
|||||||
'交易附言[ Remark ]',
|
'交易附言[ Remark ]',
|
||||||
'用途[ Purpose ]',
|
'用途[ Purpose ]',
|
||||||
'备注[ Remarks ]',
|
'备注[ Remarks ]',
|
||||||
|
'交易备注',
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
$currency = $bankName === '网商银行'
|
$currency = $bankName === '网商银行'
|
||||||
@ -865,11 +879,8 @@ final class BankBillStatementImporter
|
|||||||
}
|
}
|
||||||
|
|
||||||
$companyName = trim((string) ($rawMetadata['company_name'] ?? ''));
|
$companyName = trim((string) ($rawMetadata['company_name'] ?? ''));
|
||||||
$accountNo = $this->digits((string) (
|
$accountNo = $this->digits((string) ($rawMetadata['account_no'] ?? ''));
|
||||||
$rawMetadata['account_no']
|
$cardNo = $this->digits((string) ($rawMetadata['card_no'] ?? ''));
|
||||||
?? $rawMetadata['card_no']
|
|
||||||
?? ''
|
|
||||||
));
|
|
||||||
if ($accountNo === '') {
|
if ($accountNo === '') {
|
||||||
throw new InvalidArgumentException('华夏银行个人卡明细缺少“账号”或“卡号”。');
|
throw new InvalidArgumentException('华夏银行个人卡明细缺少“账号”或“卡号”。');
|
||||||
}
|
}
|
||||||
@ -881,12 +892,103 @@ final class BankBillStatementImporter
|
|||||||
'company_name' => $companyName,
|
'company_name' => $companyName,
|
||||||
'account_short' => $companyName,
|
'account_short' => $companyName,
|
||||||
'account_no' => $accountNo,
|
'account_no' => $accountNo,
|
||||||
'card_no' => $this->digits((string) ($rawMetadata['card_no'] ?? '')),
|
'card_no' => $cardNo,
|
||||||
'currency' => trim((string) ($rawMetadata['currency'] ?? '')) ?: '人民币',
|
'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>}
|
* @return array{0:int,1:array<int,string>,2:array<string,mixed>}
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -124,6 +124,15 @@ final class BankBillTemplateExporter
|
|||||||
'对方开户行',
|
'对方开户行',
|
||||||
'附言',
|
'附言',
|
||||||
],
|
],
|
||||||
|
'招商银行个人卡' => [
|
||||||
|
'交易日期',
|
||||||
|
'交易时间',
|
||||||
|
'收入',
|
||||||
|
'支出',
|
||||||
|
'余额',
|
||||||
|
'交易类型',
|
||||||
|
'交易备注',
|
||||||
|
],
|
||||||
'杭州银行' => [
|
'杭州银行' => [
|
||||||
'序号',
|
'序号',
|
||||||
'交易时间',
|
'交易时间',
|
||||||
@ -272,6 +281,7 @@ final class BankBillTemplateExporter
|
|||||||
'label' => match ($bank) {
|
'label' => match ($bank) {
|
||||||
'中国工商银行' => '工商银行 PDF 明细',
|
'中国工商银行' => '工商银行 PDF 明细',
|
||||||
'华夏银行个人卡' => '华夏银行个人卡明细',
|
'华夏银行个人卡' => '华夏银行个人卡明细',
|
||||||
|
'招商银行个人卡' => '招商银行个人卡明细',
|
||||||
'支付宝' => '支付宝账单模板',
|
'支付宝' => '支付宝账单模板',
|
||||||
'农业银行' => '农业银行明细',
|
'农业银行' => '农业银行明细',
|
||||||
default => $bank . '月度模板',
|
default => $bank . '月度模板',
|
||||||
@ -344,16 +354,18 @@ final class BankBillTemplateExporter
|
|||||||
|
|
||||||
return match ($bank) {
|
return match ($bank) {
|
||||||
'中国工商银行' => 'pdf',
|
'中国工商银行' => 'pdf',
|
||||||
'华夏银行个人卡', '农业银行', '江南农商行' => self::FORMAT_BANK_FILE,
|
'华夏银行个人卡', '招商银行个人卡', '农业银行', '江南农商行' => self::FORMAT_BANK_FILE,
|
||||||
default => 'xlsx',
|
default => 'xlsx',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function storageBankName(string $templateBank): string
|
public static function storageBankName(string $templateBank): string
|
||||||
{
|
{
|
||||||
return $templateBank === '华夏银行个人卡'
|
return match ($templateBank) {
|
||||||
? '华夏银行'
|
'华夏银行个人卡' => '华夏银行',
|
||||||
: $templateBank;
|
'招商银行个人卡' => '招商银行',
|
||||||
|
default => $templateBank,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function uploadOnlyMessage(string $bank, string $scope): ?string
|
public static function uploadOnlyMessage(string $bank, string $scope): ?string
|
||||||
|
|||||||
@ -0,0 +1,27 @@
|
|||||||
|
<?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('原因'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,200 @@
|
|||||||
|
<?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
|
||||||
|
{
|
||||||
|
if (str_contains(preg_replace('/\s+/u', '', $type) ?? '', '拦截费')) return '拦截费';
|
||||||
|
return match ($type) { '改地址费' => '改地址', '拦截','拦截退回','拦截退回运费' => '拦截费', default => $type };
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -157,6 +157,8 @@ class DingInvoiceSyncService
|
|||||||
|
|
||||||
public function latestPendingMonth(): ?string
|
public function latestPendingMonth(): ?string
|
||||||
{
|
{
|
||||||
|
$this->ensureMissingAvailableMonths();
|
||||||
|
|
||||||
$monthQuery = $this->connection->table('ding_invoice_flow_mirror')
|
$monthQuery = $this->connection->table('ding_invoice_flow_mirror')
|
||||||
->where('source_scope', $this->scope())
|
->where('source_scope', $this->scope())
|
||||||
->whereNotNull('process_instance_id')
|
->whereNotNull('process_instance_id')
|
||||||
@ -168,6 +170,73 @@ class DingInvoiceSyncService
|
|||||||
return trim((string) $month) ?: null;
|
return trim((string) $month) ?: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function ensureMissingAvailableMonths(): void
|
||||||
|
{
|
||||||
|
$schema = Schema::connection($this->connection->getName());
|
||||||
|
if (! $schema->hasTable('ding_process_payment_line_mirror')
|
||||||
|
|| ! $schema->hasTable('ding_process_detail_mirror')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$scope = $this->scope();
|
||||||
|
$query = $this->connection->table('ding_process_payment_line_mirror as payment')
|
||||||
|
->join('ding_process_detail_mirror as detail', function ($join): void {
|
||||||
|
$join->on('detail.source_scope', '=', 'payment.source_scope')
|
||||||
|
->on('detail.business_id', '=', 'payment.business_id');
|
||||||
|
})
|
||||||
|
->where('payment.source_scope', $scope)
|
||||||
|
->whereNotNull('payment.paid_month')
|
||||||
|
->where('payment.paid_month', '!=', '')
|
||||||
|
->where(
|
||||||
|
'payment.paid_month',
|
||||||
|
'>=',
|
||||||
|
(string) config('ding_invoice_data.first_supported_month', '2026-10'),
|
||||||
|
)
|
||||||
|
->where('payment.paid_month', '<=', now()->format('Y-m'));
|
||||||
|
DingInvoiceProcessScope::apply($query, 'detail');
|
||||||
|
|
||||||
|
$months = $query
|
||||||
|
->distinct()
|
||||||
|
->orderBy('payment.paid_month')
|
||||||
|
->pluck('payment.paid_month')
|
||||||
|
->map(static fn (mixed $month): string => trim((string) $month))
|
||||||
|
->filter()
|
||||||
|
->values();
|
||||||
|
$latestMonth = (string) $months->last();
|
||||||
|
|
||||||
|
foreach ($months as $month) {
|
||||||
|
$businessQuery = $this->connection->table('ding_process_payment_line_mirror as payment')
|
||||||
|
->where('payment.source_scope', $scope)
|
||||||
|
->where('payment.paid_month', $month)
|
||||||
|
->whereExists(function (Builder $exists): void {
|
||||||
|
$exists->selectRaw('1')
|
||||||
|
->from('ding_process_detail_mirror as detail')
|
||||||
|
->whereColumn('detail.source_scope', 'payment.source_scope')
|
||||||
|
->whereColumn('detail.business_id', 'payment.business_id');
|
||||||
|
DingInvoiceProcessScope::apply($exists, 'detail');
|
||||||
|
});
|
||||||
|
$businessIds = $businessQuery
|
||||||
|
->distinct()
|
||||||
|
->pluck('payment.business_id')
|
||||||
|
->map(static fn (mixed $businessId): string => trim((string) $businessId))
|
||||||
|
->filter()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
$existingBusinessIds = $this->connection->table('ding_invoice_flow_mirror')
|
||||||
|
->where('source_scope', $scope)
|
||||||
|
->whereIn('business_id', $businessIds)
|
||||||
|
->pluck('business_id')
|
||||||
|
->map(static fn (mixed $businessId): string => trim((string) $businessId))
|
||||||
|
->all();
|
||||||
|
if ($month !== $latestMonth
|
||||||
|
&& array_diff($businessIds, $existingBusinessIds) === []) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->ensureFlowsForMonth($month, $scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private function applyScanCandidates(Builder $query): void
|
private function applyScanCandidates(Builder $query): void
|
||||||
{
|
{
|
||||||
$now = now();
|
$now = now();
|
||||||
@ -245,14 +314,25 @@ class DingInvoiceSyncService
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$businessIds = $payments->pluck('business_id')->unique()->values()->all();
|
||||||
$details = $this->connection->table('ding_process_detail_mirror')
|
$details = $this->connection->table('ding_process_detail_mirror')
|
||||||
->where('source_scope', $scope)
|
->where('source_scope', $scope)
|
||||||
->whereIn('business_id', $payments->pluck('business_id')->unique()->all())
|
->whereIn('business_id', $businessIds)
|
||||||
|
->get()
|
||||||
|
->groupBy('business_id');
|
||||||
|
$allPayments = $this->connection->table('ding_process_payment_line_mirror')
|
||||||
|
->where('source_scope', $scope)
|
||||||
|
->whereIn('business_id', $businessIds)
|
||||||
|
->where(
|
||||||
|
'paid_month',
|
||||||
|
'>=',
|
||||||
|
(string) config('ding_invoice_data.first_supported_month', '2026-10'),
|
||||||
|
)
|
||||||
->get()
|
->get()
|
||||||
->groupBy('business_id');
|
->groupBy('business_id');
|
||||||
$existing = $this->connection->table('ding_invoice_flow_mirror')
|
$existing = $this->connection->table('ding_invoice_flow_mirror')
|
||||||
->where('source_scope', $scope)
|
->where('source_scope', $scope)
|
||||||
->where('paid_month', $month)
|
->whereIn('business_id', $businessIds)
|
||||||
->get()
|
->get()
|
||||||
->keyBy('business_id');
|
->keyBy('business_id');
|
||||||
$now = now();
|
$now = now();
|
||||||
@ -261,6 +341,19 @@ class DingInvoiceSyncService
|
|||||||
$businessId = trim((string) $businessId);
|
$businessId = trim((string) $businessId);
|
||||||
$detail = ($details->get($businessId) ?? collect())->first();
|
$detail = ($details->get($businessId) ?? collect())->first();
|
||||||
$current = $existing->get($businessId);
|
$current = $existing->get($businessId);
|
||||||
|
$businessAllPayments = $allPayments->get($businessId, collect());
|
||||||
|
$canonicalMonth = trim((string) (
|
||||||
|
$current?->paid_month
|
||||||
|
?: $businessAllPayments->min('paid_month')
|
||||||
|
?: ''
|
||||||
|
));
|
||||||
|
if ($canonicalMonth === '' || ($current === null && $canonicalMonth !== $month)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$canonicalPayments = $businessAllPayments
|
||||||
|
->filter(
|
||||||
|
static fn (object $payment): bool => (string) $payment->paid_month === $canonicalMonth,
|
||||||
|
);
|
||||||
$documentType = trim((string) (
|
$documentType = trim((string) (
|
||||||
$detail?->document_type
|
$detail?->document_type
|
||||||
?: $current?->document_type
|
?: $current?->document_type
|
||||||
@ -273,19 +366,19 @@ class DingInvoiceSyncService
|
|||||||
'source_scope' => $scope,
|
'source_scope' => $scope,
|
||||||
'business_id' => $businessId,
|
'business_id' => $businessId,
|
||||||
'process_instance_id' => trim((string) (
|
'process_instance_id' => trim((string) (
|
||||||
$businessPayments->firstWhere('process_instance_id', '!=', '')
|
$businessAllPayments->firstWhere('process_instance_id', '!=', '')
|
||||||
?->process_instance_id
|
?->process_instance_id
|
||||||
?? ''
|
?? ''
|
||||||
)),
|
)),
|
||||||
'paid_month' => $month,
|
'paid_month' => $canonicalMonth,
|
||||||
'title' => mb_substr($current?->title ?: ($detail?->purpose ?: ''), 0, 255) ?: null,
|
'title' => mb_substr($current?->title ?: ($detail?->purpose ?: ''), 0, 255) ?: null,
|
||||||
'originator_name' => mb_substr($current?->originator_name ?: ($detail?->originator_name ?: ''), 0, 100) ?: null,
|
'originator_name' => mb_substr($current?->originator_name ?: ($detail?->originator_name ?: ''), 0, 100) ?: null,
|
||||||
'document_type' => mb_substr($current?->document_type ?: ($detail?->document_type ?: ''), 0, 100) ?: null,
|
'document_type' => mb_substr($current?->document_type ?: ($detail?->document_type ?: ''), 0, 100) ?: null,
|
||||||
'expense_type' => mb_substr($current?->expense_type ?: ($detail?->account_name ?: ''), 0, 255) ?: null,
|
'expense_type' => mb_substr($current?->expense_type ?: ($detail?->account_name ?: ''), 0, 255) ?: null,
|
||||||
'payee_name' => mb_substr($current?->payee_name ?: ($detail?->payee_name ?: ''), 0, 255) ?: null,
|
'payee_name' => mb_substr($current?->payee_name ?: ($detail?->payee_name ?: ''), 0, 255) ?: null,
|
||||||
'paid_at' => $current?->paid_at ?: $businessPayments->min('paid_at'),
|
'paid_at' => $canonicalPayments->min('paid_at'),
|
||||||
'payment_amount' => round((float) $businessPayments->sum('amount'), 2),
|
'payment_amount' => round((float) $canonicalPayments->sum('amount'), 2),
|
||||||
'payment_total' => round((float) $businessPayments->sum('amount'), 2),
|
'payment_total' => round((float) $businessAllPayments->sum('amount'), 2),
|
||||||
'invoice_count' => (int) ($current?->invoice_count ?? 0),
|
'invoice_count' => (int) ($current?->invoice_count ?? 0),
|
||||||
'invoice_total' => (float) ($current?->invoice_total ?? 0),
|
'invoice_total' => (float) ($current?->invoice_total ?? 0),
|
||||||
'scan_status' => $current?->scan_status ?: 'pending',
|
'scan_status' => $current?->scan_status ?: 'pending',
|
||||||
|
|||||||
@ -67,7 +67,11 @@ final class FinanceLedgerBankBalanceCurrentCalculator
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$details[$accountShort] = $bill !== null
|
$useBankBillBaseline = $bill !== null
|
||||||
|
&& ($opening === null
|
||||||
|
|| substr((string) $bill['txn_date'], 0, 10)
|
||||||
|
>= substr((string) $opening->opening_date, 0, 10));
|
||||||
|
$details[$accountShort] = $useBankBillBaseline
|
||||||
? [
|
? [
|
||||||
'balance' => round((float) $bill['balance'], 2),
|
'balance' => round((float) $bill['balance'], 2),
|
||||||
'balance_source' => 'bank_bill_plus_transactions',
|
'balance_source' => 'bank_bill_plus_transactions',
|
||||||
|
|||||||
@ -904,7 +904,6 @@ final class FreightCarrierRules
|
|||||||
'mode' => 'C',
|
'mode' => 'C',
|
||||||
'first' => 3,
|
'first' => 3,
|
||||||
'coef' => 6000,
|
'coef' => 6000,
|
||||||
'overlen' => [160, 7],
|
|
||||||
'sub_fee' => 3.5,
|
'sub_fee' => 3.5,
|
||||||
],
|
],
|
||||||
'崔桥顺丰干配' => [
|
'崔桥顺丰干配' => [
|
||||||
@ -1233,6 +1232,7 @@ final class FreightCarrierRules
|
|||||||
'四强圆通' => [
|
'四强圆通' => [
|
||||||
'mode' => 'A',
|
'mode' => 'A',
|
||||||
'coef' => 10000,
|
'coef' => 10000,
|
||||||
|
'ceil' => true,
|
||||||
],
|
],
|
||||||
'木际邮政' => [
|
'木际邮政' => [
|
||||||
'mode' => 'E',
|
'mode' => 'E',
|
||||||
|
|||||||
@ -9,6 +9,7 @@ use Carbon\Carbon;
|
|||||||
use Illuminate\Database\ConnectionInterface;
|
use Illuminate\Database\ConnectionInterface;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Modules\EcommerceFinance\Repositories\LinehaulFreightRepository;
|
||||||
use Modules\EcommerceFinance\Services\Jushuitan\ShippingWeightPrecision;
|
use Modules\EcommerceFinance\Services\Jushuitan\ShippingWeightPrecision;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -39,7 +40,8 @@ class ShippingFreightService
|
|||||||
/** 已登记「请求结束后重算」的应用实例(spl_object_id)。 */
|
/** 已登记「请求结束后重算」的应用实例(spl_object_id)。 */
|
||||||
private static ?int $flushRegisteredFor = null;
|
private static ?int $flushRegisteredFor = null;
|
||||||
|
|
||||||
public function __construct(private readonly ShippingFreightCalculator $calculator, private readonly ReturnRouteFreightCalculator $returnRoutes)
|
public function __construct(private readonly ShippingFreightCalculator $calculator, private readonly ReturnRouteFreightCalculator $returnRoutes,
|
||||||
|
private readonly LinehaulFreightRepository $linehaul)
|
||||||
{
|
{
|
||||||
$this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
$this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
||||||
}
|
}
|
||||||
@ -157,6 +159,9 @@ class ShippingFreightService
|
|||||||
}
|
}
|
||||||
$name = trim((string) ($pkg['express_name1'] ?? ''));
|
$name = trim((string) ($pkg['express_name1'] ?? ''));
|
||||||
$name = FreightCarrierRules::ALIAS[$name] ?? $name;
|
$name = FreightCarrierRules::ALIAS[$name] ?? $name;
|
||||||
|
if (LinehaulFreightRepository::supports($name)) {
|
||||||
|
return $this->calculateLinehaul($pkg);
|
||||||
|
}
|
||||||
if (ReturnRouteFreightCalculator::supports($name)) {
|
if (ReturnRouteFreightCalculator::supports($name)) {
|
||||||
return $this->calculateReturnRoute($pkg, $name);
|
return $this->calculateReturnRoute($pkg, $name);
|
||||||
}
|
}
|
||||||
@ -175,6 +180,26 @@ class ShippingFreightService
|
|||||||
return $this->calculator->calculate($pkg, $this->quoteAt($name, substr((string) $pkg['ship_time'], 0, 10)), $cfg);
|
return $this->calculator->calculate($pkg, $this->quoteAt($name, substr((string) $pkg['ship_time'], 0, 10)), $cfg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function calculateLinehaul(array $pkg): array
|
||||||
|
{
|
||||||
|
$match = $pkg['linehaul'] ?? ($this->linehaul->forPackages([$pkg])[(int) $pkg['source_id']]);
|
||||||
|
$result = self::zeroResult('');
|
||||||
|
$result['mode'] = 'LINEHAUL';
|
||||||
|
$result['fee'] = null;
|
||||||
|
if ($match['error'] !== null) {
|
||||||
|
$result['status'] = $match['error'];
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
$row = $match['row'];
|
||||||
|
$result['fee'] = round((float) $row['FreightNew'], 2);
|
||||||
|
$result['formula'] = '工作平台专线运费:出库单 ' . $row['Id'] . ',逐包分摊运费 '
|
||||||
|
. ShippingFreightCalculator::fmt($result['fee']) . ' 元'
|
||||||
|
. (trim((string) $row['combsgn']) !== '' ? ';组合号 ' . $row['combsgn'] : '')
|
||||||
|
. (trim((string) $row['status']) !== '' ? ';' . $row['status'] : '');
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
private function calculateReturnRoute(array $pkg, string $carrier): array
|
private function calculateReturnRoute(array $pkg, string $carrier): array
|
||||||
{
|
{
|
||||||
// 复用落库字段;返货按吨/方取高,不套用普通快递计泡系数。
|
// 复用落库字段;返货按吨/方取高,不套用普通快递计泡系数。
|
||||||
@ -386,6 +411,14 @@ class ShippingFreightService
|
|||||||
}
|
}
|
||||||
unset($pkg);
|
unset($pkg);
|
||||||
|
|
||||||
|
$linehaul = $this->linehaul->forPackages($out);
|
||||||
|
foreach ($out as &$pkg) {
|
||||||
|
if (isset($linehaul[$pkg['source_id']])) {
|
||||||
|
$pkg['linehaul'] = $linehaul[$pkg['source_id']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($pkg);
|
||||||
|
|
||||||
return $out;
|
return $out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -7,6 +7,34 @@ use Illuminate\Validation\ValidationException;
|
|||||||
/** 按字段定义校验并整理按表维护/导入的字段值。 */
|
/** 按字段定义校验并整理按表维护/导入的字段值。 */
|
||||||
class PayablesFieldNormalizer
|
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 */
|
/** @param array<string,array{label:string,type:string}> $fields */
|
||||||
public function normalize(array $fields, array $input): array
|
public function normalize(array $fields, array $input): array
|
||||||
{
|
{
|
||||||
|
|||||||
@ -212,7 +212,7 @@ class PayablesFinalImportRunner
|
|||||||
unset($values['_action_key'], $values['__import_row_key']);
|
unset($values['_action_key'], $values['__import_row_key']);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$normalized = $this->normalizer->normalize($fields, $values);
|
$normalized = $this->normalizer->normalizeImport($fields, $values);
|
||||||
} catch (ValidationException $exception) {
|
} catch (ValidationException $exception) {
|
||||||
$this->fail($meta, $line - 1, $created, $updated, $this->rowMessage($firstRow, $line, $exception));
|
$this->fail($meta, $line - 1, $created, $updated, $this->rowMessage($firstRow, $line, $exception));
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
|
|||||||
@ -99,7 +99,7 @@ class PayablesFinalImporter
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$values = $this->normalizer->normalize($fields, $rawValues);
|
$values = $this->normalizer->normalizeImport($fields, $rawValues);
|
||||||
} catch (ValidationException $exception) {
|
} catch (ValidationException $exception) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),
|
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),
|
||||||
|
|||||||
@ -5,8 +5,8 @@ namespace Modules\EcommerceFinance\Services;
|
|||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「终版」目录的按表数据登记:确定每个页签的字段(决定导入模板与表格列)
|
* 按表维护的数据登记:确定终版页签和快递记账明细的字段、标题与存储键。
|
||||||
* 以及数据标题;数据本身独立存放,与基础目录互不影响。
|
* 各目录的数据独立存放。
|
||||||
*/
|
*/
|
||||||
class PayablesFinalRegistry
|
class PayablesFinalRegistry
|
||||||
{
|
{
|
||||||
@ -14,6 +14,8 @@ class PayablesFinalRegistry
|
|||||||
|
|
||||||
public const SECTION_COURIER = 'courier-payables-final';
|
public const SECTION_COURIER = 'courier-payables-final';
|
||||||
|
|
||||||
|
public const SECTION_COURIER_BASE = 'courier-payables';
|
||||||
|
|
||||||
/** @var array<string,string> 供应商应付(终版)页签 */
|
/** @var array<string,string> 供应商应付(终版)页签 */
|
||||||
private const SUPPLIER_TITLES = [
|
private const SUPPLIER_TITLES = [
|
||||||
'product-prices' => '商品价格',
|
'product-prices' => '商品价格',
|
||||||
@ -117,6 +119,7 @@ class PayablesFinalRegistry
|
|||||||
private readonly SupplierPayableMaintenanceRegistry $supplier,
|
private readonly SupplierPayableMaintenanceRegistry $supplier,
|
||||||
private readonly ProductPriceWorkbookImporter $productPrices,
|
private readonly ProductPriceWorkbookImporter $productPrices,
|
||||||
private readonly CourierPayableFinalRegistry $courier,
|
private readonly CourierPayableFinalRegistry $courier,
|
||||||
|
private readonly CourierBookkeepingRegistry $bookkeeping,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -131,6 +134,7 @@ class PayablesFinalRegistry
|
|||||||
return match ($section) {
|
return match ($section) {
|
||||||
self::SECTION_SUPPLIER => self::SUPPLIER_TITLES,
|
self::SECTION_SUPPLIER => self::SUPPLIER_TITLES,
|
||||||
self::SECTION_COURIER => $this->courier->titles(),
|
self::SECTION_COURIER => $this->courier->titles(),
|
||||||
|
self::SECTION_COURIER_BASE => ['bookkeeping-details' => '记账明细'],
|
||||||
default => [],
|
default => [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -139,7 +143,7 @@ class PayablesFinalRegistry
|
|||||||
{
|
{
|
||||||
$titles = $this->titles($section);
|
$titles = $this->titles($section);
|
||||||
if (! array_key_exists($dataset, $titles)) {
|
if (! array_key_exists($dataset, $titles)) {
|
||||||
throw ValidationException::withMessages(['dataset' => '不支持该终版目录页面。']);
|
throw ValidationException::withMessages(['dataset' => '不支持该数据维护页面。']);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $titles[$dataset];
|
return $titles[$dataset];
|
||||||
@ -150,6 +154,10 @@ class PayablesFinalRegistry
|
|||||||
{
|
{
|
||||||
$this->title($section, $dataset);
|
$this->title($section, $dataset);
|
||||||
|
|
||||||
|
if ($section === self::SECTION_COURIER_BASE) {
|
||||||
|
return self::MONTH_FIELD + $this->bookkeeping->fields();
|
||||||
|
}
|
||||||
|
|
||||||
if ($section === self::SECTION_COURIER) {
|
if ($section === self::SECTION_COURIER) {
|
||||||
return self::MONTH_FIELD + $this->courier->fields($dataset);
|
return self::MONTH_FIELD + $this->courier->fields($dataset);
|
||||||
}
|
}
|
||||||
@ -169,6 +177,17 @@ class PayablesFinalRegistry
|
|||||||
return self::MONTH_FIELD + $this->patchSupplierFields($dataset, $fields);
|
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
|
* @param array<string,array{label:string,type:string}> $fields
|
||||||
* @return array<string,array{label:string,type:string}>
|
* @return array<string,array{label:string,type:string}>
|
||||||
|
|||||||
@ -298,12 +298,14 @@ final class PerformanceDetailSubjectMatcher
|
|||||||
|
|
||||||
private function rowDate(object $row): string
|
private function rowDate(object $row): string
|
||||||
{
|
{
|
||||||
$date = trim((string) ($row->occurred_date ?? ''));
|
foreach (['occurred_date', 'occurred_at', 'report_month'] as $property) {
|
||||||
if ($date !== '') {
|
$date = trim((string) ($row->{$property} ?? ''));
|
||||||
return substr($date, 0, 10);
|
if ($date !== '') {
|
||||||
|
return substr($date, 0, 10);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return substr(trim((string) ($row->report_month ?? '')), 0, 10);
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
private function normalize(mixed $value): string
|
private function normalize(mixed $value): string
|
||||||
|
|||||||
@ -17,10 +17,11 @@ use Throwable;
|
|||||||
class PlantingReimbursementRobot
|
class PlantingReimbursementRobot
|
||||||
{
|
{
|
||||||
public const SETTING_KEY = 'planting_reimbursement.robot';
|
public const SETTING_KEY = 'planting_reimbursement.robot';
|
||||||
|
public const CANCEL_NOTICES_ENABLED_KEY = 'planting_reimbursement.cancel_notices_enabled';
|
||||||
|
|
||||||
public function __construct(private readonly PlantingReimbursementDirectory $directory) {}
|
public function __construct(private readonly PlantingReimbursementDirectory $directory) {}
|
||||||
|
|
||||||
/** @return array{webhook:string,secret:string,keyword:string,reporters:list<string>,digest_webhook:string,digest_secret:string} */
|
/** @return array{webhook:string,secret:string,keyword:string,reporters:list<string>,digest_webhook:string,digest_secret:string,cancel_notices_enabled:bool} */
|
||||||
public function config(): array
|
public function config(): array
|
||||||
{
|
{
|
||||||
$value = setting(self::SETTING_KEY, []);
|
$value = setting(self::SETTING_KEY, []);
|
||||||
@ -36,9 +37,17 @@ class PlantingReimbursementRobot
|
|||||||
'reporters' => array_values(array_filter(array_map('trim', (array) ($value['reporters'] ?? [])))),
|
'reporters' => array_values(array_filter(array_map('trim', (array) ($value['reporters'] ?? [])))),
|
||||||
'digest_webhook' => $this->decrypt($value['digest_webhook'] ?? ''),
|
'digest_webhook' => $this->decrypt($value['digest_webhook'] ?? ''),
|
||||||
'digest_secret' => $this->decrypt($value['digest_secret'] ?? ''),
|
'digest_secret' => $this->decrypt($value['digest_secret'] ?? ''),
|
||||||
|
'cancel_notices_enabled' => $this->cancelNoticesEnabled(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function cancelNoticesEnabled(): bool
|
||||||
|
{
|
||||||
|
$value = strtolower(trim((string) setting(self::CANCEL_NOTICES_ENABLED_KEY, '0')));
|
||||||
|
|
||||||
|
return in_array($value, ['1', 'true', 'on', 'yes'], true);
|
||||||
|
}
|
||||||
|
|
||||||
public function enabled(): bool
|
public function enabled(): bool
|
||||||
{
|
{
|
||||||
return $this->config()['webhook'] !== '';
|
return $this->config()['webhook'] !== '';
|
||||||
@ -57,13 +66,14 @@ class PlantingReimbursementRobot
|
|||||||
'reporters' => implode(',', $config['reporters']),
|
'reporters' => implode(',', $config['reporters']),
|
||||||
'digest_webhook' => $this->mask($config['digest_webhook']),
|
'digest_webhook' => $this->mask($config['digest_webhook']),
|
||||||
'has_digest_secret' => $config['digest_secret'] !== '',
|
'has_digest_secret' => $config['digest_secret'] !== '',
|
||||||
|
'cancel_notices_enabled' => $config['cancel_notices_enabled'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存设置。Webhook / 密钥留空表示沿用原值。
|
* 保存设置。Webhook / 密钥留空表示沿用原值。
|
||||||
*
|
*
|
||||||
* @param array{webhook?:string,secret?:string,keyword?:string,reporters?:string,digest_webhook?:string,digest_secret?:string,clear_digest?:bool} $input
|
* @param array{webhook?:string,secret?:string,keyword?:string,reporters?:string,digest_webhook?:string,digest_secret?:string,clear_digest?:bool,cancel_notices_enabled?:bool} $input
|
||||||
*/
|
*/
|
||||||
public function save(array $input): void
|
public function save(array $input): void
|
||||||
{
|
{
|
||||||
@ -92,6 +102,9 @@ class PlantingReimbursementRobot
|
|||||||
'digest_webhook' => $digestWebhook !== '' ? Crypt::encryptString($digestWebhook) : '',
|
'digest_webhook' => $digestWebhook !== '' ? Crypt::encryptString($digestWebhook) : '',
|
||||||
'digest_secret' => $digestSecret !== '' ? Crypt::encryptString($digestSecret) : '',
|
'digest_secret' => $digestSecret !== '' ? Crypt::encryptString($digestSecret) : '',
|
||||||
], JSON_UNESCAPED_UNICODE));
|
], JSON_UNESCAPED_UNICODE));
|
||||||
|
if (array_key_exists('cancel_notices_enabled', $input)) {
|
||||||
|
setting()->set(self::CANCEL_NOTICES_ENABLED_KEY, $input['cancel_notices_enabled'] ? '1' : '0');
|
||||||
|
}
|
||||||
setting()->save();
|
setting()->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,6 +116,10 @@ class PlantingReimbursementRobot
|
|||||||
*/
|
*/
|
||||||
public function sendNotices(int $companyId, string $date, array $notices, bool $force = false): array
|
public function sendNotices(int $companyId, string $date, array $notices, bool $force = false): array
|
||||||
{
|
{
|
||||||
|
if (! $this->cancelNoticesEnabled()) {
|
||||||
|
return ['sent' => 0, 'skipped' => count($notices), 'failed' => 0, 'unmatched' => []];
|
||||||
|
}
|
||||||
|
|
||||||
$config = $this->config();
|
$config = $this->config();
|
||||||
if ($config['webhook'] === '') {
|
if ($config['webhook'] === '') {
|
||||||
throw new RuntimeException('还没配置钉钉群机器人。');
|
throw new RuntimeException('还没配置钉钉群机器人。');
|
||||||
|
|||||||
@ -19,7 +19,7 @@ use Throwable;
|
|||||||
class PlantingReimbursementWorkbench
|
class PlantingReimbursementWorkbench
|
||||||
{
|
{
|
||||||
/** 收款人不在花名册也照常报销的例外。 */
|
/** 收款人不在花名册也照常报销的例外。 */
|
||||||
public const ROSTER_EXCEPTIONS = ['柴嘉伟(建行)', '柴嘉伟'];
|
public const ROSTER_EXCEPTIONS = ['柴嘉伟(建行)', '柴嘉伟', '蔡明君'];
|
||||||
|
|
||||||
/** 聚水潭订单镜像(ERP订单标签兜底)。 */
|
/** 聚水潭订单镜像(ERP订单标签兜底)。 */
|
||||||
public const ERP_ORDER_TABLE = 'ops_jst_qmcust_orders';
|
public const ERP_ORDER_TABLE = 'ops_jst_qmcust_orders';
|
||||||
|
|||||||
137
modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php
Normal file
137
modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\EcommerceFinance\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/** 按进仓时间同步商品级退回件;分页落暂存表,完整校验后才发布新快照。 */
|
||||||
|
class ReturnedParcelSynchronizer
|
||||||
|
{
|
||||||
|
public const DATASET = 'derived.courier-returned-parcels';
|
||||||
|
public const START = '2026-10-01';
|
||||||
|
public const TABLE = 'courier_returned_parcels';
|
||||||
|
public const STAGE = 'courier_returned_parcels_stage';
|
||||||
|
|
||||||
|
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
|
||||||
|
|
||||||
|
public function sync(string $from, string $to, ?callable $progress = null, int $batchSize = 2000): array
|
||||||
|
{
|
||||||
|
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
$until = Carbon::parse($to, 'Asia/Shanghai')->addDay()->toDateString();
|
||||||
|
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
|
||||||
|
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
|
||||||
|
$resume = $state && in_array($state->status, ['running', 'failed'], true)
|
||||||
|
&& is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to;
|
||||||
|
$generation = $resume ? $state->generation : (string) Str::uuid();
|
||||||
|
$last = $resume ? (int) $cursor['last_id'] : 0;
|
||||||
|
$batchSize = min(max($batchSize, 1), 2000);
|
||||||
|
$started = microtime(true);
|
||||||
|
$base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo + rpt.jst_returnAndRefundItem',
|
||||||
|
'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation,
|
||||||
|
'last_attempted_at' => now(), 'last_error_code' => null, 'updated_at' => now()];
|
||||||
|
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => self::DATASET], $base +
|
||||||
|
($state ? [] : ['created_at' => now()]));
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (! $resume) $db->table(self::STAGE)->delete();
|
||||||
|
$expected = $this->sourceCount($from, $until);
|
||||||
|
while (true) {
|
||||||
|
$items = $this->items($from, $until, $last, $batchSize);
|
||||||
|
if ($items === []) break;
|
||||||
|
$headers = $this->headers(array_values(array_unique(array_column($items, 'as_id'))));
|
||||||
|
$rows = [];
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$header = $headers[(string) $item['as_id']] ?? null;
|
||||||
|
if ($header === null) throw new RuntimeException('missing_after_sales_header');
|
||||||
|
$rows[] = $this->row($item, $header, $generation);
|
||||||
|
}
|
||||||
|
$last = (int) end($items)['Id'];
|
||||||
|
$db->transaction(function () use ($db, $rows, $last, $generation, $from, $to): void {
|
||||||
|
foreach (array_chunk($rows, 400) as $part) {
|
||||||
|
$db->table(self::STAGE)->upsert($part, ['source_id'], array_keys($part[0]));
|
||||||
|
}
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||||
|
'cursor' => json_encode(['from' => $from, 'to' => $to, 'last_id' => $last]),
|
||||||
|
'last_upserted_rows' => $db->table(self::STAGE)->where('generation', $generation)->count(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
$progress && $progress($db->table(self::STAGE)->where('generation', $generation)->count(), $expected);
|
||||||
|
if (count($items) < $batchSize) break;
|
||||||
|
}
|
||||||
|
$count = $db->table(self::STAGE)->where('generation', $generation)->count();
|
||||||
|
if ($count !== $expected || $count !== $this->sourceCount($from, $until)) {
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]);
|
||||||
|
throw new RuntimeException('source_count_changed_retry_required');
|
||||||
|
}
|
||||||
|
// 同一事务替换范围,失败或中断不影响页面上一版;只操作派生镜像。
|
||||||
|
$db->transaction(function () use ($db, $from, $until, $generation, $count): void {
|
||||||
|
$db->table(self::TABLE)->where('received_at', '>=', $from)->where('received_at', '<', $until)->delete();
|
||||||
|
$columns = $db->getSchemaBuilder()->getColumnListing(self::TABLE);
|
||||||
|
$db->table(self::TABLE)->insertUsing($columns, $db->table(self::STAGE)->select($columns)->where('generation', $generation));
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||||
|
'status' => 'succeeded', 'cursor' => null, 'initial_completed_at' => now(),
|
||||||
|
'last_succeeded_at' => now(), 'last_full_succeeded_at' => now(),
|
||||||
|
'window_started_at' => $from, 'window_ends_at' => $until,
|
||||||
|
'last_upserted_rows' => $count, 'mirror_row_count' => $db->table(self::TABLE)->count(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
$db->table(self::STAGE)->where('generation', $generation)->delete();
|
||||||
|
});
|
||||||
|
return ['rows' => $count, 'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2),
|
||||||
|
'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)];
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
|
||||||
|
'status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function sourceCount(string $from, string $until): int
|
||||||
|
{
|
||||||
|
return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.jst_returnAndRefundItem WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function items(string $from, string $until, int $last, int $limit): array
|
||||||
|
{
|
||||||
|
return $this->upstream()->select('SELECT TOP (' . $limit . ') Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,'
|
||||||
|
. 'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.jst_returnAndRefundItem'
|
||||||
|
. ' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime) AND Id > ? ORDER BY Id', [$from, $until, $last]);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function headers(array $ids): array
|
||||||
|
{
|
||||||
|
$rows = $this->upstream()->select('SELECT Id,as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,'
|
||||||
|
. 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),updateTime,126) AS updateTime'
|
||||||
|
. ' FROM rpt.jst_returnAndRefundInfo WHERE as_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')', $ids);
|
||||||
|
$headers = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$key = (string) $row['as_id'];
|
||||||
|
if (! isset($headers[$key]) || (int) $row['Id'] > (int) $headers[$key]['Id']) $headers[$key] = $row;
|
||||||
|
}
|
||||||
|
return $headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function upstream(): UpstreamReadOnlyQuery
|
||||||
|
{
|
||||||
|
return $this->queries->forSourceWithTimeout('operations_replica', 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function row(array $i, array $h, string $generation): array
|
||||||
|
{
|
||||||
|
return ['source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'],
|
||||||
|
'received_at' => $i['receive_date'], 'online_after_sales_no' => $h['outer_as_id'],
|
||||||
|
'order_id' => $h['o_id'], 'online_order_no' => $h['so_id'], 'waybill' => $h['l_id'],
|
||||||
|
'courier' => $h['logistics_company'], 'shop' => $h['shop_name'], 'warehouse' => $h['warehouse'],
|
||||||
|
'sku' => $i['sku_id'], 'style_code' => $i['i_id'], 'product_name' => $i['name'], 'properties' => $i['properties_value'],
|
||||||
|
'applied_qty' => $i['qty'], 'returned_qty' => $i['r_qty'], 'price' => $i['price'], 'item_amount' => $i['amount'],
|
||||||
|
'order_refund' => $h['refund'], 'status' => $h['status'], 'type' => $h['type'], 'goods_status' => $h['good_status'],
|
||||||
|
'reason' => $h['question_type'], 'remark' => trim(($h['remark'] ?? '') . "\n" . ($i['remark'] ?? '')),
|
||||||
|
'source_updated_at' => $h['updateTime'], 'generation' => $generation, 'synced_at' => now()];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -63,24 +63,26 @@ class SupplierBookkeepingValuation
|
|||||||
{
|
{
|
||||||
[$from, $to] = Repository::window($row);
|
[$from, $to] = Repository::window($row);
|
||||||
$row['valuation_window'] = substr($from, 0, 7) . ' 至 ' . substr((string) $row['started_at'], 0, 7);
|
$row['valuation_window'] = substr($from, 0, 7) . ' 至 ' . substr((string) $row['started_at'], 0, 7);
|
||||||
$month = \Illuminate\Support\Carbon::parse($from);
|
$missingMonth = Repository::missingMonth($row, $readyMonths);
|
||||||
while ($month->format('Y-m-d H:i:s') < $to) {
|
|
||||||
if (!in_array($month->format('Y-m'), $readyMonths, true)) return $this->review($row, '六个月发货文件尚未补齐:' . $month->format('Y-m'));
|
|
||||||
$month->addMonth();
|
|
||||||
}
|
|
||||||
$tracking = Repository::numbers($row['tracking_no'] ?? '');
|
$tracking = Repository::numbers($row['tracking_no'] ?? '');
|
||||||
$orders = Repository::numbers($row['online_order_no'] ?? '');
|
$orders = Repository::numbers($row['online_order_no'] ?? '');
|
||||||
|
if ($missingMonth !== null && $tracking === []) return $this->review($row, '六个月发货文件尚未补齐:' . $missingMonth);
|
||||||
$pool = [];
|
$pool = [];
|
||||||
foreach ($tracking !== [] ? $tracking : $orders as $number) {
|
foreach ($tracking !== [] ? $tracking : $orders as $number) {
|
||||||
foreach (($tracking !== [] ? $byTracking : $byOrder)[$number] ?? [] as $shipment) {
|
foreach (($tracking !== [] ? $byTracking : $byOrder)[$number] ?? [] as $shipment) {
|
||||||
|
// 已完整导入的账期保持原路径;缺文件时仅接受按明确快递号匹配的自动同步包裹。
|
||||||
|
if (($missingMonth !== null) !== (($shipment['valuation_source'] ?? '') === 'synced')) continue;
|
||||||
if ($shipment['ship_time'] !== null && ($shipment['ship_time'] < $from || $shipment['ship_time'] >= $to)) continue;
|
if ($shipment['ship_time'] !== null && ($shipment['ship_time'] < $from || $shipment['ship_time'] >= $to)) continue;
|
||||||
if ($tracking !== [] && $orders !== [] && array_intersect($shipment['order_numbers'] ?? [(string) $shipment['trade_no']], $orders) === []) continue;
|
if ($tracking !== [] && $orders !== [] && array_intersect($shipment['order_numbers'] ?? [(string) $shipment['trade_no']], $orders) === []) continue;
|
||||||
$pool[$shipment['id']] = $shipment;
|
$pool[$shipment['id']] = $shipment;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($pool === []) return $this->review($row, '六个月内未匹配到原订单/快递单号的发货记录');
|
if ($pool === []) return $this->review($row, $missingMonth === null
|
||||||
|
? '六个月内未匹配到原订单/快递单号的发货记录'
|
||||||
|
: '六个月发货文件尚未补齐:' . $missingMonth . ';同步发货明细未匹配到原快递单号');
|
||||||
$unshippedPackages = [];
|
$unshippedPackages = [];
|
||||||
foreach ($pool as $shipment) {
|
foreach ($pool as $shipment) {
|
||||||
|
if (isset($shipment['valuation_error'])) return $this->review($row, $shipment['valuation_error']);
|
||||||
$flag = trim((string) ($shipment['unshipped'] ?? ''));
|
$flag = trim((string) ($shipment['unshipped'] ?? ''));
|
||||||
// 工作平台导出的查找辅助列:#N/A 未命中名单,返回单号则确实未发出。
|
// 工作平台导出的查找辅助列:#N/A 未命中名单,返回单号则确实未发出。
|
||||||
if ($flag === '' || $flag === '#N/A') continue;
|
if ($flag === '' || $flag === '#N/A') continue;
|
||||||
@ -203,6 +205,7 @@ class SupplierBookkeepingValuation
|
|||||||
if ($estimatedPackages !== []) $basis .= ';原单运费缺失或为0,按商品成本×0.2替代运费';
|
if ($estimatedPackages !== []) $basis .= ';原单运费缺失或为0,按商品成本×0.2替代运费';
|
||||||
}
|
}
|
||||||
if ($usedBundleQuantity) $basis .= ';组合装按各条码1件计';
|
if ($usedBundleQuantity) $basis .= ';组合装按各条码1件计';
|
||||||
|
if ($missingMonth !== null) $basis .= ';按系统同步发货明细核价(原快递单号完整匹配)';
|
||||||
$row['deduction_basis'] .= ';' . $basis;
|
$row['deduction_basis'] .= ';' . $basis;
|
||||||
$row['remark'] = trim((string) ($row['remark'] ?? '')) === '' ? $basis : $row['remark'] . "\n" . $basis;
|
$row['remark'] = trim((string) ($row['remark'] ?? '')) === '' ? $basis : $row['remark'] . "\n" . $basis;
|
||||||
if (bccomp((string) $row['amount'], '0', 2) === 0) $row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_SKIP;
|
if (bccomp((string) $row['amount'], '0', 2) === 0) $row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_SKIP;
|
||||||
|
|||||||
@ -683,6 +683,9 @@ class SupplierDingTalkNotifier
|
|||||||
if ($version > 1) {
|
if ($version > 1) {
|
||||||
$lines[] = '- 本次为第 **' . $version . '** 次推送,以本次为准,之前的链接作废';
|
$lines[] = '- 本次为第 **' . $version . '** 次推送,以本次为准,之前的链接作废';
|
||||||
}
|
}
|
||||||
|
if (isset($summary['total'])) {
|
||||||
|
$lines[] = '- 含费用调整合计:**¥' . number_format((float)$summary['total'], 2) . '**,费用明细见确认页';
|
||||||
|
}
|
||||||
array_push($lines, '', '#### [打开运费确认页](' . $url . ')',
|
array_push($lines, '', '#### [打开运费确认页](' . $url . ')',
|
||||||
'- 逐单核对;对哪一单有异议,就在那一单勾选「有异议」并写原因,没有异议直接点「确认无异议」。',
|
'- 逐单核对;对哪一单有异议,就在那一单勾选「有异议」并写原因,没有异议直接点「确认无异议」。',
|
||||||
'- 提交后结果实时回传财务系统,并在本群发送回执。', '',
|
'- 提交后结果实时回传财务系统,并在本群发送回执。', '',
|
||||||
@ -723,6 +726,36 @@ class SupplierDingTalkNotifier
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function pushFreightConfirmation(string $name, string $month, array $summary, int $version, string $url): void
|
||||||
|
{
|
||||||
|
[$webhook,$config]=$this->robotFor($name,'dingtalk_freight_confirmation');
|
||||||
|
$text='### 快递账单对账确认 · '.$name."\n- 账期:**".$this->displayMonth($month).'**'
|
||||||
|
."\n- 账单运费:¥".number_format($summary['bill'],2)."\n- 应结运费:¥".number_format($summary['settle'],2)
|
||||||
|
."\n- 含费用调整合计:¥".number_format($summary['total'],2)."\n- 第 **".$version.'** 次推送,之前的链接作废'
|
||||||
|
."\n\n#### [打开运费确认页](".$url.")\n请核对本组账单,无异议请确认,有异议请逐单写明原因。结果会实时回传财务系统。";
|
||||||
|
$this->send($webhook,trim((string)($config['secret']??'')),(bool)($config['at_all']??false),$name.' · 快递账单确认',$text);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendFreightConfirmationReceipt(string $name,string $month,float $settle,array $disputes): bool
|
||||||
|
{
|
||||||
|
[$webhook,$config]=$this->robotFor($name,'dingtalk_freight_receipt');
|
||||||
|
$text='### 快递账单确认回执 · '.$name."\n- 账期:".$this->displayMonth($month)."\n- 应结运费:¥".number_format($settle,2)
|
||||||
|
."\n- 结果:".($disputes===[]?'确认无异议':'有异议 '.count($disputes).' 单,等待财务核实');
|
||||||
|
foreach(array_slice($disputes,0,10,true) as $waybill=>$reason)$text.="\n- ".$waybill.':'.mb_substr(str_replace(["\r","\n"],' ',$reason),0,100);
|
||||||
|
$this->send($webhook,trim((string)($config['secret']??'')),(bool)($config['at_all']??false),$name.' · 快递账单确认回执',$text);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendFreightReview(string $name,string $kind,string $month,int $version,array $review): void
|
||||||
|
{
|
||||||
|
[$webhook,$config]=$this->robotFor($name,'dingtalk_freight_review');
|
||||||
|
$text='### '.($kind==='dropship'?'代发运费':'快递账单').'异议处理 · '.$name."\n- 账期:".$this->displayMonth($month).' · V'.$version
|
||||||
|
."\n- 单号:".$review['waybill']."\n- 结果:".($review['decision']==='accept'?'采纳复核结果':'不采纳')
|
||||||
|
."\n- 财务回复:".str_replace(["\r","\n"],' ',$review['reply'])
|
||||||
|
."\n- 金额如有调整,以财务重新推送的新版账单为准。";
|
||||||
|
$this->send($webhook,trim((string)($config['secret']??'')),(bool)($config['at_all']??false),$name.' · 运费异议处理',$text);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return array{0:string,1:array<string,mixed>} */
|
/** @return array{0:string,1:array<string,mixed>} */
|
||||||
private function robotFor(string $supplier, string $field): array
|
private function robotFor(string $supplier, string $field): array
|
||||||
{
|
{
|
||||||
@ -904,9 +937,7 @@ class SupplierDingTalkNotifier
|
|||||||
'### 货款对账差异通知 · ' . $supplier,
|
'### 货款对账差异通知 · ' . $supplier,
|
||||||
'- 对账月份:' . ($month !== '' ? $month : '全部月份'),
|
'- 对账月份:' . ($month !== '' ? $month : '全部月份'),
|
||||||
'- 对账人:' . ($reconciler !== '' ? $reconciler : '全部'),
|
'- 对账人:' . ($reconciler !== '' ? $reconciler : '全部'),
|
||||||
'- 差异共 **' . $summary['count'] . '** 条(厂家多 ' . $summary['extra']
|
'- 差异共 **' . $summary['count'] . '** 条',
|
||||||
. ' / 数量金额不一致 ' . $summary['mismatch'] . ' / 厂家少 ' . $summary['missing']
|
|
||||||
. ' / 未定价 ' . $summary['unpriced'] . ')',
|
|
||||||
'- 差异金额:**¥' . number_format($summary['difference_amount'], 2) . '**',
|
'- 差异金额:**¥' . number_format($summary['difference_amount'], 2) . '**',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@ -324,6 +324,138 @@ class SupplierPayableOverrideStore
|
|||||||
->all();
|
->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;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。
|
* 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。
|
||||||
*
|
*
|
||||||
@ -633,6 +765,100 @@ class SupplierPayableOverrideStore
|
|||||||
return $suppliers;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 只返回指定账期涉及的供应商,供月度催办统计使用。
|
* 只返回指定账期涉及的供应商,供月度催办统计使用。
|
||||||
*
|
*
|
||||||
@ -917,6 +1143,31 @@ class SupplierPayableOverrideStore
|
|||||||
. 'ELSE ' . $summaryMonth . ' END';
|
. '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
|
private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void
|
||||||
{
|
{
|
||||||
if ($this->supportsSupplierNameIndex()) {
|
if ($this->supportsSupplierNameIndex()) {
|
||||||
|
|||||||
@ -15,6 +15,7 @@ class SupplierStatementReminder
|
|||||||
private readonly SupplierStatementStore $statements,
|
private readonly SupplierStatementStore $statements,
|
||||||
private readonly SupplierDingTalkNotifier $notifier,
|
private readonly SupplierDingTalkNotifier $notifier,
|
||||||
private readonly SupplierPayableOverrideStore $payables,
|
private readonly SupplierPayableOverrideStore $payables,
|
||||||
|
private readonly SupplierStatementUploadEligibility $uploadEligibility,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,6 +34,7 @@ class SupplierStatementReminder
|
|||||||
* reminder_end:string,
|
* reminder_end:string,
|
||||||
* final_version:string,
|
* final_version:string,
|
||||||
* source_suppliers:int,
|
* source_suppliers:int,
|
||||||
|
* exempt_suppliers:list<string>,
|
||||||
* configured:int,
|
* configured:int,
|
||||||
* missing_robot:list<string>,
|
* missing_robot:list<string>,
|
||||||
* uploaded:list<string>,
|
* uploaded:list<string>,
|
||||||
@ -67,6 +69,7 @@ class SupplierStatementReminder
|
|||||||
'reminder_end' => $reminderEnd->toDateTimeString(),
|
'reminder_end' => $reminderEnd->toDateTimeString(),
|
||||||
'final_version' => $finalVersion->toDateString(),
|
'final_version' => $finalVersion->toDateString(),
|
||||||
'source_suppliers' => 0,
|
'source_suppliers' => 0,
|
||||||
|
'exempt_suppliers' => [],
|
||||||
'configured' => 0,
|
'configured' => 0,
|
||||||
'missing_robot' => [],
|
'missing_robot' => [],
|
||||||
'uploaded' => [],
|
'uploaded' => [],
|
||||||
@ -80,6 +83,9 @@ class SupplierStatementReminder
|
|||||||
}
|
}
|
||||||
|
|
||||||
$suppliers = $this->sourceSuppliersForMonth($accountingMonth, $companyId);
|
$suppliers = $this->sourceSuppliersForMonth($accountingMonth, $companyId);
|
||||||
|
$eligibility = $this->uploadEligibility->classify($suppliers, $accountingMonth);
|
||||||
|
$suppliers = $eligibility['required'];
|
||||||
|
$result['exempt_suppliers'] = $eligibility['exempt'];
|
||||||
$onlySupplier = trim($onlySupplier);
|
$onlySupplier = trim($onlySupplier);
|
||||||
if ($onlySupplier !== '') {
|
if ($onlySupplier !== '') {
|
||||||
$suppliers = array_values(array_filter(
|
$suppliers = array_values(array_filter(
|
||||||
|
|||||||
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