Compare commits
123 Commits
fix/limeng
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e4fc0a510 | |||
| 474fc97a61 | |||
| 17bffa50d0 | |||
| 8b56efb66f | |||
| 2f74eeab39 | |||
| 59e0e46b8a | |||
| e2572c9a4c | |||
| 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 | |||
| 4fbc213c57 | |||
| 1d9a5c0c4c | |||
| a7bb3514b7 | |||
| 7318eb6dea | |||
| 9766b3b5b8 | |||
| 4e51d4a700 | |||
| 7c2a1a66ae | |||
| 045e5cc393 | |||
| ac6ed8e693 | |||
| 75cba0dde9 | |||
| 695629c61c | |||
| 34b7c1c5e7 | |||
| 4c1fdce0c6 | |||
| 2c1b5dd0e4 | |||
| 2bfbd1fc92 | |||
| f9417702a2 | |||
| 913961c4b4 | |||
| 99694bc91a | |||
| c4e0b67a5f | |||
| b1209a3f6e | |||
| 7f01e391eb | |||
| 6ca6501466 | |||
| 8504b67084 | |||
| 0156a89f87 | |||
| 8e1135bc59 | |||
| 2dca095bff | |||
| 224f9f778e | |||
| e2145556f1 | |||
| c6273cb3f6 | |||
| 7bb4667a47 | |||
| ded2789a17 | |||
| ae52465900 | |||
| 05f8cec37a | |||
| 7c362e99f1 | |||
| db9f1ff433 | |||
| de7daad880 | |||
| eee22a420a | |||
| 0c077ecdf2 | |||
| bd2ca10afc | |||
| 344c911a11 | |||
| dedb8b7f0e | |||
| e1a6d311d3 | |||
| fcd24941e7 | |||
| 75455e4a7e | |||
| 87c7338203 | |||
| 4f0622f0bb | |||
| 31a3edba76 | |||
| 2230486480 | |||
| 85bfeb6e73 | |||
| 5392ad1606 | |||
| b3abfcb6a2 | |||
| 381d8f55f2 | |||
| 501c973216 | |||
| 97d4d2a998 |
@ -285,7 +285,7 @@ SQL);
|
||||
public function allSubjectReferences(int $companyId): array
|
||||
{
|
||||
$statement = $this->pdo()->prepare(
|
||||
'SELECT company_name, company_type, taxpayer_type, business_registration_type, company_status '
|
||||
'SELECT company_name, company_type, taxpayer_type, business_registration_type, company_status, plan, registered_at '
|
||||
. 'FROM company_plan_rows '
|
||||
. 'WHERE company_id = :company_id ORDER BY id'
|
||||
);
|
||||
|
||||
@ -11,7 +11,8 @@ use Throwable;
|
||||
/**
|
||||
* 聚水潭订单标签明细的每日同步。
|
||||
*
|
||||
* 先核对历史日期是否逐日覆盖,再补齐缺口,最后替换刷新最近数日以吸收上游迟到修改。
|
||||
* 先核对历史日期是否逐日覆盖、源订单是否在标签导入后再次变化,再补刷异常日期,
|
||||
* 最后替换刷新最近数日以吸收上游迟到修改。
|
||||
*/
|
||||
class JstOrderLabelDailySynchronizer
|
||||
{
|
||||
@ -139,9 +140,17 @@ class JstOrderLabelDailySynchronizer
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读确认指定日期都已覆盖;任何缺日或订单数不一致都会阻止下游重算。
|
||||
* 只读确认指定日期都已覆盖且没有导入后的源订单变化;异常会阻止下游重算。
|
||||
*
|
||||
* @return list<array{date:string,source_orders:int,target_orders:int,target_rows:int,status:string}>
|
||||
* @return list<array{
|
||||
* date:string,
|
||||
* source_orders:int,
|
||||
* target_orders:int,
|
||||
* target_rows:int,
|
||||
* source_max_update_time:?string,
|
||||
* target_imported_at:?string,
|
||||
* status:string
|
||||
* }>
|
||||
*/
|
||||
public function assertCovered(string $from, string $to, int $companyId): array
|
||||
{
|
||||
@ -164,12 +173,20 @@ class JstOrderLabelDailySynchronizer
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐日比较源订单号数与标签明细订单号数。
|
||||
* 逐日比较源订单覆盖,并比较源订单更新时间与标签日期的完整导入时间。
|
||||
*
|
||||
* 标签拆行后同一订单会出现多行,因此不能用总行数直接比较订单完整性。
|
||||
* updateTime 晚于目标日最后导入时间,说明源订单可能只改了标签、未增删订单;
|
||||
* 这类日期也必须整日重刷,否则订单数相同但标签内容会一直停留在旧版本。
|
||||
*
|
||||
* @return list<array{
|
||||
* date:string,source_orders:int,target_orders:int,target_rows:int,status:string
|
||||
* date:string,
|
||||
* source_orders:int,
|
||||
* target_orders:int,
|
||||
* target_rows:int,
|
||||
* source_max_update_time:?string,
|
||||
* target_imported_at:?string,
|
||||
* status:string
|
||||
* }>
|
||||
*/
|
||||
public function coverage(Carbon $from, Carbon $to, int $companyId): array
|
||||
@ -182,16 +199,24 @@ class JstOrderLabelDailySynchronizer
|
||||
$sourceRows = $mirror->table('ops_jst_orders')
|
||||
->where('order_date', '>=', $start)
|
||||
->where('order_date', '<', $end)
|
||||
->selectRaw('DATE(order_date) AS day, COUNT(DISTINCT so_id) AS order_count')
|
||||
->selectRaw(
|
||||
'DATE(order_date) AS day, COUNT(DISTINCT so_id) AS order_count, '
|
||||
. 'MAX(updateTime) AS source_max_update_time',
|
||||
)
|
||||
->groupByRaw('DATE(order_date)')
|
||||
->get()
|
||||
->keyBy('day');
|
||||
|
||||
$targetRows = $target->table('jst_order_labels')
|
||||
->where('company_id', $companyId)
|
||||
->whereNull('deleted_at')
|
||||
->where('ordered_at', '>=', $start)
|
||||
->where('ordered_at', '<', $end)
|
||||
->selectRaw('DATE(ordered_at) AS day, COUNT(*) AS row_count, COUNT(DISTINCT order_no) AS order_count')
|
||||
->selectRaw(
|
||||
'DATE(ordered_at) AS day, COUNT(*) AS row_count, '
|
||||
. 'COUNT(DISTINCT order_no) AS order_count, '
|
||||
. 'MIN(created_at) AS target_imported_at',
|
||||
)
|
||||
->groupByRaw('DATE(ordered_at)')
|
||||
->get()
|
||||
->keyBy('day');
|
||||
@ -202,11 +227,19 @@ class JstOrderLabelDailySynchronizer
|
||||
$sourceOrders = (int) ($sourceRows[$date]->order_count ?? 0);
|
||||
$targetOrderCount = (int) ($targetRows[$date]->order_count ?? 0);
|
||||
$targetRowsCount = (int) ($targetRows[$date]->row_count ?? 0);
|
||||
$sourceMaxUpdateTime = $sourceRows[$date]->source_max_update_time ?? null;
|
||||
$targetImportedAt = $targetRows[$date]->target_imported_at ?? null;
|
||||
$sourceUpdatedAt = $this->timestamp($sourceMaxUpdateTime);
|
||||
$targetImportedAtCarbon = $this->timestamp($targetImportedAt);
|
||||
$sourceIsNewer = $sourceUpdatedAt !== null
|
||||
&& $targetImportedAtCarbon !== null
|
||||
&& $sourceUpdatedAt->gt($targetImportedAtCarbon);
|
||||
$status = match (true) {
|
||||
$sourceOrders === 0 => 'source_empty',
|
||||
$targetOrderCount === 0 => 'missing',
|
||||
$targetOrderCount < $sourceOrders => 'incomplete',
|
||||
$targetOrderCount > $sourceOrders => 'extra_orders',
|
||||
$sourceIsNewer => 'stale',
|
||||
default => 'ok',
|
||||
};
|
||||
|
||||
@ -215,6 +248,8 @@ class JstOrderLabelDailySynchronizer
|
||||
'source_orders' => $sourceOrders,
|
||||
'target_orders' => $targetOrderCount,
|
||||
'target_rows' => $targetRowsCount,
|
||||
'source_max_update_time' => $sourceMaxUpdateTime,
|
||||
'target_imported_at' => $targetImportedAt,
|
||||
'status' => $status,
|
||||
];
|
||||
}
|
||||
@ -288,7 +323,18 @@ class JstOrderLabelDailySynchronizer
|
||||
private function issueSummary(array $issues): string
|
||||
{
|
||||
return implode(',', array_map(
|
||||
static fn (array $issue): string => $issue['date'] . '=' . $issue['status'],
|
||||
static function (array $issue): string {
|
||||
$detail = $issue['date'] . '=' . $issue['status'];
|
||||
if (($issue['status'] ?? null) === 'stale') {
|
||||
$detail .= sprintf(
|
||||
'(源更新时间 %s,标签导入时间 %s)',
|
||||
$issue['source_max_update_time'] ?? '空',
|
||||
$issue['target_imported_at'] ?? '空',
|
||||
);
|
||||
}
|
||||
|
||||
return $detail;
|
||||
},
|
||||
$issues,
|
||||
));
|
||||
}
|
||||
@ -319,4 +365,17 @@ class JstOrderLabelDailySynchronizer
|
||||
|
||||
return $date->format('Y-m-d') === $value ? $date : null;
|
||||
}
|
||||
|
||||
private function timestamp(mixed $value): ?Carbon
|
||||
{
|
||||
if ($value === null || trim((string) $value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Carbon::parse((string) $value, 'Asia/Shanghai');
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -367,7 +367,7 @@ class JstOrderLabelImporter
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function labelsForRecord(string $labels, string $sellerRemark): array
|
||||
public function labelsForRecord(string $labels, string $sellerRemark): array
|
||||
{
|
||||
$labels = $this->splitLabels($labels);
|
||||
if (stripos($sellerRemark, self::SELLER_REMARK_LABEL) !== false
|
||||
|
||||
@ -9,7 +9,7 @@ use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 每日编排:先核对标签覆盖,再同步种菜报销工单,最后重算业绩明细种菜金额。
|
||||
* 每日编排:先同步种菜报销工单,再核对标签覆盖,最后重算业绩明细种菜金额。
|
||||
*/
|
||||
class StoreReceiptPlantingDailySynchronizer
|
||||
{
|
||||
@ -37,15 +37,16 @@ class StoreReceiptPlantingDailySynchronizer
|
||||
throw new InvalidArgumentException('公司 ID 无效。');
|
||||
}
|
||||
|
||||
$coverage = $this->labelCoverage->assertCovered(
|
||||
$fromDate->toDateString(),
|
||||
$toDate->toDateString(),
|
||||
$companyId,
|
||||
);
|
||||
$months = $this->months($months, $toDate);
|
||||
$this->assertWorkOrderSourceReady();
|
||||
|
||||
if ($dryRun) {
|
||||
$coverage = $this->labelCoverage->assertCovered(
|
||||
$fromDate->toDateString(),
|
||||
$toDate->toDateString(),
|
||||
$companyId,
|
||||
);
|
||||
|
||||
return [
|
||||
'status' => 'ready',
|
||||
'from' => $fromDate->toDateString(),
|
||||
@ -65,6 +66,24 @@ class StoreReceiptPlantingDailySynchronizer
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$coverage = $this->labelCoverage->assertCovered(
|
||||
$fromDate->toDateString(),
|
||||
$toDate->toDateString(),
|
||||
$companyId,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
return [
|
||||
'status' => 'failed',
|
||||
'error' => '种菜明细已同步,但标签覆盖检查失败:' . $exception->getMessage(),
|
||||
'from' => $fromDate->toDateString(),
|
||||
'to' => $toDate->toDateString(),
|
||||
'months' => $months,
|
||||
'planting_sync' => $plantingSync,
|
||||
'dry_run' => false,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'ready_to_refresh',
|
||||
'from' => $fromDate->toDateString(),
|
||||
|
||||
@ -49,10 +49,7 @@ class ImportPayablesFinal extends Command
|
||||
}
|
||||
|
||||
$fields = $registry->fields($section, $dataset);
|
||||
$storeDataset = 'final:'
|
||||
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
|
||||
. ':'
|
||||
. $dataset;
|
||||
$storeDataset = $registry->storeDataset($section, $dataset);
|
||||
$totalCreated = 0;
|
||||
$totalUpdated = 0;
|
||||
$totalRows = 0;
|
||||
|
||||
18
app/Console/Commands/ImportPortalFreightBills.php
Normal file
18
app/Console/Commands/ImportPortalFreightBills.php
Normal file
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\CourierBills\PortalFreightBillImports;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
final class ImportPortalFreightBills extends Command
|
||||
{
|
||||
protected $signature = 'portal-freight:import-pending';
|
||||
protected $description = '受限批容器处理一份厂家或快递门户运费账单';
|
||||
|
||||
public function handle(PortalFreightBillImports $imports): int
|
||||
{
|
||||
$imports->processNext();
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
44
app/Console/Commands/ImportWorkPlatformCourierRobots.php
Normal file
44
app/Console/Commands/ImportWorkPlatformCourierRobots.php
Normal file
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\WorkPlatformCourierRobots;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use RuntimeException;
|
||||
|
||||
class ImportWorkPlatformCourierRobots extends Command
|
||||
{
|
||||
protected $signature = 'courier-bills:import-platform-robots {file : Private JSON export of courier payable robot rows} {--company=1} {--apply : Save the reviewed exact matches}';
|
||||
protected $description = '预演或导入工作平台快递应付群机器人配置;不发送消息';
|
||||
|
||||
public function handle(CourierBillStore $store, WorkPlatformCourierRobots $matcher, SupplierDingTalkNotifier $notifier): int
|
||||
{
|
||||
$path = (string) $this->argument('file');
|
||||
if (! is_file($path) || filesize($path) > 2 * 1024 * 1024) throw new RuntimeException('配置文件不存在或超过 2MB。');
|
||||
$rows = json_decode(file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($rows) || ! array_is_list($rows) || count($rows) > 10000) throw new RuntimeException('配置文件必须是最多 10000 条的数组。');
|
||||
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
|
||||
$result = $matcher->match($store->groups(), $rows);
|
||||
$this->line('名称匹配:' . count($result['robots']) . ';未匹配:' . count($result['unmatched']) . ';有歧义:' . count($result['ambiguous']));
|
||||
foreach ($result['robots'] as $name => $robot) $this->line($name . ' → ' . ($robot['group_name'] ?: '工作平台已配置群') . '(配置 ' . $robot['source_id'] . ')');
|
||||
$this->line('未匹配:' . implode('、', $result['unmatched']));
|
||||
$this->line('有歧义:' . implode('、', $result['ambiguous']));
|
||||
if (! $this->option('apply')) return self::SUCCESS;
|
||||
$backup = 'private/courier-robot-backups/' . now()->format('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.enc';
|
||||
$backedUp = Storage::disk('local')->put($backup, Crypt::encryptString(json_encode([
|
||||
'company_id' => (int) $this->option('company'),
|
||||
'value' => setting('supplier_reconciliation.dingtalk_robots', []),
|
||||
], JSON_THROW_ON_ERROR)));
|
||||
if (! $backedUp || ! chmod(Storage::disk('local')->path($backup), 0600)) {
|
||||
throw new RuntimeException('原配置备份失败,未修改机器人配置。');
|
||||
}
|
||||
$notifier->importCourierRobots($result['robots']);
|
||||
$this->info('已保存 ' . count($result['robots']) . ' 家;原配置已加密备份:' . $backup . ';未发送消息。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -117,7 +117,7 @@ class LockFinanceLedgerMonthlyOpening extends Command
|
||||
->orderBy('balance_date')
|
||||
->orderBy('balance_at')
|
||||
->orderBy('id')
|
||||
->get(['account_no', 'account_balance', 'available_balance']) as $row) {
|
||||
->get(['account_no', 'balance_date', 'account_balance', 'available_balance']) as $row) {
|
||||
$accountNo = $this->accountNo($row->account_no);
|
||||
if ($accountNo !== '') {
|
||||
$snapshotBefore[$accountNo] = $row;
|
||||
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
72
app/Console/Commands/PlantingReimbursementAutoConfirm.php
Normal file
72
app/Console/Commands/PlantingReimbursementAutoConfirm.php
Normal file
@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementBatches as Batches;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementGate as Gate;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 每天 10:30 锁定当天种菜报销批次(确认本批):放行检查通过就把待处理 + 处理中的校验结果固定下来,
|
||||
* 之后在聚工单整批锁单、取消、标记打款都按这份来。没通过(比如同步不新鲜)时 10:40、10:50 再试;
|
||||
* 已确认的跳过。不依赖钉钉群机器人,不改聚工单。11:20 的汇总推送仍会兜底确认一次。
|
||||
*/
|
||||
class PlantingReimbursementAutoConfirm extends Command
|
||||
{
|
||||
protected $signature = 'planting-reimbursement:auto-confirm
|
||||
{--date= : 报销日期 Y-m-d,默认今天}
|
||||
{--dry-run : 只检查,不确认}';
|
||||
|
||||
protected $description = '放行检查通过后自动确认(锁定)当天种菜报销批次';
|
||||
|
||||
public function handle(Workbench $workbench, Batches $batches, Repository $repository): int
|
||||
{
|
||||
$date = trim((string) $this->option('date')) ?: Workbench::defaultDate();
|
||||
try {
|
||||
Workbench::parseDate($date);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$failed = false;
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
$companyId = (int) $company->id;
|
||||
if ($batches->get($companyId, $date) !== null) {
|
||||
$this->line("#{$companyId}: {$date} 已确认,跳过");
|
||||
continue;
|
||||
}
|
||||
if (! in_array($repository->syncStatus()['code'], ['ready', 'failed'], true)) {
|
||||
$this->line("#{$companyId}: 聚工单镜像未就绪,跳过");
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$result = $workbench->build($companyId, $date);
|
||||
$gate = Gate::check($result);
|
||||
if (! $gate['ok']) {
|
||||
$this->warn("#{$companyId}: {$date} 放行检查没通过,暂不确认:" . implode(';', $gate['reasons']));
|
||||
$failed = true;
|
||||
continue;
|
||||
}
|
||||
if ($this->option('dry-run')) {
|
||||
$this->line("#{$companyId}: {$date} 可以确认:" . $result['summary']['source']['count'] . ' 单');
|
||||
continue;
|
||||
}
|
||||
$batch = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
|
||||
$this->info("#{$companyId}: 已确认 {$date} 批次 " . $batch['summary']['source']['count'] . ' 单');
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error("#{$companyId}: 确认失败:" . $exception->getMessage());
|
||||
$failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -13,7 +13,7 @@ use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
||||
use Throwable;
|
||||
|
||||
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */
|
||||
/** 每天 11:20 推送种菜报销批次汇总;逐单不予报销通知须已启用。不改聚工单。 */
|
||||
class PlantingReimbursementDailyDigest extends Command
|
||||
{
|
||||
protected $signature = 'planting-reimbursement:daily-digest
|
||||
@ -48,7 +48,9 @@ class PlantingReimbursementDailyDigest extends Command
|
||||
}
|
||||
|
||||
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')) {
|
||||
$this->line($title . "\n" . $text);
|
||||
continue;
|
||||
@ -67,7 +69,7 @@ class PlantingReimbursementDailyDigest extends Command
|
||||
}
|
||||
|
||||
/** @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();
|
||||
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
||||
@ -75,7 +77,7 @@ class PlantingReimbursementDailyDigest extends Command
|
||||
$lines = ['#### ' . $title];
|
||||
|
||||
$stale = $sync['code'] !== 'ready' || $sync['last_succeeded_at'] === null
|
||||
|| now()->diffInMinutes(\Illuminate\Support\Carbon::parse($sync['last_succeeded_at']), true) > 20;
|
||||
|| \Modules\EcommerceFinance\Services\PlantingClock::minutesSince((string) $sync['last_succeeded_at']) > 20;
|
||||
if ($stale) {
|
||||
$lines[] = '> **聚工单数据不是最新的**(最后同步成功:' . ($sync['last_succeeded_at'] ? substr($sync['last_succeeded_at'], 0, 16) : '无') . '),先别按下面结果报销。';
|
||||
}
|
||||
@ -92,7 +94,7 @@ class PlantingReimbursementDailyDigest extends Command
|
||||
$confirmedNow = false;
|
||||
if ($result === null) {
|
||||
$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');
|
||||
$confirmedNow = true;
|
||||
}
|
||||
@ -118,6 +120,8 @@ class PlantingReimbursementDailyDigest extends Command
|
||||
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
|
||||
} elseif ($s['notices'] === []) {
|
||||
$lines[] = '- 没有要取消或复查的工单';
|
||||
} elseif (! $robot->cancelNoticesEnabled()) {
|
||||
$lines[] = '- 取消 / 待复查逐单通知已暂停,测试完成前不会发送';
|
||||
} elseif ($sendNotices) {
|
||||
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
|
||||
$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;
|
||||
}
|
||||
}
|
||||
93
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
93
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。
|
||||
*/
|
||||
class RefreshAccountMappingCoverage extends Command
|
||||
{
|
||||
protected $signature = 'account-mapping:refresh-coverage
|
||||
{month? : all 或账单月份 YYYY-MM}
|
||||
{--pending : 处理页面登记的下一个刷新请求}
|
||||
{--monthly : 本月尚未成功刷新时执行跨月刷新}';
|
||||
|
||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||
|
||||
public function handle(AccountMappingCoverage $coverage): int
|
||||
{
|
||||
$runningPath = null;
|
||||
$month = trim((string) $this->argument('month')) ?: null;
|
||||
$monthly = (bool) $this->option('monthly');
|
||||
if ($monthly && $this->option('pending')) {
|
||||
$this->error('--monthly 与 --pending 不能同时使用。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($this->option('pending')) {
|
||||
$request = $coverage->claimPendingRefresh();
|
||||
if ($request === null) {
|
||||
$this->line('没有待处理的未映射清单刷新请求。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$month = $request['month'];
|
||||
$runningPath = $request['path'];
|
||||
}
|
||||
if ($monthly) {
|
||||
if (! $coverage->monthlyRefreshDue()) {
|
||||
$this->line('本月未映射清单已生成,无需重复刷新。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$month = 'all';
|
||||
}
|
||||
|
||||
try {
|
||||
$isAll = $month === 'all';
|
||||
$raw = $isAll
|
||||
? $coverage->refreshAllMonths()
|
||||
: $coverage->refreshForMonth($month);
|
||||
if (($raw['status'] ?? '') === 'refreshing') {
|
||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||
if ($runningPath !== null) {
|
||||
$coverage->requeuePendingRefresh($runningPath);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$summary = $isAll
|
||||
? $coverage->missingAcrossMonths()
|
||||
: $coverage->missingForMonth($month);
|
||||
$this->info(sprintf(
|
||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
||||
$isAll ? '跨月全部账单' : (string) $summary['month'],
|
||||
(int) $summary['missing_item_count'],
|
||||
(int) $summary['missing_row_count'],
|
||||
(int) $summary['source_rows'],
|
||||
memory_get_peak_usage(true) / 1048576,
|
||||
));
|
||||
if ($runningPath !== null) {
|
||||
$coverage->finishPendingRefresh($runningPath, true);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
if ($month !== null) {
|
||||
$coverage->markFailed($month, $exception->getMessage());
|
||||
}
|
||||
if ($runningPath !== null) {
|
||||
$coverage->finishPendingRefresh($runningPath, false, $exception->getMessage());
|
||||
}
|
||||
$this->error('未映射账单项目刷新失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
74
app/Console/Commands/RemindDropshipFreightUpload.php
Normal file
74
app/Console/Commands/RemindDropshipFreightUpload.php
Normal file
@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Http\Controllers\Business\DropshipFreightController;
|
||||
use App\Models\Common\Company;
|
||||
use App\Support\DropshipFreight\DropshipUploadReminder;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
|
||||
/** 每月 1–14 日自动提醒还没上传上月代发运费账单的厂家(14 日截止,逾期本月货款和运费不予结算)。 */
|
||||
class RemindDropshipFreightUpload extends Command
|
||||
{
|
||||
protected $signature = 'dropship-freight:remind-upload
|
||||
{--date= : 按哪天算,格式 Y-m-d,默认今天(北京时间)}
|
||||
{--force : 不看开关、不看当天是否已发、不限 1–14 日}
|
||||
{--dry-run : 只列出会提醒哪些厂家,不发}';
|
||||
|
||||
protected $description = '每月 1–14 日提醒还没上传上月代发运费账单的代发厂家';
|
||||
|
||||
public function handle(DropshipUploadReminder $reminder): int
|
||||
{
|
||||
$date = trim((string) $this->option('date'));
|
||||
if ($date !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
|
||||
$this->error('日期格式无效,应为 Y-m-d。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$today = $date !== '' ? CarbonImmutable::createFromFormat('Y-m-d', $date, DropshipUploadReminder::TIMEZONE)->startOfDay() : DropshipUploadReminder::today();
|
||||
$force = (bool) $this->option('force');
|
||||
if ($today->day > DropshipUploadReminder::DEADLINE_DAY && ! $force) {
|
||||
$this->line($today->format('Y-m-d') . ':只在每月 1–' . DropshipUploadReminder::DEADLINE_DAY . ' 日提醒。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$month = DropshipUploadReminder::billMonth($today);
|
||||
$failed = false;
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
$label = "#{$company->id} {$company->name} {$month}";
|
||||
if (! DropshipUploadReminder::enabled() && ! $force) {
|
||||
$this->line($label . ':自动提醒已关闭');
|
||||
continue;
|
||||
}
|
||||
$portal = route('business.supplier-portal.home', ['company_id' => $company->id]);
|
||||
if ($this->option('dry-run')) {
|
||||
$plan = $reminder->targets($month);
|
||||
$this->line($label . ':会提醒 ' . count($plan['targets']) . ' 家:' . implode('、', array_map(static fn ($f): string => (string) $f->name, $plan['targets']))
|
||||
. ';已上传 ' . count($plan['done']) . ' 家;没有代发发货 ' . count($plan['no_shipment']) . ' 家;没配机器人 ' . count($plan['no_robot']) . ' 家'
|
||||
. ($plan['no_robot'] !== [] ? ':' . implode('、', $plan['no_robot']) : '') . ';入口 ' . $portal);
|
||||
continue;
|
||||
}
|
||||
$lock = sprintf('dropship-upload-reminder:%d:%s:%s', $company->id, $month, $today->format('Y-m-d'));
|
||||
if (! $force && ! Cache::add($lock, true, now()->addDays(2))) {
|
||||
$this->line($label . ':今天已经提醒过');
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$result = $reminder->remind($month, $portal, null, $today);
|
||||
$this->info($label . ':' . DropshipFreightController::reminderSummary($month, $result));
|
||||
$failed = $failed || $result['failed'] !== [];
|
||||
} catch (Throwable $error) {
|
||||
Cache::forget($lock);
|
||||
report($error);
|
||||
$this->error($label . ':自动提醒失败:' . $error->getMessage());
|
||||
$failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
59
app/Console/Commands/RunPayablesUnpricedCycle.php
Normal file
59
app/Console/Commands/RunPayablesUnpricedCycle.php
Normal file
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
|
||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||
use Throwable;
|
||||
|
||||
class RunPayablesUnpricedCycle extends Command
|
||||
{
|
||||
protected $signature = 'payables:unpriced-cycle:auto
|
||||
{--period= : 货款账期,格式 YYYY-MM,默认上月}
|
||||
{--cutoff= : 工作平台价格截止日,格式 YYYY-MM-DD,默认为本月1日}
|
||||
{--company=1 : 公司 ID}
|
||||
{--user= : 操作用户 ID}';
|
||||
|
||||
protected $description = '每月2日使用工作平台价格镜像自动生成上月未定价转本月定价数据';
|
||||
|
||||
public function handle(
|
||||
PayablesUnpricedCycleProcessor $processor,
|
||||
SupplierPayableOverrideStore $store,
|
||||
): int {
|
||||
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
|
||||
$now = now($timezone);
|
||||
$period = trim((string) $this->option('period')) ?: $now->copy()->subMonthNoOverflow()->format('Y-m');
|
||||
$cutoff = trim((string) $this->option('cutoff')) ?: $now->copy()->startOfMonth()->toDateString();
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$userId = $this->option('user') !== null ? (int) $this->option('user') : null;
|
||||
|
||||
try {
|
||||
$completed = $store->findLatestRow(
|
||||
PayablesUnpricedCycleProcessor::RUN_DATASET,
|
||||
['summary_month' => $period, 'status' => 'completed'],
|
||||
$companyId,
|
||||
);
|
||||
if ($completed !== null) {
|
||||
$this->info("账期 {$period} 已完成,本次自动任务跳过。");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$result = $processor->processFromPlatformPrices(
|
||||
$period,
|
||||
$cutoff,
|
||||
$companyId,
|
||||
$userId,
|
||||
);
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('自动定价失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -13,15 +13,17 @@ class SendSupplierStatementReminders extends Command
|
||||
{
|
||||
protected $signature = 'supplier-statement:send-reminders
|
||||
{--date= : 执行日期,格式 Y-m-d,默认今天}
|
||||
{--slot= : 催办时段,10 或 16;默认按当前小时判断}
|
||||
{--supplier= : 仅检查指定供应商}
|
||||
{--dry-run : 只预览,不发送也不记录}';
|
||||
|
||||
protected $description = '在每月 1-14 日提醒上月有入库数据但尚未上传对账单的供应商';
|
||||
protected $description = '在每月 1-14 日 10:00、16:00 提醒上月有入库数据但尚未上传对账单的供应商';
|
||||
|
||||
public function handle(SupplierStatementReminder $reminder): int
|
||||
{
|
||||
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
|
||||
$dateValue = trim((string) $this->option('date')) ?: now($timezone)->toDateString();
|
||||
$dateOption = trim((string) $this->option('date'));
|
||||
$dateValue = $dateOption !== '' ? $dateOption : now($timezone)->toDateString();
|
||||
try {
|
||||
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
|
||||
} catch (Throwable) {
|
||||
@ -37,12 +39,32 @@ class SendSupplierStatementReminders extends Command
|
||||
|
||||
$failed = false;
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$slot = trim((string) $this->option('slot'));
|
||||
if ($slot === '') {
|
||||
$slot = now($timezone)->hour < 16 ? '10' : '16';
|
||||
}
|
||||
if (! in_array($slot, ['10', '16'], true)) {
|
||||
$this->error('催办时段只能是 10 或 16。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$startsAt = Carbon::parse(
|
||||
(string) config('supplier_reconciliation.reminder.starts_at', '2026-12-03 00:00:00'),
|
||||
$timezone,
|
||||
)->startOfDay();
|
||||
if ($dateOption === '' && $date->lt($startsAt)) {
|
||||
$this->line('对账单双向催办尚未到启用日期,将从 ' . $startsAt->toDateString() . ' 开始。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
$lock = Cache::lock(sprintf(
|
||||
'supplier-statement-reminder:%d:%s',
|
||||
'supplier-statement-reminder:%d:%s:%s',
|
||||
$company->id,
|
||||
$date->toDateString(),
|
||||
$slot,
|
||||
), 900);
|
||||
if (! $dryRun && ! $lock->get()) {
|
||||
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
|
||||
@ -55,6 +77,7 @@ class SendSupplierStatementReminders extends Command
|
||||
(int) $company->id,
|
||||
$dryRun,
|
||||
trim((string) $this->option('supplier')),
|
||||
$slot,
|
||||
);
|
||||
if (! $result['reminder_day']) {
|
||||
$this->line("#{$company->id} {$company->name}: 今天不在 1-14 日催办窗口");
|
||||
@ -66,11 +89,13 @@ class SendSupplierStatementReminders extends Command
|
||||
}
|
||||
|
||||
$this->line(sprintf(
|
||||
'#%d %s %s: 入库供应商 %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->name,
|
||||
$result['accounting_month'],
|
||||
$slot,
|
||||
$result['source_suppliers'],
|
||||
count($result['exempt_suppliers']),
|
||||
$result['configured'],
|
||||
$dryRun ? '将提醒' : '已发送',
|
||||
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 InvalidArgumentException;
|
||||
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\BusinessMirrorSynchronizer;
|
||||
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
||||
@ -92,6 +95,19 @@ class SyncBusinessMirrors extends Command
|
||||
$result['batches'],
|
||||
$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('专线镜像已同步,发货数据核算结果未完成更新,请重跑专线运费核算。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 每日退款专属批次只处理配置内的退款表,不能继续进入
|
||||
|
||||
@ -17,7 +17,7 @@ class SyncJstOrderLabelsDaily extends Command
|
||||
{--dry-run : 只检查并输出计划,不写库}
|
||||
{--json : 输出 JSON}';
|
||||
|
||||
protected $description = '先核对聚水潭订单标签历史覆盖,补齐缺口后刷新最近数据';
|
||||
protected $description = '先核对聚水潭订单标签历史覆盖和源订单变化,补刷异常日期后刷新最近数据';
|
||||
|
||||
public function handle(JstOrderLabelDailySynchronizer $synchronizer): int
|
||||
{
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1563,10 +1563,12 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
$attachedDiscount = 0.0;
|
||||
$attachedOffset = 0.0;
|
||||
$attachedDefaultCompensation = 0.0;
|
||||
$attachedRefund = 0.0;
|
||||
foreach ($groups as $group) {
|
||||
$attachedDiscount += (float) $group['discount_amount'];
|
||||
$attachedOffset += (float) $group['offset_amount'];
|
||||
$attachedDefaultCompensation += (float) $group['default_compensation_amount'];
|
||||
$attachedRefund += (float) $group['refund_amount'];
|
||||
}
|
||||
$unattachedRows = 0;
|
||||
foreach ($promoRowsByKey as $key => $count) {
|
||||
@ -1576,11 +1578,32 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
}
|
||||
// A 方案:挂不到订单行的优惠/冲减也补成行(收入/商品/差额留空),金额不丢。
|
||||
foreach ($promoOnlyGroups as $key => $group) {
|
||||
if ($group['order_identity'] !== '' && isset($groups[$group['shop_key'] . '|' . $group['order_identity']])) {
|
||||
$mainKey = $group['shop_key'] . '|' . $group['order_identity'];
|
||||
if (isset($groups[$mainKey])) {
|
||||
unset($promoOnlyGroups[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
$promoOnlyDiscount = 0.0;
|
||||
$promoOnlyOffset = 0.0;
|
||||
$promoOnlyDefaultCompensation = 0.0;
|
||||
$promoOnlyRefund = 0.0;
|
||||
foreach ($promoOnlyGroups as $group) {
|
||||
$promoOnlyDiscount += (float) $group['discount_amount'];
|
||||
$promoOnlyOffset += (float) $group['offset_amount'];
|
||||
$promoOnlyDefaultCompensation += (float) $group['default_compensation_amount'];
|
||||
$promoOnlyRefund += (float) $group['refund_amount'];
|
||||
}
|
||||
self::assertSourceAmountConserved('优惠', $discountTotal, $attachedDiscount, $promoOnlyDiscount);
|
||||
self::assertSourceAmountConserved('冲减', $offsetTotal, $attachedOffset, $promoOnlyOffset);
|
||||
self::assertSourceAmountConserved(
|
||||
'违约赔付',
|
||||
$defaultCompensationTotal,
|
||||
$attachedDefaultCompensation,
|
||||
$promoOnlyDefaultCompensation,
|
||||
);
|
||||
self::assertSourceAmountConserved('退款', $refundTotal, $attachedRefund, $promoOnlyRefund);
|
||||
|
||||
return compact(
|
||||
'groups', 'promoOnlyGroups', 'paymentTotal', 'incomeTotal', 'discountTotal',
|
||||
'offsetTotal', 'defaultCompensationTotal', 'refundTotal', 'moneyRemarkRows',
|
||||
@ -1589,6 +1612,25 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
);
|
||||
}
|
||||
|
||||
private static function assertSourceAmountConserved(
|
||||
string $label,
|
||||
float $sourceTotal,
|
||||
float $attachedTotal,
|
||||
float $promoOnlyTotal,
|
||||
): void {
|
||||
if (abs(round($sourceTotal - $attachedTotal - $promoOnlyTotal, 2)) <= 0.005) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'账单聚合金额校验失败:%s 原始 %s,主行 %s,补行 %s。',
|
||||
$label,
|
||||
number_format($sourceTotal, 2, '.', ''),
|
||||
number_format($attachedTotal, 2, '.', ''),
|
||||
number_format($promoOnlyTotal, 2, '.', ''),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* A 方案补行的入库数据:收入/商品/差额留空,只带优惠/冲减金额与原因标注。
|
||||
*
|
||||
|
||||
@ -49,6 +49,11 @@ class SyncStoreReceiptPlantingDaily extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (($result['status'] ?? '') === 'failed') {
|
||||
$this->outputResult($result);
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ((bool) $this->option('dry-run')) {
|
||||
$this->outputResult($result);
|
||||
return self::SUCCESS;
|
||||
|
||||
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
|
||||
class WarmSupplierReconciliationFinanceFilters extends Command
|
||||
{
|
||||
protected $signature = 'supplier-reconciliation:warm-finance-filters
|
||||
{--company=1 : 公司 ID}';
|
||||
|
||||
protected $description = '预热财务端供应商对账的月份和对账人筛选缓存';
|
||||
|
||||
public function handle(SupplierReconciliationPageData $pageData): int
|
||||
{
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$pageData->warmFinanceFilters($companyId);
|
||||
$this->info("公司 {$companyId} 的财务端供应商对账筛选缓存已预热。");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -71,6 +71,14 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 使用生产批处理入口,避免在网页容器运行全量退回件同步。
|
||||
$schedule->exec('sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels')
|
||||
->cron('0 10,16 * * *')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(60)
|
||||
->appendOutputTo(storage_path('logs/returned-parcels-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。
|
||||
$schedule->command('business-mirror:archive-store-information')
|
||||
->dailyAt('07:00')
|
||||
@ -103,6 +111,14 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 代发运费:每月 1–14 日 10:00 提醒还没上传上月代发运费账单的厂家(14 日截止,逾期本月货款和运费不予结算)。
|
||||
$schedule->command('dropship-freight:remind-upload')
|
||||
->cron('0 10 1-14 * *')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(60)
|
||||
->appendOutputTo(storage_path('logs/dropship-upload-reminder.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
|
||||
$schedule->command('inventory:sync-warehouse-mapping-alert')
|
||||
->dailyAt('10:15')
|
||||
|
||||
@ -9,12 +9,15 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingSuggestion;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 财务规则 · 科目映射表的维护接口。
|
||||
@ -29,6 +32,21 @@ class AccountMappingActions extends Controller
|
||||
/** 操作记录保留并展示的条数 */
|
||||
private const HISTORY_LIMIT = 500;
|
||||
|
||||
/** 页面与模板当前维护的字段;goods 仅为历史导入兼容保留。 */
|
||||
private const VISIBLE_FIELDS = [
|
||||
'platform',
|
||||
'item',
|
||||
'memo',
|
||||
'invoice',
|
||||
'category',
|
||||
'feeMemo',
|
||||
'dAcct',
|
||||
'dSub',
|
||||
'cAcct',
|
||||
'cSub',
|
||||
'basis',
|
||||
];
|
||||
|
||||
private const HISTORY_ACTION_LABELS = [
|
||||
'create' => '新增',
|
||||
'update' => '修改',
|
||||
@ -56,6 +74,8 @@ class AccountMappingActions extends Controller
|
||||
private readonly AccountMappingValidator $validator,
|
||||
private readonly AccountMappingCoa $coa,
|
||||
private readonly AccountMappingWorkbookImporter $importer,
|
||||
private readonly AccountMappingCoverage $coverage,
|
||||
private readonly AccountMappingSuggestion $suggestion,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
@ -67,6 +87,49 @@ class AccountMappingActions extends Controller
|
||||
return response()->json($this->payload());
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前账单里有、但科目映射表里没有同平台同项目的账单项目。
|
||||
*/
|
||||
public function coverage(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'month' => ['nullable', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||
'refresh' => ['nullable', 'boolean'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$month = trim((string) ($data['month'] ?? ''));
|
||||
$refresh = (bool) ($data['refresh'] ?? false);
|
||||
$payload = $month === ''
|
||||
? $this->coverage->missingAcrossMonths($refresh, false)
|
||||
: $this->coverage->missingForMonth($month, $refresh, false);
|
||||
|
||||
return response()->json($payload);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return response()->json([
|
||||
'message' => '未映射账单项目暂时无法读取,请稍后重试。',
|
||||
], 503);
|
||||
}
|
||||
}
|
||||
|
||||
/** 补映射时按同名账单项目查找可带入的既有规则。 */
|
||||
public function suggest(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'platform' => ['required', 'string', 'max:120'],
|
||||
'item' => ['required', 'string', 'max:500'],
|
||||
]);
|
||||
|
||||
return response()->json($this->suggestion->suggest(
|
||||
(string) $data['platform'],
|
||||
(string) $data['item'],
|
||||
));
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$values = $this->payloadValues($request);
|
||||
@ -345,17 +408,15 @@ class AccountMappingActions extends Controller
|
||||
throw new RuntimeException('无法创建导出文件。');
|
||||
}
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, array_values(AccountMappingStore::LABELS));
|
||||
fputcsv($csv, array_map(
|
||||
static fn (string $field): string => AccountMappingStore::LABELS[$field],
|
||||
self::VISIBLE_FIELDS,
|
||||
));
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
$row = [];
|
||||
foreach (array_keys(AccountMappingStore::LABELS) as $field) {
|
||||
$value = (string) ($rule[$field] ?? '');
|
||||
// 商品名称关键词留空时导出成「-」,与页面一致(导回来会按空处理)
|
||||
if ($field === 'goods' && trim($value) === '') {
|
||||
$value = '-';
|
||||
}
|
||||
$row[] = $this->csvText($value);
|
||||
foreach (self::VISIBLE_FIELDS as $field) {
|
||||
$row[] = $this->csvText((string) ($rule[$field] ?? ''));
|
||||
}
|
||||
fputcsv($csv, $row);
|
||||
}
|
||||
@ -370,8 +431,8 @@ class AccountMappingActions extends Controller
|
||||
public function template(): StreamedResponse
|
||||
{
|
||||
$samples = [
|
||||
['得物', '平台服务费', '平台服务费', '-', '0.06', '费用', '平台服务费', '销售费用', '平台服务费', '其他货币资金', '', '支出基准'],
|
||||
['淘宝', '交易收入', '订单', '-', '-', '收入', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
|
||||
['得物', '平台服务费', '平台服务费', '0.06', '费用', '平台服务费', '销售费用', '平台服务费', '其他货币资金', '', '支出基准'],
|
||||
['淘宝', '交易收入', '订单', '-', '收入', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
|
||||
];
|
||||
|
||||
return response()->streamDownload(function () use ($samples): void {
|
||||
@ -380,7 +441,10 @@ class AccountMappingActions extends Controller
|
||||
throw new RuntimeException('无法创建模板文件。');
|
||||
}
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, array_values(AccountMappingStore::LABELS));
|
||||
fputcsv($csv, array_map(
|
||||
static fn (string $field): string => AccountMappingStore::LABELS[$field],
|
||||
self::VISIBLE_FIELDS,
|
||||
));
|
||||
foreach ($samples as $sample) {
|
||||
fputcsv($csv, $sample);
|
||||
}
|
||||
|
||||
@ -7,13 +7,16 @@ use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\StatementExporter;
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\CourierBills\Rebooks;
|
||||
use App\Support\CourierBills\Waybill;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
|
||||
final class CourierBillController extends Controller
|
||||
@ -35,7 +38,11 @@ final class CourierBillController extends Controller
|
||||
$db = $this->store->db();
|
||||
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
|
||||
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
|
||||
$data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()];
|
||||
// 推送上传链接默认推上个月(新月份还没有对账单时,$month 会停在最近有对账单的月份)
|
||||
$pushMonth = self::monthParam($request->query('month')) ?? max($month, now()->subMonthNoOverflow()->format('Y-m'));
|
||||
$groups = $this->store->groups();
|
||||
$data += ['cbMonth' => $month, 'cbPushMonth' => $pushMonth, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups,
|
||||
'cbRobots' => app(SupplierDingTalkNotifier::class)->configurationMap(array_map(static fn ($g): string => (string) $g->name, $groups))];
|
||||
$data += match ($view) {
|
||||
'statement' => $this->statementData($request),
|
||||
'details' => $this->detailsData($request, $month),
|
||||
@ -74,7 +81,7 @@ final class CourierBillController extends Controller
|
||||
})->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')),
|
||||
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
||||
]];
|
||||
@ -114,6 +121,8 @@ final class CourierBillController extends Controller
|
||||
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
||||
}
|
||||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
||||
$items=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->summaryItems((int)$statement->id,$items);
|
||||
$items=app(Rebooks::class)->summaryItems((int)$statement->id,$items);
|
||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
||||
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||||
$shippingSync = null;
|
||||
@ -127,9 +136,31 @@ final class CourierBillController extends Controller
|
||||
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
||||
|
||||
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,
|
||||
'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
|
||||
@ -185,22 +216,51 @@ final class CourierBillController extends Controller
|
||||
|
||||
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'])];
|
||||
}
|
||||
|
||||
public function jointUploadLink(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'],
|
||||
'joint' => ['required', Rule::in(array_keys(\App\Support\CourierBills\CourierJointUploads::SETS))]]);
|
||||
$url = $this->guard(fn () => app(\App\Support\CourierBills\CourierUploadLink::class)
|
||||
->jointPageUrl((int) (company_id() ?: 1), $data['joint'], $data['month']));
|
||||
|
||||
return redirect()->away($url);
|
||||
}
|
||||
|
||||
private function ledgerData(Request $request): array
|
||||
{
|
||||
$db = $this->store->db();
|
||||
$search = Waybill::normalize((string) $request->query('waybill'));
|
||||
|
||||
return [
|
||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported')
|
||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->groupBy('g.name', 'l.settle_month')->selectRaw(sprintf('%s as group_name, %s as settle_month, COUNT(*) as n, SUM(%s) as amount, SUM(CASE WHEN %s IS NULL THEN 1 ELSE 0 END) as imported',
|
||||
...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['g.name', 'l.settle_month', 'l.amount', 'l.statement_id'])))
|
||||
->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(),
|
||||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('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']),
|
||||
'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(),
|
||||
];
|
||||
}
|
||||
|
||||
@ -402,14 +462,17 @@ final class CourierBillController extends Controller
|
||||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
||||
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
||||
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||||
], [], ['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']))
|
||||
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||||
if ($exists) {
|
||||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||||
}
|
||||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||||
$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'], '已保存分组。');
|
||||
}
|
||||
@ -424,12 +487,55 @@ final class CourierBillController extends Controller
|
||||
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
||||
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
||||
if ($result['rejected'] > 0) {
|
||||
$message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : '');
|
||||
$message .= ',' . $result['rejected'] . ' 行单号或结算月份认不出,未导入';
|
||||
}
|
||||
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
}
|
||||
|
||||
/** 导入已经补过的记账(系统上线前手工补的),补过的单以后不再补。 */
|
||||
public function importRebooks(Request $request)
|
||||
{
|
||||
return $this->importRebookFile($request, 'rebooks', '已补记录', function (string $path, string $extension): string {
|
||||
$r = app(Rebooks::class)->importRefunds($path, $extension);
|
||||
|
||||
return '读到 ' . $r['rows'] . ' 行,新增 ' . $r['inserted'] . ' 条已补记录' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||
});
|
||||
}
|
||||
|
||||
/** 导入复核记账:这单现在应扣多少,本期补款 = 当时扣的 − 现在应扣。 */
|
||||
public function importRebookReviews(Request $request)
|
||||
{
|
||||
return $this->importRebookFile($request, 'reviews', '复核记账', function (string $path, string $extension, string $name): string {
|
||||
$r = app(Rebooks::class)->importReviews($path, $extension, $name);
|
||||
|
||||
return '读到 ' . $r['rows'] . ' 行,导入 ' . $r['inserted'] . ' 条复核记账' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||
});
|
||||
}
|
||||
|
||||
/** 补记账规则改了、复核导了之后,重排还没确认的对账单小汇总。 */
|
||||
private function importRebookFile(Request $request, string $field, string $label, callable $import)
|
||||
{
|
||||
$file = $request->validate([$field => ['required', 'file', 'max:51200']], [], [$field => $label . '文件'])[$field];
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages([$field => '只支持 xlsx、xls、csv。']);
|
||||
}
|
||||
$message = $this->guard(fn () => $import($file->getRealPath(), $extension, $file->getClientOriginalName()));
|
||||
$this->refreshOpenStatements();
|
||||
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
}
|
||||
|
||||
private function refreshOpenStatements(?int $groupId = null): void
|
||||
{
|
||||
$matcher = app(\App\Support\CourierBills\CourierBillMatcher::class);
|
||||
$this->store->db()->table('courier_bill_statements')->where('status', 'open')
|
||||
->when($groupId !== null, fn ($q) => $q->where('group_id', $groupId))
|
||||
->where('bill_month', '>=', now()->subMonthsNoOverflow(2)->format('Y-m'))->pluck('id')
|
||||
->each(fn ($id) => $matcher->refreshSummary((int) $id));
|
||||
}
|
||||
|
||||
public function exportStatement(Request $request, int $statement)
|
||||
{
|
||||
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
@ -479,6 +585,69 @@ final class CourierBillController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
/** 给对账分组配这家快递的钉钉对账群机器人(群设置 → 机器人 → 自定义,安全设置选「加签」)。 */
|
||||
public function saveRobot(Request $request, int $group)
|
||||
{
|
||||
$data = $request->validate(['webhook' => ['nullable', 'string', 'max:500'], 'secret' => ['nullable', 'string', 'max:256']]);
|
||||
$g = collect($this->store->groups())->firstWhere('id', $group);
|
||||
abort_if($g === null, 404);
|
||||
app(SupplierDingTalkNotifier::class)->save((string) $g->name, (string) ($data['webhook'] ?? ''), (string) ($data['secret'] ?? ''), false);
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已保存「' . $g->name . '」的钉钉对账群机器人。');
|
||||
}
|
||||
|
||||
/** 往快递钉钉对账群推这个月的免登录上传链接:传 group 只推这一家,不传就推所有配了机器人的分组。 */
|
||||
public function pushUploadLinks(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'group' => ['nullable', 'integer']]);
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$groups = collect($this->store->groups());
|
||||
if (! empty($data['group'])) {
|
||||
$groups = $groups->where('id', (int) $data['group']);
|
||||
abort_if($groups->isEmpty(), 404);
|
||||
}
|
||||
$configured = array_flip($notifier->configuredSuppliers());
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
$sent = $failed = [];
|
||||
$skipped = 0;
|
||||
// 批量推送:这个月已经推过、已经有账单的跳过;单独推某一家照发
|
||||
$pushes = app(\App\Support\CourierBills\CourierUploadPushes::class);
|
||||
$done = empty($data['group']) ? $pushes->done($data['month'], $companyId) : ['pushed' => [], 'uploaded' => []];
|
||||
$alreadyPushed = $alreadyUploaded = 0;
|
||||
foreach ($groups as $g) {
|
||||
if (isset($done['uploaded'][(int) $g->id])) {
|
||||
$alreadyUploaded++;
|
||||
continue;
|
||||
}
|
||||
if (isset($done['pushed'][(int) $g->id])) {
|
||||
$alreadyPushed++;
|
||||
continue;
|
||||
}
|
||||
if (! isset($configured[$g->name])) {
|
||||
$skipped++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$notifier->pushCourierUploadLink((string) $g->name, $data['month'],
|
||||
app(\App\Support\CourierBills\CourierUploadLink::class)->pageUrl($companyId, (int) $g->id, $data['month']));
|
||||
$sent[] = $g->name;
|
||||
$pushes->record($data['month'], (int) $g->id, $companyId, user()?->id);
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$failed[] = $g->name . '(发送失败,请检查群机器人配置)';
|
||||
}
|
||||
}
|
||||
if (! empty($data['group']) && $sent === [] && $failed === []) {
|
||||
throw ValidationException::withMessages(['courier_bills' => '这家还没有配置钉钉对账群机器人,请先在「对账分组」里配置。']);
|
||||
}
|
||||
|
||||
return $this->back($request, [], '已推送 ' . $data['month'] . ' 上传链接 ' . count($sent) . ' 家' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 30)) : '')
|
||||
. ($failed !== [] ? ';失败 ' . count($failed) . ' 家:' . implode('、', $failed) : '')
|
||||
. ($alreadyUploaded > 0 ? ';' . $alreadyUploaded . ' 家这个月已经有账单,没再推' : '')
|
||||
. ($alreadyPushed > 0 ? ';' . $alreadyPushed . ' 家这个月已经推过,没再推(要重发到「对账分组」里单独点)' : '')
|
||||
. ($skipped > 0 && empty($data['group']) ? ';' . $skipped . ' 家没配钉钉群机器人,没推' : '') . '。');
|
||||
}
|
||||
|
||||
private function back(Request $request, array $query, string $message)
|
||||
{
|
||||
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request),
|
||||
|
||||
@ -31,13 +31,13 @@ class CourierOnboardings extends Controller
|
||||
'courier_name' => ['required', 'string', 'max:100'],
|
||||
'invite_label' => ['nullable', 'string', 'max:100'],
|
||||
'valid_days' => ['nullable', 'integer', 'min:1', 'max:180'],
|
||||
'workplatform_expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/'],
|
||||
'workplatform_expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_.-]+$/'],
|
||||
// 资料由内部人员在钉钉后续节点补充;兼容旧请求中明确提交的字段。
|
||||
...CourierOnboarding::profileRules(true),
|
||||
], [
|
||||
'courier_name.required' => '请先定好系统快递名称(需与报价名、发货数据里的快递名称一致)。',
|
||||
'workplatform_expcode.required' => '请填写快递公司代码(与快递资料「快递公司代码」一致)。',
|
||||
'workplatform_expcode.regex' => '快递公司代码只能包含字母、数字、下划线和短横线。',
|
||||
'workplatform_expcode.regex' => '快递公司代码只能包含字母、数字、英文句点(.)、下划线和短横线。',
|
||||
...CourierOnboarding::profileMessages(),
|
||||
], CourierOnboarding::profileAttributes());
|
||||
$code = strtoupper(trim((string) $data['workplatform_expcode']));
|
||||
|
||||
@ -47,8 +47,8 @@ class CourierProfiles extends Controller
|
||||
public function storePaymentAccountForCode(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(
|
||||
['expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/']],
|
||||
['expcode.required' => '请填写快递公司代码。', 'expcode.regex' => '快递公司代码只能是字母、数字、下划线或短横线。'],
|
||||
['expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_.-]+$/']],
|
||||
['expcode.required' => '请填写快递公司代码。', 'expcode.regex' => '快递公司代码只能包含字母、数字、英文句点(.)、下划线和短横线。'],
|
||||
);
|
||||
|
||||
return $this->storePaymentAccount($request, trim($data['expcode']));
|
||||
|
||||
117
app/Http/Controllers/Business/CourierUploadShare.php
Normal file
117
app/Http/Controllers/Business/CourierUploadShare.php
Normal file
@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\CourierJointUploads;
|
||||
use App\Support\CourierBills\CourierUploadLink;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\PortalFreightBillImports;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 推送到快递钉钉对账群的免登录上传页:下载模板、按模板上传这一家这个月的账单,上传后进入快递账单对账。
|
||||
*/
|
||||
final class CourierUploadShare extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CourierBillStore $store,
|
||||
private readonly CourierUploadLink $links,
|
||||
private readonly FreightBillTemplate $template,
|
||||
private readonly PortalFreightBillImports $imports,
|
||||
) {}
|
||||
|
||||
public function show(Request $request, string $token): Response
|
||||
{
|
||||
$t = $this->target($request, $token);
|
||||
$expires = $this->expiresAt($request);
|
||||
$query = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']);
|
||||
if ($t['joint'] !== null) $query->where('extra_group_ids', json_encode(['joint_upload' => $t['payload']['joint']]));
|
||||
else $query->where(fn ($q) => $q->whereNull('extra_group_ids')->orWhere('extra_group_ids', 'not like', '%"joint_upload"%'));
|
||||
$files = $query->orderByDesc('id')->limit(20)->get();
|
||||
$pending = array_map(static fn (array $file): object => (object) [
|
||||
'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'],
|
||||
'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'],
|
||||
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'], $t['joint']['key'] ?? null));
|
||||
$files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values();
|
||||
|
||||
return response()->view('business.pages.courier-payables.courier-bills.upload-share', [
|
||||
'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files,
|
||||
'expiresAt' => $expires, 'confirmed' => $t['confirmed'],
|
||||
'joint' => $t['joint'], 'uploadLabel' => $t['joint']['label'] ?? $t['group']->name,
|
||||
'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires),
|
||||
'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $token, $t['companyId'], $expires),
|
||||
])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive',
|
||||
'Referrer-Policy' => 'no-referrer']);
|
||||
}
|
||||
|
||||
public function template(Request $request, string $token): StreamedResponse
|
||||
{
|
||||
$t = $this->target($request, $token);
|
||||
|
||||
return $this->template->download(($t['joint']['label'] ?? $t['group']->name) . '_' . $t['month'] . '_账单上传模板.xlsx');
|
||||
}
|
||||
|
||||
public function upload(Request $request, string $token): RedirectResponse
|
||||
{
|
||||
$t = $this->target($request, $token);
|
||||
$back = $this->links->signedRoute('signed.courier-bill-upload.show', $token, $t['companyId'], $this->expiresAt($request));
|
||||
if ($t['confirmed']) {
|
||||
throw ValidationException::withMessages(['upload' => '这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。']);
|
||||
}
|
||||
$request->validate(['import' => ['required', 'file', 'max:51200']], [], ['import' => '账单文件']);
|
||||
$file = $request->file('import');
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages(['upload' => '只支持 xlsx、xls、csv,请用上传模板。']);
|
||||
}
|
||||
$this->imports->submit($file, [
|
||||
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
|
||||
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
|
||||
'source' => 'courier_upload_link',
|
||||
'joint' => $t['payload']['joint'],
|
||||
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
|
||||
]);
|
||||
|
||||
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
|
||||
}
|
||||
|
||||
/** @return array{companyId:int,group:object,month:string,confirmed:bool,joint:?array,payload:array} */
|
||||
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, '链接无效或已过期。');
|
||||
$group = collect($this->store->groups())->firstWhere('id', $payload['group_id']);
|
||||
abort_if($group === null, 404, '链接无效或已过期。');
|
||||
$joint = null;
|
||||
if ($payload['joint'] !== null) {
|
||||
try { $joint = app(CourierJointUploads::class)->verify($payload['joint']); }
|
||||
catch (\RuntimeException $e) { abort(410, $e->getMessage()); }
|
||||
}
|
||||
$confirmed = $this->store->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$group->id])
|
||||
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
|
||||
|
||||
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed, 'joint' => $joint, 'payload' => $payload];
|
||||
}
|
||||
|
||||
private function expiresAt(Request $request): CarbonImmutable
|
||||
{
|
||||
$expires = (int) $request->query('expires', 0);
|
||||
|
||||
return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(CourierUploadLink::TTL_DAYS);
|
||||
}
|
||||
|
||||
private static function monthLabel(string $month): string
|
||||
{
|
||||
[$y, $m] = explode('-', $month);
|
||||
|
||||
return (int) $y . '年' . (int) $m . '月';
|
||||
}
|
||||
}
|
||||
@ -2,16 +2,24 @@
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Support\CourierBills\Category;
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\DropshipFreight\DropshipConfirmation;
|
||||
use App\Support\DropshipFreight\DropshipBillSummary;
|
||||
use App\Support\DropshipFreight\DropshipExporter;
|
||||
use App\Support\DropshipFreight\DropshipFees;
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use App\Support\DropshipFreight\DropshipReconciler;
|
||||
use App\Support\DropshipFreight\DropshipShareLink;
|
||||
use App\Support\DropshipFreight\DropshipUploadReminder;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
|
||||
final class DropshipFreightController extends Controller
|
||||
@ -22,6 +30,7 @@ final class DropshipFreightController extends Controller
|
||||
public function __construct(
|
||||
private readonly DropshipFreightStore $store,
|
||||
private readonly DropshipReconciler $reconciler,
|
||||
private readonly DropshipConfirmation $confirmations,
|
||||
) {}
|
||||
|
||||
public function page(Request $request): array
|
||||
@ -62,7 +71,17 @@ final class DropshipFreightController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfTotals' => [
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
|
||||
$fees = app(DropshipFees::class)->rows($month, array_column($rows, 'settle', 'factory_id'), self::companyId());
|
||||
$feeTotals = [];
|
||||
foreach ([...array_keys(DropshipFees::COLUMNS), 'total'] as $key) {
|
||||
$feeTotals[$key] = round(array_sum(array_map(static fn (array $f): float => $key === 'total' ? $f['total'] : $f['values'][$key], $fees)), 2);
|
||||
}
|
||||
|
||||
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfStates' => $this->confirmations->states($month, self::companyId()),
|
||||
'dfFees' => $fees, 'dfFeeTotals' => $feeTotals,
|
||||
'dfRobots' => $notifier->configurationMap(array_column($rows, 'factory')), 'dfTotals' => [
|
||||
'bill' => array_sum(array_column($rows, 'bill')), 'settle' => array_sum(array_column($rows, 'settle')),
|
||||
'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')),
|
||||
]];
|
||||
@ -77,6 +96,17 @@ final class DropshipFreightController extends Controller
|
||||
$result = $this->reconciler->factoryMonth($factory, $month);
|
||||
$status = (string) $request->query('status', '');
|
||||
$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') {
|
||||
$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)) {
|
||||
@ -87,7 +117,17 @@ final class DropshipFreightController extends Controller
|
||||
['path' => $request->url(), 'query' => $request->query()]);
|
||||
$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,
|
||||
'dfBillSummary' => app(DropshipBillSummary::class)->build($factory, $month, $result['rows']),
|
||||
'dfState' => $state, 'dfDisputes' => $disputes, 'dfCurrentDisputes' => $currentDisputes, 'dfDisputeMap' => $disputeMap,
|
||||
'dfSearch' => $search, 'dfFactoryStates' => $this->confirmations->states($month,self::companyId()), 'dfHistory' => $this->confirmations->history($month, (int)$factory->id, self::companyId()),
|
||||
'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
|
||||
@ -95,7 +135,8 @@ final class DropshipFreightController extends Controller
|
||||
$files = $this->store->db()->table('dropship_bill_files as f')->leftJoin('dropship_factories as d', 'd.id', '=', 'f.factory_id')
|
||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'd.name as factory_name']);
|
||||
|
||||
return ['dfFiles' => $files];
|
||||
return ['dfFiles' => $files, 'dfAutoRemind' => DropshipUploadReminder::enabled(),
|
||||
'dfDeadline' => DropshipUploadReminder::deadline($month)->format('n月j日')];
|
||||
}
|
||||
|
||||
public function upload(Request $request)
|
||||
@ -180,6 +221,129 @@ final class DropshipFreightController extends Controller
|
||||
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
|
||||
}
|
||||
|
||||
/** 财务点「核对完成」/「撤销」:核对完成的厂家才能推送给厂家确认。 */
|
||||
public function check(Request $request, int $factory)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'checked' => ['required', 'boolean']]);
|
||||
$f = $this->factory($factory);
|
||||
$summary = $this->reconciler->factoryMonth($f, $data['month'])['summary'];
|
||||
$this->guard(fn () => $this->confirmations->check($data['month'], $f, $summary, (bool) $data['checked'], self::companyId(),
|
||||
user()?->id, self::user()));
|
||||
|
||||
return $this->back($request, [], (bool) $data['checked'] ? '「' . $f->name . '」' . $data['month'] . ' 已标记核对完成,可以推送给厂家确认。'
|
||||
: '已撤销「' . $f->name . '」的核对完成。');
|
||||
}
|
||||
|
||||
/** 各厂家汇总:改这家这个月的快递记账、补运费、退回费等(空着 = 用厂家附加费表自动带入的值)和备注。 */
|
||||
public function saveFees(Request $request, int $factory)
|
||||
{
|
||||
$rules = ['month' => ['required', 'date_format:Y-m'], 'note' => ['nullable', 'string', 'max:255']];
|
||||
foreach (DropshipFees::EDITABLE as $key) {
|
||||
$rules['fees.' . $key] = ['nullable', 'numeric', 'between:-99999999,99999999'];
|
||||
}
|
||||
$data = $request->validate($rules, [], array_combine(array_map(static fn (string $k): string => 'fees.' . $k, DropshipFees::EDITABLE),
|
||||
array_map(static fn (string $k): string => DropshipFees::COLUMNS[$k], DropshipFees::EDITABLE)));
|
||||
$f = $this->factory($factory);
|
||||
app(DropshipFees::class)->save($data['month'], (int) $f->id, (array) ($data['fees'] ?? []), (string) ($data['note'] ?? ''), self::companyId(), user()?->id);
|
||||
|
||||
return $this->back($request, [], '已保存「' . $f->name . '」' . $data['month'] . ' 的费用和备注。');
|
||||
}
|
||||
|
||||
/** 推送到厂家钉钉群(和供应商货款对账同一个群机器人),附免登录确认页链接;重新推送版本号加一,旧链接作废。 */
|
||||
public function push(Request $request, int $factory)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m']]);
|
||||
$month = $data['month'];
|
||||
$f = $this->factory($factory);
|
||||
$result = $this->reconciler->factoryMonth($f, $month);
|
||||
$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']);
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
if (! $notifier->configuration((string) $f->name)['configured']) {
|
||||
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
|
||||
}
|
||||
$companyId = self::companyId();
|
||||
$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);
|
||||
try {
|
||||
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
|
||||
} catch (Throwable $error) {
|
||||
$this->confirmations->markFailed($month, (int) $f->id, $companyId, $error->getMessage());
|
||||
report($error);
|
||||
throw ValidationException::withMessages(['dropship' => '推送失败:' . $error->getMessage()]);
|
||||
}
|
||||
$this->confirmations->markPushed($month, (int) $f->id, $companyId);
|
||||
|
||||
return $this->back($request, [], '已推送到「' . $f->name . '」钉钉群(第 ' . $version . ' 次),等厂家在确认页确认。');
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知厂家上传代发运费账单:传 factory 只通知这一家;不传就通知这个月还没上传、且配了钉钉群机器人的全部厂家。
|
||||
*/
|
||||
public function notifyUpload(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
|
||||
$month = $data['month'];
|
||||
$single = ! empty($data['factory']);
|
||||
if ($single) {
|
||||
abort_if(collect($this->store->factories())->where('id', (int) $data['factory'])->isEmpty(), 404);
|
||||
}
|
||||
$result = app(DropshipUploadReminder::class)->remind($month, route('business.supplier-portal.home', ['company_id' => self::companyId()]),
|
||||
$single ? (int) $data['factory'] : null);
|
||||
if ($single && $result['no_robot'] !== []) {
|
||||
throw ValidationException::withMessages(['dropship' => '这家还没有配置钉钉群机器人(在供应商对账里配置,和货款对账同一个群)。']);
|
||||
}
|
||||
|
||||
return $this->back($request, [], self::reminderSummary($month, $result) . '。');
|
||||
}
|
||||
|
||||
/** 自动提醒开关。 */
|
||||
public function autoRemind(Request $request)
|
||||
{
|
||||
$on = $request->boolean('enabled');
|
||||
DropshipUploadReminder::setEnabled($on);
|
||||
|
||||
return $this->back($request, [], $on
|
||||
? '已开启自动提醒:每月 1–' . DropshipUploadReminder::DEADLINE_DAY . ' 日 ' . DropshipUploadReminder::SEND_TIME . ' 提醒还没上传上月代发运费账单的厂家。'
|
||||
: '已关闭自动提醒。');
|
||||
}
|
||||
|
||||
/** @param array{sent:list<string>,failed:list<string>,done:list<string>,no_shipment:list<string>,no_robot:list<string>,deadline:mixed} $r */
|
||||
public static function reminderSummary(string $month, array $r): string
|
||||
{
|
||||
return '已通知 ' . count($r['sent']) . ' 家上传 ' . $month . ' 代发运费账单' . ($r['sent'] !== [] ? ':' . implode('、', array_slice($r['sent'], 0, 40)) : '')
|
||||
. ($r['deadline'] !== null ? '(写明 ' . $r['deadline']->format('n月j日') . ' 截止,逾期本月货款和运费不予结算)' : '')
|
||||
. ($r['done'] !== [] ? ';' . count($r['done']) . ' 家已经上传,没再通知' : '')
|
||||
. ($r['no_shipment'] !== [] ? ';' . count($r['no_shipment']) . ' 家这个月没有代发发货,没通知' : '')
|
||||
. ($r['no_robot'] !== [] ? ';' . count($r['no_robot']) . ' 家没配钉钉群机器人:' . implode('、', array_slice($r['no_robot'], 0, 40)) : '')
|
||||
. ($r['failed'] !== [] ? ';发送失败:' . implode('、', $r['failed']) : '');
|
||||
}
|
||||
|
||||
/** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */
|
||||
public static function attention(array $rows): int
|
||||
{
|
||||
return count(array_filter($rows, static fn (array $r): bool => $r['bill'] !== null && $r['status'] !== Category::MATCH));
|
||||
}
|
||||
|
||||
private function factory(int $id): object
|
||||
{
|
||||
$factory = collect($this->store->factories())->firstWhere('id', $id);
|
||||
abort_if($factory === null, 404);
|
||||
|
||||
return $factory;
|
||||
}
|
||||
|
||||
private static function companyId(): int
|
||||
{
|
||||
return (int) (company_id() ?: 1);
|
||||
}
|
||||
|
||||
public function export(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
|
||||
@ -221,8 +385,8 @@ final class DropshipFreightController extends Controller
|
||||
|
||||
return response()->streamDownload(function () use ($factories, $month, $own): void {
|
||||
$book = new StreamingWorkbook();
|
||||
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)',
|
||||
'差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
||||
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '最终结算运费',
|
||||
'差额(厂家−最终结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
||||
$details = [];
|
||||
foreach ($factories as $factory) {
|
||||
$result = $this->reconciler->factoryMonth($factory, $month, $own);
|
||||
@ -233,10 +397,10 @@ final class DropshipFreightController extends Controller
|
||||
}
|
||||
foreach ($details as [$factory, $rows]) {
|
||||
$sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28);
|
||||
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true);
|
||||
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '最终结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true);
|
||||
foreach ($rows as $r) {
|
||||
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'],
|
||||
$r['diff'], $r['label'], $r['note'], $r['formula']]);
|
||||
$r['final'] ?? $r['settle'], $r['diff'], $r['label'], $r['note'], $r['formula']]);
|
||||
}
|
||||
}
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
|
||||
8
app/Http/Controllers/Business/DropshipFreightShare.php
Normal file
8
app/Http/Controllers/Business/DropshipFreightShare.php
Normal file
@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
final class DropshipFreightShare extends FreightConfirmationShare
|
||||
{
|
||||
protected string $kind = 'dropship';
|
||||
}
|
||||
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']);
|
||||
}
|
||||
}
|
||||
@ -1156,6 +1156,14 @@ class Pages extends Controller
|
||||
]));
|
||||
}
|
||||
|
||||
// 银行账户流水入口已下线,旧地址回到账单流水数据的首个有效页面。
|
||||
if ($section === 'billing-transactions' && $page === 'bank-transactions') {
|
||||
return redirect()->route('business.pages.show', [
|
||||
'section' => $section,
|
||||
'page' => 'store-receiving-bills',
|
||||
]);
|
||||
}
|
||||
|
||||
$pages = collect($sectionConfig['pages'] ?? []);
|
||||
|
||||
if ($pages->isEmpty()) {
|
||||
@ -1769,7 +1777,7 @@ class Pages extends Controller
|
||||
// 数据按天同步,同一组筛选 5 分钟内复用结果,避免来回切换筛选项重复扫整月。
|
||||
$differenceMaterialized = DifferenceMaterialization::materialized($month);
|
||||
$dataVersion = DifferenceMaterialization::dataVersion($month);
|
||||
$statsCacheKey = 'performance-details-aggregate-v2:' . md5(serialize([
|
||||
$statsCacheKey = 'performance-details-aggregate-v3:' . md5(serialize([
|
||||
$month,
|
||||
[$platformFilter, $storeFilter, $companyFilter, $statusFilter, $remarkFilter, $unmatchedReasonFilter, $differenceState, $orderNo],
|
||||
$crossMonthOnly,
|
||||
@ -1881,7 +1889,7 @@ class Pages extends Controller
|
||||
$storeFilter,
|
||||
array_map('strval', $filterOptions['stores'] ?? []),
|
||||
)));
|
||||
$companyOptions = array_keys($subjectContext['stores_by_company']);
|
||||
$companyOptions = array_keys($subjectContext['company_windows']);
|
||||
sort($companyOptions, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
$stats['company_options'] = array_values(array_unique(array_merge(
|
||||
$companyFilter,
|
||||
@ -2400,16 +2408,15 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前账期的店铺 → 主体映射。
|
||||
* 当前账期的店铺与主体期间映射。
|
||||
*
|
||||
* 主体字段由店铺当前存续主体派生,镜像表里没有可直接筛选的主体列;
|
||||
* 这里统一生成店铺名单、展示映射和“主体 → 店铺”关系,供页面、联动统计和导出共用。
|
||||
* 业绩明细按发生日期匹配主体生效、失效区间;这里生成当月每天实际对应的
|
||||
* “主体 → 店铺日期窗口”,供页面、指标、联动统计和导出共用。
|
||||
*
|
||||
* @return array{
|
||||
* store_names:list<string>,
|
||||
* subject_map:array<string,mixed>,
|
||||
* companies_by_store:array<string,string>,
|
||||
* stores_by_company:array<string,list<string>>
|
||||
* company_windows:array<string,list<array{store_name:string,effective_at:string,expires_at:string}>>
|
||||
* }
|
||||
*/
|
||||
private function receiptOrderMatchSubjectContext(string $month): array
|
||||
@ -2417,7 +2424,7 @@ class Pages extends Controller
|
||||
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
$storeNames = cache()->remember(
|
||||
'performance-details-subject-stores-v1:' . $companyId . ':' . $month,
|
||||
'performance-details-subject-stores-v2:' . $companyId . ':' . $month,
|
||||
now()->addHours(6),
|
||||
static fn (): array => DB::connection($connection)->table('store_receipt_order_match_rows')
|
||||
->where('report_month', $month)
|
||||
@ -2434,30 +2441,61 @@ class Pages extends Controller
|
||||
->all(),
|
||||
);
|
||||
|
||||
$subjectMap = $this->currentStoreSubjectMap($storeNames);
|
||||
$subjectMap = $this->performanceSubjectMap($storeNames);
|
||||
$matcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
$companiesByStore = [];
|
||||
$storesByCompany = [];
|
||||
foreach ($storeNames as $storeName) {
|
||||
$companyName = trim($matcher->companyForStore((string) $storeName, $subjectMap));
|
||||
if ($companyName === '') {
|
||||
continue;
|
||||
}
|
||||
$companiesByStore[(string) $storeName] = $companyName;
|
||||
$storesByCompany[$companyName][] = (string) $storeName;
|
||||
}
|
||||
ksort($storesByCompany, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
$companyWindows = cache()->remember(
|
||||
'performance-details-subject-windows-v1:'
|
||||
. $companyId . ':' . $month . ':' . sha1(serialize($subjectMap)),
|
||||
now()->addMinutes(5),
|
||||
static function () use ($matcher, $month, $storeNames, $subjectMap): array {
|
||||
$companyWindows = [];
|
||||
$monthStart = Carbon::parse($month)->startOfMonth();
|
||||
$monthEnd = $monthStart->copy()->endOfMonth();
|
||||
foreach ($storeNames as $storeName) {
|
||||
$cursor = $monthStart->copy();
|
||||
$openCompany = '';
|
||||
$openFrom = null;
|
||||
$lastDate = null;
|
||||
while ($cursor->lessThanOrEqualTo($monthEnd)) {
|
||||
$date = $cursor->toDateString();
|
||||
$companyName = trim($matcher->companyForStoreDate((string) $storeName, $date, $subjectMap));
|
||||
if ($companyName !== $openCompany) {
|
||||
if ($openCompany !== '' && $openFrom !== null && $lastDate !== null) {
|
||||
$companyWindows[$openCompany][] = [
|
||||
'store_name' => (string) $storeName,
|
||||
'effective_at' => $openFrom,
|
||||
'expires_at' => $lastDate,
|
||||
];
|
||||
}
|
||||
$openCompany = $companyName;
|
||||
$openFrom = $companyName !== '' ? $date : null;
|
||||
}
|
||||
$lastDate = $date;
|
||||
$cursor->addDay();
|
||||
}
|
||||
if ($openCompany !== '' && $openFrom !== null && $lastDate !== null) {
|
||||
$companyWindows[$openCompany][] = [
|
||||
'store_name' => (string) $storeName,
|
||||
'effective_at' => $openFrom,
|
||||
'expires_at' => $lastDate,
|
||||
];
|
||||
}
|
||||
}
|
||||
ksort($companyWindows, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
|
||||
return $companyWindows;
|
||||
},
|
||||
);
|
||||
|
||||
return [
|
||||
'store_names' => array_values($storeNames),
|
||||
'subject_map' => $subjectMap,
|
||||
'companies_by_store' => $companiesByStore,
|
||||
'stores_by_company' => $storesByCompany,
|
||||
'company_windows' => $companyWindows,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 主体筛选转换成镜像里的店铺条件;主体映射采用页面行展示的同一套当前主体口径。
|
||||
* 主体筛选转换成镜像里的店铺与发生日期条件;与页面行展示使用同一套期间口径。
|
||||
*
|
||||
* @param \Illuminate\Database\Query\Builder $query
|
||||
* @param list<string> $companyFilter
|
||||
@ -2479,19 +2517,30 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
$subjectContext ??= $this->receiptOrderMatchSubjectContext($month);
|
||||
$stores = [];
|
||||
$windows = [];
|
||||
foreach ($companyFilter as $companyName) {
|
||||
foreach ($subjectContext['stores_by_company'][$companyName] ?? [] as $storeName) {
|
||||
$stores[(string) $storeName] = true;
|
||||
foreach ($subjectContext['company_windows'][$companyName] ?? [] as $window) {
|
||||
$windows[] = $window;
|
||||
}
|
||||
}
|
||||
if ($stores === []) {
|
||||
if ($windows === []) {
|
||||
$query->whereRaw('1 = 0');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$query->whereIn('store_name', array_keys($stores));
|
||||
$query->where(function ($matches) use ($windows): void {
|
||||
$first = true;
|
||||
foreach ($windows as $window) {
|
||||
$condition = static function ($scope) use ($window): void {
|
||||
$scope->where('store_name', (string) $window['store_name'])
|
||||
->where('occurred_date', '>=', (string) $window['effective_at'])
|
||||
->where('occurred_date', '<=', (string) $window['expires_at']);
|
||||
};
|
||||
$first ? $matches->where($condition) : $matches->orWhere($condition);
|
||||
$first = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -2575,7 +2624,7 @@ class Pages extends Controller
|
||||
|
||||
// 联动统计要跑几次全表聚合,短时间内重复请求(页面加载 + 下拉刷新)直接吃缓存
|
||||
// 缓存键带上规则指纹、物化状态与数据版本:规则调整或重新物化后不会复用旧口径的结果。
|
||||
$cacheKey = 'performance-details-facets-v2:' . md5(serialize([
|
||||
$cacheKey = 'performance-details-facets-v3:' . md5(serialize([
|
||||
$month,
|
||||
$filters,
|
||||
$orderNo,
|
||||
@ -2683,6 +2732,7 @@ class Pages extends Controller
|
||||
$wantDifference = in_array('有差额', $differenceValues, true);
|
||||
$wantNoDifference = in_array('无差额', $differenceValues, true);
|
||||
$subjectContext = $this->receiptOrderMatchSubjectContext($month);
|
||||
$needsSubjectDate = in_array('company_name', $columns, true);
|
||||
|
||||
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
// 已物化的账期直接读规则序号列与默认差额列;未物化时回退实时规则表达式。
|
||||
@ -2698,7 +2748,9 @@ class Pages extends Controller
|
||||
->table('store_receipt_order_match_rows')
|
||||
->where('report_month', $month)
|
||||
->whereNotIn('platform', self::RECEIPT_MATCH_EXCLUDED_PLATFORMS)
|
||||
->select(['platform', 'store_name', 'match_status', 'remark'])
|
||||
->select($needsSubjectDate
|
||||
? ['platform', 'store_name', 'occurred_date', 'match_status', 'remark']
|
||||
: ['platform', 'store_name', 'match_status', 'remark'])
|
||||
->selectRaw($baseDifferenceExpression . ' AS base_difference')
|
||||
->selectRaw($reasonIndexExpression . ' AS reason_index');
|
||||
|
||||
@ -2733,10 +2785,14 @@ class Pages extends Controller
|
||||
$outer->whereRaw('ABS(' . $effective . ')' . ($wantDifference ? ' > 0.005' : ' <= 0.005'));
|
||||
}
|
||||
|
||||
$select = ['platform', 'store_name', 'match_status', 'remark', 'reason_index', 'base_difference'];
|
||||
if ($needsSubjectDate) {
|
||||
$select[] = 'occurred_date';
|
||||
}
|
||||
$rows = $outer
|
||||
->select(['platform', 'store_name', 'match_status', 'remark', 'reason_index', 'base_difference'])
|
||||
->select($select)
|
||||
->selectRaw('COUNT(*) AS total')
|
||||
->groupBy(['platform', 'store_name', 'match_status', 'remark', 'reason_index', 'base_difference'])
|
||||
->groupBy($select)
|
||||
->get();
|
||||
|
||||
$counts = [
|
||||
@ -2749,10 +2805,12 @@ class Pages extends Controller
|
||||
'difference_state' => [],
|
||||
];
|
||||
$wanted = array_fill_keys($columns, true);
|
||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
foreach ($rows as $row) {
|
||||
$total = (int) ($row->total ?? 0);
|
||||
$platform = (string) ($row->platform ?? '');
|
||||
$store = (string) ($row->store_name ?? '');
|
||||
$occurredDate = substr((string) ($row->occurred_date ?? ''), 0, 10);
|
||||
$status = (string) ($row->match_status ?? '');
|
||||
$rawRemark = trim((string) ($row->remark ?? ''));
|
||||
$reasonIndex = (int) ($row->reason_index ?? 0);
|
||||
@ -2765,7 +2823,11 @@ class Pages extends Controller
|
||||
$counts['store_name'][$store] = ($counts['store_name'][$store] ?? 0) + $total;
|
||||
}
|
||||
if (isset($wanted['company_name']) && $store !== '') {
|
||||
$companyName = trim((string) ($subjectContext['companies_by_store'][$store] ?? ''));
|
||||
$companyName = trim($subjectMatcher->companyForStoreDate(
|
||||
$store,
|
||||
$occurredDate,
|
||||
$subjectContext['subject_map'],
|
||||
));
|
||||
if ($companyName !== '') {
|
||||
$counts['company_name'][$companyName] = ($counts['company_name'][$companyName] ?? 0) + $total;
|
||||
}
|
||||
@ -2846,16 +2908,22 @@ class Pages extends Controller
|
||||
|
||||
$counts = [];
|
||||
if ($column === 'company_name') {
|
||||
$rows = $query->select('store_name')
|
||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
$rows = $query->select('store_name', 'occurred_date')
|
||||
->selectRaw('COUNT(*) AS total')
|
||||
->whereNotNull('store_name')
|
||||
->where('store_name', '!=', '')
|
||||
->groupBy('store_name')
|
||||
->pluck('total', 'store_name');
|
||||
foreach ($rows as $store => $total) {
|
||||
$companyName = trim((string) ($subjectContext['companies_by_store'][(string) $store] ?? ''));
|
||||
if ($companyName !== '' && (int) $total > 0) {
|
||||
$counts[$companyName] = ($counts[$companyName] ?? 0) + (int) $total;
|
||||
->groupBy('store_name', 'occurred_date')
|
||||
->get();
|
||||
foreach ($rows as $row) {
|
||||
$total = (int) ($row->total ?? 0);
|
||||
$companyName = trim($subjectMatcher->companyForStoreDate(
|
||||
(string) ($row->store_name ?? ''),
|
||||
substr((string) ($row->occurred_date ?? ''), 0, 10),
|
||||
$subjectContext['subject_map'],
|
||||
));
|
||||
if ($companyName !== '' && $total > 0) {
|
||||
$counts[$companyName] = ($counts[$companyName] ?? 0) + $total;
|
||||
}
|
||||
}
|
||||
} elseif ($column === 'remark') {
|
||||
@ -3036,7 +3104,7 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
$subjectMap = $this->currentStoreSubjectMap(
|
||||
$subjectMap = $this->performanceSubjectMap(
|
||||
(clone $query)->whereNotNull('store_name')->where('store_name', '!=', '')
|
||||
->distinct()->pluck('store_name')->all(),
|
||||
);
|
||||
@ -3134,7 +3202,7 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
/** @param list<string> $storeNames @return array<string,mixed> */
|
||||
private function currentStoreSubjectMap(array $storeNames): array
|
||||
private function performanceSubjectMap(array $storeNames): array
|
||||
{
|
||||
$names = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $name): string => trim((string) $name),
|
||||
@ -3142,7 +3210,7 @@ class Pages extends Controller
|
||||
))));
|
||||
sort($names, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
$cacheKey = 'current-store-subject-map-v2:'
|
||||
$cacheKey = 'performance-details-subject-map-v3:'
|
||||
. $companyId . ':' . sha1(implode("\n", $names));
|
||||
|
||||
return cache()->remember(
|
||||
@ -4970,17 +5038,14 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。
|
||||
* 按表维护的页面数据:终版页签及快递记账明细使用各自的独立数据集。
|
||||
*
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
protected function payablesFinalData(array $section, ?array $page): ?array
|
||||
{
|
||||
$sectionSlug = (string) ($section['slug'] ?? '');
|
||||
if (empty($page) || ! in_array($sectionSlug, [
|
||||
PayablesFinalRegistry::SECTION_SUPPLIER,
|
||||
PayablesFinalRegistry::SECTION_COURIER,
|
||||
], true)) {
|
||||
if (empty($page)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -4999,9 +5064,7 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
$keyword = trim((string) request('keyword', ''));
|
||||
$storeDataset = PayablesFinalActions::DATASET_PREFIX
|
||||
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
|
||||
. $dataset;
|
||||
$storeDataset = $registry->storeDataset($sectionSlug, $dataset);
|
||||
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
||||
$requestedMonth = trim((string) request('month', ''));
|
||||
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
||||
@ -5909,6 +5972,7 @@ class Pages extends Controller
|
||||
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
||||
'shipping-data' => $this->contentForShippingData(),
|
||||
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
||||
'returned-parcels' => app(ReturnedParcelController::class)->page(request()),
|
||||
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
||||
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
||||
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
||||
@ -5938,6 +6002,7 @@ class Pages extends Controller
|
||||
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
||||
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
||||
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
|
||||
'raw-statements' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->rawStatementsData(),
|
||||
'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
|
||||
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
||||
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
||||
@ -7199,6 +7264,9 @@ class Pages extends Controller
|
||||
['field' => 'barcode', 'label' => '条形码', 'type' => 'identifier'],
|
||||
['field' => 'product_name', 'label' => '商品名称', 'type' => 'text'],
|
||||
['field' => 'qty', 'label' => '数量', 'type' => 'number'],
|
||||
['field' => 'qc_charge_weight', 'label' => '计费重量(kg)', 'type' => 'number'],
|
||||
['field' => 'qc_rate', 'label' => '续重/费率', 'type' => 'text'],
|
||||
['field' => 'qc_freight', 'label' => '核算运费', 'type' => 'number'],
|
||||
['field' => 'pkg_count', 'label' => '件数', 'type' => 'text'],
|
||||
['field' => 'receiver_state', 'label' => '省', 'type' => 'text'],
|
||||
['field' => 'buyer_nick', 'label' => '买家昵称', 'type' => 'text'],
|
||||
@ -7210,6 +7278,9 @@ class Pages extends Controller
|
||||
['field' => 'freight', 'label' => '运费', 'type' => 'number'],
|
||||
['field' => 'online_weight', 'label' => '线上重量', 'type' => 'number'],
|
||||
['field' => 'actual_weight', 'label' => '实称重量', 'type' => 'number'],
|
||||
['field' => 'qc_measured_weight', 'label' => '称重重量(kg)', 'type' => 'number'],
|
||||
['field' => 'qc_first_price', 'label' => '首重(元)', 'type' => 'number'],
|
||||
['field' => 'qc_miandan', 'label' => '面单(元)', 'type' => 'number'],
|
||||
['field' => 'length_cm', 'label' => '长(cm)', 'type' => 'number'],
|
||||
['field' => 'width_cm', 'label' => '宽(cm)', 'type' => 'number'],
|
||||
['field' => 'height_cm', 'label' => '高(cm)', 'type' => 'number'],
|
||||
@ -7242,15 +7313,10 @@ class Pages extends Controller
|
||||
['field' => 'settle_freight', 'label' => '结算运费', 'type' => 'number'],
|
||||
['field' => 'front_no', 'label' => '换单前单号', 'type' => 'identifier'],
|
||||
// 报价核算(按报价管理里发货日生效的报价)
|
||||
['field' => 'qc_freight', 'label' => '核算运费', 'type' => 'number'],
|
||||
['field' => 'qc_diff', 'label' => '核算-聚水潭运费', 'type' => 'number'],
|
||||
['field' => 'qc_quote_version', 'label' => '报价版本', 'type' => 'identifier'],
|
||||
['field' => 'qc_basis', 'label' => '结算重量依据', 'type' => 'text'],
|
||||
['field' => 'qc_settle_weight', 'label' => '核算结算重量(kg)', 'type' => 'number'],
|
||||
['field' => 'qc_charge_weight', 'label' => '计费重量(kg)', 'type' => 'number'],
|
||||
['field' => 'qc_first_price', 'label' => '首重(元)', 'type' => 'number'],
|
||||
['field' => 'qc_rate', 'label' => '续重/费率', 'type' => 'text'],
|
||||
['field' => 'qc_miandan', 'label' => '面单(元)', 'type' => 'number'],
|
||||
['field' => 'qc_flat_price', 'label' => '一口价(元)', 'type' => 'number'],
|
||||
['field' => 'qc_extra_fee', 'label' => '多件/超长加收(元)', 'type' => 'number'],
|
||||
['field' => 'qc_formula', 'label' => '核算公式', 'type' => 'text'],
|
||||
@ -8742,6 +8808,7 @@ class Pages extends Controller
|
||||
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
||||
$pagePaymentAmount = '0.00';
|
||||
$filteredPaymentAmount = '0.00';
|
||||
$storePaymentSummary = [];
|
||||
$shopNames = [];
|
||||
$paymentReasons = [];
|
||||
$error = null;
|
||||
@ -8764,7 +8831,7 @@ class Pages extends Controller
|
||||
$shopNames = $filterOptions['shops'];
|
||||
$paymentReasons = $filterOptions['payment_reasons'];
|
||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
$subjectMap = $this->currentStoreSubjectMap(array_values(array_unique(array_merge(
|
||||
$subjectMap = $this->performanceSubjectMap(array_values(array_unique(array_merge(
|
||||
$shopNames,
|
||||
array_map(
|
||||
static fn (mixed $row): string => trim((string) data_get($row, 'shop_name', '')),
|
||||
@ -8772,7 +8839,7 @@ class Pages extends Controller
|
||||
),
|
||||
))));
|
||||
$items = Collection::make($result['data'] ?? [])->map(
|
||||
static fn (mixed $row): array => $subjectMatcher->applyArray(
|
||||
static fn (mixed $row): array => $subjectMatcher->applyArrayCurrent(
|
||||
is_array($row) ? $row : (array) $row,
|
||||
$subjectMap,
|
||||
),
|
||||
@ -8786,6 +8853,9 @@ class Pages extends Controller
|
||||
);
|
||||
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
||||
$filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00');
|
||||
$storePaymentSummary = is_array($result['store_summary'] ?? null)
|
||||
? $result['store_summary']
|
||||
: [];
|
||||
}
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
@ -8800,6 +8870,7 @@ class Pages extends Controller
|
||||
'smallPaymentSyncStatus' => $syncStatus,
|
||||
'smallPaymentPageAmount' => $pagePaymentAmount,
|
||||
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
||||
'smallPaymentStoreSummary' => $storePaymentSummary,
|
||||
'smallPaymentShops' => $shopNames,
|
||||
'smallPaymentReasons' => $paymentReasons,
|
||||
'smallPaymentStatuses' => [
|
||||
@ -8837,7 +8908,7 @@ class Pages extends Controller
|
||||
|
||||
$filterOptions = $this->smallPaymentWorkOrders->filterOptions();
|
||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||
$subjectMap = $this->currentStoreSubjectMap($filterOptions['shops'] ?? []);
|
||||
$subjectMap = $this->performanceSubjectMap($filterOptions['shops'] ?? []);
|
||||
|
||||
return $this->streamSmallPaymentWorkOrderCsv(
|
||||
$this->smallPaymentWorkOrders->exportRows($filters),
|
||||
@ -8964,7 +9035,7 @@ class Pages extends Controller
|
||||
fputcsv($csv, array_column($columns, 'label'));
|
||||
foreach ($rows as $row) {
|
||||
if ($subjectMatcher !== null) {
|
||||
$row = $subjectMatcher->applyArray(
|
||||
$row = $subjectMatcher->applyArrayCurrent(
|
||||
is_array($row) ? $row : (array) $row,
|
||||
$subjectMap,
|
||||
);
|
||||
|
||||
@ -16,8 +16,7 @@ use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 「终版」目录的按表数据:界面与基础页面一致,数据独立存放
|
||||
* (数据集键 final:<目录>:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。
|
||||
* 终版页签和快递记账明细的导入、导出及编辑,各入口使用独立数据集。
|
||||
*/
|
||||
class PayablesFinalActions extends Controller
|
||||
{
|
||||
@ -171,9 +170,7 @@ class PayablesFinalActions extends Controller
|
||||
|
||||
private function storeDataset(Request $request): string
|
||||
{
|
||||
$section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier';
|
||||
|
||||
return self::DATASET_PREFIX . $section . ':' . $this->dataset($request);
|
||||
return $this->registry->storeDataset($this->section($request), $this->dataset($request));
|
||||
}
|
||||
|
||||
private function csvText(mixed $value): string
|
||||
|
||||
@ -19,6 +19,9 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
/** 种菜报销工作台:上传参考名单、维护种菜额度规则、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
|
||||
class PlantingReimbursementWorkbench extends Controller
|
||||
{
|
||||
/** 需要放行检查通过才能导出的类型。 */
|
||||
private const GATED_EXPORTS = ['import-template'];
|
||||
|
||||
public function upload(Request $request, string $kind, References $references)
|
||||
{
|
||||
abort_unless(isset(References::KINDS[$kind]), 404);
|
||||
@ -59,9 +62,12 @@ class PlantingReimbursementWorkbench extends Controller
|
||||
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
|
||||
}
|
||||
// 放行检查替代原来的「去聚工单人工核对、勾选已核对」。
|
||||
$gate = Gate::check($result);
|
||||
if (! $gate['ok']) {
|
||||
return $this->back(request())->with('error', '暂不能导出:' . implode(';', $gate['reasons']) . '。');
|
||||
// 对账、报销明细随时可导出核对(只读,不影响任何操作);导入模版会被导入聚工单,仍需放行检查通过。
|
||||
if (in_array($type, self::GATED_EXPORTS, true)) {
|
||||
$gate = Gate::check($result);
|
||||
if (! $gate['ok']) {
|
||||
return $this->back(request())->with('error', '暂不能导出:' . implode(';', $gate['reasons']) . '。');
|
||||
}
|
||||
}
|
||||
$spreadsheet = $exporter->build($type, $result);
|
||||
|
||||
@ -82,14 +88,21 @@ class PlantingReimbursementWorkbench extends Controller
|
||||
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
||||
'digest_secret' => (string) $request->input('digest_secret', ''),
|
||||
'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', '钉钉机器人设置已保存。');
|
||||
}
|
||||
|
||||
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */
|
||||
/** 按发起人发送取消 / 待复查通知,须已启用逐单通知且放行检查通过。 */
|
||||
public function notify(Request $request, PageData $page, Robot $robot)
|
||||
{
|
||||
if (! $robot->cancelNoticesEnabled()) {
|
||||
return $this->back($request)->with('error', '取消 / 待复查工单通知已暂停,测试完成前不会发送。');
|
||||
}
|
||||
|
||||
$filters = $page->filters();
|
||||
try {
|
||||
$result = $page->build($filters);
|
||||
@ -158,7 +171,7 @@ class PlantingReimbursementWorkbench extends Controller
|
||||
|
||||
return response()->streamDownload(static function () use ($csv): void {
|
||||
echo $csv;
|
||||
}, '种菜额度规则_' . now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}, '种菜额度规则_' . \Modules\EcommerceFinance\Services\PlantingClock::now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
/** 报销佣金人员:新增一人。 */
|
||||
@ -195,7 +208,7 @@ class PlantingReimbursementWorkbench extends Controller
|
||||
return $this->back($request, 'pwb-commission')->with('error', '报销佣金人员导入失败:' . $exception->getMessage());
|
||||
}
|
||||
|
||||
return $this->back($request, 'pwb-commission')->with('success', sprintf('报销佣金人员导入:新增 %d 人,已在名单里 %d 人。', $result['added'], $result['skipped']));
|
||||
return $this->back($request, 'pwb-commission')->with('success', sprintf('报销佣金人员导入:新增 %d 人,更新报销平台 %d 人,未变 %d 人。', $result['added'], $result['updated'], $result['skipped']));
|
||||
}
|
||||
|
||||
public function exportCommission(CommissionPeople $people)
|
||||
@ -204,7 +217,7 @@ class PlantingReimbursementWorkbench extends Controller
|
||||
|
||||
return response()->streamDownload(static function () use ($csv): void {
|
||||
echo $csv;
|
||||
}, '报销佣金人员_' . now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}, '报销佣金人员_' . \Modules\EcommerceFinance\Services\PlantingClock::now()->format('Ymd') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
/** 预览钉钉表单:页面带上 ding_preview=1 时读取钉钉表单结构并按本批填好展示,不上传、不发起。 */
|
||||
|
||||
@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Services\Auth\SupplierPortalAccess;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\PortalFreightBills;
|
||||
use App\Support\CourierBills\PortalFreightBillImports;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 厂家门户(钉钉登录的供应商对账入口)上传运费账单:代发厂家传代发运费账单,快递传快递账单,统一模板、严格校验。
|
||||
* 厂家/快递只能给钉钉组织里绑定的自己上传;财务在同一页面可以代任意一家上传。
|
||||
*/
|
||||
final class PortalFreightBillController extends Controller
|
||||
{
|
||||
public const KINDS = ['dropship' => '代发运费账单', 'courier' => '快递账单'];
|
||||
|
||||
public function __construct(
|
||||
private readonly FreightBillTemplate $template,
|
||||
private readonly PortalFreightBills $portal,
|
||||
private readonly SupplierPortalAccess $access,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
}
|
||||
|
||||
public function template(): StreamedResponse
|
||||
{
|
||||
return $this->template->download('运费账单上传模板.xlsx');
|
||||
}
|
||||
|
||||
public function upload(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'kind' => ['required', 'in:dropship,courier'],
|
||||
'month' => ['required', 'date_format:Y-m'],
|
||||
'group' => ['nullable', 'integer'],
|
||||
'import' => ['required', 'file', 'max:51200'],
|
||||
], [], ['import' => '账单文件', 'month' => '账单月份']);
|
||||
$file = $request->file('import');
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']);
|
||||
}
|
||||
$name = $this->effectiveName($request);
|
||||
if ($data['kind'] === 'dropship') {
|
||||
$target = $this->portal->factory($name);
|
||||
} else {
|
||||
$groups = $this->portal->groups($name);
|
||||
$target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0));
|
||||
}
|
||||
if ($target === null) {
|
||||
throw ValidationException::withMessages(['freight_bill' => '当前厂家或快递分组不匹配,请联系财务。']);
|
||||
}
|
||||
app(PortalFreightBillImports::class)->submit($file, [
|
||||
'name' => $name, 'kind' => $data['kind'], 'month' => $data['month'], 'target_id' => (int) $target->id,
|
||||
'company_id' => (int) company_id(), 'user_id' => (int) $request->user()->id,
|
||||
'uploader' => mb_substr((string) ($request->user()->name ?: $request->user()->email) . '(门户)', 0, 64),
|
||||
]);
|
||||
|
||||
return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。');
|
||||
}
|
||||
|
||||
/** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */
|
||||
private function effectiveName(Request $request): string
|
||||
{
|
||||
$user = $request->user();
|
||||
$name = trim((string) $request->input('supplier', ''));
|
||||
if ($user && SupplierPortalAccess::isSupplierUser($user)) {
|
||||
$names = $this->access->supplierNamesFor($user);
|
||||
abort_if($names === [], 403, '当前钉钉账号未绑定有效厂家,请联系财务人员。');
|
||||
if (count($names) === 1 && $name === '') {
|
||||
return $names[0];
|
||||
}
|
||||
abort_unless(in_array($name, $names, true), 403, '该厂家不在当前账号的授权范围内。');
|
||||
|
||||
return $name;
|
||||
}
|
||||
if ($name === '') {
|
||||
throw ValidationException::withMessages(['freight_bill' => '请先选择厂家。']);
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
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\SupplierReturnCsvExporter;
|
||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementWorkbookExporter;
|
||||
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
@ -26,6 +27,8 @@ use Throwable;
|
||||
*/
|
||||
class SupplierReconciliation extends Controller
|
||||
{
|
||||
private const RAW_STATEMENT_PER_PAGE = 50;
|
||||
|
||||
public function __construct(
|
||||
private readonly SupplierStatementTemplate $template,
|
||||
private readonly SupplierStatementStore $statements,
|
||||
@ -36,6 +39,8 @@ class SupplierReconciliation extends Controller
|
||||
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
||||
private readonly SupplierPortalAccess $supplierPortalAccess,
|
||||
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
||||
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||
private readonly SupplierStatementWorkbookExporter $statementWorkbookExporter,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
@ -58,18 +63,29 @@ class SupplierReconciliation extends Controller
|
||||
$supplierPortalUpload = $request->user()
|
||||
&& SupplierPortalAccess::isSupplierUser($request->user());
|
||||
$supplier = $this->effectiveSupplier($request);
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
$uploadWindow = $this->pageData->statementUploadWindow($supplier, $companyId);
|
||||
if ($uploadWindow['locked']) {
|
||||
$errors = ['import' => $uploadWindow['message']];
|
||||
if ($request->expectsJson()) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return back()->withErrors($errors);
|
||||
}
|
||||
|
||||
$records = $this->template->parse($request->file('import'), $supplier);
|
||||
$rows = $this->statements->save(
|
||||
$supplier,
|
||||
$records,
|
||||
(string) $request->file('import')->getClientOriginalName(),
|
||||
(int) (company_id() ?: 1),
|
||||
$companyId,
|
||||
user_id() ? (int) user_id() : null,
|
||||
);
|
||||
|
||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||
$receiptNotice = '';
|
||||
$notices = [];
|
||||
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||
if ($supplierPortalUpload) {
|
||||
try {
|
||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||
@ -78,14 +94,30 @@ class SupplierReconciliation extends Controller
|
||||
$records,
|
||||
);
|
||||
if ($receiptSent) {
|
||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
||||
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
||||
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||
}
|
||||
|
||||
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 .= $receiptNotice !== '' ? $receiptNotice : '。';
|
||||
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json(['message' => $message, 'rows' => $rows])
|
||||
@ -145,6 +177,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
|
||||
{
|
||||
$request->validate([
|
||||
@ -283,7 +375,7 @@ class SupplierReconciliation extends Controller
|
||||
}
|
||||
$differences = array_values(array_filter(
|
||||
$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') {
|
||||
|
||||
@ -7,12 +7,14 @@ use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
@ -30,6 +32,7 @@ class SupplierReconciliation extends Controller
|
||||
private readonly SupplierReconciliationPageData $pageData,
|
||||
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
||||
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
||||
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||
) {
|
||||
}
|
||||
|
||||
@ -64,6 +67,15 @@ class SupplierReconciliation extends Controller
|
||||
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
|
||||
]);
|
||||
[, $supplier, $companyId] = $this->supplierContext();
|
||||
$uploadWindow = $this->pageData->statementUploadWindow($supplier, $companyId);
|
||||
if ($uploadWindow['locked']) {
|
||||
$errors = ['import' => $uploadWindow['message']];
|
||||
if ($request->expectsJson()) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return back()->withErrors($errors);
|
||||
}
|
||||
|
||||
$records = $this->template->parse($request->file('import'), $supplier);
|
||||
$rows = $this->statements->save(
|
||||
@ -74,7 +86,7 @@ class SupplierReconciliation extends Controller
|
||||
user_id() ? (int) user_id() : null,
|
||||
);
|
||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||
$receiptNotice = '';
|
||||
$notices = [];
|
||||
try {
|
||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||
$supplier,
|
||||
@ -82,13 +94,30 @@ class SupplierReconciliation extends Controller
|
||||
$records,
|
||||
);
|
||||
if ($receiptSent) {
|
||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
||||
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||
}
|
||||
} catch (Throwable $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()
|
||||
? response()->json(['message' => $message, 'rows' => $rows])
|
||||
@ -110,9 +139,10 @@ class SupplierReconciliation extends Controller
|
||||
public function confirmAllReturns(Request $request): RedirectResponse
|
||||
{
|
||||
[, $supplier, $companyId] = $this->supplierContext();
|
||||
$month = $this->pageData->accountingMonthKey();
|
||||
$keys = array_values(array_map(
|
||||
static fn (array $row): string => (string) ($row['_action_key'] ?? ''),
|
||||
$this->pageData->returnRowsForFilters($supplier, $companyId, $request->all()),
|
||||
$this->pageData->returnRowsForFilters($supplier, $companyId, $request->all(), $month),
|
||||
));
|
||||
$confirmed = $this->returnConfirmations->confirmAll(
|
||||
$supplier,
|
||||
@ -127,7 +157,12 @@ class SupplierReconciliation extends Controller
|
||||
public function exportReturns(Request $request): StreamedResponse
|
||||
{
|
||||
[, $supplier, $companyId] = $this->supplierContext();
|
||||
$rows = $this->pageData->returnRowsForFilters($supplier, $companyId, $request->query());
|
||||
$rows = $this->pageData->returnRowsForFilters(
|
||||
$supplier,
|
||||
$companyId,
|
||||
$request->query(),
|
||||
$this->pageData->accountingMonthKey(),
|
||||
);
|
||||
|
||||
return $this->returnCsvExporter->download($rows, $supplier);
|
||||
}
|
||||
@ -137,7 +172,11 @@ class SupplierReconciliation extends Controller
|
||||
$request->validate(['key' => ['required', 'string', 'max:191']]);
|
||||
[, $supplier, $companyId] = $this->supplierContext();
|
||||
$key = (string) $request->input('key');
|
||||
$owned = collect($this->pageData->returnRows($supplier, $companyId))
|
||||
$owned = collect($this->pageData->returnRowsForMonth(
|
||||
$supplier,
|
||||
$companyId,
|
||||
$this->pageData->accountingMonthKey(),
|
||||
))
|
||||
->contains(static fn (array $row): bool => (string) ($row['_action_key'] ?? '') === $key);
|
||||
abort_unless($owned, 403, '该退货明细不属于当前厂家账号。');
|
||||
|
||||
|
||||
@ -13,11 +13,13 @@ class SupplierPortalSupplier extends Model
|
||||
'supplier_name',
|
||||
'dingtalk_group_id',
|
||||
'dingtalk_group_name',
|
||||
'manually_bound',
|
||||
'last_verified_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'dingtalk_group_id' => 'integer',
|
||||
'manually_bound' => 'boolean',
|
||||
'last_verified_at' => 'datetime',
|
||||
];
|
||||
|
||||
|
||||
@ -8,6 +8,7 @@ use App\Models\Auth\SupplierPortalSupplier;
|
||||
use App\Models\Auth\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||
@ -129,6 +130,20 @@ class SupplierPortalAccess
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
// 快递:部门名是快递账单对账分组名或承运商名的,也能登录厂家门户上传快递账单(不在供应商主档里)
|
||||
foreach (\App\Support\CourierBills\PortalFreightBills::courierNames(array_keys($groupsByName)) as $courierName) {
|
||||
if (isset($matchedSupplierNames[$courierName])) {
|
||||
continue;
|
||||
}
|
||||
usort($groupsByName[$courierName], static fn (array $left, array $right): int =>
|
||||
(int) ($right['depth'] ?? 0) <=> (int) ($left['depth'] ?? 0));
|
||||
$resolved[] = [
|
||||
'supplier_name' => $courierName,
|
||||
'supplier_code' => '',
|
||||
'dingtalk_group_id' => (int) ($groupsByName[$courierName][0]['Id'] ?? 0),
|
||||
'dingtalk_group_name' => $courierName,
|
||||
];
|
||||
}
|
||||
foreach (array_keys($matchedSupplierNames) as $supplierName) {
|
||||
$matchingRows = array_values(array_filter(
|
||||
$supplierRows,
|
||||
@ -209,24 +224,27 @@ class SupplierPortalAccess
|
||||
);
|
||||
|
||||
foreach ($suppliers as $resolvedSupplier) {
|
||||
SupplierPortalSupplier::query()->updateOrCreate(
|
||||
[
|
||||
'company_id' => $companyId,
|
||||
'user_id' => $user->id,
|
||||
'supplier_name' => $resolvedSupplier['supplier_name'],
|
||||
],
|
||||
[
|
||||
'supplier_code' => $resolvedSupplier['supplier_code'] ?? null,
|
||||
'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'],
|
||||
'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'],
|
||||
'last_verified_at' => now(),
|
||||
],
|
||||
);
|
||||
$binding = SupplierPortalSupplier::query()->firstOrNew([
|
||||
'company_id' => $companyId,
|
||||
'user_id' => $user->id,
|
||||
'supplier_name' => $resolvedSupplier['supplier_name'],
|
||||
]);
|
||||
$binding->fill([
|
||||
'supplier_code' => $resolvedSupplier['supplier_code'] ?? null,
|
||||
'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'],
|
||||
'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'],
|
||||
'last_verified_at' => now(),
|
||||
]);
|
||||
if (! $binding->exists) {
|
||||
$binding->manually_bound = false;
|
||||
}
|
||||
$binding->save();
|
||||
}
|
||||
|
||||
SupplierPortalSupplier::query()
|
||||
->where('company_id', $companyId)
|
||||
->where('user_id', $user->id)
|
||||
->where('manually_bound', false)
|
||||
->whereNotIn('supplier_name', $suppliers->pluck('supplier_name')->all())
|
||||
->delete();
|
||||
|
||||
@ -238,6 +256,41 @@ class SupplierPortalAccess
|
||||
});
|
||||
}
|
||||
|
||||
public function bindManualSupplier(
|
||||
User $user,
|
||||
int $companyId,
|
||||
string $supplierName,
|
||||
): SupplierPortalSupplier {
|
||||
$supplierName = trim($supplierName);
|
||||
if ($supplierName === '') {
|
||||
throw new InvalidArgumentException('供应商名称不能为空。');
|
||||
}
|
||||
|
||||
$matches = array_values(array_filter(
|
||||
$this->suppliers->suppliersByNames([$supplierName]),
|
||||
static fn (object $supplier): bool =>
|
||||
trim((string) ($supplier->scmname ?? '')) === $supplierName,
|
||||
));
|
||||
if (count($matches) !== 1) {
|
||||
throw new InvalidArgumentException('供应商主档中必须存在唯一同名厂家。');
|
||||
}
|
||||
|
||||
return SupplierPortalSupplier::query()->updateOrCreate(
|
||||
[
|
||||
'company_id' => $companyId,
|
||||
'user_id' => $user->id,
|
||||
'supplier_name' => $supplierName,
|
||||
],
|
||||
[
|
||||
'supplier_code' => trim((string) ($matches[0]->scmcode ?? '')),
|
||||
'dingtalk_group_id' => 0,
|
||||
'dingtalk_group_name' => $supplierName,
|
||||
'manually_bound' => true,
|
||||
'last_verified_at' => now(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
public function mappingFor(User $user): ?SupplierPortalIdentity
|
||||
{
|
||||
if (! self::isSupplierUser($user)) {
|
||||
|
||||
@ -21,7 +21,7 @@ final class BillParser
|
||||
/** 金额列名里出现这些字,整张表当附加费表,不读。 */
|
||||
public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价'];
|
||||
/** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */
|
||||
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目'];
|
||||
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目', '附加费类型'];
|
||||
|
||||
private const HEADER_SCAN_ROWS = 15;
|
||||
private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额'];
|
||||
@ -169,7 +169,7 @@ final class BillParser
|
||||
}
|
||||
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
||||
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||
$skip[$sheet] = ['附加费表:按单号和费用类型匹配结算', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
||||
$freight[] = $sheet;
|
||||
} else {
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -44,14 +44,20 @@ final class CourierBillMatcher
|
||||
|
||||
$settled = [];
|
||||
foreach (array_chunk($waybills, 500) as $chunk) {
|
||||
foreach ($db->table('courier_bill_ledger')->where('group_id', $statement->group_id)->whereIn('waybill_no', $chunk)
|
||||
->where('settle_month', '<>', $month)->get(['waybill_no', 'settle_month']) as $row) {
|
||||
$settled[strtoupper($row->waybill_no)] = $row->settle_month;
|
||||
// 查重按单号:别的月份结算过(不论哪个分组、系统确认还是历史导入)就算重复,取最早那个月
|
||||
foreach ($db->table('courier_bill_ledger')->whereIn('waybill_no', $chunk)
|
||||
->where('settle_month', '<>', $month)->orderBy('settle_month')->get(['waybill_no', 'settle_month']) as $row) {
|
||||
$settled[strtoupper($row->waybill_no)] ??= $row->settle_month;
|
||||
}
|
||||
}
|
||||
$unshipped = $this->unshipped->unshippedSources($waybills);
|
||||
$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])));
|
||||
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
||||
@ -88,7 +94,7 @@ final class CourierBillMatcher
|
||||
$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 {
|
||||
foreach ($updates as $id => $values) {
|
||||
@ -253,13 +259,17 @@ final class CourierBillMatcher
|
||||
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
||||
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
||||
$kinds['配件补发扣款'] = 'accessory';
|
||||
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
|
||||
$surchargeMatcher->courier($statementId);
|
||||
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
|
||||
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
|
||||
$fees = $this->surchargeItems($statementId);
|
||||
$template = $this->templateFor($statementId);
|
||||
$this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
|
||||
$sort = 8000;
|
||||
foreach ($fees as $item => $sum) {
|
||||
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
||||
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填
|
||||
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
|
||||
$items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
|
||||
$kinds[$item] = 'fee';
|
||||
}
|
||||
}
|
||||
@ -301,6 +311,34 @@ final class CourierBillMatcher
|
||||
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 历史账单补接附加费时只更新费用行,保留原运费与手工小汇总。 */
|
||||
public function refreshSurchargeSummary(int $statementId): void
|
||||
{
|
||||
$db=self::db();
|
||||
$db->transaction(function()use($db,$statementId):void{
|
||||
$statement=$db->table('courier_bill_statements')->where('id',$statementId)->lockForUpdate()->first();
|
||||
if(!$statement||$statement->status==='confirmed')return;
|
||||
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($statementId);
|
||||
if(!$matcher->ready())return;
|
||||
$sums=$matcher->query('courier',$statementId)->selectRaw('summary_label,SUM(bill_amount) AS bill,SUM(self_amount) AS self')
|
||||
->groupBy('summary_label')->get();
|
||||
$auto=[];foreach($sums as $sum)$auto[$sum->summary_label]=['bill'=>(float)$sum->bill,'self'=>(float)$sum->self,'kind'=>'fee'];
|
||||
$template=$this->templateFor($statementId);
|
||||
$rows=$template===null?array_map(fn($label,$v)=>['label'=>$label]+$v,array_keys($auto),array_values($auto))
|
||||
:array_values(array_filter(SummaryTemplate::apply($template,$auto,(int)substr($statement->bill_month,5,2)),fn($r)=>$r['fee']));
|
||||
foreach($rows as $row){
|
||||
$existing=$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->where('label',$row['label'])->orderBy('id')->first();
|
||||
if($existing){
|
||||
if(!$existing->manual)$db->table('courier_bill_summary_items')->where('id',$existing->id)->update(['self_amount'=>round((float)$row['self'],2)]);
|
||||
}else{
|
||||
$sort=(int)$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->max('sort')+1;
|
||||
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$statementId,'label'=>$row['label'],
|
||||
'bill_amount'=>$row['bill'],'self_amount'=>round((float)$row['self'],2),'manual'=>false,'sort'=>$sort]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
||||
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
||||
@ -328,6 +366,38 @@ final class CourierBillMatcher
|
||||
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 补记账:按扣款月份各一行「补X月记账」(快递金额空、自算为补款金额),照模板落到「补9月记账」「2026.8-9月记账补款」「补记账」这类行。
|
||||
* 已经手工加了补记账行时不再自动加,免得补两次;记账明细、复核还没导时不加。
|
||||
*
|
||||
* @param list<string>|null $template
|
||||
* @param \Illuminate\Support\Collection<string,int> $manualLabels
|
||||
* @param array<string,array{bill:?float,self:float,sort:int}> $items
|
||||
* @param array<string,string> $kinds
|
||||
*/
|
||||
private function addRebooks(int $statementId, ?array $template, $manualLabels, array &$items, array &$kinds): void
|
||||
{
|
||||
foreach ($manualLabels->keys() as $label) {
|
||||
if (Rebooks::isRebookLabel((string) $label)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
$plan = app(Rebooks::class)->forStatement($statementId, $template);
|
||||
} catch (\Throwable $error) {
|
||||
report($error);
|
||||
|
||||
return;
|
||||
}
|
||||
$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> */
|
||||
public function feeLabels(int $statementId): array
|
||||
{
|
||||
@ -379,7 +449,7 @@ final class CourierBillMatcher
|
||||
|
||||
/**
|
||||
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。
|
||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
|
||||
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
||||
*
|
||||
* @return array<string,float>
|
||||
@ -394,9 +464,11 @@ final class CourierBillMatcher
|
||||
return [];
|
||||
}
|
||||
$result = [];
|
||||
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
|
||||
foreach ($primaryIds as $fileId => $primaryId) {
|
||||
$primary = (int) $primaryId;
|
||||
$files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
|
||||
foreach ($files as $file) {
|
||||
$fileId = (int) $file->id;
|
||||
$primary = (int) $file->statement_id;
|
||||
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
|
||||
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
||||
if (! (clone $rows)->exists()) {
|
||||
continue;
|
||||
@ -414,11 +486,14 @@ final class CourierBillMatcher
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void {
|
||||
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
|
||||
$assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId)
|
||||
->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : [];
|
||||
$shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all(), array_keys($names));
|
||||
foreach ($chunk as $row) {
|
||||
$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;
|
||||
}
|
||||
$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),
|
||||
'updated_at' => now(),
|
||||
];
|
||||
if (array_key_exists('rebook_months', $data)) {
|
||||
// 补记账补几个月:空 = 按小汇总识别
|
||||
$values['rebook_months'] = in_array($data['rebook_months'], [null, ''], true) ? null : min(max((int) $data['rebook_months'], 0), Rebooks::MAX_MONTHS);
|
||||
}
|
||||
if ($id === null) {
|
||||
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
||||
}
|
||||
@ -352,6 +356,41 @@ final class CourierBillStore
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/** 门户上传仅写入已授权分组;不从可控文件名或合并账单配置扩展到其他分组。 */
|
||||
public function uploadFor(\Illuminate\Http\UploadedFile $file, string $month, int $groupId, string $user): int
|
||||
{
|
||||
$groups = $this->groups();
|
||||
if (! collect($groups)->contains('id', $groupId)) throw new RuntimeException('快递分组不存在。');
|
||||
$id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month, [$groupId], $groups, $user, true);
|
||||
foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId);
|
||||
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
|
||||
{
|
||||
@ -384,6 +423,7 @@ final class CourierBillStore
|
||||
$db->transaction(function () use ($db, $file): void {
|
||||
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
|
||||
if(app(SurchargeSettlementMatcher::class)->ready())$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('file_id',$file->id)->delete();
|
||||
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
||||
});
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
@ -413,7 +453,7 @@ final class CourierBillStore
|
||||
* @param list<int> $groupIds
|
||||
* @param list<object> $groups
|
||||
*/
|
||||
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): 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));
|
||||
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||
@ -422,11 +462,11 @@ final class CourierBillStore
|
||||
$group = $groupIds !== []
|
||||
? collect($groups)->firstWhere('id', $groupIds[0])
|
||||
: self::identify($name, $groups);
|
||||
$extra = array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)]));
|
||||
$extra = $portal ? [] : array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)]));
|
||||
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
|
||||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
|
||||
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
||||
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
|
||||
'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
|
||||
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
||||
]);
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
@ -435,17 +475,23 @@ final class CourierBillStore
|
||||
return $id;
|
||||
}
|
||||
if ($group !== null) {
|
||||
$this->ingest($id, $group);
|
||||
$this->ingest($id, $group, false, $portal);
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */
|
||||
private function ingest(int $fileId, object $group, bool $reread = false): void
|
||||
private function ingest(int $fileId, object $group, bool $reread = false, bool $portal = false): void
|
||||
{
|
||||
$db = $this->db();
|
||||
$file = $db->table('courier_bill_files')->find($fileId);
|
||||
$joint = json_decode((string) $file->extra_group_ids, true)['joint_upload'] ?? null;
|
||||
if ($joint !== null) {
|
||||
$set = app(CourierJointUploads::class)->verify($joint);
|
||||
$this->lockJointTargets($set['group_ids'], (string) $file->bill_month);
|
||||
$portal = true;
|
||||
}
|
||||
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
|
||||
if ($statement !== null && $statement->status === 'confirmed') {
|
||||
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
||||
@ -471,7 +517,7 @@ final class CourierBillStore
|
||||
$feeCount = 0;
|
||||
$overlap = null;
|
||||
try {
|
||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$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') {
|
||||
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
||||
}
|
||||
@ -480,7 +526,9 @@ final class CourierBillStore
|
||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
|
||||
}
|
||||
$db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete();
|
||||
$overrides = ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
|
||||
$overrides = $portal
|
||||
? ['waybill_header' => '单号', 'amount_header' => '运费', 'weight_header' => '重量']
|
||||
: ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
|
||||
foreach ($this->parser->parse($path, $extension, $overrides) as $item) {
|
||||
if ($item['type'] === 'sheet') {
|
||||
$sheets[] = isset($item['skipped'])
|
||||
@ -550,7 +598,7 @@ final class CourierBillStore
|
||||
$db->table('courier_bill_surcharges')->insert($fees);
|
||||
}
|
||||
|
||||
return $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) {
|
||||
if ($reread) {
|
||||
@ -581,7 +629,7 @@ final class CourierBillStore
|
||||
$notes[] = '没有找到含单号和运费列的工作表';
|
||||
}
|
||||
if ($feeCount > 0) {
|
||||
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
|
||||
$notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
|
||||
}
|
||||
$unread = [];
|
||||
foreach ($sheets as $sheet) {
|
||||
@ -629,6 +677,8 @@ final class CourierBillStore
|
||||
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
||||
{
|
||||
$db = $this->db();
|
||||
$metadata = json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true);
|
||||
if (isset($metadata['joint_upload'])) return $this->splitJoint($fileId, $month, $metadata['joint_upload']);
|
||||
$groups = collect($this->groups());
|
||||
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
|
||||
$bundle = trim((string) ($primary->bundle ?? ''));
|
||||
@ -651,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']);
|
||||
$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 = [];
|
||||
$strangers = [];
|
||||
foreach ($lines as $line) {
|
||||
@ -709,6 +760,56 @@ final class CourierBillStore
|
||||
return implode(';', $parts);
|
||||
}
|
||||
|
||||
/** 只在签名授权范围内逐批归组;任何无法归属的行整份退回,避免留在错误的主分组。 */
|
||||
private function splitJoint(int $fileId, string $month, array $scope): string
|
||||
{
|
||||
$db = $this->db();
|
||||
$set = app(CourierJointUploads::class)->verify($scope);
|
||||
$this->lockJointTargets($set['group_ids'], $month);
|
||||
$owners = [];
|
||||
$statements = [];
|
||||
foreach ($set['groups'] as $g) {
|
||||
foreach (array_intersect(array_unique([$g->name, ...$g->express_names]), $set['names']) as $name) {
|
||||
if (isset($owners[$name]) && $owners[$name] !== (int) $g->id) throw new RuntimeException('联合上传快递名称重复,请联系财务。');
|
||||
$owners[$name] = (int) $g->id;
|
||||
}
|
||||
$statement = $db->table('courier_bill_statements')->where('group_id', $g->id)->where('bill_month', $month)->first();
|
||||
if ($statement !== null) $statements[(int) $g->id] = (int) $statement->id;
|
||||
}
|
||||
$counts = [];
|
||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void {
|
||||
$shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all(), 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
||||
* 涉及的对账单有已确认结算的就不动。
|
||||
@ -914,7 +1015,7 @@ final class CourierBillStore
|
||||
return $files;
|
||||
}
|
||||
|
||||
/** 确认结算:锁定对账单,结算台账记下这批单号。 */
|
||||
/** 确认结算:锁定对账单,结算台账记下这批单号;这期补记账补的单记进补记账台账(补过的不再补)。 */
|
||||
public function confirm(int $statementId, string $user): void
|
||||
{
|
||||
$db = $this->db();
|
||||
@ -947,6 +1048,9 @@ final class CourierBillStore
|
||||
if ($buffer !== []) {
|
||||
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
|
||||
}
|
||||
$rebooks = app(Rebooks::class);
|
||||
$rebooks->forget((int) $statement->id);
|
||||
$rebooks->record((int) $statement->id);
|
||||
$db->table('courier_bill_statements')->where('id', $statement->id)->update([
|
||||
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
|
||||
]);
|
||||
@ -958,6 +1062,7 @@ final class CourierBillStore
|
||||
$db = $this->db();
|
||||
$db->transaction(function () use ($db, $statementId): void {
|
||||
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
||||
app(Rebooks::class)->forget($statementId);
|
||||
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
||||
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
||||
]);
|
||||
@ -1085,19 +1190,21 @@ final class CourierBillStore
|
||||
});
|
||||
}
|
||||
|
||||
/** 历史导入的已结算单号不分对账分组,group_id 记 0;查重按单号,不看分组。 */
|
||||
public const LEDGER_NO_GROUP = 0;
|
||||
|
||||
/**
|
||||
* 导入历史已结算单号:表头含 分组、单号、结算月份,可选 金额。
|
||||
* 导入系统上线前已结算的单号:只要「单号」「结算月份」两列(可带「金额」)。导入后这些单号再出现在任何一家的账单里,
|
||||
* 只要结算月份不是本月,就归「重复」。
|
||||
*
|
||||
* @return array{rows:int,inserted:int,unknown_groups:list<string>,rejected:int}
|
||||
* @return array{rows:int,inserted:int,rejected:int}
|
||||
*/
|
||||
public function importLedger(string $path, string $extension): array
|
||||
{
|
||||
$groups = collect($this->groups())->keyBy('name');
|
||||
$reader = new BillWorkbookReader();
|
||||
$rows = 0;
|
||||
$inserted = 0;
|
||||
$rejected = 0;
|
||||
$unknown = [];
|
||||
$buffer = [];
|
||||
$flush = function () use (&$buffer, &$inserted): void {
|
||||
if ($buffer !== []) {
|
||||
@ -1112,32 +1219,26 @@ final class CourierBillStore
|
||||
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
|
||||
$find = static fn (array $names): ?int => collect($names)->map(static fn ($n) => array_search($n, $header, true))
|
||||
->first(static fn ($i) => $i !== false);
|
||||
$columns = ['group' => $find(['分组', '对账分组']), 'waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
||||
$columns = ['waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
||||
'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])];
|
||||
if ($columns['group'] === null || $columns['waybill'] === null || $columns['month'] === null) {
|
||||
throw new RuntimeException('表头须含「分组」「单号」「结算月份」三列(金额可选)。');
|
||||
if ($columns['waybill'] === null || $columns['month'] === null) {
|
||||
throw new RuntimeException('表头须含「单号」「结算月份」两列(金额可选)。');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$groupName = trim((string) ($row[$columns['group']] ?? ''));
|
||||
$waybillRaw = trim((string) ($row[$columns['waybill']] ?? ''));
|
||||
if ($groupName === '' && $waybillRaw === '') {
|
||||
$monthRaw = trim((string) ($row[$columns['month']] ?? ''));
|
||||
if ($waybillRaw === '' && $monthRaw === '') {
|
||||
continue;
|
||||
}
|
||||
$rows++;
|
||||
$group = $groups->get($groupName);
|
||||
if ($group === null) {
|
||||
$unknown[$groupName] = true;
|
||||
$rejected++;
|
||||
continue;
|
||||
}
|
||||
$waybill = Waybill::normalize($waybillRaw);
|
||||
$month = self::month((string) ($row[$columns['month']] ?? ''));
|
||||
$month = self::month($monthRaw);
|
||||
if ($waybill === null || $month === null) {
|
||||
$rejected++;
|
||||
continue;
|
||||
}
|
||||
$buffer[] = ['group_id' => $group->id, 'waybill_no' => $waybill, 'settle_month' => $month,
|
||||
$buffer[] = ['group_id' => self::LEDGER_NO_GROUP, 'waybill_no' => $waybill, 'settle_month' => $month,
|
||||
'amount' => $columns['amount'] === null ? null : BillParser::number($row[$columns['amount']] ?? null),
|
||||
'statement_id' => null, 'created_at' => now()];
|
||||
if (count($buffer) >= 500) {
|
||||
@ -1148,7 +1249,7 @@ final class CourierBillStore
|
||||
}
|
||||
$flush();
|
||||
|
||||
return ['rows' => $rows, 'inserted' => $inserted, 'unknown_groups' => array_keys($unknown), 'rejected' => $rejected];
|
||||
return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected];
|
||||
}
|
||||
|
||||
private function assertOpen(int $statementId): void
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
63
app/Support/CourierBills/CourierUploadLink.php
Normal file
63
app/Support/CourierBills/CourierUploadLink.php
Normal file
@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 快递上传账单的免登录链接:推送到这家快递的钉钉对账群,链接里带公司、对账分组、账单月份(加密 + Laravel 签名),
|
||||
* 只能给这一家这一个月上传,不能看别家,也看不到对账结果。
|
||||
*/
|
||||
final class CourierUploadLink
|
||||
{
|
||||
public const TTL_DAYS = 30;
|
||||
|
||||
public function pageUrl(int $companyId, int $groupId, string $month): string
|
||||
{
|
||||
return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId);
|
||||
}
|
||||
|
||||
public function jointPageUrl(int $companyId, string $key, string $month): string
|
||||
{
|
||||
$joint = app(CourierJointUploads::class)->snapshot($key);
|
||||
$payload = ['company_id' => $companyId, 'group_id' => $joint['group_ids'][0], 'month' => $month, 'joint' => $joint];
|
||||
$token = rtrim(strtr(base64_encode(Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR))), '+/', '-_'), '=');
|
||||
|
||||
return $this->signedRoute('signed.courier-bill-upload.show', $token, $companyId);
|
||||
}
|
||||
|
||||
public function signedRoute(string $routeName, string $token, int $companyId, ?\DateTimeInterface $expires = null): string
|
||||
{
|
||||
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
|
||||
}
|
||||
|
||||
/** @return array{group_id:int,month:string,joint:?array}|null */
|
||||
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['group_id'] ?? 0) <= 0
|
||||
|| preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
$payload = json_encode(['company_id' => $companyId, 'group_id' => $groupId, 'month' => $month], JSON_THROW_ON_ERROR);
|
||||
|
||||
return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '=');
|
||||
}
|
||||
}
|
||||
34
app/Support/CourierBills/CourierUploadPushes.php
Normal file
34
app/Support/CourierBills/CourierUploadPushes.php
Normal file
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||
|
||||
/**
|
||||
* 快递上传链接推送记录:批量「推送上传链接到快递群」时,这个月已经推过的、已经有账单的分组跳过,免得重复打扰;
|
||||
* 在「对账分组」里单独点某一家照发。记录按月存在 supplier_payable_overrides(dataset = courier-upload-link-pushed:YYYY-MM,记录键 = 分组 id)。
|
||||
*/
|
||||
final class CourierUploadPushes
|
||||
{
|
||||
public const DATASET = 'courier-upload-link-pushed:';
|
||||
|
||||
public function __construct(private readonly SupplierPayableOverrideStore $store) {}
|
||||
|
||||
/** @return array{pushed:array<int,true>,uploaded:array<int,true>} 这个月已推过 / 已有账单的分组 id */
|
||||
public function done(string $month, int $companyId): array
|
||||
{
|
||||
$pushed = [];
|
||||
foreach ($this->store->listRows(self::DATASET . $month, $companyId) as $row) {
|
||||
$pushed[(int) $row['_action_key']] = true;
|
||||
}
|
||||
$uploaded = CourierBillMatcher::db()->table('courier_bill_statements')->where('bill_month', $month)->where('line_count', '>', 0)
|
||||
->distinct()->pluck('group_id')->mapWithKeys(static fn ($id): array => [(int) $id => true])->all();
|
||||
|
||||
return ['pushed' => $pushed, 'uploaded' => $uploaded];
|
||||
}
|
||||
|
||||
public function record(string $month, int $groupId, int $companyId, ?int $userId): void
|
||||
{
|
||||
$this->store->save(self::DATASET . $month, (string) $groupId, ['pushed_at' => now()->toDateTimeString()], $companyId, $userId, 'courier_upload_link');
|
||||
}
|
||||
}
|
||||
263
app/Support/CourierBills/FreightBillTemplate.php
Normal file
263
app/Support/CourierBills/FreightBillTemplate.php
Normal file
@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 快递 / 代发厂家自己上传运费账单用的统一模板,两张表:
|
||||
* - 第一张「账单」:单号、省、重量、运费、快递名称、面单、费率。第一行必须就是这 7 列;单号、运费必填,重量、面单、费率填了就得是数字。
|
||||
* - 「附加费」:快递单号、附加费金额、附加费类型。没有附加费可以空着;填了就三列都要填,金额是数字。
|
||||
* 快递账单的附加费表只读金额进小汇总(不逐单核对);代发运费只核运费,附加费表随原文件保存。
|
||||
*/
|
||||
final class FreightBillTemplate
|
||||
{
|
||||
public const HEADERS = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率'];
|
||||
/** 旧模板第 5 列叫「送货备注」,照样收。 */
|
||||
private const LEGACY_HEADERS = ['送货备注' => '快递名称'];
|
||||
public const SURCHARGE_SHEET = '附加费';
|
||||
public const SURCHARGE_HEADERS = ['快递单号', '附加费金额', '附加费类型'];
|
||||
/** 写在附加费表表头右边(空一列)的说明,校验时不算表头。 */
|
||||
public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可;附加费类型填:补运费、退回费、拦截费、改地址费、翻箱费、超长费';
|
||||
private const MAX_ERRORS = 10;
|
||||
private const TOTAL_WORDS = ['合计', '总计', '小计'];
|
||||
|
||||
public function __construct(private readonly BillWorkbookReader $reader) {}
|
||||
|
||||
public function download(string $fileName): StreamedResponse
|
||||
{
|
||||
return response()->streamDownload(static function (): void {
|
||||
$book = new StreamingWorkbook();
|
||||
$book->row('账单', self::HEADERS, true);
|
||||
$book->row(self::SURCHARGE_SHEET, [...self::SURCHARGE_HEADERS, '', self::SURCHARGE_NOTE], true);
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
}, $fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。
|
||||
*
|
||||
* @return array{rows:int,waybills:int,amount:float,surcharge_rows:int,surcharge_amount:float}
|
||||
*/
|
||||
public function validate(string $path, string $extension): array
|
||||
{
|
||||
try {
|
||||
$sheets = $this->reader->sheets($path, $extension);
|
||||
$rows = $sheets->current();
|
||||
} catch (Throwable $error) {
|
||||
throw new RuntimeException('读不了这个文件:' . $error->getMessage());
|
||||
}
|
||||
if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) {
|
||||
throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。');
|
||||
}
|
||||
$result = $this->validateBill($rows);
|
||||
$surcharge = ['surcharge_rows' => 0, 'surcharge_amount' => 0.0];
|
||||
try {
|
||||
for ($sheets->next(); $sheets->valid(); $sheets->next()) {
|
||||
if (trim((string) $sheets->key()) === self::SURCHARGE_SHEET) {
|
||||
$surcharge = $this->validateSurcharge($sheets->current());
|
||||
} else {
|
||||
throw new RuntimeException('请只保留模板的「账单」和可选的「附加费」工作表,不要附带其他工作表。');
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException $error) {
|
||||
throw $error;
|
||||
} catch (Throwable $error) {
|
||||
throw new RuntimeException('读不了「附加费」表:' . $error->getMessage());
|
||||
}
|
||||
|
||||
return $result + $surcharge;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「附加费」表按附加费类型汇总金额(表头不对、没有这张表都返回空)。代发汇总按类型自动带入各费用列。
|
||||
*
|
||||
* @return array<string,float> 附加费类型 => 金额
|
||||
*/
|
||||
public function surchargesByType(string $path, string $extension): array
|
||||
{
|
||||
$result = [];
|
||||
try {
|
||||
foreach ($this->reader->sheets($path, $extension) as $name => $rows) {
|
||||
if (! str_contains(trim((string) $name), self::SURCHARGE_SHEET)) { // 「附加费」「厂家账单-附加费」都认
|
||||
continue;
|
||||
}
|
||||
$header = null;
|
||||
foreach ($rows as $row) {
|
||||
$cells = array_slice(array_map(static fn ($v): string => trim((string) $v), $row), 0, count(self::SURCHARGE_HEADERS));
|
||||
if (implode('', $cells) === '') {
|
||||
continue;
|
||||
}
|
||||
if ($header === null) {
|
||||
$header = array_values(self::trimTail($cells));
|
||||
if ($header !== self::SURCHARGE_HEADERS) {
|
||||
return [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$fee = BillParser::number($cells[1] ?? null);
|
||||
$type = $cells[2] ?? '';
|
||||
if ($fee === null || $type === '' || ($cells[0] ?? '') === '' || in_array($cells[0], self::TOTAL_WORDS, true)) {
|
||||
continue;
|
||||
}
|
||||
$result[$type] = round(($result[$type] ?? 0) + $fee, 2);
|
||||
}
|
||||
}
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** 逐行保留单号与类型,不能只汇总账单金额后丢失匹配依据。 */
|
||||
public function surchargeRows(string $path,string $extension): \Generator
|
||||
{
|
||||
foreach($this->reader->sheets($path,$extension) as $name=>$rows){
|
||||
if(!str_contains(trim((string)$name),self::SURCHARGE_SHEET))continue;
|
||||
$header=false;
|
||||
foreach($rows as $number=>$row){
|
||||
$cells=array_slice(array_map(static fn($v):string=>trim((string)$v),$row),0,3);
|
||||
if(implode('',$cells)==='')continue;
|
||||
if(!$header){
|
||||
if(array_values(self::trimTail($cells))!==self::SURCHARGE_HEADERS)throw new RuntimeException('附加费表头不符合模板,无法逐单核对。');
|
||||
$header=true;continue;
|
||||
}
|
||||
if(in_array($cells[0]??'',self::TOTAL_WORDS,true))continue;
|
||||
$waybill=Waybill::normalize($cells[0]??'');$amount=BillParser::number($cells[1]??null);$type=$cells[2]??'';
|
||||
if($waybill===null||$amount===null||$type==='')throw new RuntimeException('附加费第 '.$number.' 行缺少完整单号、金额或类型。');
|
||||
yield ['sheet'=>(string)$name,'row_no'=>(int)$number,'waybill_no'=>$waybill,'item'=>$type,'amount'=>$amount];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{rows:int,waybills:int,amount:float} */
|
||||
private function validateBill(?iterable $rows): array
|
||||
{
|
||||
if ($rows === null) {
|
||||
throw new RuntimeException('文件是空的。');
|
||||
}
|
||||
$errors = [];
|
||||
$header = null;
|
||||
$count = 0;
|
||||
$amount = 0.0;
|
||||
$waybills = [];
|
||||
foreach ($rows as $index => $row) {
|
||||
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
|
||||
if ($header === null) {
|
||||
$cells[0] = preg_replace('/^\x{FEFF}/u', '', $cells[0] ?? '');
|
||||
$header = array_map(static fn (string $h): string => self::LEGACY_HEADERS[$h] ?? $h, array_values(self::trimTail($cells)));
|
||||
if ($header !== self::HEADERS) {
|
||||
throw new RuntimeException('请用上传模板:第一行必须依次是「' . implode('、', self::HEADERS) . '」,现在是「'
|
||||
. implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (implode('', $cells) === '') {
|
||||
continue;
|
||||
}
|
||||
$line = (int) $index;
|
||||
$waybill = $cells[0] ?? '';
|
||||
if (in_array($waybill, self::TOTAL_WORDS, true)) {
|
||||
continue;
|
||||
}
|
||||
if ($waybill === '') {
|
||||
$errors[] = '第 ' . $line . ' 行没有单号';
|
||||
} elseif (Waybill::normalize($waybill) === null) {
|
||||
$errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
|
||||
}
|
||||
$freight = BillParser::number($cells[3] ?? null);
|
||||
if ($freight === null || ! is_finite($freight)) {
|
||||
$errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字');
|
||||
}
|
||||
foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) {
|
||||
$value = BillParser::number($cells[$col] ?? null);
|
||||
if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) {
|
||||
$errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字';
|
||||
}
|
||||
}
|
||||
if (count($errors) >= self::MAX_ERRORS) {
|
||||
break;
|
||||
}
|
||||
$count++;
|
||||
if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。');
|
||||
$amount += (float) $freight;
|
||||
$waybills[$waybill] = true;
|
||||
}
|
||||
if ($header === null) {
|
||||
throw new RuntimeException('文件是空的。');
|
||||
}
|
||||
if ($errors !== []) {
|
||||
throw new RuntimeException('账单有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:'
|
||||
. implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。');
|
||||
}
|
||||
if ($count === 0) {
|
||||
throw new RuntimeException('模板里还没有填账单明细。');
|
||||
}
|
||||
return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)];
|
||||
}
|
||||
|
||||
/** @return array{surcharge_rows:int,surcharge_amount:float} */
|
||||
private function validateSurcharge(iterable $rows): array
|
||||
{
|
||||
$errors = [];
|
||||
$header = null;
|
||||
$count = 0;
|
||||
$amount = 0.0;
|
||||
foreach ($rows as $index => $row) {
|
||||
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
|
||||
if ($header === null) {
|
||||
if (implode('', $cells) === '') {
|
||||
continue;
|
||||
}
|
||||
$header = array_values(self::trimTail(array_slice($cells, 0, count(self::SURCHARGE_HEADERS))));
|
||||
if ($header !== self::SURCHARGE_HEADERS) {
|
||||
throw new RuntimeException('「附加费」表第一行必须依次是「' . implode('、', self::SURCHARGE_HEADERS) . '」,现在是「'
|
||||
. implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$cells = array_slice($cells, 0, count(self::SURCHARGE_HEADERS));
|
||||
if (implode('', $cells) === '' || in_array($cells[0] ?? '', self::TOTAL_WORDS, true)) {
|
||||
continue;
|
||||
}
|
||||
$line = (int) $index;
|
||||
if (($cells[0] ?? '') === '') {
|
||||
$errors[] = '附加费第 ' . $line . ' 行没有快递单号';
|
||||
} elseif (Waybill::normalize($cells[0]) === null) {
|
||||
$errors[] = '附加费第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
|
||||
}
|
||||
$fee = BillParser::number($cells[1] ?? null);
|
||||
if ($fee === null || ! is_finite($fee)) {
|
||||
$errors[] = '附加费第 ' . $line . ' 行金额' . (($cells[1] ?? '') === '' ? '没填' : '「' . $cells[1] . '」不是数字');
|
||||
}
|
||||
if (($cells[2] ?? '') === '') {
|
||||
$errors[] = '附加费第 ' . $line . ' 行没写附加费类型';
|
||||
}
|
||||
if (count($errors) >= self::MAX_ERRORS) {
|
||||
break;
|
||||
}
|
||||
$count++;
|
||||
if ($count > 100000) throw new RuntimeException('每份附加费表最多100,000行,请分批上传。');
|
||||
$amount += (float) $fee;
|
||||
}
|
||||
if ($errors !== []) {
|
||||
throw new RuntimeException('「附加费」表有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:'
|
||||
. implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。');
|
||||
}
|
||||
|
||||
return ['surcharge_rows' => $count, 'surcharge_amount' => round($amount, 2)];
|
||||
}
|
||||
|
||||
/** @param list<string> $cells */
|
||||
private static function trimTail(array $cells): array
|
||||
{
|
||||
while ($cells !== [] && end($cells) === '') {
|
||||
array_pop($cells);
|
||||
}
|
||||
|
||||
return $cells;
|
||||
}
|
||||
}
|
||||
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');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
156
app/Support/CourierBills/PortalFreightBillImports.php
Normal file
156
app/Support/CourierBills/PortalFreightBillImports.php
Normal file
@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use App\Models\Auth\User;
|
||||
use App\Services\Auth\SupplierPortalAccess;
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** 沿用文件任务模式;网页只收文件,受限批容器逐个校验、读入,不自动重试。 */
|
||||
final class PortalFreightBillImports
|
||||
{
|
||||
public const ROOT = 'private/portal-freight-bills';
|
||||
|
||||
public function submit(UploadedFile $file, array $details): void
|
||||
{
|
||||
$token = (string) Str::uuid();
|
||||
$dir = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token);
|
||||
if (! mkdir($dir, 0700, true)) throw new RuntimeException('无法保存账单,请稍后重试。');
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
$file->move($dir, 'input.' . $extension);
|
||||
$task = $details + ['token' => $token, 'extension' => $extension,
|
||||
'original_name' => mb_substr($file->getClientOriginalName(), 0, 255),
|
||||
'status' => 'queued', 'created_at' => now('Asia/Shanghai')->toDateTimeString(), 'message' => null];
|
||||
$this->write($task);
|
||||
$queue = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending');
|
||||
if (! is_dir($queue)) mkdir($queue, 0700, true);
|
||||
touch($queue . '/' . $token);
|
||||
}
|
||||
|
||||
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')) ?: [];
|
||||
rsort($files);
|
||||
$out = [];
|
||||
foreach ($files as $path) {
|
||||
$task = json_decode((string) file_get_contents($path), true);
|
||||
if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue;
|
||||
if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue;
|
||||
if ($month !== null && $task['month'] !== $month) continue;
|
||||
if (($task['joint']['key'] ?? null) !== $jointKey) continue;
|
||||
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
|
||||
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
|
||||
'message' => $task['message'], 'at' => $task['created_at']];
|
||||
if (count($out) >= 10) break;
|
||||
}
|
||||
usort($out, static fn ($a, $b) => strcmp($b['at'], $a['at']));
|
||||
return array_slice($out, 0, 10);
|
||||
}
|
||||
|
||||
public function processNext(): bool
|
||||
{
|
||||
$pending = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending/*')) ?: [];
|
||||
sort($pending);
|
||||
foreach ($pending as $marker) {
|
||||
$token = basename($marker);
|
||||
if (! Str::isUuid($token)) continue;
|
||||
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token . '/task.json');
|
||||
$task = json_decode((string) file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($task['status'] !== 'queued') {
|
||||
// 上次进程中断后不重导,保留现场供财务核对。
|
||||
if ($task['status'] === 'running') $this->write(array_replace($task, ['status' => 'failed', 'message' => '处理曾中断,请联系财务核对后重新上传。']));
|
||||
unlink($marker);
|
||||
return true;
|
||||
}
|
||||
$task['status'] = 'running';
|
||||
$this->write($task);
|
||||
try {
|
||||
$this->process($task);
|
||||
$task['status'] = 'completed';
|
||||
} catch (Throwable $e) {
|
||||
$task['status'] = 'failed';
|
||||
$task['message'] = $e instanceof RuntimeException && ! $e instanceof \Illuminate\Database\QueryException
|
||||
? mb_substr($e->getMessage(), 0, 500) : '账单处理失败,请联系财务核对。';
|
||||
report($e);
|
||||
}
|
||||
$this->write($task);
|
||||
unlink($marker);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private function process(array $task): void
|
||||
{
|
||||
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
|
||||
if (($task['source'] ?? null) === 'courier_upload_link') {
|
||||
if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。');
|
||||
$joint = isset($task['joint']) ? app(CourierJointUploads::class)->verify($task['joint']) : null;
|
||||
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$task['target_id']])
|
||||
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
|
||||
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
|
||||
}
|
||||
} else {
|
||||
$user = User::find($task['user_id']);
|
||||
if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。');
|
||||
if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。');
|
||||
}
|
||||
$portal = app(PortalFreightBills::class);
|
||||
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/input.' . $task['extension']);
|
||||
$validated = app(FreightBillTemplate::class)->validate($path, $task['extension']);
|
||||
if ($task['kind'] === 'dropship') {
|
||||
$factory = $portal->factory($task['name']);
|
||||
if ($factory === null || (int) $factory->id !== $task['target_id']) throw new RuntimeException('厂家设置已变化,请联系财务。');
|
||||
$store = app(DropshipFreightStore::class);
|
||||
$id = $store->uploadFor($task['original_name'], $path, $task['month'], $task['target_id'], $task['uploader']);
|
||||
$row = $store->db()->table('dropship_bill_files')->find($id);
|
||||
} else {
|
||||
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
|
||||
$store = app(CourierBillStore::class);
|
||||
$file = new UploadedFile($path, $task['original_name'], null, null, true);
|
||||
$id = isset($joint) ? $store->uploadJoint($file, $task['month'], $task['joint'], $task['uploader'])
|
||||
: $store->uploadFor($file, $task['month'], $task['target_id'], $task['uploader']);
|
||||
$row = $store->db()->table('courier_bill_files')->find($id);
|
||||
}
|
||||
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));
|
||||
// 回执采用实际读入金额,避免重复单号等过滤后仍报上传文件总额。
|
||||
$surchargeRows = $validated['surcharge_rows'];
|
||||
$surchargeAmount = $validated['surcharge_amount'];
|
||||
if ($task['kind'] === 'courier') {
|
||||
$fees = $store->db()->table('courier_bill_surcharges')->where('file_id', $id);
|
||||
$surchargeRows = $fees->count();
|
||||
$surchargeAmount = round((float) $fees->sum('amount'), 2);
|
||||
}
|
||||
$summary = ['rows' => (int) ($row->row_count ?? $row->waybill_count), 'waybills' => (int) ($row->waybill_count ?? $row->row_count),
|
||||
'amount' => round((float) $row->amount - ($task['kind'] === 'courier' ? $surchargeAmount : 0), 2),
|
||||
'surcharge_rows' => $surchargeRows, 'surcharge_amount' => $surchargeAmount];
|
||||
if ($surchargeRows > 0) {
|
||||
$message = '附加费 ' . number_format($surchargeRows) . ' 行,合计 ' . number_format($surchargeAmount, 2) . ' 元'
|
||||
. ($task['kind'] === 'dropship' ? '(随原文件保存,不计入代发运费)' : '(计入小汇总)');
|
||||
$store->db()->table($task['kind'] === 'dropship' ? 'dropship_bill_files' : 'courier_bill_files')->where('id', $id)
|
||||
->update(['message' => mb_substr(implode(';', array_filter([$row->message, $message])), 0, 255)]);
|
||||
}
|
||||
try {
|
||||
app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($task['name'], $task['kind'] === 'dropship' ? '代发运费账单' : '快递账单', $task['month'], $task['original_name'], $summary);
|
||||
} catch (Throwable $e) { report($e); }
|
||||
}
|
||||
|
||||
private function write(array $task): void
|
||||
{
|
||||
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/task.json');
|
||||
if (file_put_contents($path . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX) === false) throw new RuntimeException('账单状态保存失败。');
|
||||
chmod($path . '.tmp', 0600);
|
||||
rename($path . '.tmp', $path);
|
||||
$index = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $task['company_id'] . '/' . hash('sha256', $task['name']));
|
||||
if (! is_dir($index)) mkdir($index, 0700, true);
|
||||
$indexPath = $index . '/' . str_replace([' ', ':', '-'], '', $task['created_at']) . '-' . $task['token'] . '.json';
|
||||
file_put_contents($indexPath . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX);
|
||||
chmod($indexPath . '.tmp', 0600);
|
||||
rename($indexPath . '.tmp', $indexPath);
|
||||
}
|
||||
}
|
||||
105
app/Support/CourierBills/PortalFreightBills.php
Normal file
105
app/Support/CourierBills/PortalFreightBills.php
Normal file
@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 厂家门户里的「运费账单」:代发厂家上传代发运费账单、快递上传快递账单,都按统一模板。
|
||||
* 代发厂家按厂家名对上代发厂家设置;快递按承运商名对上快递账单对账分组(分组名或小汇总承运商)。
|
||||
*/
|
||||
final class PortalFreightBills
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CourierBillStore $courier,
|
||||
private readonly DropshipFreightStore $dropship,
|
||||
) {}
|
||||
|
||||
public function factory(string $name): ?object
|
||||
{
|
||||
try {
|
||||
return collect($this->dropship->factories())->first(static fn (object $f): bool => trim((string) $f->name) === trim($name));
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<object> 这个承运商名对应的快递对账分组 */
|
||||
public function groups(string $name): array
|
||||
{
|
||||
$name = trim($name);
|
||||
try {
|
||||
return array_values(array_filter($this->courier->groups(), static fn (object $g): bool => $name !== ''
|
||||
&& (trim((string) $g->name) === $name || trim((string) ($g->summary_carrier ?? '')) === $name)));
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 财务代传入口包含尚未上传货款对账单的代发厂家与快递。 */
|
||||
public function names(): array
|
||||
{
|
||||
try {
|
||||
return array_values(array_unique([
|
||||
...array_map(static fn ($f) => (string) $f->name, $this->dropship->factories()),
|
||||
...array_map(static fn ($g) => (string) $g->name, $this->courier->groups()),
|
||||
]));
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 钉钉组织里能认作「快递」的部门名:快递对账分组名和小汇总承运商名。
|
||||
*
|
||||
* @param list<string> $names
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function courierNames(array $names): array
|
||||
{
|
||||
$names = array_values(array_unique(array_filter(array_map('trim', $names))));
|
||||
if ($names === []) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
$db = CourierBillMatcher::db();
|
||||
$found = $db->table('courier_bill_groups')->whereIn('name', $names)->pluck('name')
|
||||
->merge($db->table('courier_bill_groups')->whereIn('summary_carrier', $names)->pluck('summary_carrier'))
|
||||
->map(static fn ($n): string => trim((string) $n))->unique()->values()->all();
|
||||
} catch (Throwable) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_intersect($names, $found));
|
||||
}
|
||||
|
||||
/** @return array{factory:?object,groups:list<object>,files:list<array<string,mixed>>} */
|
||||
public function panel(string $name): array
|
||||
{
|
||||
$factory = $this->factory($name);
|
||||
$groups = $this->groups($name);
|
||||
$files = app(PortalFreightBillImports::class)->recent((int) company_id(), $name);
|
||||
try {
|
||||
if ($factory !== null) {
|
||||
foreach ($this->dropship->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->orderByDesc('id')->limit(10)
|
||||
->get() as $f) {
|
||||
$files[] = ['kind' => '代发运费', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->waybill_count,
|
||||
'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at];
|
||||
}
|
||||
}
|
||||
if ($groups !== []) {
|
||||
$ids = array_map(static fn (object $g): int => (int) $g->id, $groups);
|
||||
foreach ($this->courier->db()->table('courier_bill_files')->whereIn('group_id', $ids)->orderByDesc('id')->limit(10)->get() as $f) {
|
||||
$files[] = ['kind' => '快递账单', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->row_count,
|
||||
'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at];
|
||||
}
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// 表没建好时只是不显示上传记录
|
||||
}
|
||||
usort($files, static fn (array $a, array $b): int => strcmp($b['at'], $a['at']));
|
||||
|
||||
return ['factory' => $factory, 'groups' => $groups, 'files' => array_slice($files, 0, 10)];
|
||||
}
|
||||
}
|
||||
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_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
|
||||
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
|
||||
'data_source' => '数据来源',
|
||||
'origin_state' => '始发省', 'origin_city' => '始发市',
|
||||
];
|
||||
|
||||
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
|
||||
@ -56,7 +58,7 @@ final class ShippingLookup
|
||||
* @param list<string> $waybills
|
||||
* @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 = [];
|
||||
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;
|
||||
}
|
||||
|
||||
@ -109,7 +116,7 @@ final class ShippingLookup
|
||||
* @param list<string> $waybills
|
||||
* @return array<string,array<string,mixed>> 键为大写单号
|
||||
*/
|
||||
public function details(array $waybills): array
|
||||
public function details(array $waybills, array $expressNames = []): array
|
||||
{
|
||||
$result = [];
|
||||
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 === []) {
|
||||
return;
|
||||
}
|
||||
yield from app(ReturnPickupLookup::class)->monthWaybills($expressNames, $month);
|
||||
$expressNames = array_values(array_diff($expressNames, array_values(ReturnPickupLookup::CARRIERS)));
|
||||
if ($expressNames === []) return;
|
||||
// 按天走 ship_time 索引,单次只扫一天的发货行。
|
||||
$day = strtotime($month . '-01');
|
||||
$end = strtotime($month . '-01 +1 month');
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Modules\EcommerceFinance\Services\CourierBookkeepingRegistry;
|
||||
|
||||
/**
|
||||
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
||||
@ -64,6 +65,8 @@ final class StatementExporter
|
||||
{
|
||||
$db = CourierBillMatcher::db();
|
||||
$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;
|
||||
$groupNames = [];
|
||||
$book = new StreamingWorkbook();
|
||||
@ -91,7 +94,8 @@ final class StatementExporter
|
||||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||||
$bill = 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;
|
||||
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
||||
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
||||
@ -119,12 +123,12 @@ final class StatementExporter
|
||||
}
|
||||
foreach ($sheets as $name => $filter) {
|
||||
$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) {
|
||||
$book->row($name, $fullHeader, 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) {
|
||||
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
||||
$cells = $this->originalCells($line, $sources, $original);
|
||||
@ -163,22 +167,143 @@ final class StatementExporter
|
||||
// 未提供:发货数据有、账单没有
|
||||
$headerWritten = false;
|
||||
$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) {
|
||||
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], 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) {
|
||||
$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)]);
|
||||
}
|
||||
});
|
||||
|
||||
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
|
||||
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
|
||||
$this->writeNotes($book, $ids, $originals);
|
||||
$book->writeTo($output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 补记账子表:全部历史记账及本期差额(已补记录不重复计入),表名照手工版「补9月记账」「2026.8-9月记账补款」。
|
||||
*
|
||||
* @param list<int> $ids
|
||||
* @param list<string> $tail
|
||||
* @param array<int,string> $groupNames
|
||||
*/
|
||||
private function writeRebooks(StreamingWorkbook $book, array $ids, array $tail, array $groupNames, bool $multi): void
|
||||
{
|
||||
$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 === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
|
||||
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
|
||||
str_starts_with($kind, 'rebook:') => $find(static fn (string $n): bool => Rebooks::labelCovers($n, (int) substr($kind, 7))),
|
||||
$kind === 'fee' => self::feeSlot($key, $find),
|
||||
default => null,
|
||||
};
|
||||
|
||||
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]);
|
||||
});
|
||||
}
|
||||
}
|
||||
92
app/Support/CourierBills/WorkPlatformCourierRobots.php
Normal file
92
app/Support/CourierBills/WorkPlatformCourierRobots.php
Normal file
@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** 按财务分组名称匹配工作平台的快递名称或群名;组合分组任一名称命中即可。 */
|
||||
final class WorkPlatformCourierRobots
|
||||
{
|
||||
/** 负责人明确指定的对应关系,目标必须命中工作平台完整业务名称。 */
|
||||
private const DESIGNATED_NAMES = [
|
||||
'北京韵达-乐鑫达' => '北京大件韵达',
|
||||
'樵舍中通' => '樵舍中通',
|
||||
'樵舍中通-上楼' => '樵舍中通',
|
||||
'樵舍中通上楼' => '樵舍中通',
|
||||
'江西中通快运' => '樵舍中通',
|
||||
'江西新建中通' => '樵舍中通',
|
||||
'山东中通快运' => '樵舍中通',
|
||||
'南昌樵舍仓仓储费' => '樵舍中通',
|
||||
'中通快运专线' => '常州中通快运',
|
||||
'宿迁中通快运' => '沭阳中通快运',
|
||||
'山东顺丰干配' => '顺德德邦',
|
||||
'河北中通-江三' => '顺德德邦',
|
||||
'苏北顺丰干配大件' => '顺德德邦',
|
||||
];
|
||||
|
||||
public function match(array $groups, array $rows): array
|
||||
{
|
||||
$platformRows = [];
|
||||
foreach ($rows as $row) {
|
||||
if (! is_array($row) || ! isset($row['Id'])) {
|
||||
throw new RuntimeException('机器人配置缺少有效的记录编号。');
|
||||
}
|
||||
if (trim((string) ($row['forModel'] ?? '')) !== '快递应付') continue;
|
||||
$platformRows[] = $row;
|
||||
}
|
||||
$robots = $unmatched = $ambiguous = [];
|
||||
foreach ($groups as $group) {
|
||||
$name = (string) $group->name;
|
||||
$designatedName = self::DESIGNATED_NAMES[$name] ?? null;
|
||||
$candidates = [];
|
||||
$bestScore = 0;
|
||||
$names = preg_split('/[|++、,,;;]+/u', $name, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
foreach ($platformRows as $row) {
|
||||
$keys = array_filter(array_map('trim', explode('|', (string) ($row['businessKey'] ?? ''))));
|
||||
if ($designatedName !== null) {
|
||||
if (in_array($designatedName, $keys, true)) $candidates[(string) $row['Id']] = $row;
|
||||
continue;
|
||||
}
|
||||
$platformGroup = (string) ($row['groupname'] ?? '');
|
||||
$score = 0;
|
||||
foreach ($names as $part) {
|
||||
$part = trim($part);
|
||||
if ($part === '') continue;
|
||||
// 负责人明确这两家独立,缺少本家配置时也不能借用另一家。
|
||||
if (in_array($part, ['常州德邦', '常州德邦逆向'], true)) {
|
||||
if (in_array($part, $keys, true)) $score = max($score, 100000 + mb_strlen($part));
|
||||
continue;
|
||||
}
|
||||
if (str_contains($platformGroup, $part)) $score = max($score, mb_strlen($part));
|
||||
foreach ($keys as $key) {
|
||||
if ($part === $key) {
|
||||
$score = max($score, 100000 + mb_strlen($key));
|
||||
} elseif (str_contains($part, $key) || str_contains($key, $part)) {
|
||||
$score = max($score, min(mb_strlen($part), mb_strlen($key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($score > $bestScore) {
|
||||
$candidates = [];
|
||||
$bestScore = $score;
|
||||
}
|
||||
if ($score > 0 && $score === $bestScore) $candidates[(string) $row['Id']] = $row;
|
||||
}
|
||||
if ($candidates === []) { $unmatched[] = $name; continue; }
|
||||
if (count($candidates) !== 1) { $ambiguous[] = $name; continue; }
|
||||
$row = reset($candidates);
|
||||
$webhook = trim((string) ($row['webAccesstoken'] ?? ''));
|
||||
if ($webhook === '') { $unmatched[] = $name; continue; }
|
||||
if (! str_starts_with($webhook, 'https://')) {
|
||||
$webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' . rawurlencode($webhook);
|
||||
}
|
||||
$robots[$name] = [
|
||||
'webhook' => $webhook, 'secret' => trim((string) ($row['Secret'] ?? '')),
|
||||
'group_name' => trim(preg_replace('/[\x00-\x1F\x7F]/u', '', (string) ($row['groupname'] ?? '')) ?? ''),
|
||||
'source_id' => (string) $row['Id'], 'source_updated_at' => (string) ($row['modifytime'] ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
return compact('robots', 'unmatched', 'ambiguous');
|
||||
}
|
||||
}
|
||||
104
app/Support/DropshipFreight/DropshipBillSummary.php
Normal file
104
app/Support/DropshipFreight/DropshipBillSummary.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\Category;
|
||||
|
||||
/** 明细页面与导出共用的小汇总;分类及金额沿用原导出口径。 */
|
||||
final class DropshipBillSummary
|
||||
{
|
||||
public const FEE_LABEL = '厂家账单-附加费';
|
||||
|
||||
public function __construct(private readonly DropshipFreightStore $store) {}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows 未按页面筛选的整月核算结果 */
|
||||
public function build(object $factory, string $month, array $rows): array
|
||||
{
|
||||
$template = $this->store->summaryTemplate($factory, $month);
|
||||
$billTotal = $settleTotal = null;
|
||||
$extras = [];
|
||||
foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) {
|
||||
$extras[DropshipReconciler::LABELS[$category]] = null;
|
||||
}
|
||||
foreach ($rows as $r) {
|
||||
if ($r['bill'] === null) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) {
|
||||
$billTotal = (float) $billTotal + (float) $r['bill'];
|
||||
$final = $r['final'] ?? $r['settle'];
|
||||
if ($final !== null) {
|
||||
$settleTotal = (float) $settleTotal + (float) $final;
|
||||
}
|
||||
} elseif ($r['status'] === Category::LATER) {
|
||||
$label = Category::label(Category::LATER, (string) $r['status_month']);
|
||||
$extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill'];
|
||||
} elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) {
|
||||
$extras[$label] = (float) $extras[$label] + (float) $r['bill'];
|
||||
}
|
||||
}
|
||||
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
|
||||
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
|
||||
$fee = 0.0;
|
||||
$hasFee = false;
|
||||
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
|
||||
->where('status', 'parsed')->get(['id', 'stored_path', 'sheets']) as $file) {
|
||||
$fees = $this->store->feesFor($file);
|
||||
if ($fees !== []) {
|
||||
$fee += array_sum($fees);
|
||||
$hasFee = true;
|
||||
}
|
||||
}
|
||||
// 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行
|
||||
$labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras)
|
||||
|| ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l))));
|
||||
if (! $hasFee) {
|
||||
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费')));
|
||||
}
|
||||
if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
|
||||
array_unshift($labels, '运费');
|
||||
}
|
||||
foreach (array_keys($extras) as $label) {
|
||||
if (! in_array($label, array_map('trim', $labels), true)) {
|
||||
$labels[] = $label;
|
||||
}
|
||||
}
|
||||
$feeLabel = null;
|
||||
if ($hasFee) {
|
||||
$feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL;
|
||||
if (! in_array($feeLabel, $labels, true)) {
|
||||
$labels[] = $feeLabel;
|
||||
}
|
||||
}
|
||||
$items = [];
|
||||
$sums = ['bill' => 0.0, 'settle' => 0.0];
|
||||
foreach (array_values($labels) as $label) {
|
||||
[$bill, $settle] = match (true) {
|
||||
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
|
||||
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
|
||||
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int) $factory->id, $month)],
|
||||
default => [null, null],
|
||||
};
|
||||
$items[] = ['label' => $label, 'bill' => $bill, 'settle' => $settle,
|
||||
'diff' => $bill === null && $settle === null ? null : round((float) $bill - (float) $settle, 2)];
|
||||
$sums['bill'] += (float) $bill;
|
||||
$sums['settle'] += (float) $settle;
|
||||
}
|
||||
$sums = array_map(static fn (float $value): float => round($value, 2), $sums);
|
||||
$sums['diff'] = round($sums['bill'] - $sums['settle'], 2);
|
||||
|
||||
return ['title' => $template['title'], 'headers' => array_slice(array_pad($template['headers'], 3, ''), 0, 3),
|
||||
'rows' => $items, 'total_label' => $template['total'], 'totals' => $sums];
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
return round((float) $matcher->query('dropship', $factoryId, $month)->sum('self_amount'), 2);
|
||||
}
|
||||
}
|
||||
13
app/Support/DropshipFreight/DropshipConfirmation.php
Normal file
13
app/Support/DropshipFreight/DropshipConfirmation.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\FreightConfirmation;
|
||||
|
||||
final class DropshipConfirmation extends FreightConfirmation
|
||||
{
|
||||
public const DATASET = 'dropship-freight-confirm';
|
||||
public const DISPUTES = 'dropship-freight-dispute:';
|
||||
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中',
|
||||
self::PUSHED => '已推送,待厂家确认', self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议'];
|
||||
}
|
||||
@ -21,6 +21,8 @@ use RuntimeException;
|
||||
*/
|
||||
final class DropshipExporter
|
||||
{
|
||||
/** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */
|
||||
public const FEE_LABEL = DropshipBillSummary::FEE_LABEL;
|
||||
private const CHUNK = 500;
|
||||
|
||||
public function __construct(
|
||||
@ -78,6 +80,7 @@ final class DropshipExporter
|
||||
$lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?');
|
||||
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_')));
|
||||
$tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
|
||||
$front = self::frontColumns();
|
||||
|
||||
// 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张)
|
||||
$sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)];
|
||||
@ -91,13 +94,13 @@ final class DropshipExporter
|
||||
if ($picked === []) {
|
||||
continue;
|
||||
}
|
||||
$book->row($name, [...$original, ...array_keys(StatementExporter::FRONT), ...array_values($rest), ...$tail], true);
|
||||
$book->row($name, [...$original, ...array_keys($front), ...array_values($rest), ...$tail], true);
|
||||
foreach (array_chunk($picked, self::CHUNK) as $chunk) {
|
||||
$details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['ship_waybill'], $chunk));
|
||||
foreach ($chunk as $r) {
|
||||
$ship = $details[strtoupper((string) $r['ship_waybill'])] ?? [];
|
||||
$cells = $this->originalCells($r, $sources, $original, $lookup);
|
||||
foreach (StatementExporter::FRONT as $field) {
|
||||
foreach ($front as $field) {
|
||||
$cells[] = $this->front($field, $r, $ship);
|
||||
}
|
||||
foreach (array_keys($rest) as $field) {
|
||||
@ -135,46 +138,31 @@ final class DropshipExporter
|
||||
}
|
||||
|
||||
$this->writeNotes($book, $rows, $originals);
|
||||
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
|
||||
$book->writeTo($output);
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。运费行系统填(厂家开的运费合计 / 按我方核算的结算运费),
|
||||
* 货款、记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。
|
||||
* 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。
|
||||
* - 运费行:原始 = 按我方结算的那些单(一致、运费有差、系统未核算、前月补提供)厂家开的运费,简尚核对 = 最终结算运费;
|
||||
* - 厂家开了运费但这个月不付的,按分类各加一行(快递不符、重复、匹配不到、未发出、跨月订单-X月):原始 = 厂家开的运费,简尚核对 = 0;
|
||||
* 这样「原始」合计 = 厂家账单运费合计。手工汇总里已有同名类目的就填在那一行,不重复加;
|
||||
* - 记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。
|
||||
*/
|
||||
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
|
||||
{
|
||||
$template = $this->store->summaryTemplate($factory, $month);
|
||||
$billTotal = $settleTotal = null;
|
||||
foreach ($rows as $r) {
|
||||
if ($r['bill'] !== null) {
|
||||
$billTotal = (float) $billTotal + (float) $r['bill'];
|
||||
}
|
||||
if ($r['settle'] !== null) {
|
||||
$settleTotal = (float) $settleTotal + (float) $r['settle'];
|
||||
}
|
||||
$summary = app(DropshipBillSummary::class)->build($factory, $month, $rows);
|
||||
$book->row('汇总', [$summary['title'], ...$summary['headers']], true);
|
||||
foreach ($summary['rows'] as $index => $item) {
|
||||
$book->row('汇总', [$item['label'], $item['bill'], $item['settle'], self::diff($index + 2, $item['bill'], $item['settle'])]);
|
||||
}
|
||||
$labels = $template['labels'];
|
||||
if (($billTotal !== null || $settleTotal !== null) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
|
||||
array_unshift($labels, '运费');
|
||||
}
|
||||
$book->row('汇总', [$template['title'], ...array_slice(array_pad($template['headers'], 3, ''), 0, 3)], true);
|
||||
$sums = [0.0, 0.0];
|
||||
foreach ($labels as $index => $label) {
|
||||
$n = $index + 2;
|
||||
[$bill, $settle] = DropshipSummaryTemplate::isFreight($label)
|
||||
? [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)] : [null, null];
|
||||
$sums[0] += (float) $bill;
|
||||
$sums[1] += (float) $settle;
|
||||
$book->row('汇总', [$label, $bill, $settle, self::diff($n, $bill, $settle)]);
|
||||
}
|
||||
$last = count($labels) + 1;
|
||||
$last = count($summary['rows']) + 1;
|
||||
$n = $last + 1;
|
||||
$book->row('汇总', [$template['total'], new XlsxFormula('SUM(B2:B' . $last . ')', round($sums[0], 2)),
|
||||
new XlsxFormula('SUM(C2:C' . $last . ')', round($sums[1], 2)), new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', round($sums[0] - $sums[1], 2))], true);
|
||||
$book->row('汇总', [$summary['total_label'], new XlsxFormula('SUM(B2:B' . $last . ')', $summary['totals']['bill']),
|
||||
new XlsxFormula('SUM(C2:C' . $last . ')', $summary['totals']['settle']),
|
||||
new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', $summary['totals']['diff'])], true);
|
||||
}
|
||||
|
||||
/** 差异 = 原始 − 简尚,两格都空就空着(公式,手工填了会跟着算)。 */
|
||||
private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula
|
||||
{
|
||||
return new XlsxFormula('IF(COUNT(B' . $row . ':C' . $row . ')=0,"",N(B' . $row . ')-N(C' . $row . '))',
|
||||
@ -327,13 +315,30 @@ final class DropshipExporter
|
||||
}, $original);
|
||||
}
|
||||
|
||||
/** 对账表前面几列:照快递对账单的,「核算运费」后面加「最终结算运费」。 @return array<string,string> */
|
||||
private static function frontColumns(): array
|
||||
{
|
||||
$result = [];
|
||||
foreach (StatementExporter::FRONT as $label => $field) {
|
||||
$result[$label] = $field;
|
||||
if ($field === 'qc_freight') {
|
||||
$result['最终结算运费'] = '_final';
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function front(string $field, array $r, array $ship): string|float|null
|
||||
{
|
||||
return match ($field) {
|
||||
'_measured' => $ship['qc_measured_weight'] ?? null,
|
||||
'_unshipped' => null,
|
||||
'_weight_diff' => null,
|
||||
'_freight_diff' => $r['bill'] !== null && ($ship['qc_freight'] ?? null) !== null ? round((float) $r['bill'] - (float) $ship['qc_freight'], 2) : null,
|
||||
'_final' => $r['final'] ?? $r['settle'] ?? null,
|
||||
// 运费差 = 厂家运费 − 最终结算运费
|
||||
'_freight_diff' => $r['bill'] !== null && ($r['final'] ?? $r['settle'] ?? null) !== null
|
||||
? round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle']), 2) : null,
|
||||
default => self::value($field, $ship[$field] ?? null),
|
||||
};
|
||||
}
|
||||
|
||||
158
app/Support/DropshipFreight/DropshipFees.php
Normal file
158
app/Support/DropshipFreight/DropshipFees.php
Normal file
@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||
|
||||
/**
|
||||
* 代发各厂家汇总里的费用列:快递运费、快递记账、补运费、补记账、退回费、拦截费、改地址费、翻箱费、超长费、合计运费、备注。
|
||||
* - 快递运费 = 结算运费(按我方核算),不能改;
|
||||
* - 其余各列先按厂家上传模板「附加费」表的附加费类型自动带入,财务可以逐家改(清空就回到自动值);
|
||||
* - 合计运费 = 快递运费 + 补运费 + 退回费 + 拦截费 + 改地址费 + 翻箱费 + 超长费 − 快递记账 + 补记账。
|
||||
* 快递记账是扣款,按正数记、表里显示成负数。
|
||||
* 手工改的值按月存在 supplier_payable_overrides(dataset = dropship-freight-fees:YYYY-MM,记录键 = 厂家 id)。
|
||||
*/
|
||||
final class DropshipFees
|
||||
{
|
||||
public const DATASET = 'dropship-freight-fees:';
|
||||
|
||||
public const COLUMNS = ['freight' => '快递运费', 'booking' => '快递记账', 'extra_freight' => '补运费', 'extra_booking' => '补记账',
|
||||
'returned' => '退回费', 'intercept' => '拦截费', 'readdress' => '改地址费', 'repack' => '翻箱费', 'overlength' => '超长费'];
|
||||
|
||||
/** 财务可以改的列(快递运费取结算运费,不在这里改)。 */
|
||||
public const EDITABLE = ['booking', 'extra_freight', 'extra_booking', 'returned', 'intercept', 'readdress', 'repack', 'overlength'];
|
||||
|
||||
/** 附加费类型里出现这些字就归到这一列,按顺序认(「补记账」先于「记账」,「拦截退回」算拦截费)。 */
|
||||
private const MATCH = ['extra_booking' => ['补记账'], 'booking' => ['记账'], 'extra_freight' => ['补运费', '补运'],
|
||||
'intercept' => ['拦截'], 'readdress' => ['改地址', '改址'], 'repack' => ['翻箱'], 'overlength' => ['超长'], 'returned' => ['退回', '退件', '退货']];
|
||||
|
||||
public function __construct(
|
||||
private readonly DropshipFreightStore $store,
|
||||
private readonly SupplierPayableOverrideStore $overrides,
|
||||
) {}
|
||||
|
||||
public static function classify(string $type): ?string
|
||||
{
|
||||
foreach (self::MATCH as $key => $words) {
|
||||
foreach ($words as $word) {
|
||||
if (str_contains($type, $word)) {
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @param array<string,float|int|null> $v */
|
||||
public static function total(array $v): float
|
||||
{
|
||||
$plus = ['freight', 'extra_freight', 'returned', 'intercept', 'readdress', 'repack', 'overlength', 'extra_booking'];
|
||||
|
||||
return round(array_sum(array_map(static fn (string $k): float => (float) ($v[$k] ?? 0), $plus)) - abs((float) ($v['booking'] ?? 0)), 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 各厂家这个月的费用列。
|
||||
*
|
||||
* @param array<int,float> $settle 厂家 id => 结算运费
|
||||
* @return array<int,array{values:array<string,float>,auto:array<string,float>,manual:array<string,bool>,other:array<string,float>,note:string,total:float}>
|
||||
*/
|
||||
public function rows(string $month, array $settle, int $companyId): array
|
||||
{
|
||||
$auto = $this->auto($month);
|
||||
$manual = [];
|
||||
foreach ($this->overrides->listRows(self::DATASET . $month, $companyId) as $row) {
|
||||
$manual[(int) $row['_action_key']] = $row;
|
||||
}
|
||||
$result = [];
|
||||
foreach ($settle as $factoryId => $freight) {
|
||||
$values = ['freight' => round((float) $freight, 2)];
|
||||
$flags = [];
|
||||
foreach (self::EDITABLE as $key) {
|
||||
$set = $manual[$factoryId]['fees'][$key] ?? null;
|
||||
$flags[$key] = $set !== null;
|
||||
$values[$key] = round((float) ($set ?? $auto[$factoryId]['fees'][$key] ?? 0), 2);
|
||||
}
|
||||
$values['booking'] = abs($values['booking']);
|
||||
$autoValues = array_map(static fn ($v): float => round((float) $v, 2), $auto[$factoryId]['fees'] ?? []);
|
||||
if (isset($autoValues['booking'])) {
|
||||
$autoValues['booking'] = abs($autoValues['booking']);
|
||||
}
|
||||
$result[$factoryId] = ['values' => $values, 'auto' => $autoValues, 'manual' => $flags, 'other' => $auto[$factoryId]['other'] ?? [],
|
||||
'note' => (string) ($manual[$factoryId]['note'] ?? ''), 'total' => self::total($values)];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存手工改的值:空着的列回到自动值。
|
||||
*
|
||||
* @param array<string,mixed> $fees 列 => 金额(空 = 自动)
|
||||
*/
|
||||
public function save(string $month, int $factoryId, array $fees, string $note, int $companyId, ?int $userId): void
|
||||
{
|
||||
$values = [];
|
||||
foreach (self::EDITABLE as $key) {
|
||||
$raw = trim((string) ($fees[$key] ?? ''));
|
||||
if ($raw !== '') {
|
||||
$values[$key] = round($key === 'booking' ? abs((float) $raw) : (float) $raw, 2);
|
||||
}
|
||||
}
|
||||
$this->overrides->save(self::DATASET . $month, (string) $factoryId, ['fees' => $values, 'note' => mb_substr(trim($note), 0, 255)],
|
||||
$companyId, $userId, 'dropship_fees');
|
||||
}
|
||||
|
||||
/**
|
||||
* 厂家上传的账单里「附加费」表按类型汇总的金额。
|
||||
*
|
||||
* @return array<int,array{fees:array<string,float>,other:array<string,float>}>
|
||||
*/
|
||||
public function auto(string $month): array
|
||||
{
|
||||
$result = [];
|
||||
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
|
||||
$indexed=$matcher->ready()?$this->store->db()->table('dropship_bill_surcharges')->where('bill_month',$month)->distinct()->pluck('factory_id')->all():[];
|
||||
$hasMatchedFiles=$indexed!==[];
|
||||
if($hasMatchedFiles){
|
||||
$rows=$this->store->db()->table($matcher::TABLE)->where('scope','dropship')->where('bill_month',$month)
|
||||
->selectRaw('owner_id,item,SUM(self_amount) AS amount')->groupBy('owner_id','item')->get();
|
||||
foreach($rows as $row){
|
||||
if($row->amount===null)continue;
|
||||
$key=self::classify($row->item);$id=(int)$row->owner_id;
|
||||
if($key===null)$result[$id]['other'][$row->item]=(float)$row->amount;
|
||||
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+(float)$row->amount;
|
||||
}
|
||||
// 已确认账期维持原自动值,不因接入新的核对方式重写已确认金额。
|
||||
$states=app(DropshipConfirmation::class)->states($month,(int)(company_id()?:1));
|
||||
$confirmed=array_keys(array_filter($states,fn($s)=>($s['status']??'')==='confirmed'));
|
||||
foreach($confirmed as $id)unset($result[$id]);
|
||||
$legacy=$this->store->db()->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')
|
||||
->where(fn($q)=>$q->whereNotIn('factory_id',$indexed)->orWhereIn('factory_id',$confirmed));
|
||||
foreach($legacy->get(['id','factory_id','stored_path','sheets']) as $file){
|
||||
foreach($this->store->feesFor($file) as $type=>$amount){
|
||||
$key=self::classify($type);$id=(int)$file->factory_id;
|
||||
if($key===null)$result[$id]['other'][$type]=($result[$id]['other'][$type]??0)+$amount;
|
||||
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+$amount;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
$files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed')
|
||||
->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']);
|
||||
foreach ($files as $file) {
|
||||
foreach ($this->store->feesFor($file) as $type => $amount) {
|
||||
$id = (int) $file->factory_id;
|
||||
$key = self::classify((string) $type);
|
||||
if ($key === null) {
|
||||
$result[$id]['other'][(string) $type] = round(($result[$id]['other'][(string) $type] ?? 0) + (float) $amount, 2);
|
||||
} else {
|
||||
$result[$id]['fees'][$key] = round(($result[$id]['fees'][$key] ?? 0) + (float) $amount, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,9 @@ namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\BillWorkbookReader;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@ -31,6 +33,73 @@ final class DropshipFreightStore
|
||||
private readonly CourierBillStore $courierBills,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 这份账单「附加费」表按类型的金额(类型 => 金额)。入库时记在 sheets 里;之前入库的老文件现读原文件补记一次。
|
||||
*
|
||||
* @return array<string,float>
|
||||
*/
|
||||
public function feesFor(object $file): array
|
||||
{
|
||||
$sheets = (array) json_decode((string) ($file->sheets ?? ''), true);
|
||||
$surcharge = array_filter($sheets, static fn ($sheet): bool => is_array($sheet)
|
||||
&& str_contains((string) ($sheet['sheet'] ?? ''), FreightBillTemplate::SURCHARGE_SHEET));
|
||||
if ($surcharge === []) {
|
||||
return []; // sheets 里列着原文件每张表,没有附加费表就不用读文件
|
||||
}
|
||||
$fees = [];
|
||||
if (array_filter($surcharge, static fn (array $sheet): bool => array_key_exists('fees', $sheet)) !== []) {
|
||||
foreach ($surcharge as $sheet) {
|
||||
foreach ((array) ($sheet['fees'] ?? []) as $type => $amount) {
|
||||
$fees[(string) $type] = round(($fees[(string) $type] ?? 0) + (float) $amount, 2);
|
||||
}
|
||||
}
|
||||
|
||||
return $fees;
|
||||
}
|
||||
if (empty($file->stored_path) || ! Storage::disk(self::DISK)->exists((string) $file->stored_path)) {
|
||||
return [];
|
||||
}
|
||||
$fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path((string) $file->stored_path),
|
||||
pathinfo((string) $file->stored_path, PATHINFO_EXTENSION));
|
||||
if (! empty($file->id)) {
|
||||
$this->db()->table('dropship_bill_files')->where('id', $file->id)
|
||||
->update(['sheets' => json_encode(self::withFees($sheets, $fees), JSON_UNESCAPED_UNICODE)]);
|
||||
}
|
||||
|
||||
return $fees;
|
||||
}
|
||||
|
||||
/** 把附加费金额记到 sheets 里「附加费」那张表的记录上(没有附加费也记个空的,下次不用再读文件);不新增记录,导出按记录数给原表起名。 */
|
||||
private static function withFees(array $sheets, array $fees): array
|
||||
{
|
||||
$note = $fees === [] ? '没有附加费' : '附加费按类型记入各厂家汇总和小汇总';
|
||||
$done = false;
|
||||
foreach ($sheets as $i => $sheet) {
|
||||
if (! $done && is_array($sheet) && str_contains((string) ($sheet['sheet'] ?? ''), FreightBillTemplate::SURCHARGE_SHEET)) {
|
||||
$sheets[$i]['fees'] = $fees;
|
||||
$sheets[$i]['note'] = $note;
|
||||
$done = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $sheets;
|
||||
}
|
||||
|
||||
/** 新上传时在已有事务内保存;历史文件通过受限批处理命令回读。 */
|
||||
public function storeSurchargeRows(object $file,int $factoryId): void
|
||||
{
|
||||
if(!app(SurchargeSettlementMatcher::class)->ready())return;
|
||||
$db=$this->db();
|
||||
$db->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
|
||||
$rows=[];
|
||||
foreach((new FreightBillTemplate(new BillWorkbookReader()))->surchargeRows(
|
||||
Storage::disk(self::DISK)->path($file->stored_path),pathinfo($file->stored_path,PATHINFO_EXTENSION)) as $row){
|
||||
$rows[]=$row+['file_id'=>$file->id,'factory_id'=>$factoryId,'bill_month'=>$file->bill_month];
|
||||
if(count($rows)>=300){$db->table('dropship_bill_surcharges')->insert($rows);$rows=[];}
|
||||
}
|
||||
if($rows!==[])$db->table('dropship_bill_surcharges')->insert($rows);
|
||||
}
|
||||
|
||||
public function db(): ConnectionInterface
|
||||
{
|
||||
return DB::connection('business_mirror');
|
||||
@ -174,6 +243,17 @@ final class DropshipFreightStore
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/** 厂家自己上传(厂家门户):已经知道是哪家,不用从文件名认。 */
|
||||
public function uploadFor(string $name, string $path, string $month, int $factoryId, string $user): int
|
||||
{
|
||||
$factory = collect($this->factories())->firstWhere('id', $factoryId);
|
||||
if ($factory === null) {
|
||||
throw new RuntimeException('厂家不存在。');
|
||||
}
|
||||
|
||||
return $this->register($name, $path, $month, [$factory], $user, $factory);
|
||||
}
|
||||
|
||||
public function assign(int $fileId, int $factoryId): void
|
||||
{
|
||||
$file = $this->db()->table('dropship_bill_files')->find($fileId);
|
||||
@ -194,9 +274,14 @@ final class DropshipFreightStore
|
||||
}
|
||||
$this->db()->transaction(function () use ($file): void {
|
||||
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
||||
if(app(SurchargeSettlementMatcher::class)->ready()){
|
||||
$this->db()->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
|
||||
$this->db()->table(SurchargeSettlementMatcher::TABLE)->where('scope','dropship')->where('file_id',$file->id)->delete();
|
||||
}
|
||||
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
||||
});
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -209,14 +294,14 @@ final class DropshipFreightStore
|
||||
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
|
||||
->orderByDesc('bill_month')->first();
|
||||
if ($row === null) {
|
||||
return DropshipSummaryTemplate::fallback($month, (string) $factory->name) + ['from' => null];
|
||||
return DropshipSummaryTemplate::withoutDropped(DropshipSummaryTemplate::fallback($month, (string) $factory->name)) + ['from' => null];
|
||||
}
|
||||
$delta = ((int) substr($month, 0, 4) - (int) substr((string) $row->bill_month, 0, 4)) * 12
|
||||
+ (int) substr($month, 5, 2) - (int) substr((string) $row->bill_month, 5, 2);
|
||||
$template = DropshipSummaryTemplate::roll(['title' => (string) $row->title, 'headers' => array_values((array) json_decode((string) $row->headers, true)),
|
||||
'labels' => array_values((array) json_decode((string) $row->labels, true)), 'total' => (string) $row->total_label], $delta);
|
||||
|
||||
return $template + ['from' => (string) $row->bill_month];
|
||||
return DropshipSummaryTemplate::withoutDropped($template) + ['from' => (string) $row->bill_month];
|
||||
}
|
||||
|
||||
/**
|
||||
@ -287,12 +372,12 @@ final class DropshipFreightStore
|
||||
}
|
||||
|
||||
/** @param list<object> $factories */
|
||||
private function register(string $name, string $path, string $month, array $factories, string $user): int
|
||||
private function register(string $name, string $path, string $month, array $factories, string $user, ?object $known = null): int
|
||||
{
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
|
||||
$factory = self::identify($name, $factories);
|
||||
$factory = $known ?? self::identify($name, $factories);
|
||||
$id = (int) $this->db()->table('dropship_bill_files')->insertGetId([
|
||||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory',
|
||||
'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null,
|
||||
@ -320,6 +405,10 @@ final class DropshipFreightStore
|
||||
return;
|
||||
}
|
||||
$lines = $result['lines'];
|
||||
// 按上传模板填的「附加费」表:按类型记下金额,各厂家汇总里自动带入退回费、拦截费等列
|
||||
$fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path($file->stored_path),
|
||||
pathinfo($file->stored_path, PATHINFO_EXTENSION));
|
||||
$result['sheets'] = self::withFees($result['sheets'], $fees);
|
||||
$notes = [];
|
||||
if ($lines === []) {
|
||||
$notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空';
|
||||
@ -341,6 +430,7 @@ final class DropshipFreightStore
|
||||
$lines = array_diff_key($lines, array_flip($others));
|
||||
}
|
||||
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
||||
$this->storeSurchargeRows($file,$factoryId);
|
||||
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
||||
foreach (array_chunk($lines, 500, true) as $chunk) {
|
||||
$insert = [];
|
||||
@ -359,6 +449,7 @@ final class DropshipFreightStore
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
});
|
||||
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
|
||||
}
|
||||
|
||||
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
||||
|
||||
@ -136,35 +136,49 @@ final class DropshipReconciler
|
||||
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array
|
||||
{
|
||||
$calc = $i['calc'] ?? null;
|
||||
$settle = in_array($status, self::PAYABLE, true) ? $calc : null;
|
||||
|
||||
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
|
||||
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
|
||||
'settle' => in_array($status, self::PAYABLE, true) ? $calc : null,
|
||||
'settle' => $settle, 'final' => self::final($billed, $settle),
|
||||
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
|
||||
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
|
||||
'note' => $note, 'formula' => $i['formula'] ?? null];
|
||||
}
|
||||
|
||||
/** 最终结算运费:按我方核算结算,但厂家开得比核算少(厂家运费 − 结算运费 < 0)就按厂家运费结。 */
|
||||
public static function final(?float $billed, ?float $settle): ?float
|
||||
{
|
||||
return $settle !== null && $billed !== null && $billed < $settle ? round($billed, 2) : $settle;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows */
|
||||
public static function summarize(object $factory, string $month, array $rows): array
|
||||
{
|
||||
$counts = array_fill_keys(array_keys(self::LABELS), 0);
|
||||
$bill = $settle = 0.0;
|
||||
$billedCount = $over = $under = 0;
|
||||
$bill = $settle = $calcSettle = 0.0;
|
||||
$billedCount = $over = $under = $capped = 0;
|
||||
foreach ($rows as $row) {
|
||||
$counts[$row['status']]++;
|
||||
if ($row['bill'] !== null) {
|
||||
$billedCount++;
|
||||
$bill += $row['bill'];
|
||||
}
|
||||
$settle += (float) $row['settle'];
|
||||
$calcSettle += (float) $row['settle'];
|
||||
$final = array_key_exists('final', $row) ? $row['final'] : self::final($row['bill'], $row['settle']);
|
||||
$settle += (float) $final;
|
||||
if ($final !== null && $row['settle'] !== null && $final < $row['settle']) {
|
||||
$capped++;
|
||||
}
|
||||
if ($row['status'] === Category::DIFF) {
|
||||
$row['diff'] > 0 ? $over++ : $under++;
|
||||
}
|
||||
}
|
||||
|
||||
return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month,
|
||||
// settle = 最终结算运费(各厂家汇总、小汇总、推送厂家确认都用它);calc_settle = 按我方核算的结算运费;capped = 按厂家运费结的单数
|
||||
'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2),
|
||||
'calc_settle' => round($calcSettle, 2), 'capped' => $capped,
|
||||
'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under,
|
||||
'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
|
||||
}
|
||||
@ -180,6 +194,14 @@ final class DropshipReconciler
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 这家这个月有没有代发发货(批量催上传账单时,没有代发发货的厂家不催)。 @param list<string>|null $own 自有快递名称 */
|
||||
public function hasDropship(object $factory, string $month, ?array $own = null): bool
|
||||
{
|
||||
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
|
||||
|
||||
return $this->dropshipWaybills($factory, $keywords, array_flip($own ?? $this->store->ownExpressNames()), $month) !== [];
|
||||
}
|
||||
|
||||
/** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list<string> */
|
||||
private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array
|
||||
{
|
||||
|
||||
60
app/Support/DropshipFreight/DropshipShareLink.php
Normal file
60
app/Support/DropshipFreight/DropshipShareLink.php
Normal file
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 代发运费确认页的免登录链接(同供应商对账的货款确认页):
|
||||
* 公司、厂家、月份、推送版本放进加密令牌,URL 再做 Laravel 签名,厂家只能看本厂家本次推送的账期。
|
||||
*/
|
||||
final class DropshipShareLink
|
||||
{
|
||||
public const TTL_DAYS = 30;
|
||||
|
||||
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
|
||||
{
|
||||
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, array $query = []): string
|
||||
{
|
||||
$url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [
|
||||
'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 */
|
||||
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)), '+/', '-_'), '=');
|
||||
}
|
||||
}
|
||||
@ -17,7 +17,9 @@ final class DropshipSummaryTemplate
|
||||
public const TOTALS = ['合计', '汇总', '总计'];
|
||||
|
||||
/** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */
|
||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计'];
|
||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账'], 'total' => '合计'];
|
||||
/** 小汇总里不要的类目(手工汇总里带了也去掉)。 */
|
||||
public const DROPPED = ['代发', '退货'];
|
||||
|
||||
/**
|
||||
* 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。
|
||||
@ -95,6 +97,15 @@ final class DropshipSummaryTemplate
|
||||
return $template;
|
||||
}
|
||||
|
||||
/** 去掉「代发」「退货」这类不要的类目(带月份的如「10月退货」也算)。 */
|
||||
public static function withoutDropped(array $template): array
|
||||
{
|
||||
$template['labels'] = array_values(array_filter($template['labels'], static fn (string $l): bool => ! in_array(
|
||||
trim(preg_replace('/^\d{1,2}月|\d{1,2}月$/u', '', trim($l)) ?? ''), self::DROPPED, true)));
|
||||
|
||||
return $template;
|
||||
}
|
||||
|
||||
public static function fallback(string $month, string $factory): array
|
||||
{
|
||||
$template = self::DEFAULT;
|
||||
|
||||
124
app/Support/DropshipFreight/DropshipUploadReminder.php
Normal file
124
app/Support/DropshipFreight/DropshipUploadReminder.php
Normal file
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 代发运费账单上传提醒:往厂家钉钉对账群(和货款对账同一个群)发厂家对账入口链接。
|
||||
* - 手动:上传厂家账单页「通知厂家上传」、代发厂家设置里单家「通知上传」;
|
||||
* - 自动:每月 1–14 日 10:00(dropship-freight:remind-upload),提醒上个月的账单,14 日截止,逾期本月货款和运费不予结算。
|
||||
* 批量提醒只发给「这个月有代发发货、还没上传、配了机器人」的厂家;单家提醒照发。
|
||||
*/
|
||||
final class DropshipUploadReminder
|
||||
{
|
||||
public const DEADLINE_DAY = 14;
|
||||
public const SEND_TIME = '10:00';
|
||||
public const SETTING_KEY = 'dropship_freight.auto_upload_reminder';
|
||||
public const TIMEZONE = 'Asia/Shanghai';
|
||||
|
||||
public function __construct(
|
||||
private readonly DropshipFreightStore $store,
|
||||
private readonly DropshipReconciler $reconciler,
|
||||
private readonly SupplierDingTalkNotifier $notifier,
|
||||
) {}
|
||||
|
||||
/** 自动提醒开关(按公司),默认开。 */
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return (string) setting(self::SETTING_KEY, '1') !== '0';
|
||||
}
|
||||
|
||||
public static function setEnabled(bool $on): void
|
||||
{
|
||||
setting()->set(self::SETTING_KEY, $on ? '1' : '0');
|
||||
setting()->save();
|
||||
}
|
||||
|
||||
public static function today(): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::now(self::TIMEZONE)->startOfDay();
|
||||
}
|
||||
|
||||
/** 这天要催的账单月:上个月。 */
|
||||
public static function billMonth(CarbonInterface $day): string
|
||||
{
|
||||
return CarbonImmutable::parse($day->format('Y-m-d'), self::TIMEZONE)->startOfMonth()->subMonth()->format('Y-m');
|
||||
}
|
||||
|
||||
/** 账单月的上传截止日:次月 14 日。 */
|
||||
public static function deadline(string $month): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::createFromFormat('Y-m-d', $month . '-01', self::TIMEZONE)->startOfDay()->addMonth()->day(self::DEADLINE_DAY);
|
||||
}
|
||||
|
||||
/** 今天还在这个账单月的上传期(次月 1–14 日)里,就返回截止日,提醒里写明截止和逾期后果;否则 null。 */
|
||||
public static function deadlineFor(string $month, CarbonInterface $today): ?CarbonImmutable
|
||||
{
|
||||
$deadline = self::deadline($month);
|
||||
$day = CarbonImmutable::parse($today->format('Y-m-d'), self::TIMEZONE);
|
||||
|
||||
return $day->greaterThanOrEqualTo($deadline->startOfMonth()) && $day->lessThanOrEqualTo($deadline) ? $deadline : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个月要提醒的厂家。
|
||||
*
|
||||
* @return array{targets:list<object>,done:list<string>,no_shipment:list<string>,no_robot:list<string>}
|
||||
*/
|
||||
public function targets(string $month, ?int $factoryId = null): array
|
||||
{
|
||||
$factories = collect($this->store->factories());
|
||||
$single = $factoryId !== null;
|
||||
if ($single) {
|
||||
$factories = $factories->where('id', $factoryId)->values();
|
||||
}
|
||||
$uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id')
|
||||
->where('status', '!=', 'failed')->distinct()->pluck('factory_id')->map('intval')->all());
|
||||
$robots = $this->notifier->configurationMap($factories->pluck('name')->map('strval')->all());
|
||||
$own = $single ? [] : $this->store->ownExpressNames();
|
||||
$result = ['targets' => [], 'done' => [], 'no_shipment' => [], 'no_robot' => []];
|
||||
foreach ($factories as $factory) {
|
||||
$name = (string) $factory->name;
|
||||
if (! $single && isset($uploaded[(int) $factory->id])) {
|
||||
$result['done'][] = $name;
|
||||
} elseif (! ($robots[$name]['configured'] ?? false)) {
|
||||
$result['no_robot'][] = $name;
|
||||
} elseif (! $single && ! $this->reconciler->hasDropship($factory, $month, $own)) {
|
||||
$result['no_shipment'][] = $name;
|
||||
} else {
|
||||
$result['targets'][] = $factory;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发提醒。
|
||||
*
|
||||
* @return array{sent:list<string>,failed:list<string>,done:list<string>,no_shipment:list<string>,no_robot:list<string>,deadline:?CarbonImmutable}
|
||||
*/
|
||||
public function remind(string $month, string $portalUrl, ?int $factoryId = null, ?CarbonInterface $today = null): array
|
||||
{
|
||||
$today ??= self::today();
|
||||
$deadline = self::deadlineFor($month, $today);
|
||||
$plan = $this->targets($month, $factoryId);
|
||||
$sent = $failed = [];
|
||||
foreach ($plan['targets'] as $factory) {
|
||||
try {
|
||||
$this->notifier->pushDropshipUploadReminder((string) $factory->name, $month, $portalUrl, $deadline, $today);
|
||||
$sent[] = (string) $factory->name;
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$failed[] = (string) $factory->name;
|
||||
}
|
||||
}
|
||||
unset($plan['targets']);
|
||||
|
||||
return ['sent' => $sent, 'failed' => $failed, 'deadline' => $deadline] + $plan;
|
||||
}
|
||||
}
|
||||
@ -11,10 +11,14 @@ namespace App\Support;
|
||||
class ReturnPickupFreightCalculator
|
||||
{
|
||||
private const CARRIER_MAP = [
|
||||
'速寄递' => '申通',
|
||||
'申通' => '申通',
|
||||
'德邦' => '德邦',
|
||||
'中通快运' => '中通快运',
|
||||
'速寄递' => '申通退货',
|
||||
'申通' => '申通退货',
|
||||
'申通退货' => '申通退货',
|
||||
'德邦' => '常州德邦逆向',
|
||||
'常州德邦' => '常州德邦逆向',
|
||||
'常州德邦逆向' => '常州德邦逆向',
|
||||
'中通快运' => '中通快运逆向',
|
||||
'中通快运逆向' => '中通快运逆向',
|
||||
];
|
||||
|
||||
private const PROVINCES = [
|
||||
@ -49,6 +53,8 @@ class ReturnPickupFreightCalculator
|
||||
?float $length = null,
|
||||
?float $width = null,
|
||||
?float $height = null,
|
||||
?string $pickupDate = null,
|
||||
?float $volumeCm3 = null,
|
||||
): array {
|
||||
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
|
||||
|
||||
@ -59,8 +65,8 @@ class ReturnPickupFreightCalculator
|
||||
$length = max((float) $length, 0);
|
||||
$width = max((float) $width, 0);
|
||||
$height = max((float) $height, 0);
|
||||
$volumeWeight = ($length > 0 && $width > 0 && $height > 0)
|
||||
? round($length * $width * $height / 6000, 4)
|
||||
$volumeWeight = ($volumeCm3 !== null || ($length > 0 && $width > 0 && $height > 0))
|
||||
? round(max(0, $volumeCm3 ?? ($length * $width * $height)) / 6000, 4)
|
||||
: 0.0;
|
||||
$settlement = round(max($grossWeight, $volumeWeight), 4);
|
||||
|
||||
@ -78,6 +84,9 @@ class ReturnPickupFreightCalculator
|
||||
}
|
||||
|
||||
$rule = $this->rules[$carrier] ?? [];
|
||||
if ($pickupDate !== null && ! empty($rule['effective_date']) && $pickupDate < $rule['effective_date']) {
|
||||
return $this->missing('取件日期早于该逆向物流报价执行日期');
|
||||
}
|
||||
$mode = (string) ($rule['pricing_mode'] ?? '');
|
||||
$maxSide = max($length, $width, $height);
|
||||
$sideSum = $length + $width + $height;
|
||||
|
||||
@ -11,7 +11,7 @@ namespace App\Support;
|
||||
* - 到达:报价「到达地」可写完整名称(如「兰考华兰家具」)、省份(如「江苏」)、
|
||||
* 「省份+地名」(如「河南兰考」)或城市(如「青岛」),多个用 / 分隔。
|
||||
* 传入的到达地可以是厂家名或收货地址;完整名称 > 城市/地名 > 省份,取最具体的一条。
|
||||
* 运费 = max(按吨, 按方)(各自四舍五入到分)+ 派送费(门槛与金额按报价行设置)。
|
||||
* 运费 = max(按吨, 按方)(各自四舍五入到分)+ 派送费 + 提货费(门槛与金额按报价行设置,提货费只在该行填写时收)。
|
||||
*/
|
||||
final class ReturnRouteFreightCalculator
|
||||
{
|
||||
@ -52,11 +52,16 @@ final class ReturnRouteFreightCalculator
|
||||
|
||||
$best = [];
|
||||
$bestScore = 0;
|
||||
$matchedRoute = false;
|
||||
$pricingDate = $shipDate ?? now()->toDateString();
|
||||
foreach ($this->rates ??= $this->snapshot->load()['rates'] as $rate) {
|
||||
if (($rate['layout'] ?? null) !== ReverseLogisticsQuoteSnapshot::LAYOUT_ROUTE_TON_VOLUME || $rate['carrier'] !== $carrier) continue;
|
||||
$originScore = self::originScore((string) $rate['origin'], $origin, $warehouse, $originProvince);
|
||||
$destinationScore = self::destinationScore((string) $rate['destination'], $destination, $destinationName);
|
||||
if ($originScore === 0 || $destinationScore === 0) continue;
|
||||
$matchedRoute = true;
|
||||
if (($rate['effective_date'] !== null && $pricingDate < $rate['effective_date'])
|
||||
|| (($rate['end_date'] ?? null) !== null && $pricingDate > $rate['end_date'])) continue;
|
||||
$score = $originScore * 10 + $destinationScore;
|
||||
if ($score > $bestScore) {
|
||||
$best = [$rate];
|
||||
@ -65,12 +70,9 @@ final class ReturnRouteFreightCalculator
|
||||
$best[] = $rate;
|
||||
}
|
||||
}
|
||||
if ($best === []) return $this->missing('报价未覆盖该路线');
|
||||
if ($best === []) return $this->missing($matchedRoute ? '发货日没有生效的逆向物流报价' : '报价未覆盖该路线');
|
||||
if (count($best) !== 1) return $this->missing('该路线存在多条报价,请核对报价版本');
|
||||
$rate = $best[0];
|
||||
if ($shipDate !== null && $rate['effective_date'] !== null && $shipDate < $rate['effective_date']) {
|
||||
return $this->missing('发货日没有生效的逆向物流报价');
|
||||
}
|
||||
if (!$rate['available']) return $this->missing('该线路缺少有效吨价或方价');
|
||||
|
||||
$tons = $weightKg / 1000;
|
||||
@ -79,11 +81,12 @@ final class ReturnRouteFreightCalculator
|
||||
$byVolume = round($cubicMeters * $rate['volume_price'], 2);
|
||||
$freight = max($byTon, $byVolume);
|
||||
$delivery = ReverseLogisticsQuoteSnapshot::deliveryFeeFor($rate, $cubicMeters);
|
||||
$pickup = ReverseLogisticsQuoteSnapshot::pickupFeeFor($rate, $cubicMeters);
|
||||
|
||||
return [
|
||||
'covered' => true, 'reason' => null, 'carrier' => $carrier, 'origin' => $rate['origin'], 'destination' => $rate['destination'],
|
||||
'tons' => $tons, 'cubic_meters' => $cubicMeters, 'by_ton' => $byTon, 'by_volume' => $byVolume,
|
||||
'freight' => $freight, 'delivery_fee' => $delivery, 'payable' => round($freight + $delivery, 2),
|
||||
'freight' => $freight, 'delivery_fee' => $delivery, 'pickup_fee' => $pickup, 'payable' => round($freight + $delivery + $pickup, 2),
|
||||
'pending_confirmation' => $rate['pending_confirmation'], 'effective_date' => $rate['effective_date'],
|
||||
'quote_id' => 'RL-' . substr(hash('sha256', $rate['sheet_name'] . '|' . $rate['effective_date']), 0, 20),
|
||||
'ton_price' => $rate['ton_price'], 'volume_price' => $rate['volume_price'],
|
||||
|
||||
@ -200,6 +200,12 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
$volume = $this->amount($row[5] ?? null);
|
||||
$source = trim((string) ($row[6] ?? ''));
|
||||
$delivery = $this->deliveryRule($row);
|
||||
$start = trim((string) ($row[14] ?? ''));
|
||||
$end = trim((string) ($row[15] ?? ''));
|
||||
$validDate = static function (string $date): bool {
|
||||
return preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $parts) === 1
|
||||
&& checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1]);
|
||||
};
|
||||
$rates[] = array_replace($this->rateRow($context, count($rates) + 1, [
|
||||
'origin' => $origin,
|
||||
'destination' => $destination,
|
||||
@ -209,7 +215,8 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
'source' => $source,
|
||||
]), [
|
||||
'layout' => self::LAYOUT_ROUTE_TON_VOLUME,
|
||||
'effective_date' => $context['effective_date'],
|
||||
'effective_date' => $start === '' ? $context['effective_date'] : $start,
|
||||
'end_date' => $end === '' ? null : $end,
|
||||
'origin_key' => $origin,
|
||||
'destination_key' => $destination,
|
||||
'origin_province' => trim((string) ($row[1] ?? '')),
|
||||
@ -221,15 +228,20 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
'pending_confirmation' => $source === '待物流确认',
|
||||
'remark' => trim((string) ($row[7] ?? '')),
|
||||
'source_cells' => $this->cellRef(4, $index).':'.$this->cellRef(5, $index),
|
||||
'available' => $ton !== null && $ton >= 0 && $volume !== null && $volume >= 0,
|
||||
] + $delivery);
|
||||
'available' => $ton !== null && $ton >= 0 && $volume !== null && $volume >= 0
|
||||
&& ($start === '' || $validDate($start)) && ($end === '' || $validDate($end))
|
||||
&& ($start === '' || $end === '' || $start <= $end),
|
||||
] + $delivery + ['surcharge_label' => self::surchargeLabel($delivery)]);
|
||||
}
|
||||
$first = $rates[0] ?? $this->deliveryRule([]);
|
||||
$deliveryVariants = array_unique(array_map(static fn (array $rate) => self::deliveryLabel($rate), $rates));
|
||||
$deliveryText = count($deliveryVariants) > 1 ? '派送费门槛与金额按线路设置(见线路)' : self::deliveryLabel($first);
|
||||
|
||||
return [
|
||||
'rule' => array_replace($this->rateRule($context, [
|
||||
'pricing_mode' => self::LAYOUT_ROUTE_TON_VOLUME,
|
||||
'pricing_label' => '按吨与按方分别四舍五入到分后取高,' . self::deliveryLabel($first) . ',含卸货',
|
||||
'pricing_label' => '按吨与按方分别四舍五入到分后取高,' . $deliveryText . ',含卸货'
|
||||
. (array_filter($rates, static fn (array $rate) => ($rate['pickup_fee'] ?? null) !== null) !== [] ? ';部分线路另收提货费(见线路备注)' : ''),
|
||||
'base_label' => '吨价',
|
||||
'increment_label' => '方价',
|
||||
'route_label' => '出发仓 → 到达地;到达地可写完整名称、省份或「省份/城市」,多个用 / 分隔',
|
||||
@ -502,22 +514,56 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
/**
|
||||
* 返货线路派送费:可选列 I 派送费门槛(方)、J 门槛含等于(是/否)、K 派送费(元/票)。
|
||||
* 缺省沿用中铁客退口径:不足 15 方加收 50 元/票。
|
||||
* 提货费(叠加在派送费之外,只有填了才收):可选列 L 提货费门槛(方)、M 门槛含等于(是/否)、N 提货费(元/票)。
|
||||
*
|
||||
* @param array<int,mixed> $row
|
||||
* @return array{delivery_threshold:float,delivery_inclusive:bool,delivery_fee:float}
|
||||
* @return array{delivery_threshold:float,delivery_inclusive:bool,delivery_fee:float,pickup_threshold:?float,pickup_inclusive:bool,pickup_fee:?float}
|
||||
*/
|
||||
private function deliveryRule(array $row): array
|
||||
{
|
||||
$threshold = $this->amount($row[8] ?? null);
|
||||
$fee = $this->amount($row[10] ?? null);
|
||||
$pickupThreshold = $this->amount($row[11] ?? null);
|
||||
$pickupFee = $this->amount($row[13] ?? null);
|
||||
$yes = static fn (mixed $cell): bool => in_array(trim((string) ($cell ?? '')), ['是', '含', 'Y', 'y', '1'], true);
|
||||
|
||||
return [
|
||||
'delivery_threshold' => $threshold ?? 15.0,
|
||||
'delivery_inclusive' => in_array(trim((string) ($row[9] ?? '')), ['是', '含', 'Y', 'y', '1'], true),
|
||||
'delivery_inclusive' => $yes($row[9] ?? null),
|
||||
'delivery_fee' => $fee ?? 50.0,
|
||||
'pickup_threshold' => $pickupThreshold !== null && $pickupFee !== null ? $pickupThreshold : null,
|
||||
'pickup_inclusive' => $yes($row[12] ?? null),
|
||||
'pickup_fee' => $pickupThreshold !== null && $pickupFee !== null ? $pickupFee : null,
|
||||
];
|
||||
}
|
||||
|
||||
/** 线路附加费说明:派送费,及填写了的提货费。 */
|
||||
public static function surchargeLabel(array $rule): string
|
||||
{
|
||||
$label = '派送费:' . self::deliveryLabel($rule);
|
||||
if (($rule['pickup_fee'] ?? null) !== null && ($rule['pickup_threshold'] ?? null) !== null) {
|
||||
$label .= ';提货费:' . self::deliveryLabel([
|
||||
'delivery_threshold' => (float) $rule['pickup_threshold'],
|
||||
'delivery_inclusive' => (bool) ($rule['pickup_inclusive'] ?? false),
|
||||
'delivery_fee' => (float) $rule['pickup_fee'],
|
||||
]) . '(另收)';
|
||||
}
|
||||
|
||||
return $label;
|
||||
}
|
||||
|
||||
/** 返货线路体积是否需要加收提货费(未设置提货费的线路为 0)。 */
|
||||
public static function pickupFeeFor(array $rate, float $cubicMeters): float
|
||||
{
|
||||
if (($rate['pickup_fee'] ?? null) === null || ($rate['pickup_threshold'] ?? null) === null) {
|
||||
return 0.0;
|
||||
}
|
||||
$threshold = (float) $rate['pickup_threshold'];
|
||||
$charged = ($rate['pickup_inclusive'] ?? false) ? $cubicMeters <= $threshold + 1e-9 : $cubicMeters < $threshold - 1e-9;
|
||||
|
||||
return $charged ? (float) $rate['pickup_fee'] : 0.0;
|
||||
}
|
||||
|
||||
/** @param array{delivery_threshold:float,delivery_inclusive:bool,delivery_fee:float} $rule */
|
||||
public static function deliveryLabel(array $rule): string
|
||||
{
|
||||
@ -689,6 +735,12 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
|
||||
private function inferCompanyName(string $name): string
|
||||
{
|
||||
foreach (['申通' => '申通退货', '常州德邦' => '常州德邦逆向', '中通快运' => '中通快运逆向',
|
||||
'中铁' => '中铁客退', '常州松宇货运' => '常州松宇货运'] as $match => $displayName) {
|
||||
if (str_contains($name, $match)) {
|
||||
return $displayName;
|
||||
}
|
||||
}
|
||||
$companyName = trim((string) preg_replace('/(?:逆向|退货|报价表|报价)$/u', '', $name));
|
||||
|
||||
return $companyName !== '' ? $companyName : $name;
|
||||
@ -696,6 +748,11 @@ final class ReverseLogisticsQuoteSnapshot
|
||||
|
||||
private function inferCarrier(string $name): string
|
||||
{
|
||||
foreach (['申通' => '申通退货', '常州德邦' => '常州德邦逆向', '中通快运' => '中通快运逆向'] as $match => $carrier) {
|
||||
if (str_contains($name, $match)) {
|
||||
return $carrier;
|
||||
}
|
||||
}
|
||||
if (str_contains($name, '中铁')) return '中铁客退';
|
||||
if (str_contains($name, '松宇')) return '常州松宇货运';
|
||||
|
||||
|
||||
@ -127,6 +127,14 @@ class SidebarPermissions
|
||||
$allowed[] = 'process-data/invoice-data';
|
||||
}
|
||||
|
||||
if (in_array('courier-payables/shipping-data', $allowed, true)) {
|
||||
$allowed[] = 'courier-payables/returned-parcels';
|
||||
}
|
||||
|
||||
if (in_array('supplier-reconciliation/finance-data', $allowed, true)) {
|
||||
$allowed[] = 'supplier-reconciliation/raw-statements';
|
||||
}
|
||||
|
||||
return array_values(array_unique($allowed));
|
||||
}
|
||||
|
||||
|
||||
@ -43,6 +43,7 @@ return [
|
||||
* existing table, but do not keep querying the upstream source.
|
||||
*/
|
||||
'datasets' => [
|
||||
'jiansun.dbo.jst_shipFreight_view' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货数据专线核算运费'],
|
||||
// Small organization and catalog dimensions stay in MariaDB.
|
||||
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
|
||||
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],
|
||||
@ -81,6 +82,9 @@ return [
|
||||
|
||||
// 淘系(天猫/淘宝)订单与售后:聚水潭 qmcust 表族,订单售后费用明细页需要与
|
||||
// jst_Orders 系列合并读取,因此保持常规同步(不等待列式库启用)。
|
||||
'operations_replica.rpt.jst_qmcust_salesoutbound' => [
|
||||
'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货线上重量精度恢复', 'sync' => 'always',
|
||||
],
|
||||
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
||||
'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系订单',
|
||||
'partition_column' => 'order_date', 'sync' => 'always',
|
||||
|
||||
@ -586,7 +586,6 @@ $navigation = [
|
||||
'title' => '账单流水数据',
|
||||
'icon' => 'receipt_long',
|
||||
'pages' => [
|
||||
['slug' => 'bank-transactions', 'title' => '银行账户流水'],
|
||||
[
|
||||
'slug' => 'store-receiving-bills',
|
||||
'title' => '店铺收款账户账单',
|
||||
@ -814,6 +813,7 @@ $navigation = [
|
||||
'icon' => 'fact_check',
|
||||
'pages' => [
|
||||
['slug' => 'finance-data', 'title' => '财务端数据'],
|
||||
['slug' => 'raw-statements', 'title' => '原始账单'],
|
||||
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
||||
],
|
||||
],
|
||||
@ -1043,7 +1043,7 @@ $navigation = [
|
||||
'title' => '安装明细',
|
||||
'tabs' => [
|
||||
['slug' => 'details', 'title' => '安装明细', 'icon' => 'table_view'],
|
||||
['slug' => 'fee-trend', 'title' => '安装费汇总', 'icon' => 'trending_up'],
|
||||
['slug' => 'fee-trend', 'title' => '安装公司使用趋势', 'icon' => 'trending_up'],
|
||||
],
|
||||
],
|
||||
['slug' => 'promotion-expenses', 'title' => '推广费用'],
|
||||
|
||||
@ -10,6 +10,9 @@ return [
|
||||
| Entries are appended to an existing section in configuration order.
|
||||
|
|
||||
*/
|
||||
'courier-payables' => [
|
||||
['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'],
|
||||
],
|
||||
'module_sections' => [
|
||||
[
|
||||
'position_after' => 'inventory-management',
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
return [
|
||||
'dataset_key' => 'operations_replica.rpt.ding_invoices',
|
||||
'first_supported_month' => '2026-10',
|
||||
'document_types' => [
|
||||
'公摊日常报销',
|
||||
'店铺日常报销',
|
||||
|
||||
@ -1,13 +1,48 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// 上传入口不设截止时间;系统只在 1-14 日催办未上传厂家,15 日财务出上月终版。
|
||||
// 系统在 1-14 日催办未上传厂家;15 日 12:00 后已确认厂家不能继续上传或覆盖。
|
||||
'reminder_end_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_REMINDER_END_DAY', 14))),
|
||||
'final_version_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_FINAL_VERSION_DAY', 15))),
|
||||
'confirmed_upload_lock_day' => max(1, min(28, (int) env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_DAY', 15))),
|
||||
'confirmed_upload_lock_hour' => max(0, min(23, (int) env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_HOUR', 12))),
|
||||
'confirmed_upload_lock_timezone' => env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_TIMEZONE', 'Asia/Shanghai'),
|
||||
'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' => [
|
||||
// 每天运行任务;仅在上传提醒窗口(默认 1-14 日)内执行,15 日不得再催办。
|
||||
// 1-14 日每天 10:00、16:00 运行,15 日不得再催办。
|
||||
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
||||
'starts_at' => env('SUPPLIER_STATEMENT_REMINDER_START_AT', '2026-12-03 00:00:00'),
|
||||
],
|
||||
];
|
||||
|
||||
@ -342,6 +342,17 @@ return [
|
||||
],
|
||||
|
||||
'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' => [
|
||||
@ -429,6 +440,12 @@ return [
|
||||
['outer_oi_id(64)', 'Id'],
|
||||
],
|
||||
],
|
||||
'operations_replica.rpt.jst_qmcust_salesoutbound' => [
|
||||
'source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_qmcust_salesoutbound',
|
||||
'target' => 'ops_jst_precise_outbound', 'keys' => ['Id'], 'watermark' => 'local_updated',
|
||||
'columns' => ['Id', 'io_id', 'l_id', 'io_date', 'weight', 'status', 'local_updated'],
|
||||
'indexes' => [['io_id', 'Id'], ['local_updated', 'Id']],
|
||||
],
|
||||
'operations_replica.rpt.jst_sku' => [
|
||||
'source_key' => 'operations_replica',
|
||||
'schema' => 'rpt',
|
||||
@ -538,10 +555,12 @@ return [
|
||||
|
||||
// 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里,
|
||||
// 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。
|
||||
// 订单售后费用明细等页面需要把两套来源合并展示。
|
||||
// operations_replica 中的同名对象是无索引报表视图,按更新时间读取会在
|
||||
// 上游超时;订单和明细改读 jiansun 中带主键/时间索引的实体表。数据集键
|
||||
// 保留原值,以续用既有镜像状态和目标表。
|
||||
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
||||
'source_key' => 'operations_replica',
|
||||
'schema' => 'rpt',
|
||||
'source_key' => 'jiansun',
|
||||
'schema' => 'dbo',
|
||||
'object' => 'jst_qmcust_orderlist',
|
||||
'target' => 'ops_jst_qmcust_orders',
|
||||
'keys' => ['Id'],
|
||||
@ -554,8 +573,8 @@ return [
|
||||
],
|
||||
],
|
||||
'operations_replica.rpt.jst_qmcust_orderlist_item' => [
|
||||
'source_key' => 'operations_replica',
|
||||
'schema' => 'rpt',
|
||||
'source_key' => 'jiansun',
|
||||
'schema' => 'dbo',
|
||||
'object' => 'jst_qmcust_orderlist_item',
|
||||
'target' => 'ops_jst_qmcust_order_items',
|
||||
'keys' => ['Id'],
|
||||
@ -1095,6 +1114,9 @@ return [
|
||||
['updateTime', 'Id'],
|
||||
['express_company', 'createTime', 'Id'],
|
||||
['transactionNo', 'Id'],
|
||||
['Id'],
|
||||
['returnExpressNo(191)', 'Id'],
|
||||
['express_company', 'expressPickupTime', 'Id'],
|
||||
],
|
||||
],
|
||||
'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [
|
||||
|
||||
@ -0,0 +1,34 @@
|
||||
<?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 (! Schema::hasTable('supplier_portal_suppliers')
|
||||
|| Schema::hasColumn('supplier_portal_suppliers', 'manually_bound')) {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::table('supplier_portal_suppliers', function (Blueprint $table): void {
|
||||
$table->boolean('manually_bound')
|
||||
->default(false)
|
||||
->after('dingtalk_group_name');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('supplier_portal_suppliers')
|
||||
|| ! Schema::hasColumn('supplier_portal_suppliers', 'manually_bound')) {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::table('supplier_portal_suppliers', function (Blueprint $table): void {
|
||||
$table->dropColumn('manually_bound');
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -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));
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -213,6 +213,10 @@ CRON_TZ=Asia/Shanghai
|
||||
# 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。
|
||||
0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
|
||||
10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
|
||||
# 供应商对账财务端:持续预热月份和对账人筛选,避免缓存过期后的首个请求扫描超大数据集。
|
||||
*/10 * * * * root /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-reconciliation:warm-finance-filters --company=1 --quiet >/dev/null 2>&1
|
||||
# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。
|
||||
30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1
|
||||
0 0 * * * 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 business-mirror:warm-report-caches --quiet' >/dev/null 2>&1
|
||||
0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --quiet >/dev/null 2>&1
|
||||
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
|
||||
@ -222,10 +226,10 @@ CRON_TZ=Asia/Shanghai
|
||||
40 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1
|
||||
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
|
||||
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
|
||||
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
|
||||
10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
|
||||
# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
|
||||
30 9 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
|
||||
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖及导入后的源订单变化,补刷异常日期,再刷新最近 7 天。
|
||||
10 6 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --json >> /opt/caiwuxitong/runtime/sync-logs/jst-order-labels-daily.log 2>&1
|
||||
# 种菜明细与业绩种菜金额:每天 09:30 先同步本月/上月工单明细,再做标签覆盖和业绩重算。
|
||||
30 9 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --json >> /opt/caiwuxitong/runtime/sync-logs/planting-daily.log 2>&1
|
||||
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
|
||||
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
|
||||
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
|
||||
@ -236,12 +240,15 @@ CRON_TZ=Asia/Shanghai
|
||||
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。
|
||||
*/5 9-21 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-instant --quiet >/dev/null 2>&1
|
||||
0 10 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-digest --quiet >/dev/null 2>&1
|
||||
# 种菜报销:每天 10:30 锁定当天批次(放行检查通过即确认本批,没通过 10:40、10:50 再试;已确认跳过;不改聚工单)。
|
||||
30,40,50 10 * * * root /usr/bin/flock -n /run/caiwu-planting-confirm.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh planting-reimbursement:auto-confirm --quiet >/dev/null 2>&1
|
||||
# 种菜报销:每天 11:20 生成当天批次,汇总推到钉钉群并 @ 报销人(未配置机器人时跳过;只读)。
|
||||
20 11 * * * root /usr/bin/flock -n /run/caiwu-planting-digest.lock /usr/bin/docker exec -u www-data caiwu_app php artisan planting-reimbursement:daily-digest --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 前完成。
|
||||
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
|
||||
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
|
||||
@ -249,6 +256,8 @@ CRON_TZ=Asia/Shanghai
|
||||
30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --sources=store,withdrawal --quiet >/dev/null 2>&1
|
||||
5 * * * * root /usr/bin/flock -w 600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=2 --merge --sources=dingtalk,payable --quiet >/dev/null 2>&1
|
||||
30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1
|
||||
# 每月 1 日按上月末最后一笔真实余额锁定月度期初,供账户总览和月度资金分析直接读取。
|
||||
20 8 1 * * root /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:lock-monthly-opening --apply --quiet >/dev/null 2>&1
|
||||
# 拼多多期初:账单导入后即时尝试,每日 11:30 再扫一次未就绪店铺;只在余额恒等式通过后写入。
|
||||
30 11 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh pinduoduo-opening-balances:import --quiet >/dev/null 2>&1
|
||||
# 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。
|
||||
@ -259,7 +268,11 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
|
||||
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
|
||||
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
|
||||
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。
|
||||
@ -271,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
|
||||
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
|
||||
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
|
||||
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
|
||||
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||
|
||||
@ -292,11 +308,12 @@ CRON_TZ=Asia/Shanghai
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-ding-process-details
|
||||
|
||||
# 供应商月度对账单催办不依赖通用 Laravel 调度器;每月 1-14 日 10:00 由宿主机
|
||||
# 供应商月度对账单催办不依赖通用 Laravel 调度器;每月 1-14 日 10:00、16:00 由宿主机
|
||||
# cron 直接执行专用命令,15 日财务出上月终版。任务内部按日期和账期做幂等控制。
|
||||
cat > /etc/cron.d/caiwu-supplier-statement-reminders <<'EOF'
|
||||
CRON_TZ=Asia/Shanghai
|
||||
0 10 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
0 10 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder-10.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders --slot=10 >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
0 16 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder-16.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders --slot=16 >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-supplier-statement-reminders
|
||||
|
||||
|
||||
@ -217,6 +217,10 @@ CRON_TZ=Asia/Shanghai
|
||||
# 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。
|
||||
0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
|
||||
10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1
|
||||
# 供应商对账财务端:持续预热月份和对账人筛选,避免缓存过期后的首个请求扫描超大数据集。
|
||||
*/10 * * * * root /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-reconciliation:warm-finance-filters --company=1 --quiet >/dev/null 2>&1
|
||||
# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。
|
||||
30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1
|
||||
0 0 * * * 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 business-mirror:warm-report-caches --quiet' >/dev/null 2>&1
|
||||
0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --quiet >/dev/null 2>&1
|
||||
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
|
||||
@ -226,10 +230,10 @@ CRON_TZ=Asia/Shanghai
|
||||
40 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1
|
||||
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
|
||||
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
|
||||
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
|
||||
10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
|
||||
# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
|
||||
30 9 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
|
||||
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖及导入后的源订单变化,补刷异常日期,再刷新最近 7 天。
|
||||
10 6 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --json >> /opt/caiwuxitong/runtime/sync-logs/jst-order-labels-daily.log 2>&1
|
||||
# 种菜明细与业绩种菜金额:每天 09:30 先同步本月/上月工单明细,再做标签覆盖和业绩重算。
|
||||
30 9 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=2026-10-01 --company=1 --json >> /opt/caiwuxitong/runtime/sync-logs/planting-daily.log 2>&1
|
||||
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
|
||||
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
|
||||
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
|
||||
@ -240,12 +244,15 @@ CRON_TZ=Asia/Shanghai
|
||||
# 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总(未配置 Webhook 时自动跳过)。
|
||||
*/5 9-21 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-instant --quiet >/dev/null 2>&1
|
||||
0 10 * * * root /usr/bin/flock -n /run/caiwu-violation-push.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:push-digest --quiet >/dev/null 2>&1
|
||||
# 种菜报销:每天 10:30 锁定当天批次(放行检查通过即确认本批,没通过 10:40、10:50 再试;已确认跳过;不改聚工单)。
|
||||
30,40,50 10 * * * root /usr/bin/flock -n /run/caiwu-planting-confirm.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh planting-reimbursement:auto-confirm --quiet >/dev/null 2>&1
|
||||
# 种菜报销:每天 11:20 生成当天批次,汇总推到钉钉群并 @ 报销人(未配置机器人时跳过;只读)。
|
||||
20 11 * * * root /usr/bin/flock -n /run/caiwu-planting-digest.lock /usr/bin/docker exec -u www-data caiwu_app php artisan planting-reimbursement:daily-digest --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 前完成。
|
||||
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
|
||||
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
|
||||
@ -253,6 +260,8 @@ CRON_TZ=Asia/Shanghai
|
||||
30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --sources=store,withdrawal --quiet >/dev/null 2>&1
|
||||
5 * * * * root /usr/bin/flock -w 600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=2 --merge --sources=dingtalk,payable --quiet >/dev/null 2>&1
|
||||
30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1
|
||||
# 每月 1 日按上月末最后一笔真实余额锁定月度期初,供账户总览和月度资金分析直接读取。
|
||||
20 8 1 * * root /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:lock-monthly-opening --apply --quiet >/dev/null 2>&1
|
||||
# 拼多多期初:账单导入后即时尝试,每日 11:30 再扫一次未就绪店铺;只在余额恒等式通过后写入。
|
||||
30 11 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh pinduoduo-opening-balances:import --quiet >/dev/null 2>&1
|
||||
# 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。
|
||||
@ -263,7 +272,11 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
|
||||
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
|
||||
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
|
||||
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。
|
||||
@ -275,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
|
||||
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
|
||||
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
|
||||
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
|
||||
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
|
||||
|
||||
@ -296,11 +312,12 @@ CRON_TZ=Asia/Shanghai
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-ding-process-details
|
||||
|
||||
# 供应商月度对账单催办不依赖通用 Laravel 调度器;每月 1-14 日 10:00 由宿主机
|
||||
# 供应商月度对账单催办不依赖通用 Laravel 调度器;每月 1-14 日 10:00、16:00 由宿主机
|
||||
# cron 直接执行专用命令,15 日财务出上月终版。任务内部按日期和账期做幂等控制。
|
||||
cat > /etc/cron.d/caiwu-supplier-statement-reminders <<'EOF'
|
||||
CRON_TZ=Asia/Shanghai
|
||||
0 10 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
0 10 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder-10.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders --slot=10 >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
0 16 1-14 * * root /usr/bin/flock -n /run/caiwu-supplier-statement-reminder-16.lock /usr/bin/docker exec -u www-data caiwu_app php artisan supplier-statement:send-reminders --slot=16 >>/var/log/caiwu-supplier-statement-reminders.log 2>&1
|
||||
EOF
|
||||
chmod 644 /etc/cron.d/caiwu-supplier-statement-reminders
|
||||
|
||||
|
||||
@ -1,4 +1,9 @@
|
||||
[
|
||||
"courier-bills:match-reverse",
|
||||
"portal-freight:import-pending",
|
||||
"courier-surcharge:match-bills",
|
||||
"planting-reimbursement:auto-confirm",
|
||||
"jushuitan:apply-shipping-corrections",
|
||||
"actual-tax:import",
|
||||
"accessory-reship:import-courier-configs",
|
||||
"account-ledger-remarks:import",
|
||||
@ -9,6 +14,7 @@
|
||||
"business:import-alibaba-account-balances",
|
||||
"courier-freight:import",
|
||||
"courier-bills:import-summary-templates",
|
||||
"courier-bills:import-platform-robots",
|
||||
"dropship-freight:import-summary-templates",
|
||||
"courier-quotes:import-billing-rules",
|
||||
"dewu-bills:import-authoritative",
|
||||
@ -51,6 +57,7 @@
|
||||
"planting-details:sync-work-orders",
|
||||
"planting-details:import",
|
||||
"payables:unpriced-cycle",
|
||||
"payables:unpriced-cycle:auto",
|
||||
"payables:final-import",
|
||||
"product-catalog:import-authoritative-export",
|
||||
"product:monthly-weighted-average:base",
|
||||
|
||||
@ -8,12 +8,17 @@ is_import=0
|
||||
CAIWU_BATCH_CALLER_DIR="$PWD"
|
||||
export CAIWU_BATCH_CALLER_DIR
|
||||
case "${1:-}" in
|
||||
*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|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: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|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
|
||||
portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse) is_import=1 ;;
|
||||
planting-reimbursement:auto-confirm) is_import=1 ;;
|
||||
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
|
||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;
|
||||
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
|
||||
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
|
||||
esac
|
||||
case "${1:-}" in
|
||||
planting-reimbursement:auto-confirm)
|
||||
LOCK_FILE="${CAIWU_UPSTREAM_LOCK:-/run/caiwu-planting-confirm-worker.lock}"
|
||||
;;
|
||||
business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests)
|
||||
LOCK_FILE="${CAIWU_UPSTREAM_LOCK:-$OA_LOCK_FILE}"
|
||||
;;
|
||||
@ -22,6 +27,12 @@ case "${1:-}" in
|
||||
;;
|
||||
esac
|
||||
cd "$REMOTE_DIR"
|
||||
if [ "$1" = 'portal-freight:import-pending' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] && [ -d "$storage_root/app/private/portal-freight-bills/pending" ] || exit 0
|
||||
pending="$(find "$storage_root/app/private/portal-freight-bills/pending" -maxdepth 1 -type f -print -quit)"
|
||||
[ -n "$pending" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'account-bills:exports:run' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] && [ -d "$storage_root" ] || exit 65
|
||||
@ -47,6 +58,43 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then
|
||||
pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)"
|
||||
[ -n "$pending_request" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ]; 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
|
||||
pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.pending' -print -quit 2>/dev/null || true)"
|
||||
if [ -z "$pending_request" ]; then
|
||||
pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.running' -mmin +15 -print -quit 2>/dev/null || true)"
|
||||
fi
|
||||
[ -n "$pending_request" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = 'all' ] && [ "${3:-}" = '--monthly' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] || exit 0
|
||||
current_month="$(TZ=Asia/Shanghai date +%Y-%m)"
|
||||
if python3 - "$storage_root" "$current_month" <<'PY'
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
storage_root, current_month = sys.argv[1:3]
|
||||
paths = glob.glob(os.path.join(storage_root, 'app/account-mapping/coverage-snapshots/all-*.json'))
|
||||
paths.sort(key=os.path.getmtime, reverse=True)
|
||||
for path in paths:
|
||||
try:
|
||||
snapshot = json.loads(open(path, encoding='utf-8').read())
|
||||
except (OSError, ValueError, TypeError):
|
||||
continue
|
||||
refreshed_at = str(snapshot.get('refreshed_at', ''))
|
||||
if refreshed_at.startswith(current_month + '-'):
|
||||
sys.exit(0)
|
||||
break
|
||||
sys.exit(1)
|
||||
PY
|
||||
then
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
|
||||
@ -95,4 +143,25 @@ if [ "$1" = 'jushuitan:sync-shipping' ]; then
|
||||
sleep "${CAIWU_JST_SYNC_RETRY_WAIT:-300}"
|
||||
done
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ]; then
|
||||
container_name="caiwu_account_mapping_coverage_$$"
|
||||
cleanup_coverage_batch() {
|
||||
docker rm --force "$container_name" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_coverage_batch 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
|
||||
if [ "$1" = 'business-mirror:sync-returned-parcels' ] || [ "$1" = 'courier-surcharge:pull-customer-service' ]; then
|
||||
container_name="caiwu_returned_parcels_$$"
|
||||
cleanup_returned_parcels() {
|
||||
docker rm --force "$container_name" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_returned_parcels EXIT INT TERM
|
||||
/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \
|
||||
--name "$container_name" batch "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@"
|
||||
|
||||
@ -1,10 +1,28 @@
|
||||
# 上游业务镜像清单
|
||||
|
||||
## 发货数据专线运费
|
||||
|
||||
中铁物流、武进安能、壹米滴答专线的核算运费读取工作平台「专线运费」视图 `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 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。
|
||||
|
||||
用户确认的单票修正保存于 `jst_shipping_calculation_corrections`,按月份、运单号和快递隔离,覆盖线上重量、指定返货线路或目的地。`jushuitan:apply-shipping-corrections <JSON文件> --month=YYYY-MM --dry-run` 先核对;正式执行前保存私有备份,在事务中修改并仅重算目标包裹。文件最多256KiB/1000票,生产必须走独立批入口。原始上游数据不修改。
|
||||
|
||||
## 厂家记账月度发货导出
|
||||
|
||||
厂家记账核价使用工作平台月度导出的受控镜像,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)。
|
||||
|
||||
## 结论
|
||||
|
||||
@ -14,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 个流程。 |
|
||||
@ -80,6 +102,7 @@
|
||||
| 店铺资料 | `rpt.fys_shopInfo` | `ops_fys_shop_info` |
|
||||
| 商标资料 | `rpt.fys_TrademarkInfo` | `ops_fys_trademark_info` |
|
||||
| 订单 | `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.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` |
|
||||
|
||||
@ -7,8 +7,9 @@
|
||||
1. 对“补偿款项”“记账全款”(兼容“记账全额”),原金额大于0且小于50元,先判断原金额÷商品买家实付合计是否小于40%。命中后金额为0,不扣款,追加备注 `小于50且小于0.4,记账改0`。
|
||||
2. 未命中的,再用工单 `actual_paid_amount`(页面“实付金额”)作分母,独立判断同样的严格边界。任一轮实付缺失、无效或为0时,只跳过该轮;另一轮仍可正常判断。多商品买家实付缺一项时,不把部分金额当作完整合计。
|
||||
3. 保留厂家记账配置、代发仓发错货限制和多供应商待确认规则。只有已判定可扣款的剩余工单进入核价,不用核价推翻“不扣款”或“待确认”。
|
||||
财务明确指定的不记账工单,按公司设置 `supplier_bookkeeping.excluded_work_orders` 中的完整工单号排除,说明保留确认原因;不据此扩大为所有缺供应商工单不记账。
|
||||
工单供应商为空时,先按普通商品编码匹配商品资料;完整的 `ZH-/MKH-商品编码-数量-商品编码-数量` 组合编码拆出组件后逐个精确匹配,普通商品精确命中优先。运营组合套装从六个月内原单发货明细拆出实际商品编码,必须覆盖全部指定单号并核对订单;未发出或未完整匹配时不采用部分明细。每个组件都查到商品资料供应商后,才按当前配置、小额归零和核价规则继续处理。保留原编码,展示实际商品编码、逐编码供应商匹配说明;任一组件缺供应商或多供应商判定不一致仍待确认,不使用部分供应商扣款。不覆盖工单已有供应商。
|
||||
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
|
||||
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值;原单运费为空或0时,按对应商品成本×0.2替代,并注明“原单运费缺失或为0,按商品成本×0.2替代运费”。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
|
||||
5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。
|
||||
|
||||
6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。
|
||||
@ -18,14 +19,17 @@
|
||||
## 发货匹配
|
||||
|
||||
- 运费取工作平台月度导出“运费”;5月“系统运费”经用户确认是相同口径。不使用“结算运费”,不借用覆盖不足的现有发货表或其他年份数据。
|
||||
- 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月未完整导入时待确认。
|
||||
- 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月月度文件完整时保持原导出核价路径;缺文件且工单有明确快递号时,优先只读现有 `jst_oms_shipping` 自动同步明细,所有指定快递号和工单商品都匹配后,按同一金额规则核价,并注明“按系统同步发货明细核价(原快递单号完整匹配)”。
|
||||
- 缺六个月文件且无原单匹配的补偿/全款,仍先按小于50元且占买家实付或订单实付比例小于0.4归零;未命中时,以完整工单逐商品数量×当前商品成本核价,缺运费按成本×0.2,和原记账金额取小值。完整组合编码中的逐件数量乘工单组合数;多行商品数量逐行对应,重复编码按各行数量相加。缺数量、缺成本、只能匹配部分包裹或已匹配包裹明细不全仍待确认。运费损耗不使用无发货记录的工单回退核价;沐野竹木仍只记成本价。判定说明注明使用工单数量,不将其称为实际发货数量。
|
||||
- 自动同步来源须有成功同步记录,按现有快递号/订单号索引定点读取,换单前号仅在订单候选内精确核对;不直连上游、不改写发货数据。包裹行数须与 `pkg_count` 一致,沿用未发出名单排除,缺发货、部分单号、缺数量/商品/成本和冲突值仍待确认;自动同步来源不可用不影响文件完整的账期。
|
||||
- 有物流单号时精确匹配该单号或换单前单号,同时核对工单提供的线上订单号;无物流单号时按线上订单号匹配全部相关包裹。合并订单按拆分后的完整单号建立索引。
|
||||
- 单号及商品编码匹配前清理前后空白、不可见复制符、单引号、引号、`@` 及其全角形式;保留原始展示值及单号前导0,保留编码内部的 `-`、`+` 等合法内容,不做模糊匹配。
|
||||
- 不以平均运费替代原单运费,不借同订单其他快递单的运费;多个单号只匹配部分时待确认。
|
||||
- “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出或工单明确列出的单号被部分排除时待确认、不计扣款,保留原金额。其他辅助列错误待确认。
|
||||
- 工单商品须全部匹配。一个单元格合并多个商品编码、仅有总数量时,不推测每个商品的数量,标为待确认。
|
||||
- “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出明确判“不扣款”,保留原金额作核对;工单明确列出的单号被部分排除时仍待确认、不计部分扣款。其他辅助列错误待确认。缺文件工单回退前同样先核对共享未发出名单。
|
||||
- 工单商品须全部匹配。组合装一个单元格合并多个商品编码、仅有总数量时,沿用财务已确认的各条码1件口径,并注明“组合装按各条码1件计”;沐野竹木只记成本价的特殊规则仍要求逐商品实际数量。
|
||||
- 包裹运费只取一次;同包裹同商品的重复行不重复累计数量。运费或数量冲突时待确认,不相加、不擅自选值。
|
||||
- 缺发货、有效数量、成本价或运费时待确认,保留原金额,不计扣款合计;运费损耗的空/0运费按第5条替代,判定说明及备注明确记录“按对应商品成本合计×0.2替代运费”,成本与数量列展示替代部分的依据。补偿/全款仍将明确0运费视为有效,空运费待确认。
|
||||
- 同一快递号对应多个来源发货单时,补偿/全款仅核算含工单商品的来源单,排除同号无关配件单;仍须覆盖全部指定单号和商品,不借用无关来源单运费。工单重复展示同一商品编码时,以实际发货数量核价,不能把重复编码再次乘数量。
|
||||
- 缺发货、有效数量或成本价时待确认,保留原金额,不计扣款合计;空/0运费按第4、5条替代,成本与数量列展示替代部分的依据,不把缺失运费直接按0记账。
|
||||
- 原记账金额、匹配成本/运费/数量/快递号/期间供页面核对与导出。
|
||||
|
||||
## 月度发货导出镜像
|
||||
|
||||
15
docs/厂家门户运费账单上传.md
Normal file
15
docs/厂家门户运费账单上传.md
Normal file
@ -0,0 +1,15 @@
|
||||
# 厂家门户上传运费账单
|
||||
|
||||
厂家和快递通过原有钉钉入口进入门户,下载统一模板后提交账单。账号仅能给绑定的厂家或快递上传。财务账号沿用原页面权限,可为选定对象代传。
|
||||
|
||||
模板包含“账单”和可选的“附加费”两张表。账单第一行依次为:单号、省、重量、运费、快递名称、面单、费率;旧版第五列“送货备注”仍兼容。单号及运费必填,单号须完整,数字列须为有效数字。“附加费”表为快递单号、附加费金额、附加费类型,无附加费时可留空或不保留该表,有明细时三列必填。支持 XLSX、XLS、CSV,单份最多50MB,每张明细表最多100,000行;XLS沿用现有读取器20MB限制。CSV只包含主账单,附加费用XLSX或XLS上传。
|
||||
|
||||
网页只保存文件并显示等待处理。服务器每分钟通过现有独立批容器执行 `portal-freight:import-pending`,每次处理一份。使用共享同步锁,1 CPU、1GiB容器内存、PHP512MiB和一小时上限。无待办时不启动容器。校验失败在上传记录显示原因;进程中断不自动重导,下一次标记失败,财务核对已有记录后再决定重传。
|
||||
|
||||
后台继续使用现有代发/快递账单读取与对账规则,重复上传、已结算月份等限制仍生效。门户快递上传不会通过文件名或合并分组设置扩大目标范围。快递附加费按类型进入现有小汇总;代发附加费随原文件保存,不计入代发运费。成功回执使用实际读入行数,将运费与附加费分别显示;未配置群机器人时不发送。
|
||||
|
||||
不新增数据库表。任务文件沿用私有共享storage目录,原账单由现有账单存储流程留存。页面仅查当前对象的近期任务及最近10份已读入账单。
|
||||
|
||||
验证需包含:两类门户上传、未授权对象拒绝、停用账号拒绝、模板错误、空附加费表兼容、附加费类型与金额、额外工作表拒绝、后台隔离、重复导入和原有对账回归。性能基准以线上已有约7,500行账单为参照,使用合成账单在隔离环境测量,不向真实厂家群发送测试消息。
|
||||
|
||||
本次隔离SQLite验证:10,000行代发账单,文件222,830字节,读入0.482秒,45次数据库查询,数据库累计44.89ms;7,500行快递账单,文件167878字节,读入1.003秒,7609次查询,数据库累计243.36ms。进程峰值分别约128.7MiB和130MiB;包含测试框架开销。未对生产执行压测。
|
||||
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 小时超时继续生效。
|
||||
中断任务标记失败,联系财务核对后重传,不自动重复导入。
|
||||
26
docs/快递账单群机器人复用.md
Normal file
26
docs/快递账单群机器人复用.md
Normal file
@ -0,0 +1,26 @@
|
||||
# 快递账单群机器人复用
|
||||
|
||||
对账分组使用现有加密机器人设置。工作平台配置复制后,钉钉对账群列显示原群名和“工作平台应付群”,上传链接通知与账单上传回执使用同一份设置。只有 Webhook 的脱敏提示可见,不回显 Webhook 或加签密钥。
|
||||
|
||||
配置来源为负责人指定的工作平台“应付群机器人配置”导出,字段为 `Id`、`forModel`、`businessKey`、`groupname`、`webAccesstoken`、`Secret`、`modifytime`。导出文件只放在服务器私有目录并设为 `0600`,不得进入 Git 或日志。此功能不建立对旧业务库的自动同步,也不在页面请求时读取上游。
|
||||
|
||||
仅使用 `forModel=快递应付` 的记录,以财务系统“分组名称”为匹配依据,组合名称按 `|`、`+`、顿号或逗号分开。任一名称在工作平台群名中命中,或与 `businessKey` 中某个快递名称互相包含,即视为命中。不使用“归到承运商”和“快递名称1”代替分组名称。完整业务名称命中优先,其次取相交名称最长的一条,避免“常州德邦”抢走“常州德邦逆向”;仍有同等匹配时跳过并报告歧义。没有匹配时保留原设置。空群名不影响按业务名称匹配到的机器人发送能力。
|
||||
|
||||
先预演,核对结果后再写入:
|
||||
|
||||
常州德邦与常州德邦逆向是两家独立快递,两者只接受本家完整业务名称匹配;缺少本家配置时保持未匹配,不借用另一家的机器人。
|
||||
|
||||
北京韵达-乐鑫达按负责人指定使用“北京大件韵达+北京大件韵达临时”的机器人,匹配业务名称“北京大件韵达”。
|
||||
|
||||
樵舍中通、樵舍中通-上楼(也兼容樵舍中通上楼)、江西中通快运、江西新建中通、山东中通快运、南昌樵舍仓仓储费,统一使用包含完整业务名称“樵舍中通”的南昌对接群配置。中通快运专线使用“常州中通快运+武进韵达快运”的机器人;宿迁中通快运使用“沭阳中通快运”的机器人。指定目标不存在或存在多条时保持未匹配/有歧义,不回退到其他同名群。
|
||||
|
||||
山东顺丰干配、河北中通-江三、苏北顺丰干配大件按负责人指定使用“顺德德邦+廊坊德邦+廊坊德邦其他”的机器人,匹配业务名称“顺德德邦”。
|
||||
|
||||
```sh
|
||||
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:import-platform-robots /var/www/html/storage/app/private/courier-robot-imports/robots.json --company=1
|
||||
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:import-platform-robots /var/www/html/storage/app/private/courier-robot-imports/robots.json --company=1 --apply
|
||||
```
|
||||
|
||||
生产环境通过已登记的独立批处理入口运行,沿用互斥锁、1 CPU、1GiB 内存、PHP 512MiB 及一小时超时;本地与测试环境可直接使用 `php artisan`。命令接受最多 2MB、10000 条的配置文件。实际为几十条记录,内存中匹配并一次写入设置;不是账单导入或全量业务处理。写入前把原公司设置加密备份到 `storage/app/private/courier-robot-backups/`,备份中包含公司编号和原设置值。恢复时用同一应用密钥解密,并仅恢复该公司的 `supplier_reconciliation.dingtalk_robots` 设置。
|
||||
|
||||
导入会替换明确匹配分组的 Webhook、加签密钥和来源标记,保留无关供应商设置、互动卡片字段和发送记录。导入不发送任何群消息;原通知按钮由财务按账期手动操作。后续工作平台配置有变化时,需要重新导出、预演并导入。
|
||||
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 万行;查询按单号分批,月份按快递和取件时间索引,关联按取件主键。迁移仅增加共享镜像索引,不写上游业务数据。
|
||||
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