Compare commits
142 Commits
fix/limeng
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bddfffecec | |||
| 2a3787f400 | |||
| 05edc5f4a3 | |||
| 8e95325e21 | |||
| d2c7f0e355 | |||
| 7a584439a6 | |||
| d26532dee4 | |||
| aa7ec7aece | |||
| 10410f2792 | |||
| 24b71caca4 | |||
| 15558bc874 | |||
| 9175804957 | |||
| d30b9f6deb | |||
| 8ae0e54fbc | |||
| 7b175036e1 | |||
| 95f2633005 | |||
| cccfe8acbd | |||
| 85f8eda9ff | |||
| ff0a450e67 | |||
| 31bd498aea | |||
| 882447989d | |||
| cccca2815b | |||
| 84370c60be | |||
| 2c4062d9e2 | |||
| fc8415421a | |||
| 1abeedb96a | |||
| 77b1044565 | |||
| fd55a7736b | |||
| 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 |
@ -285,7 +285,7 @@ SQL);
|
|||||||
public function allSubjectReferences(int $companyId): array
|
public function allSubjectReferences(int $companyId): array
|
||||||
{
|
{
|
||||||
$statement = $this->pdo()->prepare(
|
$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 '
|
. 'FROM company_plan_rows '
|
||||||
. 'WHERE company_id = :company_id ORDER BY id'
|
. 'WHERE company_id = :company_id ORDER BY id'
|
||||||
);
|
);
|
||||||
|
|||||||
@ -96,6 +96,36 @@ class CourierContractPageData
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return array<string,array{start_date:?string,end_date:?string}> 同名快递取最新归档合作合同的日期。 */
|
||||||
|
public function datesByCourierNames(array $names): array
|
||||||
|
{
|
||||||
|
$names = array_values(array_unique(array_filter(array_map('trim', $names))));
|
||||||
|
if ($names === [] || ! Schema::hasTable('business_courier_agreement_signatures')) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$dates = [];
|
||||||
|
foreach (array_chunk($names, 500) as $chunk) {
|
||||||
|
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
|
||||||
|
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
|
||||||
|
->whereIn('courier_name', $chunk)
|
||||||
|
->select(['id', 'courier_name', 'payload', 'document_type', 'status'])
|
||||||
|
->orderByDesc('archived_at')->orderByDesc('id')->cursor();
|
||||||
|
foreach ($signatures as $signature) {
|
||||||
|
$name = trim((string) $signature->courier_name);
|
||||||
|
if (isset($dates[$name]) || ($payload = $signature->archivedCourierContractPayload()) === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$dates[$name] = [
|
||||||
|
'start_date' => $this->date($payload['cooperation_start_date'] ?? null),
|
||||||
|
'end_date' => $this->date($payload['cooperation_end_date'] ?? null),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $dates;
|
||||||
|
}
|
||||||
|
|
||||||
private function filters(): array
|
private function filters(): array
|
||||||
{
|
{
|
||||||
$search = request()->query('contract_search');
|
$search = request()->query('contract_search');
|
||||||
|
|||||||
@ -11,7 +11,8 @@ use Throwable;
|
|||||||
/**
|
/**
|
||||||
* 聚水潭订单标签明细的每日同步。
|
* 聚水潭订单标签明细的每日同步。
|
||||||
*
|
*
|
||||||
* 先核对历史日期是否逐日覆盖,再补齐缺口,最后替换刷新最近数日以吸收上游迟到修改。
|
* 先核对历史日期是否逐日覆盖、源订单是否在标签导入后再次变化,再补刷异常日期,
|
||||||
|
* 最后替换刷新最近数日以吸收上游迟到修改。
|
||||||
*/
|
*/
|
||||||
class JstOrderLabelDailySynchronizer
|
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
|
public function assertCovered(string $from, string $to, int $companyId): array
|
||||||
{
|
{
|
||||||
@ -164,12 +173,20 @@ class JstOrderLabelDailySynchronizer
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 逐日比较源订单号数与标签明细订单号数。
|
* 逐日比较源订单覆盖,并比较源订单更新时间与标签日期的完整导入时间。
|
||||||
*
|
*
|
||||||
* 标签拆行后同一订单会出现多行,因此不能用总行数直接比较订单完整性。
|
* 标签拆行后同一订单会出现多行,因此不能用总行数直接比较订单完整性。
|
||||||
|
* updateTime 晚于目标日最后导入时间,说明源订单可能只改了标签、未增删订单;
|
||||||
|
* 这类日期也必须整日重刷,否则订单数相同但标签内容会一直停留在旧版本。
|
||||||
*
|
*
|
||||||
* @return list<array{
|
* @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
|
public function coverage(Carbon $from, Carbon $to, int $companyId): array
|
||||||
@ -182,16 +199,24 @@ class JstOrderLabelDailySynchronizer
|
|||||||
$sourceRows = $mirror->table('ops_jst_orders')
|
$sourceRows = $mirror->table('ops_jst_orders')
|
||||||
->where('order_date', '>=', $start)
|
->where('order_date', '>=', $start)
|
||||||
->where('order_date', '<', $end)
|
->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)')
|
->groupByRaw('DATE(order_date)')
|
||||||
->get()
|
->get()
|
||||||
->keyBy('day');
|
->keyBy('day');
|
||||||
|
|
||||||
$targetRows = $target->table('jst_order_labels')
|
$targetRows = $target->table('jst_order_labels')
|
||||||
->where('company_id', $companyId)
|
->where('company_id', $companyId)
|
||||||
|
->whereNull('deleted_at')
|
||||||
->where('ordered_at', '>=', $start)
|
->where('ordered_at', '>=', $start)
|
||||||
->where('ordered_at', '<', $end)
|
->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)')
|
->groupByRaw('DATE(ordered_at)')
|
||||||
->get()
|
->get()
|
||||||
->keyBy('day');
|
->keyBy('day');
|
||||||
@ -202,11 +227,19 @@ class JstOrderLabelDailySynchronizer
|
|||||||
$sourceOrders = (int) ($sourceRows[$date]->order_count ?? 0);
|
$sourceOrders = (int) ($sourceRows[$date]->order_count ?? 0);
|
||||||
$targetOrderCount = (int) ($targetRows[$date]->order_count ?? 0);
|
$targetOrderCount = (int) ($targetRows[$date]->order_count ?? 0);
|
||||||
$targetRowsCount = (int) ($targetRows[$date]->row_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) {
|
$status = match (true) {
|
||||||
$sourceOrders === 0 => 'source_empty',
|
$sourceOrders === 0 => 'source_empty',
|
||||||
$targetOrderCount === 0 => 'missing',
|
$targetOrderCount === 0 => 'missing',
|
||||||
$targetOrderCount < $sourceOrders => 'incomplete',
|
$targetOrderCount < $sourceOrders => 'incomplete',
|
||||||
$targetOrderCount > $sourceOrders => 'extra_orders',
|
$targetOrderCount > $sourceOrders => 'extra_orders',
|
||||||
|
$sourceIsNewer => 'stale',
|
||||||
default => 'ok',
|
default => 'ok',
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -215,6 +248,8 @@ class JstOrderLabelDailySynchronizer
|
|||||||
'source_orders' => $sourceOrders,
|
'source_orders' => $sourceOrders,
|
||||||
'target_orders' => $targetOrderCount,
|
'target_orders' => $targetOrderCount,
|
||||||
'target_rows' => $targetRowsCount,
|
'target_rows' => $targetRowsCount,
|
||||||
|
'source_max_update_time' => $sourceMaxUpdateTime,
|
||||||
|
'target_imported_at' => $targetImportedAt,
|
||||||
'status' => $status,
|
'status' => $status,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@ -288,7 +323,18 @@ class JstOrderLabelDailySynchronizer
|
|||||||
private function issueSummary(array $issues): string
|
private function issueSummary(array $issues): string
|
||||||
{
|
{
|
||||||
return implode(',', array_map(
|
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,
|
$issues,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@ -319,4 +365,17 @@ class JstOrderLabelDailySynchronizer
|
|||||||
|
|
||||||
return $date->format('Y-m-d') === $value ? $date : null;
|
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> */
|
/** @return list<string> */
|
||||||
private function labelsForRecord(string $labels, string $sellerRemark): array
|
public function labelsForRecord(string $labels, string $sellerRemark): array
|
||||||
{
|
{
|
||||||
$labels = $this->splitLabels($labels);
|
$labels = $this->splitLabels($labels);
|
||||||
if (stripos($sellerRemark, self::SELLER_REMARK_LABEL) !== false
|
if (stripos($sellerRemark, self::SELLER_REMARK_LABEL) !== false
|
||||||
|
|||||||
383
app/Business/KukaPostingBase/KukaPostingAmountPoster.php
Normal file
383
app/Business/KukaPostingBase/KukaPostingAmountPoster.php
Normal file
@ -0,0 +1,383 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Business\KukaPostingBase;
|
||||||
|
|
||||||
|
use Illuminate\Database\ConnectionInterface;
|
||||||
|
use Illuminate\Database\DatabaseManager;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class KukaPostingAmountPoster
|
||||||
|
{
|
||||||
|
public const POSTING_LABEL = '过账标签';
|
||||||
|
|
||||||
|
public const POSTED_LABEL = '是';
|
||||||
|
|
||||||
|
public const SUPPLEMENT_LABEL = '补单(订单四组)';
|
||||||
|
|
||||||
|
private const UPDATE_CHUNK = 500;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly DatabaseManager $databases,
|
||||||
|
private readonly KukaPostingBaseRepository $repository,
|
||||||
|
private readonly KukaPostingAmountSelection $selection,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function plan(int $companyId, string $period, string $targetAmount): array
|
||||||
|
{
|
||||||
|
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||||||
|
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
|
||||||
|
}
|
||||||
|
$targetCents = $this->amountToCents($targetAmount);
|
||||||
|
if ($targetCents <= 0) {
|
||||||
|
throw new InvalidArgumentException('整月过账金额必须大于 0。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$import = $this->repository->importFor($companyId, $period);
|
||||||
|
if ($import === null) {
|
||||||
|
throw new RuntimeException('当前账期尚未导入发货明细。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$connection = $this->connection();
|
||||||
|
$sourceRows = [];
|
||||||
|
$itemNumbers = [];
|
||||||
|
$storedMaterialNumbers = [];
|
||||||
|
$connection->table('kuka_posting_base_rows')
|
||||||
|
->where('company_id', $companyId)
|
||||||
|
->where('period', $period)
|
||||||
|
->select([
|
||||||
|
'id',
|
||||||
|
'send_date',
|
||||||
|
'order_date',
|
||||||
|
'source_row_number',
|
||||||
|
'source_values',
|
||||||
|
])
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(1000, function ($rows) use (
|
||||||
|
&$sourceRows,
|
||||||
|
&$itemNumbers,
|
||||||
|
&$storedMaterialNumbers,
|
||||||
|
): void {
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
try {
|
||||||
|
$values = json_decode(
|
||||||
|
(string) $row->source_values,
|
||||||
|
true,
|
||||||
|
512,
|
||||||
|
JSON_THROW_ON_ERROR,
|
||||||
|
);
|
||||||
|
} catch (Throwable) {
|
||||||
|
$values = [];
|
||||||
|
}
|
||||||
|
if (! is_array($values)) {
|
||||||
|
$values = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$itemNumber = trim((string) ($values['货号'] ?? ''));
|
||||||
|
if ($itemNumber !== '') {
|
||||||
|
$itemNumbers[$itemNumber] = true;
|
||||||
|
}
|
||||||
|
$storedMaterialNumber = trim((string) ($values['物料编号'] ?? ''));
|
||||||
|
$usesRepairedMaterial = trim((string) (
|
||||||
|
$values['物料信息修正'] ?? ''
|
||||||
|
)) === '是';
|
||||||
|
if ($usesRepairedMaterial && $storedMaterialNumber !== '') {
|
||||||
|
$storedMaterialNumbers[$storedMaterialNumber] = true;
|
||||||
|
}
|
||||||
|
$sourceRows[] = [
|
||||||
|
'id' => (int) $row->id,
|
||||||
|
'item_number' => $itemNumber,
|
||||||
|
'stored_material_number' => $storedMaterialNumber,
|
||||||
|
'uses_repaired_material' => $usesRepairedMaterial,
|
||||||
|
'quantity' => $this->decimalString($values['实发数量'] ?? null),
|
||||||
|
'date' => (string) ($row->send_date ?? $row->order_date ?? ''),
|
||||||
|
'source_row_number' => (int) $row->source_row_number,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($sourceRows === []) {
|
||||||
|
throw new RuntimeException('当前账期没有发货明细行。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$maps = $this->repository->materialMaps($companyId, array_keys($itemNumbers));
|
||||||
|
$quotations = $this->repository->effectiveQuotations(
|
||||||
|
$companyId,
|
||||||
|
collect($maps)
|
||||||
|
->pluck('material_number')
|
||||||
|
->filter()
|
||||||
|
->merge(array_keys($storedMaterialNumbers))
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$groups = [];
|
||||||
|
$eligibleRows = 0;
|
||||||
|
foreach ($sourceRows as $row) {
|
||||||
|
$materialNumber = trim((string) ($row['stored_material_number'] ?? ''));
|
||||||
|
if (! $row['uses_repaired_material'] || $materialNumber === '') {
|
||||||
|
$materialNumber = trim((string) (
|
||||||
|
$maps[$row['item_number']]->material_number ?? ''
|
||||||
|
));
|
||||||
|
}
|
||||||
|
$quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null);
|
||||||
|
if ($materialNumber === '' || $quotation === null || $row['quantity'] === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$amount = bcmul(
|
||||||
|
$this->decimalString($quotation->price_including_tax) ?? '0',
|
||||||
|
$row['quantity'],
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
$amountCents = $this->amountToCents($amount);
|
||||||
|
if ($amountCents <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$groups[$materialNumber][] = [
|
||||||
|
'id' => (int) $row['id'],
|
||||||
|
'amount_cents' => $amountCents,
|
||||||
|
'date' => (string) $row['date'],
|
||||||
|
'source_row_number' => (int) $row['source_row_number'],
|
||||||
|
];
|
||||||
|
$eligibleRows++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $this->selection->select($groups, $targetCents);
|
||||||
|
$fingerprint = hash('sha256', json_encode([
|
||||||
|
'company_id' => $companyId,
|
||||||
|
'period' => $period,
|
||||||
|
'target_cents' => $targetCents,
|
||||||
|
'file_sha256' => (string) $import->file_sha256,
|
||||||
|
'selected_ids' => $result['selected_ids'],
|
||||||
|
'selected_cents' => $result['selected_cents'],
|
||||||
|
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'company_id' => $companyId,
|
||||||
|
'period' => $period,
|
||||||
|
'target_cents' => $result['target_cents'],
|
||||||
|
'target_amount' => $this->formatAmount($result['target_cents']),
|
||||||
|
'total_cents' => $result['total_cents'],
|
||||||
|
'total_amount' => $this->formatAmount($result['total_cents']),
|
||||||
|
'selected_cents' => $result['selected_cents'],
|
||||||
|
'selected_amount' => $this->formatAmount($result['selected_cents']),
|
||||||
|
'difference_cents' => $result['difference_cents'],
|
||||||
|
'difference_amount' => $this->formatAmount(abs($result['difference_cents'])),
|
||||||
|
'is_exact' => (bool) $result['exact'],
|
||||||
|
'rows_total' => count($sourceRows),
|
||||||
|
'eligible_rows' => $eligibleRows,
|
||||||
|
'uncalculable_rows' => count($sourceRows) - $eligibleRows,
|
||||||
|
'selected_rows' => (int) $result['selected_rows'],
|
||||||
|
'material_count' => count($groups),
|
||||||
|
'selected_material_count' => (int) $result['selected_materials'],
|
||||||
|
'selected_ids' => $result['selected_ids'],
|
||||||
|
'allocations' => $result['allocations'],
|
||||||
|
'preview_hash' => $fingerprint,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $plan
|
||||||
|
* @return array{updated:int,unchanged:int}
|
||||||
|
*/
|
||||||
|
public function apply(array $plan, ?int $userId = null): array
|
||||||
|
{
|
||||||
|
if (($plan['is_exact'] ?? false) !== true) {
|
||||||
|
throw new InvalidArgumentException('过账金额与选中发货金额仍有差额,未写入过账标签。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$companyId = (int) ($plan['company_id'] ?? 0);
|
||||||
|
$period = (string) ($plan['period'] ?? '');
|
||||||
|
$selectedIds = array_fill_keys(array_map('intval', (array) ($plan['selected_ids'] ?? [])), true);
|
||||||
|
$connection = $this->connection();
|
||||||
|
$now = now();
|
||||||
|
$updated = 0;
|
||||||
|
$unchanged = 0;
|
||||||
|
|
||||||
|
$connection->transaction(function () use (
|
||||||
|
$connection,
|
||||||
|
$companyId,
|
||||||
|
$period,
|
||||||
|
$selectedIds,
|
||||||
|
$now,
|
||||||
|
$userId,
|
||||||
|
$plan,
|
||||||
|
&$updated,
|
||||||
|
&$unchanged,
|
||||||
|
): void {
|
||||||
|
$batch = [];
|
||||||
|
$flush = static function () use ($connection, &$batch): void {
|
||||||
|
if ($batch === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$connection->table('kuka_posting_base_rows')->upsert(
|
||||||
|
$batch,
|
||||||
|
['company_id', 'period', 'source_row_number'],
|
||||||
|
[
|
||||||
|
'store_name',
|
||||||
|
'internal_order_no',
|
||||||
|
'online_order_no',
|
||||||
|
'product_code',
|
||||||
|
'source_values',
|
||||||
|
'row_hash',
|
||||||
|
'imported_at',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
$batch = [];
|
||||||
|
};
|
||||||
|
|
||||||
|
$connection->table('kuka_posting_base_rows')
|
||||||
|
->where('company_id', $companyId)
|
||||||
|
->where('period', $period)
|
||||||
|
->orderBy('id')
|
||||||
|
->chunkById(self::UPDATE_CHUNK, function ($rows) use (
|
||||||
|
$selectedIds,
|
||||||
|
&$updated,
|
||||||
|
&$unchanged,
|
||||||
|
&$batch,
|
||||||
|
$flush,
|
||||||
|
): void {
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
try {
|
||||||
|
$values = json_decode(
|
||||||
|
(string) $row->source_values,
|
||||||
|
true,
|
||||||
|
512,
|
||||||
|
JSON_THROW_ON_ERROR,
|
||||||
|
);
|
||||||
|
} catch (Throwable) {
|
||||||
|
$values = [];
|
||||||
|
}
|
||||||
|
if (! is_array($values)) {
|
||||||
|
$values = [];
|
||||||
|
}
|
||||||
|
$label = isset($selectedIds[(int) $row->id])
|
||||||
|
? self::POSTED_LABEL
|
||||||
|
: self::SUPPLEMENT_LABEL;
|
||||||
|
if (trim((string) ($values[self::POSTING_LABEL] ?? '')) === $label) {
|
||||||
|
$unchanged++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$values[self::POSTING_LABEL] = $label;
|
||||||
|
$encoded = json_encode(
|
||||||
|
$values,
|
||||||
|
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||||
|
);
|
||||||
|
$batch[] = [
|
||||||
|
'company_id' => (int) $row->company_id,
|
||||||
|
'period' => (string) $row->period,
|
||||||
|
'source_row_number' => (int) $row->source_row_number,
|
||||||
|
'store_name' => (string) $row->store_name,
|
||||||
|
'internal_order_no' => $row->internal_order_no,
|
||||||
|
'online_order_no' => $row->online_order_no,
|
||||||
|
'product_code' => $row->product_code,
|
||||||
|
'source_values' => $encoded,
|
||||||
|
'row_hash' => hash('sha256', $encoded),
|
||||||
|
'imported_at' => $row->imported_at,
|
||||||
|
];
|
||||||
|
$updated++;
|
||||||
|
if (count($batch) >= self::UPDATE_CHUNK) {
|
||||||
|
$flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$flush();
|
||||||
|
|
||||||
|
$connection->table('kuka_posting_base_imports')
|
||||||
|
->where('company_id', $companyId)
|
||||||
|
->where('period', $period)
|
||||||
|
->update([
|
||||||
|
'posting_target_amount' => $plan['target_amount'],
|
||||||
|
'posting_selected_amount' => $plan['selected_amount'],
|
||||||
|
'posting_difference_amount' => '0.00',
|
||||||
|
'posting_selected_rows' => (int) $plan['selected_rows'],
|
||||||
|
'posting_material_count' => (int) $plan['material_count'],
|
||||||
|
'posting_uncalculable_rows' => (int) $plan['uncalculable_rows'],
|
||||||
|
'posting_allocation_json' => json_encode(
|
||||||
|
$plan['allocations'],
|
||||||
|
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||||
|
),
|
||||||
|
'posting_snapshot_hash' => (string) $plan['preview_hash'],
|
||||||
|
'posting_applied_by' => $userId,
|
||||||
|
'posting_applied_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
return ['updated' => $updated, 'unchanged' => $unchanged];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,mixed> $plan
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public function previewSummary(array $plan): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'period' => (string) $plan['period'],
|
||||||
|
'target_cents' => (int) $plan['target_cents'],
|
||||||
|
'target_amount' => (string) $plan['target_amount'],
|
||||||
|
'total_cents' => (int) $plan['total_cents'],
|
||||||
|
'total_amount' => (string) $plan['total_amount'],
|
||||||
|
'selected_cents' => (int) $plan['selected_cents'],
|
||||||
|
'selected_amount' => (string) $plan['selected_amount'],
|
||||||
|
'difference_cents' => (int) $plan['difference_cents'],
|
||||||
|
'difference_amount' => (string) $plan['difference_amount'],
|
||||||
|
'is_exact' => (bool) $plan['is_exact'],
|
||||||
|
'rows_total' => (int) $plan['rows_total'],
|
||||||
|
'uncalculable_rows' => (int) $plan['uncalculable_rows'],
|
||||||
|
'selected_rows' => (int) $plan['selected_rows'],
|
||||||
|
'material_count' => (int) $plan['material_count'],
|
||||||
|
'selected_material_count' => (int) $plan['selected_material_count'],
|
||||||
|
'preview_hash' => (string) $plan['preview_hash'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decimalString(mixed $value): ?string
|
||||||
|
{
|
||||||
|
$normalized = str_replace(',', '', trim((string) $value));
|
||||||
|
if ($normalized === '' || ! is_numeric($normalized)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function amountToCents(string $amount): int
|
||||||
|
{
|
||||||
|
$normalized = str_replace([',', ' '], '', trim($amount));
|
||||||
|
if (preg_match('/^(\d+)(?:\.(\d+))?$/', $normalized, $matches) !== 1) {
|
||||||
|
throw new InvalidArgumentException('金额格式不正确。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$whole = (int) $matches[1];
|
||||||
|
$fraction = str_pad($matches[2] ?? '', 3, '0');
|
||||||
|
$cents = ($whole * 100) + (int) substr($fraction, 0, 2);
|
||||||
|
if ((int) $fraction[2] >= 5) {
|
||||||
|
$cents++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cents;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function formatAmount(int $cents): string
|
||||||
|
{
|
||||||
|
return bcdiv((string) $cents, '100', 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function connection(): ConnectionInterface
|
||||||
|
{
|
||||||
|
return $this->databases->connection(
|
||||||
|
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
418
app/Business/KukaPostingBase/KukaPostingAmountSelection.php
Normal file
418
app/Business/KukaPostingBase/KukaPostingAmountSelection.php
Normal file
@ -0,0 +1,418 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Business\KukaPostingBase;
|
||||||
|
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按料号分配整月过账金额,并在每个料号内按发货日期优先选行。
|
||||||
|
*/
|
||||||
|
class KukaPostingAmountSelection
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
||||||
|
* @return array{
|
||||||
|
* exact: bool,
|
||||||
|
* target_cents: int,
|
||||||
|
* total_cents: int,
|
||||||
|
* selected_cents: int,
|
||||||
|
* difference_cents: int,
|
||||||
|
* selected_ids: list<int>,
|
||||||
|
* selected_rows: int,
|
||||||
|
* selected_materials: int,
|
||||||
|
* allocations: list<array{
|
||||||
|
* material_number: string,
|
||||||
|
* total_cents: int,
|
||||||
|
* allocated_cents: int,
|
||||||
|
* selected_cents: int,
|
||||||
|
* selected_rows: int,
|
||||||
|
* row_count: int
|
||||||
|
* }>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public function select(array $groups, int $targetCents): array
|
||||||
|
{
|
||||||
|
if ($targetCents <= 0) {
|
||||||
|
throw new InvalidArgumentException('整月过账金额必须大于 0。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$groups = $this->normalizeGroups($groups);
|
||||||
|
if ($groups === []) {
|
||||||
|
throw new InvalidArgumentException('当前账期没有可用于过账的料号和发货金额。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$totalCents = 0;
|
||||||
|
$minimumCents = 0;
|
||||||
|
foreach ($groups as $rows) {
|
||||||
|
$totalCents += array_sum(array_column($rows, 'amount_cents'));
|
||||||
|
$minimumCents += (int) $rows[0]['amount_cents'];
|
||||||
|
}
|
||||||
|
if ($targetCents > $totalCents) {
|
||||||
|
throw new InvalidArgumentException('整月过账金额不能大于可计算发货金额合计。');
|
||||||
|
}
|
||||||
|
|
||||||
|
$allocations = $this->proportionalAllocations($groups, $targetCents, $minimumCents);
|
||||||
|
$selected = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$allocation = $allocations[$materialNumber];
|
||||||
|
$prefixCents = 0;
|
||||||
|
$bestCount = 1;
|
||||||
|
$bestDifference = PHP_INT_MAX;
|
||||||
|
foreach ($rows as $index => $row) {
|
||||||
|
$prefixCents += (int) $row['amount_cents'];
|
||||||
|
$difference = abs($allocation - $prefixCents);
|
||||||
|
if ($difference < $bestDifference) {
|
||||||
|
$bestDifference = $difference;
|
||||||
|
$bestCount = $index + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ($index = 0; $index < $bestCount; $index++) {
|
||||||
|
$selected[(int) $rows[$index]['id']] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[$selected, $selectedCents] = $this->calibrate(
|
||||||
|
$groups,
|
||||||
|
$selected,
|
||||||
|
$targetCents,
|
||||||
|
);
|
||||||
|
|
||||||
|
$selectedByMaterial = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if (isset($selected[(int) $row['id']])) {
|
||||||
|
$selectedByMaterial[$materialNumber][] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$allocationRows = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$selectedRows = $selectedByMaterial[$materialNumber] ?? [];
|
||||||
|
$allocationRows[] = [
|
||||||
|
'material_number' => (string) $materialNumber,
|
||||||
|
'total_cents' => array_sum(array_column($rows, 'amount_cents')),
|
||||||
|
'allocated_cents' => $allocations[$materialNumber],
|
||||||
|
'selected_cents' => array_sum(array_column($selectedRows, 'amount_cents')),
|
||||||
|
'selected_rows' => count($selectedRows),
|
||||||
|
'row_count' => count($rows),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
usort(
|
||||||
|
$allocationRows,
|
||||||
|
static fn (array $left, array $right): int => strnatcasecmp(
|
||||||
|
$left['material_number'],
|
||||||
|
$right['material_number'],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
$selectedIds = array_keys($selected);
|
||||||
|
sort($selectedIds, SORT_NUMERIC);
|
||||||
|
$differenceCents = $targetCents - $selectedCents;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'exact' => $differenceCents === 0,
|
||||||
|
'target_cents' => $targetCents,
|
||||||
|
'total_cents' => $totalCents,
|
||||||
|
'selected_cents' => $selectedCents,
|
||||||
|
'difference_cents' => $differenceCents,
|
||||||
|
'selected_ids' => $selectedIds,
|
||||||
|
'selected_rows' => count($selectedIds),
|
||||||
|
'selected_materials' => count($selectedByMaterial),
|
||||||
|
'allocations' => $allocationRows,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
||||||
|
* @return array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>>
|
||||||
|
*/
|
||||||
|
private function normalizeGroups(array $groups): array
|
||||||
|
{
|
||||||
|
$normalized = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$materialNumber = trim((string) $materialNumber);
|
||||||
|
if ($materialNumber === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$validRows = array_values(array_filter(
|
||||||
|
$rows,
|
||||||
|
static fn (array $row): bool => (int) ($row['amount_cents'] ?? 0) > 0
|
||||||
|
&& (int) ($row['id'] ?? 0) > 0,
|
||||||
|
));
|
||||||
|
if ($validRows === []) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
usort($validRows, static function (array $left, array $right): int {
|
||||||
|
$dateComparison = strcmp((string) $left['date'], (string) $right['date']);
|
||||||
|
|
||||||
|
return $dateComparison !== 0
|
||||||
|
? $dateComparison
|
||||||
|
: ((int) $left['source_row_number'] <=> (int) $right['source_row_number']);
|
||||||
|
});
|
||||||
|
$normalized[$materialNumber] = $validRows;
|
||||||
|
}
|
||||||
|
ksort($normalized, SORT_NATURAL | SORT_FLAG_CASE);
|
||||||
|
|
||||||
|
return $normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 先保证每个料号选中最早一行,再按剩余发货金额占比分配剩余过账金额。
|
||||||
|
*
|
||||||
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
||||||
|
* @return array<string,int>
|
||||||
|
*/
|
||||||
|
private function proportionalAllocations(
|
||||||
|
array $groups,
|
||||||
|
int $targetCents,
|
||||||
|
int $minimumCents,
|
||||||
|
): array {
|
||||||
|
if ($targetCents < $minimumCents) {
|
||||||
|
throw new InvalidArgumentException(sprintf(
|
||||||
|
'整月过账金额不足:每个料号至少选择一行需要 %s。',
|
||||||
|
number_format($minimumCents / 100, 2, '.', ','),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
$extraTotal = 0;
|
||||||
|
$extraByMaterial = [];
|
||||||
|
$baseByMaterial = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$base = (int) $rows[0]['amount_cents'];
|
||||||
|
$total = array_sum(array_column($rows, 'amount_cents'));
|
||||||
|
$baseByMaterial[$materialNumber] = $base;
|
||||||
|
$extraByMaterial[$materialNumber] = $total - $base;
|
||||||
|
$extraTotal += $total - $base;
|
||||||
|
}
|
||||||
|
|
||||||
|
$remaining = $targetCents - $minimumCents;
|
||||||
|
$allocations = [];
|
||||||
|
$remainders = [];
|
||||||
|
$assigned = 0;
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$extra = $extraByMaterial[$materialNumber];
|
||||||
|
$share = 0;
|
||||||
|
$remainder = '0';
|
||||||
|
if ($remaining > 0 && $extraTotal > 0 && $extra > 0) {
|
||||||
|
$numerator = bcmul((string) $extra, (string) $remaining, 0);
|
||||||
|
$share = (int) bcdiv($numerator, (string) $extraTotal, 0);
|
||||||
|
$remainder = bcmod($numerator, (string) $extraTotal);
|
||||||
|
}
|
||||||
|
$allocations[$materialNumber] = $baseByMaterial[$materialNumber] + $share;
|
||||||
|
$assigned += $share;
|
||||||
|
$remainders[$materialNumber] = $remainder;
|
||||||
|
}
|
||||||
|
|
||||||
|
$left = $remaining - $assigned;
|
||||||
|
if ($left > 0) {
|
||||||
|
$ordered = array_keys($groups);
|
||||||
|
usort($ordered, static function (string $leftMaterial, string $rightMaterial) use (
|
||||||
|
$remainders,
|
||||||
|
$extraByMaterial,
|
||||||
|
): int {
|
||||||
|
if ($extraByMaterial[$leftMaterial] <= 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if ($extraByMaterial[$rightMaterial] <= 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bccomp($remainders[$rightMaterial], $remainders[$leftMaterial], 0)
|
||||||
|
?: strnatcasecmp($leftMaterial, $rightMaterial);
|
||||||
|
});
|
||||||
|
foreach ($ordered as $materialNumber) {
|
||||||
|
if ($left <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ($extraByMaterial[$materialNumber] > $allocations[$materialNumber]
|
||||||
|
- $baseByMaterial[$materialNumber]) {
|
||||||
|
$allocations[$materialNumber]++;
|
||||||
|
$left--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $allocations;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
|
||||||
|
* @param array<int,true> $selected
|
||||||
|
* @return array{0:array<int,true>,1:int}
|
||||||
|
*/
|
||||||
|
private function calibrate(array $groups, array $selected, int $targetCents): array
|
||||||
|
{
|
||||||
|
$rowsById = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$id = (int) $row['id'];
|
||||||
|
$row['material_number'] = $materialNumber;
|
||||||
|
$rowsById[$id] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($attempt = 0; $attempt < count($groups) + 2; $attempt++) {
|
||||||
|
$selectedCents = 0;
|
||||||
|
foreach ($rowsById as $id => $row) {
|
||||||
|
if (isset($selected[$id])) {
|
||||||
|
$selectedCents += (int) $row['amount_cents'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$difference = $targetCents - $selectedCents;
|
||||||
|
if ($difference === 0) {
|
||||||
|
return [$selected, $selectedCents];
|
||||||
|
}
|
||||||
|
|
||||||
|
$options = $this->prefixOptions($groups, $selected);
|
||||||
|
$adjustments = $this->exactPrefixAdjustment($options, $difference);
|
||||||
|
if ($adjustments === null) {
|
||||||
|
$adjustment = $this->bestApproximatePrefixOption($options, $difference);
|
||||||
|
if ($adjustment === null) {
|
||||||
|
return [$selected, $selectedCents];
|
||||||
|
}
|
||||||
|
if (abs($difference - $adjustment['delta']) >= abs($difference)) {
|
||||||
|
return [$selected, $selectedCents];
|
||||||
|
}
|
||||||
|
$adjustments = [$adjustment];
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($adjustments as $adjustment) {
|
||||||
|
$materialNumber = $adjustment['material_number'];
|
||||||
|
foreach ($groups[$materialNumber] as $row) {
|
||||||
|
unset($selected[(int) $row['id']]);
|
||||||
|
}
|
||||||
|
for ($index = 0; $index < $adjustment['count']; $index++) {
|
||||||
|
$selected[(int) $groups[$materialNumber][$index]['id']] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$selectedCents = 0;
|
||||||
|
foreach (array_keys($selected) as $id) {
|
||||||
|
$selectedCents += (int) $rowsById[$id]['amount_cents'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$selected, $selectedCents];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string,list<array<string,mixed>>> $groups
|
||||||
|
* @param array<int,true> $selected
|
||||||
|
* @return list<array{
|
||||||
|
* material_number:string,
|
||||||
|
* count:int,
|
||||||
|
* delta:int,
|
||||||
|
* count_change:int
|
||||||
|
* }>
|
||||||
|
*/
|
||||||
|
private function prefixOptions(
|
||||||
|
array $groups,
|
||||||
|
array $selected,
|
||||||
|
): array {
|
||||||
|
$options = [];
|
||||||
|
foreach ($groups as $materialNumber => $rows) {
|
||||||
|
$currentCents = 0;
|
||||||
|
$currentCount = 0;
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if (isset($selected[(int) $row['id']])) {
|
||||||
|
$currentCents += (int) $row['amount_cents'];
|
||||||
|
$currentCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$prefixCents = 0;
|
||||||
|
foreach ($rows as $index => $row) {
|
||||||
|
$prefixCents += (int) $row['amount_cents'];
|
||||||
|
$count = $index + 1;
|
||||||
|
$delta = $prefixCents - $currentCents;
|
||||||
|
if ($delta !== 0) {
|
||||||
|
$options[] = [
|
||||||
|
'material_number' => (string) $materialNumber,
|
||||||
|
'count' => $count,
|
||||||
|
'delta' => $delta,
|
||||||
|
'count_change' => abs($count - $currentCount),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调整一个或两个料号的日期前缀,寻找精确差额。
|
||||||
|
*
|
||||||
|
* @param list<array{
|
||||||
|
* material_number:string,
|
||||||
|
* count:int,
|
||||||
|
* delta:int,
|
||||||
|
* count_change:int
|
||||||
|
* }> $options
|
||||||
|
* @return list<array{material_number:string,count:int,delta:int,count_change:int}>|null
|
||||||
|
*/
|
||||||
|
private function exactPrefixAdjustment(array $options, int $difference): ?array
|
||||||
|
{
|
||||||
|
$single = null;
|
||||||
|
foreach ($options as $option) {
|
||||||
|
if ($option['delta'] === $difference
|
||||||
|
&& ($single === null || $option['count_change'] < $single['count_change'])) {
|
||||||
|
$single = $option;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($single !== null) {
|
||||||
|
return [$single];
|
||||||
|
}
|
||||||
|
|
||||||
|
$byDelta = [];
|
||||||
|
foreach ($options as $option) {
|
||||||
|
$byDelta[$option['delta']][] = $option;
|
||||||
|
}
|
||||||
|
foreach ($options as $left) {
|
||||||
|
$needed = $difference - $left['delta'];
|
||||||
|
foreach ($byDelta[$needed] ?? [] as $right) {
|
||||||
|
if ($left['material_number'] === $right['material_number']) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
$left,
|
||||||
|
$right,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{
|
||||||
|
* material_number:string,
|
||||||
|
* count:int,
|
||||||
|
* delta:int,
|
||||||
|
* count_change:int
|
||||||
|
* }> $options
|
||||||
|
* @return array{material_number:string,count:int,delta:int,count_change:int}|null
|
||||||
|
*/
|
||||||
|
private function bestApproximatePrefixOption(
|
||||||
|
array $options,
|
||||||
|
int $difference,
|
||||||
|
): ?array {
|
||||||
|
$best = null;
|
||||||
|
$bestRemaining = abs($difference);
|
||||||
|
foreach ($options as $option) {
|
||||||
|
$remaining = abs($difference - $option['delta']);
|
||||||
|
if ($remaining < $bestRemaining
|
||||||
|
|| ($remaining === $bestRemaining
|
||||||
|
&& $best !== null
|
||||||
|
&& $option['count_change'] < $best['count_change'])) {
|
||||||
|
$best = $option;
|
||||||
|
$bestRemaining = $remaining;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $best;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -21,6 +21,7 @@ class KukaPostingBasePageData
|
|||||||
* statuses: list<string>,
|
* statuses: list<string>,
|
||||||
* stores: list<string>,
|
* stores: list<string>,
|
||||||
* import: ?array<string, mixed>,
|
* import: ?array<string, mixed>,
|
||||||
|
* posting_amount: ?array<string, mixed>,
|
||||||
* summary: array<string, mixed>,
|
* summary: array<string, mixed>,
|
||||||
* error: ?string
|
* error: ?string
|
||||||
* }
|
* }
|
||||||
@ -182,6 +183,7 @@ class KukaPostingBasePageData
|
|||||||
|
|
||||||
$import = $available ? $this->repository->importFor($companyId, $period) : null;
|
$import = $available ? $this->repository->importFor($companyId, $period) : null;
|
||||||
$importData = null;
|
$importData = null;
|
||||||
|
$postingAmount = null;
|
||||||
if ($import !== null) {
|
if ($import !== null) {
|
||||||
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
|
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
|
||||||
$importData = [
|
$importData = [
|
||||||
@ -195,6 +197,20 @@ class KukaPostingBasePageData
|
|||||||
'source_sheet' => (string) $import->source_sheet,
|
'source_sheet' => (string) $import->source_sheet,
|
||||||
'completed_at' => (string) $import->completed_at,
|
'completed_at' => (string) $import->completed_at,
|
||||||
];
|
];
|
||||||
|
if (property_exists($import, 'posting_target_amount')
|
||||||
|
&& $import->posting_target_amount !== null) {
|
||||||
|
$postingAmount = [
|
||||||
|
'target_amount' => bcdiv((string) $import->posting_target_amount, '1', 2),
|
||||||
|
'selected_amount' => bcdiv((string) $import->posting_selected_amount, '1', 2),
|
||||||
|
'difference_amount' => bcdiv((string) $import->posting_difference_amount, '1', 2),
|
||||||
|
'selected_rows' => (int) $import->posting_selected_rows,
|
||||||
|
'material_count' => (int) $import->posting_material_count,
|
||||||
|
'uncalculable_rows' => (int) $import->posting_uncalculable_rows,
|
||||||
|
'applied_at' => $import->posting_applied_at
|
||||||
|
? (string) $import->posting_applied_at
|
||||||
|
: null,
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
@ -211,6 +227,7 @@ class KukaPostingBasePageData
|
|||||||
'statuses' => $statuses,
|
'statuses' => $statuses,
|
||||||
'stores' => $stores,
|
'stores' => $stores,
|
||||||
'import' => $importData,
|
'import' => $importData,
|
||||||
|
'posting_amount' => $postingAmount,
|
||||||
'summary' => [
|
'summary' => [
|
||||||
'filtered_rows' => $rows->total(),
|
'filtered_rows' => $rows->total(),
|
||||||
'rows' => (int) ($importData['row_count'] ?? 0),
|
'rows' => (int) ($importData['row_count'] ?? 0),
|
||||||
|
|||||||
76
app/Console/Commands/BackfillDropshipBillWeights.php
Normal file
76
app/Console/Commands/BackfillDropshipBillWeights.php
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Common\Company;
|
||||||
|
use App\Support\DropshipFreight\{DropshipConfirmation, FactoryBillParser};
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\{Cache, DB, Storage};
|
||||||
|
|
||||||
|
/** 只从已上传原件回补缺失重量,不重导运费、附加费或确认记录。 */
|
||||||
|
final class BackfillDropshipBillWeights extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'dropship-freight:backfill-weights {--file=*} {--all} {--company=1} {--apply}';
|
||||||
|
protected $description = '预演或备份回补厂家原账单重量,保留所有已有金额';
|
||||||
|
|
||||||
|
public function handle(FactoryBillParser $parser, DropshipConfirmation $confirmation): int
|
||||||
|
{
|
||||||
|
if (! $this->option('all') && $this->option('file') === []) {
|
||||||
|
$this->error('请选择 --file 或 --all'); return self::FAILURE;
|
||||||
|
}
|
||||||
|
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
|
||||||
|
$this->error('请通过 run-finance-batch.sh 执行'); return self::FAILURE;
|
||||||
|
}
|
||||||
|
$company = (int) $this->option('company'); Company::findOrFail($company)->makeCurrent(true);
|
||||||
|
$lock = Cache::lock('dropship-freight:backfill-weights', 3900);
|
||||||
|
if (! $lock->get()) { $this->error('重量回补正在执行'); return self::FAILURE; }
|
||||||
|
$db = DB::connection('business_mirror'); $started = microtime(true); $queries = 0; $sqlMs = 0;
|
||||||
|
DB::listen(static function ($q) use (&$queries, &$sqlMs) { $queries++; $sqlMs += $q->time; });
|
||||||
|
$folder = 'private/dropship-weight/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
|
||||||
|
try {
|
||||||
|
foreach ($db->table('dropship_bill_files')->where('status', 'parsed')->whereNotNull('factory_id')
|
||||||
|
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', $this->option('file')))->orderBy('id')->lazyById(20) as $file) {
|
||||||
|
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
|
||||||
|
$this->line(json_encode(['file' => $file->id, 'skipped' => '厂家已确认'], JSON_UNESCAPED_UNICODE)); continue;
|
||||||
|
}
|
||||||
|
$path = Storage::disk('local')->path($file->stored_path);
|
||||||
|
if (! is_file($path)) throw new \RuntimeException('原件缺失:' . $file->id);
|
||||||
|
$parsed = $parser->parse($path, pathinfo($path, PATHINFO_EXTENSION))['lines'];
|
||||||
|
$report = $db->transaction(function () use ($db, $file, $parsed, $folder, $confirmation, $company) {
|
||||||
|
$db->table('dropship_bill_files')->where('id', $file->id)->lockForUpdate()->first();
|
||||||
|
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
|
||||||
|
return ['file' => $file->id, 'skipped' => '厂家已确认'];
|
||||||
|
}
|
||||||
|
$stream = null; $scanned = $filled = $missing = $mismatched = 0;
|
||||||
|
if ($this->option('apply')) {
|
||||||
|
Storage::disk('local')->put($folder . '/' . $file->id . '.ndjson', '');
|
||||||
|
$stream = fopen(Storage::disk('local')->path($folder . '/' . $file->id . '.ndjson'), 'wb');
|
||||||
|
if (! $stream) throw new \RuntimeException('无法创建备份');
|
||||||
|
fwrite($stream, json_encode(['file' => $file], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
foreach ($db->table('dropship_bill_lines')->where('file_id', $file->id)->orderBy('id')->lazyById(500) as $line) {
|
||||||
|
$scanned++;
|
||||||
|
if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
|
||||||
|
if ($line->bill_weight !== null) continue;
|
||||||
|
$source = $parsed[$line->waybill_no] ?? null;
|
||||||
|
if ($source === null || mb_substr($source['sheet'], 0, 64) !== $line->sheet || $source['row'] !== $line->row_no
|
||||||
|
|| abs($source['amount'] - (float) $line->amount) > 0.0001) { $mismatched++; continue; }
|
||||||
|
if ($source['weight'] === null) { $missing++; continue; }
|
||||||
|
$filled++;
|
||||||
|
if ($this->option('apply')) $db->table('dropship_bill_lines')->where('id', $line->id)->whereNull('bill_weight')
|
||||||
|
->update(['bill_weight' => $source['weight']]);
|
||||||
|
}
|
||||||
|
} finally { if ($stream) fclose($stream); }
|
||||||
|
return ['file' => $file->id, 'month' => $file->bill_month, 'factory' => $file->factory_id,
|
||||||
|
'scanned' => $scanned, 'filled' => $filled, 'missing' => $missing, 'mismatched' => $mismatched, 'applied' => (bool) $this->option('apply')];
|
||||||
|
});
|
||||||
|
unset($parsed); $this->line(json_encode($report, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
|
}
|
||||||
|
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null, 'seconds' => round(microtime(true) - $started, 3),
|
||||||
|
'peak_mib' => memory_get_peak_usage(true) / 1048576, 'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
|
||||||
|
return self::SUCCESS;
|
||||||
|
} catch (\Throwable $e) { report($e); $this->error($e->getMessage()); return self::FAILURE; }
|
||||||
|
finally { $lock->release(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -49,10 +49,7 @@ class ImportPayablesFinal extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
$fields = $registry->fields($section, $dataset);
|
$fields = $registry->fields($section, $dataset);
|
||||||
$storeDataset = 'final:'
|
$storeDataset = $registry->storeDataset($section, $dataset);
|
||||||
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
|
|
||||||
. ':'
|
|
||||||
. $dataset;
|
|
||||||
$totalCreated = 0;
|
$totalCreated = 0;
|
||||||
$totalUpdated = 0;
|
$totalUpdated = 0;
|
||||||
$totalRows = 0;
|
$totalRows = 0;
|
||||||
|
|||||||
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_date')
|
||||||
->orderBy('balance_at')
|
->orderBy('balance_at')
|
||||||
->orderBy('id')
|
->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);
|
$accountNo = $this->accountNo($row->account_no);
|
||||||
if ($accountNo !== '') {
|
if ($accountNo !== '') {
|
||||||
$snapshotBefore[$accountNo] = $row;
|
$snapshotBefore[$accountNo] = $row;
|
||||||
|
|||||||
93
app/Console/Commands/MatchBillSurcharges.php
Normal file
93
app/Console/Commands/MatchBillSurcharges.php
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\CourierBillMatcher;
|
||||||
|
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||||
|
use App\Support\CourierBills\Rebooks;
|
||||||
|
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,默认上月} {--all-months : 刷新全部已有账期,需同时指定 --all --existing-only} {--refresh-rebooks : 同时刷新未确认账单的补记账汇总} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
|
||||||
|
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
|
||||||
|
|
||||||
|
public function handle(SurchargeSettlementMatcher $matcher): int
|
||||||
|
{
|
||||||
|
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent();
|
||||||
|
if ($this->option('all-months')) {
|
||||||
|
if (! $this->option('all') || ! $this->option('existing-only') || $this->option('month')) {
|
||||||
|
$this->error('--all-months 需要 --all --existing-only,且不能指定 --month');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$months = DB::connection('business_mirror')->table(SurchargeSettlementMatcher::TABLE)->select('bill_month')
|
||||||
|
->union(DB::connection('business_mirror')->table('courier_bill_statements')->select('bill_month')->where('status', '<>', 'confirmed'))
|
||||||
|
->orderBy('bill_month')->pluck('bill_month');
|
||||||
|
foreach ($months as $month) {
|
||||||
|
$status = $this->call(self::class, ['--month' => $month, '--all' => true,
|
||||||
|
'--existing-only' => true, '--refresh-rebooks' => (bool) $this->option('refresh-rebooks'), '--company' => $this->option('company')]);
|
||||||
|
if ($status !== self::SUCCESS) return $status;
|
||||||
|
}
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
$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;}
|
||||||
|
$started = microtime(true);
|
||||||
|
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.' 附加费已匹配');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($this->option('refresh-rebooks')) {
|
||||||
|
foreach ($db->table('courier_bill_statements')->where('bill_month', $month)->where('status', '<>', 'confirmed')
|
||||||
|
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', array_map('intval', $this->option('statement'))))->orderBy('id')->pluck('id') as $id) {
|
||||||
|
$db->transaction(function () use ($db, $id): void {
|
||||||
|
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
|
||||||
|
if (! $statement || $statement->status === 'confirmed') return;
|
||||||
|
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->get();
|
||||||
|
foreach (app(Rebooks::class)->summaryItems((int) $id, $items) as $item) {
|
||||||
|
if (! $item->manual && Rebooks::isRebookLabel($item->label)) {
|
||||||
|
$db->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');
|
||||||
|
$this->line(sprintf('耗时 %.2f 秒,PHP 峰值 %.2f MiB。', microtime(true) - $started, memory_get_peak_usage(true) / 1048576));
|
||||||
|
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 Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */
|
/** 每天 11:20 推送种菜报销批次汇总;逐单不予报销通知须已启用。不改聚工单。 */
|
||||||
class PlantingReimbursementDailyDigest extends Command
|
class PlantingReimbursementDailyDigest extends Command
|
||||||
{
|
{
|
||||||
protected $signature = 'planting-reimbursement:daily-digest
|
protected $signature = 'planting-reimbursement:daily-digest
|
||||||
@ -48,7 +48,9 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, ! $this->option('dry-run'));
|
$liveRun = ! $this->option('dry-run');
|
||||||
|
$sendNotices = $liveRun && $robot->cancelNoticesEnabled();
|
||||||
|
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, $liveRun, $sendNotices);
|
||||||
if ($this->option('dry-run')) {
|
if ($this->option('dry-run')) {
|
||||||
$this->line($title . "\n" . $text);
|
$this->line($title . "\n" . $text);
|
||||||
continue;
|
continue;
|
||||||
@ -67,7 +69,7 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{0:string,1:string} */
|
/** @return array{0:string,1:string} */
|
||||||
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $sendNotices): array
|
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $liveRun, bool $sendNotices): array
|
||||||
{
|
{
|
||||||
$sync = $repository->syncStatus();
|
$sync = $repository->syncStatus();
|
||||||
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
||||||
@ -75,7 +77,7 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
$lines = ['#### ' . $title];
|
$lines = ['#### ' . $title];
|
||||||
|
|
||||||
$stale = $sync['code'] !== 'ready' || $sync['last_succeeded_at'] === null
|
$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) {
|
if ($stale) {
|
||||||
$lines[] = '> **聚工单数据不是最新的**(最后同步成功:' . ($sync['last_succeeded_at'] ? substr($sync['last_succeeded_at'], 0, 16) : '无') . '),先别按下面结果报销。';
|
$lines[] = '> **聚工单数据不是最新的**(最后同步成功:' . ($sync['last_succeeded_at'] ? substr($sync['last_succeeded_at'], 0, 16) : '无') . '),先别按下面结果报销。';
|
||||||
}
|
}
|
||||||
@ -92,7 +94,7 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
$confirmedNow = false;
|
$confirmedNow = false;
|
||||||
if ($result === null) {
|
if ($result === null) {
|
||||||
$result = $workbench->build($companyId, $date);
|
$result = $workbench->build($companyId, $date);
|
||||||
if ($sendNotices && Gate::check($result)['ok']) {
|
if ($liveRun && Gate::check($result)['ok']) {
|
||||||
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
|
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
|
||||||
$confirmedNow = true;
|
$confirmedNow = true;
|
||||||
}
|
}
|
||||||
@ -118,6 +120,8 @@ class PlantingReimbursementDailyDigest extends Command
|
|||||||
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
|
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
|
||||||
} elseif ($s['notices'] === []) {
|
} elseif ($s['notices'] === []) {
|
||||||
$lines[] = '- 没有要取消或复查的工单';
|
$lines[] = '- 没有要取消或复查的工单';
|
||||||
|
} elseif (! $robot->cancelNoticesEnabled()) {
|
||||||
|
$lines[] = '- 取消 / 待复查逐单通知已暂停,测试完成前不会发送';
|
||||||
} elseif ($sendNotices) {
|
} elseif ($sendNotices) {
|
||||||
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
|
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
|
||||||
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
|
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
|
||||||
|
|||||||
@ -120,7 +120,7 @@ class PullCourierSurchargeOverlength extends Command
|
|||||||
$condition = (string) $rule->condition;
|
$condition = (string) $rule->condition;
|
||||||
$standard = (string) $rule->standard;
|
$standard = (string) $rule->standard;
|
||||||
|
|
||||||
if (preg_match('/单边超\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米|CM|㎝)/u', $condition, $matched) !== 1) {
|
if (preg_match('/单边(?:长)?超\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米|CM|㎝)/u', $condition, $matched) !== 1) {
|
||||||
$this->warn('规则 #' . $rule->id . ' 的生效条件解析不出单边阈值,已跳过:' . $condition);
|
$this->warn('规则 #' . $rule->id . ' 的生效条件解析不出单边阈值,已跳过:' . $condition);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
116
app/Console/Commands/RefreshCourierSettlement.php
Normal file
116
app/Console/Commands/RefreshCourierSettlement.php
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Common\Company;
|
||||||
|
use App\Support\CourierBills\{Category, CourierBillMatcher, SummaryMapper, WeightDifferenceSubsidy};
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\{Cache, DB, Storage};
|
||||||
|
|
||||||
|
/** 只重新应用结算口径,不重算报价或覆盖人工处理。 */
|
||||||
|
final class RefreshCourierSettlement extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--express=* : 仅刷新指定快递的运费,保留附加费} {--company=1} {--apply : 备份后更新未确认账单}';
|
||||||
|
protected $description = '应用快递运费结算口径(含按核算值结算的例外),并刷新附加费及武进韵达补款';
|
||||||
|
|
||||||
|
public function handle(CourierBillMatcher $matcher, WeightDifferenceSubsidy $subsidy): int
|
||||||
|
{
|
||||||
|
if (! $this->option('all-open') && $this->option('statement') === []) {
|
||||||
|
$this->error('请选择对账单或 --all-open');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
|
||||||
|
$this->error('请通过 run-finance-batch.sh 执行');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
|
||||||
|
$lock = Cache::lock('courier-bills:refresh-settlement', 3900);
|
||||||
|
if (! $lock->get()) { $this->error('结算刷新正在运行'); return self::FAILURE; }
|
||||||
|
$started = microtime(true);
|
||||||
|
$queries = 0; $sqlMs = 0.0;
|
||||||
|
DB::listen(static function ($query) use (&$queries, &$sqlMs): void { $queries++; $sqlMs += $query->time; });
|
||||||
|
$db = CourierBillMatcher::db();
|
||||||
|
$folder = 'private/courier-settlement/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
|
||||||
|
try {
|
||||||
|
$ids = $db->table('courier_bill_statements')->where('status', '<>', 'confirmed')
|
||||||
|
->when(! $this->option('all-open'), fn ($q) => $q->whereIn('id', $this->option('statement')))
|
||||||
|
->where('line_count', '>', 0)->orderBy('id')->pluck('id');
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
$result = $db->transaction(function () use ($db, $id, $matcher, $subsidy, $folder) {
|
||||||
|
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
|
||||||
|
if (! $statement || $statement->status === 'confirmed') return ['statement' => $id, 'skipped' => true];
|
||||||
|
$beforeSummary = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('id')->get();
|
||||||
|
$beforeFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->orderBy('id')->get();
|
||||||
|
$stream = null;
|
||||||
|
if ($this->option('apply')) {
|
||||||
|
$path = $folder . '/' . $id . '.ndjson';
|
||||||
|
Storage::disk('local')->put($path, '');
|
||||||
|
$stream = fopen(Storage::disk('local')->path($path), 'wb');
|
||||||
|
if (! $stream) throw new \RuntimeException('无法保存备份');
|
||||||
|
fwrite($stream, json_encode(['statement' => $statement, 'summary' => $beforeSummary, 'surcharges' => $beforeFees], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
|
||||||
|
}
|
||||||
|
$changed = 0; $decrease = 0.0; $scanned = 0;
|
||||||
|
try {
|
||||||
|
foreach ($db->table('courier_bill_lines')->where('statement_id', $id)
|
||||||
|
->when($this->option('express') !== [], fn ($q) => $q->whereIn('express_name', $this->option('express')))
|
||||||
|
->orderBy('id')->lazyById(500) as $line) {
|
||||||
|
$scanned++;
|
||||||
|
if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
|
||||||
|
if ($line->resolution !== null || ! in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)) continue;
|
||||||
|
$amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution, $line->express_name);
|
||||||
|
if (($amount === null) === ($line->self_amount === null) && ($amount === null || abs($amount - (float) $line->self_amount) < 0.00001)) continue;
|
||||||
|
$changed++; $decrease += (float) $line->self_amount - (float) $amount;
|
||||||
|
if ($this->option('apply')) $db->table('courier_bill_lines')->where('id', $line->id)->update(['self_amount' => $amount]);
|
||||||
|
}
|
||||||
|
} finally { if ($stream) fclose($stream); }
|
||||||
|
$weight = $subsidy->summary((int) $id);
|
||||||
|
$existing = $beforeSummary->firstWhere('label', WeightDifferenceSubsidy::LABEL);
|
||||||
|
$subsidyChanged = ! ($existing?->manual) && abs((float) ($existing?->self_amount ?? 0) - $weight['amount']) > 0.00001;
|
||||||
|
$feeChanges = 0; $feeDecrease = 0.0;
|
||||||
|
foreach ($beforeFees as $fee) {
|
||||||
|
if ($this->option('express') === [] && $fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) {
|
||||||
|
$feeChanges++; $feeDecrease += (float) $fee->self_amount - round((float) $fee->bill_amount, 2);
|
||||||
|
if ($this->option('apply')) $db->table('bill_surcharge_matches')->where('id', $fee->id)->update([
|
||||||
|
'self_amount' => round((float) $fee->bill_amount, 2),
|
||||||
|
'match_note' => $fee->match_note . ';快递提供金额较低,按快递金额结算',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($this->option('apply') && ($changed > 0 || $subsidyChanged || $feeChanges > 0)) {
|
||||||
|
$matcher->refreshSummary((int) $id, false);
|
||||||
|
// 只允许报价核价金额按较低的快递提供金额下调。
|
||||||
|
$fields = ['file_id', 'sheet', 'row_no', 'waybill_no', 'item', 'bill_amount', 'self_amount'];
|
||||||
|
$normalize = static fn ($rows) => $rows->map(fn ($r) => array_intersect_key((array) $r, array_flip($fields)))->sortBy(fn ($r) => json_encode($r))->values()->all();
|
||||||
|
$expectedFees = $beforeFees->map(function ($fee) {
|
||||||
|
$copy = clone $fee;
|
||||||
|
if ($this->option('express') === [] && $copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', '');
|
||||||
|
return $copy;
|
||||||
|
});
|
||||||
|
$afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get();
|
||||||
|
if ($normalize($expectedFees) != $normalize($afterFees)) throw new \RuntimeException('附加费来源发生变化,本张账单已回退');
|
||||||
|
$protected = static fn ($rows) => $rows->filter(fn ($r) => $r->manual || ($r->label !== WeightDifferenceSubsidy::LABEL
|
||||||
|
&& in_array(SummaryMapper::classify($r->label), ['AL', 'supplement'], true)))
|
||||||
|
->map(fn ($r) => [$r->label, $r->bill_amount === null ? null : (float) $r->bill_amount,
|
||||||
|
$r->self_amount === null ? null : (float) $r->self_amount, (bool) $r->manual])
|
||||||
|
->sortBy(fn ($r) => json_encode($r))->values()->all();
|
||||||
|
if ($protected($beforeSummary) != $protected($db->table('courier_bill_summary_items')->where('statement_id', $id)->get())) {
|
||||||
|
throw new \RuntimeException('人工金额、配件扣款或补记账发生变化,本张账单已回退');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ['statement' => $id, 'month' => $statement->bill_month, 'scanned' => $scanned,
|
||||||
|
'changed' => $changed, 'settlement_decrease' => round($decrease, 2), 'weight_subsidy' => $weight,
|
||||||
|
'fee_changes' => $feeChanges, 'fee_decrease' => round($feeDecrease, 2),
|
||||||
|
'applied' => (bool) $this->option('apply')];
|
||||||
|
});
|
||||||
|
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
|
}
|
||||||
|
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null,
|
||||||
|
'seconds' => round(microtime(true) - $started, 3), 'peak_mib' => round(memory_get_peak_usage(true) / 1048576, 2),
|
||||||
|
'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
|
||||||
|
return self::SUCCESS;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
report($e); $this->error($e->getMessage());
|
||||||
|
return self::FAILURE;
|
||||||
|
} finally { $lock->release(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
27
app/Console/Commands/RefreshShippingTracking.php
Normal file
27
app/Console/Commands/RefreshShippingTracking.php
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Support\ShippingTrackingRefresh;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class RefreshShippingTracking extends Command
|
||||||
|
{
|
||||||
|
protected $signature='jushuitan:refresh-tracking {--source-id=* : 定向校准包裹源键,最多500个} {--max-batches=4}';
|
||||||
|
protected $description='按上游更新时间校准现有发货单号并保留换单前信息,不重算运费';
|
||||||
|
|
||||||
|
public function handle(ShippingTrackingRefresh $refresh): int
|
||||||
|
{
|
||||||
|
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
|
||||||
|
ini_set('memory_limit', '512M');
|
||||||
|
set_time_limit(1800);
|
||||||
|
$ids=$this->option('source-id');
|
||||||
|
if(count($ids)>500||collect($ids)->contains(fn($id)=>!ctype_digit((string)$id)||(int)$id<1)){$this->error('包裹源键无效。');return self::FAILURE;}
|
||||||
|
$started=microtime(true);$queries=0;$sqlMs=0;
|
||||||
|
\Illuminate\Support\Facades\DB::listen(function($q)use(&$queries,&$sqlMs){$queries++;$sqlMs+=$q->time;});
|
||||||
|
$r=$refresh->sync($ids,min(4,max(1,(int)$this->option('max-batches'))));
|
||||||
|
$this->line('运单校准:扫描 '.$r['scanned'].' 个源键,更新 '.$r['changed'].' 个包裹,补回 '.$r['names'].' 条旧快递名称,状态 '.$r['status']);
|
||||||
|
$this->line(sprintf('耗时 %.3f 秒,PHP 峰值 %.1f MiB,数据库查询 %d 次 / %.1f ms',microtime(true)-$started,memory_get_peak_usage(true)/1048576,$queries,$sqlMs));
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
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
|
protected $signature = 'supplier-statement:send-reminders
|
||||||
{--date= : 执行日期,格式 Y-m-d,默认今天}
|
{--date= : 执行日期,格式 Y-m-d,默认今天}
|
||||||
|
{--slot= : 催办时段,10 或 16;默认按当前小时判断}
|
||||||
{--supplier= : 仅检查指定供应商}
|
{--supplier= : 仅检查指定供应商}
|
||||||
{--dry-run : 只预览,不发送也不记录}';
|
{--dry-run : 只预览,不发送也不记录}';
|
||||||
|
|
||||||
protected $description = '在每月 1-14 日提醒上月有入库数据但尚未上传对账单的供应商';
|
protected $description = '在每月 1-14 日 10:00、16:00 提醒上月有入库数据但尚未上传对账单的供应商';
|
||||||
|
|
||||||
public function handle(SupplierStatementReminder $reminder): int
|
public function handle(SupplierStatementReminder $reminder): int
|
||||||
{
|
{
|
||||||
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
|
$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 {
|
try {
|
||||||
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
|
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
@ -37,12 +39,32 @@ class SendSupplierStatementReminders extends Command
|
|||||||
|
|
||||||
$failed = false;
|
$failed = false;
|
||||||
$dryRun = (bool) $this->option('dry-run');
|
$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) {
|
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||||
$company->makeCurrent();
|
$company->makeCurrent();
|
||||||
$lock = Cache::lock(sprintf(
|
$lock = Cache::lock(sprintf(
|
||||||
'supplier-statement-reminder:%d:%s',
|
'supplier-statement-reminder:%d:%s:%s',
|
||||||
$company->id,
|
$company->id,
|
||||||
$date->toDateString(),
|
$date->toDateString(),
|
||||||
|
$slot,
|
||||||
), 900);
|
), 900);
|
||||||
if (! $dryRun && ! $lock->get()) {
|
if (! $dryRun && ! $lock->get()) {
|
||||||
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
|
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
|
||||||
@ -55,6 +77,7 @@ class SendSupplierStatementReminders extends Command
|
|||||||
(int) $company->id,
|
(int) $company->id,
|
||||||
$dryRun,
|
$dryRun,
|
||||||
trim((string) $this->option('supplier')),
|
trim((string) $this->option('supplier')),
|
||||||
|
$slot,
|
||||||
);
|
);
|
||||||
if (! $result['reminder_day']) {
|
if (! $result['reminder_day']) {
|
||||||
$this->line("#{$company->id} {$company->name}: 今天不在 1-14 日催办窗口");
|
$this->line("#{$company->id} {$company->name}: 今天不在 1-14 日催办窗口");
|
||||||
@ -66,11 +89,13 @@ class SendSupplierStatementReminders extends Command
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->line(sprintf(
|
$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->id,
|
||||||
$company->name,
|
$company->name,
|
||||||
$result['accounting_month'],
|
$result['accounting_month'],
|
||||||
|
$slot,
|
||||||
$result['source_suppliers'],
|
$result['source_suppliers'],
|
||||||
|
count($result['exempt_suppliers']),
|
||||||
$result['configured'],
|
$result['configured'],
|
||||||
$dryRun ? '将提醒' : '已发送',
|
$dryRun ? '将提醒' : '已发送',
|
||||||
count($dryRun ? $result['previewed'] : $result['sent']),
|
count($dryRun ? $result['previewed'] : $result['sent']),
|
||||||
|
|||||||
192
app/Console/Commands/SummarizeBillRange.php
Normal file
192
app/Console/Commands/SummarizeBillRange.php
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class SummarizeBillRange extends Command
|
||||||
|
{
|
||||||
|
private const ALLOWED_TABS = [
|
||||||
|
'taobao-alipay',
|
||||||
|
'taobao-wechat',
|
||||||
|
'pinduoduo',
|
||||||
|
'jd-wallet',
|
||||||
|
'jd-transactions',
|
||||||
|
'jingxi',
|
||||||
|
'douyin',
|
||||||
|
'dewu',
|
||||||
|
'dewu-alipay',
|
||||||
|
'xiaohongshu',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $signature = 'bill-sync:summarize-range
|
||||||
|
{--tabs= : 逗号分隔的账单页签}
|
||||||
|
{--from= : 开始日期 YYYY-MM-DD}
|
||||||
|
{--to= : 截止日期 YYYY-MM-DD}
|
||||||
|
{--company-id=1 : 公司 ID}
|
||||||
|
{--json : 输出 JSON}';
|
||||||
|
|
||||||
|
protected $description = '按指定日期范围和页签汇总财务系统账单笔数、收入与支出';
|
||||||
|
|
||||||
|
public function handle(): int
|
||||||
|
{
|
||||||
|
$tabs = array_values(array_unique(array_filter(array_map(
|
||||||
|
static fn (string $tab): string => trim($tab),
|
||||||
|
explode(',', (string) $this->option('tabs')),
|
||||||
|
))));
|
||||||
|
$unknownTabs = array_values(array_diff($tabs, self::ALLOWED_TABS));
|
||||||
|
if ($tabs === [] || $unknownTabs !== []) {
|
||||||
|
$this->error('账单页签无效:' . ($unknownTabs ? implode(',', $unknownTabs) : '不能为空'));
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$from = $this->date((string) $this->option('from'));
|
||||||
|
$to = $this->date((string) $this->option('to'));
|
||||||
|
if ($from === null || $to === null || $from->gt($to)) {
|
||||||
|
$this->error('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$companyId = max(1, (int) $this->option('company-id'));
|
||||||
|
$fromText = $from->toDateString();
|
||||||
|
$toText = $to->toDateString();
|
||||||
|
$platforms = [];
|
||||||
|
$rowCount = 0;
|
||||||
|
$incomeCents = 0;
|
||||||
|
$expenseCents = 0;
|
||||||
|
|
||||||
|
foreach ($tabs as $tab) {
|
||||||
|
try {
|
||||||
|
$summary = $this->summary($tab, $fromText, $toText, $companyId);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$this->error("账单页签 {$tab} 汇总失败。");
|
||||||
|
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
$platforms[$tab] = $summary;
|
||||||
|
$rowCount += $summary['row_count'];
|
||||||
|
$incomeCents += $summary['income_cents'];
|
||||||
|
$expenseCents += $summary['expense_cents'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = [
|
||||||
|
'from' => $fromText,
|
||||||
|
'to' => $toText,
|
||||||
|
'company_id' => $companyId,
|
||||||
|
'row_count' => $rowCount,
|
||||||
|
'income_cents' => $incomeCents,
|
||||||
|
'expense_cents' => $expenseCents,
|
||||||
|
'platforms' => $platforms,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ((bool) $this->option('json')) {
|
||||||
|
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||||
|
} else {
|
||||||
|
$this->table(
|
||||||
|
['页签', '笔数', '收入', '支出'],
|
||||||
|
array_map(
|
||||||
|
static fn (string $tab, array $summary): array => [
|
||||||
|
$tab,
|
||||||
|
number_format($summary['row_count']),
|
||||||
|
number_format($summary['income_cents'] / 100, 2),
|
||||||
|
number_format($summary['expense_cents'] / 100, 2),
|
||||||
|
],
|
||||||
|
array_keys($platforms),
|
||||||
|
array_values($platforms),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
$this->line(sprintf(
|
||||||
|
'合计:%d 笔,收入 %.2f,支出 %.2f',
|
||||||
|
$rowCount,
|
||||||
|
$incomeCents / 100,
|
||||||
|
$expenseCents / 100,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
|
||||||
|
private function summary(string $tab, string $from, string $to, int $companyId): array
|
||||||
|
{
|
||||||
|
if ($tab === 'xiaohongshu') {
|
||||||
|
$summary = DB::table('ec_account_bills')
|
||||||
|
->where('company_id', $companyId)
|
||||||
|
->where('bill_type', 'xiaohongshu')
|
||||||
|
->where('occurred_at', '>=', $from . ' 00:00:00')
|
||||||
|
->where('occurred_at', '<', Carbon::parse($to)->addDay()->toDateString() . ' 00:00:00')
|
||||||
|
->selectRaw(
|
||||||
|
'COUNT(*) AS row_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
|
||||||
|
)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
return $this->normalize($summary->row_count, $summary->income, $summary->expense);
|
||||||
|
}
|
||||||
|
|
||||||
|
$filters = ['start' => $from, 'end' => $to];
|
||||||
|
$result = match ($tab) {
|
||||||
|
'taobao-alipay' => app(StoreReceivingAlipayBillMirrorRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)
|
||||||
|
->paginateAccountBills($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'jd-wallet' => app(StoreReceivingJdWalletBillRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'jd-transactions' => app(JdDailyBillRepository::class)
|
||||||
|
->forPlatform('jd')
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'jingxi' => app(JdDailyBillRepository::class)
|
||||||
|
->forPlatform('jingxi')
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'douyin' => app(StoreReceivingDouyinBillMirrorRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'dewu' => app(StoreReceivingDewuBillMirrorRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)
|
||||||
|
->paginate($filters, 'occurred_at', 'desc', 1, 1),
|
||||||
|
};
|
||||||
|
|
||||||
|
return $this->normalize(
|
||||||
|
$result['total'] ?? ($result['summary']['count'] ?? 0),
|
||||||
|
$result['summary']['income'] ?? 0,
|
||||||
|
$result['summary']['expense'] ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
|
||||||
|
private function normalize(mixed $rows, mixed $income, mixed $expense): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'row_count' => (int) $rows,
|
||||||
|
'income_cents' => (int) round((float) $income * 100),
|
||||||
|
'expense_cents' => (int) round((float) $expense * 100),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function date(string $value): ?Carbon
|
||||||
|
{
|
||||||
|
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
|
||||||
|
|
||||||
|
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,9 @@ use Illuminate\Console\Command;
|
|||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
use InvalidArgumentException;
|
use InvalidArgumentException;
|
||||||
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
|
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
|
||||||
|
use Modules\EcommerceFinance\Repositories\LinehaulFreightRepository;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
|
||||||
|
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
|
||||||
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
|
||||||
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
|
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
|
||||||
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
||||||
@ -92,6 +95,19 @@ class SyncBusinessMirrors extends Command
|
|||||||
$result['batches'],
|
$result['batches'],
|
||||||
$result['rows'],
|
$result['rows'],
|
||||||
));
|
));
|
||||||
|
if ($key === LinehaulFreightRepository::DATASET && $result['status'] === 'succeeded'
|
||||||
|
&& ((bool) $task['full'] || $result['rows'] > 0)) {
|
||||||
|
try {
|
||||||
|
$freight = app(ShippingFreightService::class)->recalculate(
|
||||||
|
FreightCarrierRules::START_DATE, now()->addDay()->format('Y-m-d'), LinehaulFreightRepository::CARRIERS);
|
||||||
|
$this->info(sprintf('专线运费已更新:%d 个包裹,匹配成功 %d 个,待核对 %d 个。',
|
||||||
|
$freight['packages'], $freight['ok'], $freight['packages'] - $freight['ok']));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$failed = true;
|
||||||
|
Log::error('专线镜像已同步,核算结果更新失败。', ['exception' => $exception::class]);
|
||||||
|
$this->error('专线镜像已同步,发货数据核算结果未完成更新,请重跑专线运费核算。');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 每日退款专属批次只处理配置内的退款表,不能继续进入
|
// 每日退款专属批次只处理配置内的退款表,不能继续进入
|
||||||
|
|||||||
@ -17,7 +17,7 @@ class SyncJstOrderLabelsDaily extends Command
|
|||||||
{--dry-run : 只检查并输出计划,不写库}
|
{--dry-run : 只检查并输出计划,不写库}
|
||||||
{--json : 输出 JSON}';
|
{--json : 输出 JSON}';
|
||||||
|
|
||||||
protected $description = '先核对聚水潭订单标签历史覆盖,补齐缺口后刷新最近数据';
|
protected $description = '先核对聚水潭订单标签历史覆盖和源订单变化,补刷异常日期后刷新最近数据';
|
||||||
|
|
||||||
public function handle(JstOrderLabelDailySynchronizer $synchronizer): int
|
public function handle(JstOrderLabelDailySynchronizer $synchronizer): int
|
||||||
{
|
{
|
||||||
|
|||||||
60
app/Console/Commands/SyncReturnedParcels.php
Normal file
60
app/Console/Commands/SyncReturnedParcels.php
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
<?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= : 进仓结束日期(含)} {--deduplicate : 只合并现有镜像中两来源相同的售后商品,不读取上游} {--match-surcharges : 同步成功后刷新已有未确认账单附加费}';
|
||||||
|
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 {
|
||||||
|
if ($this->option('deduplicate')) {
|
||||||
|
$this->info('退回件来源校准完成:合并重复商品明细 '.$synchronizer->deduplicate().' 行。');
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
$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']));
|
||||||
|
if ($this->option('match-surcharges')) {
|
||||||
|
// 新退回可能属于更早账期,沿用既有确认和人工保留保护。
|
||||||
|
return $this->call(MatchBillSurcharges::class, ['--all' => true, '--existing-only' => true, '--all-months' => true, '--refresh-rebooks' => true]);
|
||||||
|
}
|
||||||
|
return self::SUCCESS;
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。');
|
||||||
|
return self::FAILURE;
|
||||||
|
} finally {
|
||||||
|
$lock->release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,28 +2,76 @@
|
|||||||
|
|
||||||
namespace App\Console\Commands;
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Support\UnshippedSourceSynchronizer;
|
||||||
use App\Support\UnshippedWaybills;
|
use App\Support\UnshippedWaybills;
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\Cache;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
final class SyncUnshippedWaybills extends Command
|
final class SyncUnshippedWaybills extends Command
|
||||||
{
|
{
|
||||||
protected $signature = 'courier:sync-unshipped-waybills';
|
protected $signature = 'courier:sync-unshipped-waybills {--source= : 只刷新指定来源} {--skip-returned : 退回件已刷新时复用该完整结果} {--max-batches=0 : 仓内工单每轮最大批次,0表示至完成}';
|
||||||
protected $description = '从共享镜像和已导入订单日志重算未发出明细';
|
protected $description = '从当前业务副本和发货换单记录刷新未发出明细';
|
||||||
|
|
||||||
public function handle(UnshippedWaybills $waybills): int
|
public function handle(UnshippedWaybills $waybills, UnshippedSourceSynchronizer $sources): int
|
||||||
{
|
{
|
||||||
$failed = false;
|
if (app()->environment('production') && !env('FINANCE_BATCH_CONTAINER')) {
|
||||||
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
|
$this->error('请通过 run-finance-batch.sh 执行。');
|
||||||
if (!$waybills->sync($source)) {
|
return self::FAILURE;
|
||||||
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning');
|
}
|
||||||
$this->warn($label.':'.$warning);
|
$selected = (string) $this->option('source');
|
||||||
$failed = true;
|
if ($selected !== '' && !array_key_exists($selected, UnshippedWaybills::SYNC_SOURCES)) {
|
||||||
} else {
|
$this->error('未知来源');
|
||||||
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
|
return self::FAILURE;
|
||||||
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
|
}
|
||||||
}
|
$lock = Cache::lock('courier-unshipped-sync', 2100);
|
||||||
|
if (!$lock->get()) {
|
||||||
|
$this->warn('未发出明细正在同步,本次跳过。');
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
$failed = false;
|
||||||
|
try {
|
||||||
|
$returnedOk = true;
|
||||||
|
if (!$this->option('skip-returned') && ($selected === '' || str_starts_with($selected, 'intercept_'))) {
|
||||||
|
$returnedOk = $this->call('business-mirror:sync-returned-parcels') === self::SUCCESS;
|
||||||
|
}
|
||||||
|
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
|
||||||
|
if ($selected !== '' && $selected !== $source) continue;
|
||||||
|
try {
|
||||||
|
if ($source === 'warehouse') {
|
||||||
|
$result = $sources->warehouse(max(0, (int) $this->option('max-batches')),
|
||||||
|
fn ($n, $last, $high) => $this->line("仓内未发:已扫描 {$n} 行,游标 {$last}/{$high}"));
|
||||||
|
if ($result['status'] === 'running') {
|
||||||
|
$this->line('仓内未发:分批同步进行中,保留上次完整结果。');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$ok = true;
|
||||||
|
} elseif (str_starts_with($source, 'intercept_')) {
|
||||||
|
if (!$returnedOk) throw new \RuntimeException('退回件刷新失败,保留上次未发出结果。');
|
||||||
|
$sources->intercept($source);
|
||||||
|
$ok = true;
|
||||||
|
} else {
|
||||||
|
$ok = $waybills->sync($source);
|
||||||
|
}
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
$ok = false;
|
||||||
|
$safeMessages = ['退回件明细尚未完成刷新,保留上次结果。', '退回件来源覆盖不足,保留上次结果。', '退回件刷新失败,保留上次未发出结果。'];
|
||||||
|
$warning = in_array($error->getMessage(), $safeMessages, true) ? $error->getMessage() : '来源读取失败,保留上次完整结果。';
|
||||||
|
$waybills->connection()->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], ['warning' => $warning]);
|
||||||
|
}
|
||||||
|
if (!$ok) {
|
||||||
|
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning');
|
||||||
|
$this->warn($label.':'.$warning);
|
||||||
|
$failed = true;
|
||||||
|
} else {
|
||||||
|
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
|
||||||
|
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $failed ? self::FAILURE : self::SUCCESS;
|
||||||
|
} finally {
|
||||||
|
$lock->release();
|
||||||
}
|
}
|
||||||
|
|
||||||
return $failed ? self::FAILURE : 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'))
|
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
|
||||||
->runInBackground();
|
->runInBackground();
|
||||||
|
|
||||||
|
// 使用生产批处理入口,避免在网页容器运行全量退回件同步。
|
||||||
|
$schedule->exec('sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels')
|
||||||
|
->cron('0 10,16 * * *')
|
||||||
|
->timezone('Asia/Shanghai')
|
||||||
|
->withoutOverlapping(60)
|
||||||
|
->appendOutputTo(storage_path('logs/returned-parcels-sync.log'))
|
||||||
|
->runInBackground();
|
||||||
|
|
||||||
// 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。
|
// 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。
|
||||||
$schedule->command('business-mirror:archive-store-information')
|
$schedule->command('business-mirror:archive-store-information')
|
||||||
->dailyAt('07:00')
|
->dailyAt('07:00')
|
||||||
@ -103,6 +111,14 @@ class Kernel extends ConsoleKernel
|
|||||||
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
|
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
|
||||||
->runInBackground();
|
->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')
|
$schedule->command('inventory:sync-warehouse-mapping-alert')
|
||||||
->dailyAt('10:15')
|
->dailyAt('10:15')
|
||||||
|
|||||||
@ -9,12 +9,15 @@ use Illuminate\Http\Request;
|
|||||||
use Illuminate\Routing\Controller;
|
use Illuminate\Routing\Controller;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
||||||
|
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||||
|
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||||
|
use Modules\EcommerceFinance\Services\AccountMappingSuggestion;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
||||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 财务规则 · 科目映射表的维护接口。
|
* 财务规则 · 科目映射表的维护接口。
|
||||||
@ -29,6 +32,21 @@ class AccountMappingActions extends Controller
|
|||||||
/** 操作记录保留并展示的条数 */
|
/** 操作记录保留并展示的条数 */
|
||||||
private const HISTORY_LIMIT = 500;
|
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 = [
|
private const HISTORY_ACTION_LABELS = [
|
||||||
'create' => '新增',
|
'create' => '新增',
|
||||||
'update' => '修改',
|
'update' => '修改',
|
||||||
@ -56,6 +74,8 @@ class AccountMappingActions extends Controller
|
|||||||
private readonly AccountMappingValidator $validator,
|
private readonly AccountMappingValidator $validator,
|
||||||
private readonly AccountMappingCoa $coa,
|
private readonly AccountMappingCoa $coa,
|
||||||
private readonly AccountMappingWorkbookImporter $importer,
|
private readonly AccountMappingWorkbookImporter $importer,
|
||||||
|
private readonly AccountMappingCoverage $coverage,
|
||||||
|
private readonly AccountMappingSuggestion $suggestion,
|
||||||
) {
|
) {
|
||||||
$this->middleware('auth');
|
$this->middleware('auth');
|
||||||
$this->middleware('company.identify');
|
$this->middleware('company.identify');
|
||||||
@ -67,6 +87,49 @@ class AccountMappingActions extends Controller
|
|||||||
return response()->json($this->payload());
|
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
|
public function store(Request $request): JsonResponse
|
||||||
{
|
{
|
||||||
$values = $this->payloadValues($request);
|
$values = $this->payloadValues($request);
|
||||||
@ -345,17 +408,15 @@ class AccountMappingActions extends Controller
|
|||||||
throw new RuntimeException('无法创建导出文件。');
|
throw new RuntimeException('无法创建导出文件。');
|
||||||
}
|
}
|
||||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
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) {
|
foreach ($rules as $rule) {
|
||||||
$row = [];
|
$row = [];
|
||||||
foreach (array_keys(AccountMappingStore::LABELS) as $field) {
|
foreach (self::VISIBLE_FIELDS as $field) {
|
||||||
$value = (string) ($rule[$field] ?? '');
|
$row[] = $this->csvText((string) ($rule[$field] ?? ''));
|
||||||
// 商品名称关键词留空时导出成「-」,与页面一致(导回来会按空处理)
|
|
||||||
if ($field === 'goods' && trim($value) === '') {
|
|
||||||
$value = '-';
|
|
||||||
}
|
|
||||||
$row[] = $this->csvText($value);
|
|
||||||
}
|
}
|
||||||
fputcsv($csv, $row);
|
fputcsv($csv, $row);
|
||||||
}
|
}
|
||||||
@ -370,8 +431,8 @@ class AccountMappingActions extends Controller
|
|||||||
public function template(): StreamedResponse
|
public function template(): StreamedResponse
|
||||||
{
|
{
|
||||||
$samples = [
|
$samples = [
|
||||||
['得物', '平台服务费', '平台服务费', '-', '0.06', '费用', '平台服务费', '销售费用', '平台服务费', '其他货币资金', '', '支出基准'],
|
['得物', '平台服务费', '平台服务费', '0.06', '费用', '平台服务费', '销售费用', '平台服务费', '其他货币资金', '', '支出基准'],
|
||||||
['淘宝', '交易收入', '订单', '-', '-', '收入', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
|
['淘宝', '交易收入', '订单', '-', '收入', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
|
||||||
];
|
];
|
||||||
|
|
||||||
return response()->streamDownload(function () use ($samples): void {
|
return response()->streamDownload(function () use ($samples): void {
|
||||||
@ -380,7 +441,10 @@ class AccountMappingActions extends Controller
|
|||||||
throw new RuntimeException('无法创建模板文件。');
|
throw new RuntimeException('无法创建模板文件。');
|
||||||
}
|
}
|
||||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
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) {
|
foreach ($samples as $sample) {
|
||||||
fputcsv($csv, $sample);
|
fputcsv($csv, $sample);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,13 +7,16 @@ use App\Support\CourierBills\CourierBillMatcher;
|
|||||||
use App\Support\CourierBills\CourierBillStore;
|
use App\Support\CourierBills\CourierBillStore;
|
||||||
use App\Support\CourierBills\StatementExporter;
|
use App\Support\CourierBills\StatementExporter;
|
||||||
use App\Support\CourierBills\StreamingWorkbook;
|
use App\Support\CourierBills\StreamingWorkbook;
|
||||||
|
use App\Support\CourierBills\Rebooks;
|
||||||
use App\Support\CourierBills\Waybill;
|
use App\Support\CourierBills\Waybill;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Routing\Controller;
|
use Illuminate\Routing\Controller;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
|
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
|
||||||
final class CourierBillController extends Controller
|
final class CourierBillController extends Controller
|
||||||
@ -35,7 +38,11 @@ final class CourierBillController extends Controller
|
|||||||
$db = $this->store->db();
|
$db = $this->store->db();
|
||||||
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
|
$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'));
|
$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) {
|
$data += match ($view) {
|
||||||
'statement' => $this->statementData($request),
|
'statement' => $this->statementData($request),
|
||||||
'details' => $this->detailsData($request, $month),
|
'details' => $this->detailsData($request, $month),
|
||||||
@ -74,7 +81,7 @@ final class CourierBillController extends Controller
|
|||||||
})->all();
|
})->all();
|
||||||
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
||||||
|
|
||||||
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [
|
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbConfirmationStates' => app(\App\Support\CourierBills\FreightConfirmation::class)->states($month,(int)(company_id()?:1)), 'cbTotals' => [
|
||||||
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
||||||
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
||||||
]];
|
]];
|
||||||
@ -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();
|
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
||||||
}
|
}
|
||||||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
||||||
|
$items=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->summaryItems((int)$statement->id,$items);
|
||||||
|
$items=app(Rebooks::class)->summaryItems((int)$statement->id,$items);
|
||||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
||||||
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||||||
$shippingSync = null;
|
$shippingSync = null;
|
||||||
@ -127,9 +136,31 @@ final class CourierBillController extends Controller
|
|||||||
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
||||||
|
|
||||||
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
||||||
|
'cbConfirmation' => app(\App\Support\CourierBills\FreightConfirmation::class)->state($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
|
'cbDisputes' => app(\App\Support\CourierBills\FreightConfirmation::class)->disputes($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
|
'cbConfirmHistory' => app(\App\Support\CourierBills\FreightConfirmation::class)->history($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
|
||||||
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
||||||
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
|
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
|
||||||
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id)];
|
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id), 'cbRebook' => $this->rebookSummary((int) $statement->id),
|
||||||
|
'cbSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
|
||||||
|
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('courier',(int)$statement->id)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 单家对账单上的补记账说明:补几个月、本期补几单多少、还有几单待复核。 @return array<string,mixed>|null */
|
||||||
|
private function rebookSummary(int $statementId): ?array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$plan = app(Rebooks::class)->forStatement($statementId);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$rows = collect($plan['rows']);
|
||||||
|
|
||||||
|
return ['months' => $plan['months'], 'source' => $plan['source'], 'window' => $plan['window'],
|
||||||
|
'count' => $rows->where('amount', '>', 0)->count(), 'amount' => round((float) $rows->sum('amount'), 2),
|
||||||
|
'pending' => $rows->where('status', '资料缺失待核对')->count(), 'done' => $rows->filter(fn ($r) => str_starts_with($r['status'], '已补'))->count()];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function detailsData(Request $request, string $month): array
|
private function detailsData(Request $request, string $month): array
|
||||||
@ -185,22 +216,51 @@ final class CourierBillController extends Controller
|
|||||||
|
|
||||||
private function uploadData(string $month): array
|
private function uploadData(string $month): array
|
||||||
{
|
{
|
||||||
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
$jointUploads = [];
|
||||||
|
foreach (\App\Support\CourierBills\CourierJointUploads::SETS as $key => $set) {
|
||||||
|
try {
|
||||||
|
app(\App\Support\CourierBills\CourierJointUploads::class)->resolve($key);
|
||||||
|
$jointUploads[$key] = $set;
|
||||||
|
} catch (RuntimeException) { /* 分组未配置的环境不显示入口。 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['cbJointUploads' => $jointUploads, 'cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
||||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function jointUploadLink(Request $request)
|
||||||
|
{
|
||||||
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'],
|
||||||
|
'joint' => ['required', Rule::in(array_keys(\App\Support\CourierBills\CourierJointUploads::SETS))]]);
|
||||||
|
$url = $this->guard(fn () => app(\App\Support\CourierBills\CourierUploadLink::class)
|
||||||
|
->jointPageUrl((int) (company_id() ?: 1), $data['joint'], $data['month']));
|
||||||
|
|
||||||
|
return redirect()->away($url);
|
||||||
|
}
|
||||||
|
|
||||||
private function ledgerData(Request $request): array
|
private function ledgerData(Request $request): array
|
||||||
{
|
{
|
||||||
$db = $this->store->db();
|
$db = $this->store->db();
|
||||||
$search = Waybill::normalize((string) $request->query('waybill'));
|
$search = Waybill::normalize((string) $request->query('waybill'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
'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('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')
|
->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(),
|
->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']),
|
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||||||
'cbSearch' => $search,
|
'cbSearch' => $search,
|
||||||
|
'cbRebookStats' => $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
|
||||||
|
->groupBy('r.refund_month', 'r.deduct_month', 'g.name', 'r.source')
|
||||||
|
->selectRaw(sprintf('%s as refund_month, %s as deduct_month, %s as group_name, %s as source, COUNT(*) as n, SUM(%s) as amount',
|
||||||
|
...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['r.refund_month', 'r.deduct_month', 'g.name', 'r.source', 'r.amount'])))
|
||||||
|
->orderByDesc('r.refund_month')->orderBy('r.deduct_month')->orderBy('g.name')->limit(500)->get(),
|
||||||
|
'cbRebookReviews' => $db->table('courier_bill_rebook_reviews')->groupBy('deduct_month')
|
||||||
|
->selectRaw('deduct_month, COUNT(*) as n, MAX(updated_at) as at')->orderByDesc('deduct_month')->limit(24)->get(),
|
||||||
|
'cbRebookHits' => $search === null ? collect() : $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
|
||||||
|
->where('r.waybill_no', $search)->orderBy('r.deduct_month')->get(['r.*', 'g.name as group_name']),
|
||||||
|
'cbRebookReviewHits' => $search === null ? collect() : $db->table('courier_bill_rebook_reviews')->where('waybill_no', $search)->orderBy('deduct_month')->get(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -402,14 +462,17 @@ final class CourierBillController extends Controller
|
|||||||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
||||||
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
||||||
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||||||
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
|
'rebook_months' => ['nullable', 'in:0,1,2'],
|
||||||
|
], [], ['name' => '分组名称', 'express_names' => '快递名称1', 'rebook_months' => '补记账']);
|
||||||
|
$data['rebook_months'] ??= null;
|
||||||
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
||||||
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||||||
if ($exists) {
|
if ($exists) {
|
||||||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||||||
}
|
}
|
||||||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||||||
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
$id = $this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||||||
|
$this->refreshOpenStatements($id);
|
||||||
|
|
||||||
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
||||||
}
|
}
|
||||||
@ -424,12 +487,55 @@ final class CourierBillController extends Controller
|
|||||||
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
||||||
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
||||||
if ($result['rejected'] > 0) {
|
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 . '。');
|
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 导入已经补过的记账(系统上线前手工补的),补过的单以后不再补。 */
|
||||||
|
public function importRebooks(Request $request)
|
||||||
|
{
|
||||||
|
return $this->importRebookFile($request, 'rebooks', '已补记录', function (string $path, string $extension): string {
|
||||||
|
$r = app(Rebooks::class)->importRefunds($path, $extension);
|
||||||
|
|
||||||
|
return '读到 ' . $r['rows'] . ' 行,新增 ' . $r['inserted'] . ' 条已补记录' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 导入复核记账:这单现在应扣多少,本期补款 = 当时扣的 − 现在应扣。 */
|
||||||
|
public function importRebookReviews(Request $request)
|
||||||
|
{
|
||||||
|
return $this->importRebookFile($request, 'reviews', '复核记账', function (string $path, string $extension, string $name): string {
|
||||||
|
$r = app(Rebooks::class)->importReviews($path, $extension, $name);
|
||||||
|
|
||||||
|
return '读到 ' . $r['rows'] . ' 行,导入 ' . $r['inserted'] . ' 条复核记账' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 补记账规则改了、复核导了之后,重排还没确认的对账单小汇总。 */
|
||||||
|
private function importRebookFile(Request $request, string $field, string $label, callable $import)
|
||||||
|
{
|
||||||
|
$file = $request->validate([$field => ['required', 'file', 'max:51200']], [], [$field => $label . '文件'])[$field];
|
||||||
|
$extension = strtolower($file->getClientOriginalExtension());
|
||||||
|
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||||
|
throw ValidationException::withMessages([$field => '只支持 xlsx、xls、csv。']);
|
||||||
|
}
|
||||||
|
$message = $this->guard(fn () => $import($file->getRealPath(), $extension, $file->getClientOriginalName()));
|
||||||
|
$this->refreshOpenStatements();
|
||||||
|
|
||||||
|
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function refreshOpenStatements(?int $groupId = null): void
|
||||||
|
{
|
||||||
|
$matcher = app(\App\Support\CourierBills\CourierBillMatcher::class);
|
||||||
|
$this->store->db()->table('courier_bill_statements')->where('status', 'open')
|
||||||
|
->when($groupId !== null, fn ($q) => $q->where('group_id', $groupId))
|
||||||
|
->where('bill_month', '>=', now()->subMonthsNoOverflow(2)->format('Y-m'))->pluck('id')
|
||||||
|
->each(fn ($id) => $matcher->refreshSummary((int) $id));
|
||||||
|
}
|
||||||
|
|
||||||
public function exportStatement(Request $request, int $statement)
|
public function exportStatement(Request $request, int $statement)
|
||||||
{
|
{
|
||||||
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||||
@ -456,13 +562,16 @@ final class CourierBillController extends Controller
|
|||||||
return response()->streamDownload(function () use ($query): void {
|
return response()->streamDownload(function () use ($query): void {
|
||||||
$book = new StreamingWorkbook();
|
$book = new StreamingWorkbook();
|
||||||
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
|
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
|
||||||
'核算运费', '计费重量', '自算金额', '差异', '未发出来源', '处理结果', '处理人'], true);
|
'核算运费', '结算重量', '结算运费', '运费差', '计费重量', '重量差', '未发出来源', '处理结果', '处理人'], true);
|
||||||
foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) {
|
foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) {
|
||||||
|
$comparison = \App\Support\CourierBills\SettlementComparison::courier($line);
|
||||||
$book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no,
|
$book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no,
|
||||||
$line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight,
|
$line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight,
|
||||||
Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name,
|
Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name,
|
||||||
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->charge_weight === null ? null : (float) $line->charge_weight,
|
$line->calc_freight === null ? null : (float) $line->calc_freight,
|
||||||
$line->self_amount === null ? null : (float) $line->self_amount, round((float) $line->bill_amount - (float) $line->self_amount, 2),
|
$comparison['settlement_weight'],
|
||||||
|
$line->self_amount === null ? null : (float) $line->self_amount, $comparison['freight_diff'],
|
||||||
|
$line->charge_weight === null ? null : (float) $line->charge_weight, $comparison['weight_diff'],
|
||||||
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
|
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
|
||||||
}
|
}
|
||||||
$book->writeTo(fopen('php://output', 'wb'));
|
$book->writeTo(fopen('php://output', 'wb'));
|
||||||
@ -479,6 +588,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)
|
private function back(Request $request, array $query, string $message)
|
||||||
{
|
{
|
||||||
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request),
|
$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'],
|
'courier_name' => ['required', 'string', 'max:100'],
|
||||||
'invite_label' => ['nullable', 'string', 'max:100'],
|
'invite_label' => ['nullable', 'string', 'max:100'],
|
||||||
'valid_days' => ['nullable', 'integer', 'min:1', 'max:180'],
|
'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),
|
...CourierOnboarding::profileRules(true),
|
||||||
], [
|
], [
|
||||||
'courier_name.required' => '请先定好系统快递名称(需与报价名、发货数据里的快递名称一致)。',
|
'courier_name.required' => '请先定好系统快递名称(需与报价名、发货数据里的快递名称一致)。',
|
||||||
'workplatform_expcode.required' => '请填写快递公司代码(与快递资料「快递公司代码」一致)。',
|
'workplatform_expcode.required' => '请填写快递公司代码(与快递资料「快递公司代码」一致)。',
|
||||||
'workplatform_expcode.regex' => '快递公司代码只能包含字母、数字、下划线和短横线。',
|
'workplatform_expcode.regex' => '快递公司代码只能包含字母、数字、英文句点(.)、下划线和短横线。',
|
||||||
...CourierOnboarding::profileMessages(),
|
...CourierOnboarding::profileMessages(),
|
||||||
], CourierOnboarding::profileAttributes());
|
], CourierOnboarding::profileAttributes());
|
||||||
$code = strtoupper(trim((string) $data['workplatform_expcode']));
|
$code = strtoupper(trim((string) $data['workplatform_expcode']));
|
||||||
|
|||||||
@ -47,8 +47,8 @@ class CourierProfiles extends Controller
|
|||||||
public function storePaymentAccountForCode(Request $request): RedirectResponse
|
public function storePaymentAccountForCode(Request $request): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(
|
$data = $request->validate(
|
||||||
['expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/']],
|
['expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_.-]+$/']],
|
||||||
['expcode.required' => '请填写快递公司代码。', 'expcode.regex' => '快递公司代码只能是字母、数字、下划线或短横线。'],
|
['expcode.required' => '请填写快递公司代码。', 'expcode.regex' => '快递公司代码只能包含字母、数字、英文句点(.)、下划线和短横线。'],
|
||||||
);
|
);
|
||||||
|
|
||||||
return $this->storePaymentAccount($request, trim($data['expcode']));
|
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,26 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers\Business;
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\Category;
|
||||||
use App\Support\CourierBills\StreamingWorkbook;
|
use App\Support\CourierBills\StreamingWorkbook;
|
||||||
|
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||||
|
use App\Support\DropshipFreight\DropshipConfirmation;
|
||||||
|
use App\Support\DropshipFreight\DropshipBillSummary;
|
||||||
use App\Support\DropshipFreight\DropshipExporter;
|
use App\Support\DropshipFreight\DropshipExporter;
|
||||||
|
use App\Support\DropshipFreight\DropshipOverviewExporter;
|
||||||
|
use App\Support\DropshipFreight\DropshipFees;
|
||||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||||
use App\Support\DropshipFreight\DropshipReconciler;
|
use App\Support\DropshipFreight\DropshipReconciler;
|
||||||
|
use App\Support\DropshipFreight\DropshipShareLink;
|
||||||
|
use App\Support\DropshipFreight\DropshipUploadReminder;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
use Illuminate\Routing\Controller;
|
use Illuminate\Routing\Controller;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
|
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
|
||||||
final class DropshipFreightController extends Controller
|
final class DropshipFreightController extends Controller
|
||||||
@ -22,6 +32,7 @@ final class DropshipFreightController extends Controller
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly DropshipFreightStore $store,
|
private readonly DropshipFreightStore $store,
|
||||||
private readonly DropshipReconciler $reconciler,
|
private readonly DropshipReconciler $reconciler,
|
||||||
|
private readonly DropshipConfirmation $confirmations,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function page(Request $request): array
|
public function page(Request $request): array
|
||||||
@ -62,7 +73,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')),
|
'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')),
|
'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')),
|
||||||
]];
|
]];
|
||||||
@ -77,6 +98,20 @@ final class DropshipFreightController extends Controller
|
|||||||
$result = $this->reconciler->factoryMonth($factory, $month);
|
$result = $this->reconciler->factoryMonth($factory, $month);
|
||||||
$status = (string) $request->query('status', '');
|
$status = (string) $request->query('status', '');
|
||||||
$rows = $result['rows'];
|
$rows = $result['rows'];
|
||||||
|
if (in_array($status, ['weight_diff', 'price_diff', 'missing_weight'], true)) {
|
||||||
|
$rows = array_values(array_filter($rows, static fn (array $r): bool => $r['diff_kind'] === $status));
|
||||||
|
}
|
||||||
|
$state = $this->confirmations->state($month, (int) $factory->id, self::companyId());
|
||||||
|
$disputes = $this->confirmations->disputes($month, (int) $factory->id, self::companyId());
|
||||||
|
$currentDisputes = array_values(array_filter($disputes, fn ($d) => (int) $d['version'] === (int) ($state['version'] ?? 0)));
|
||||||
|
$disputeMap = array_column($currentDisputes, null, 'waybill');
|
||||||
|
if ($status === 'disputed') {
|
||||||
|
$rows = array_values(array_filter($rows, fn ($r) => isset($disputeMap[$r['waybill']])));
|
||||||
|
}
|
||||||
|
$search = mb_substr(trim((string) $request->query('q', '')), 0, 64);
|
||||||
|
if ($search !== '') {
|
||||||
|
$rows = array_values(array_filter($rows, fn ($r) => str_contains(strtoupper($r['waybill']), strtoupper($search))));
|
||||||
|
}
|
||||||
if ($status === 'attention') {
|
if ($status === 'attention') {
|
||||||
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
|
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
|
||||||
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
|
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
|
||||||
@ -87,7 +122,17 @@ final class DropshipFreightController extends Controller
|
|||||||
['path' => $request->url(), 'query' => $request->query()]);
|
['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();
|
$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
|
private function uploadData(string $month): array
|
||||||
@ -95,7 +140,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')
|
$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']);
|
->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)
|
public function upload(Request $request)
|
||||||
@ -180,10 +226,159 @@ final class DropshipFreightController extends Controller
|
|||||||
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
|
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function export(Request $request)
|
public function rematch(Request $request, int $factory)
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'month' => ['required', 'date_format:Y-m'],
|
||||||
|
'df_view' => ['nullable', 'in:overview,factory'],
|
||||||
|
]);
|
||||||
|
$f = $this->factory($factory);
|
||||||
|
$state = $this->confirmations->state($data['month'], (int) $f->id, self::companyId());
|
||||||
|
if (($state['status'] ?? null) === DropshipConfirmation::CONFIRMED) {
|
||||||
|
throw ValidationException::withMessages(['dropship' => '厂家已确认的账单不能重新匹配。']);
|
||||||
|
}
|
||||||
|
$this->guard(fn () => app(SurchargeSettlementMatcher::class)->dropship((int) $f->id, $data['month']));
|
||||||
|
|
||||||
|
// 运费分类实时计算,返回页面时读取最新发货和核算数据;附加费需刷新持久化的匹配结果。
|
||||||
|
$view = $data['df_view'] ?? 'factory';
|
||||||
|
return $this->back($request, ['df_view' => $view, 'month' => $data['month'],
|
||||||
|
...($view === 'factory' ? ['factory' => (int) $f->id] : [])],
|
||||||
|
'已按最新发货数据、核算运费和附加费重新匹配「' . $f->name . '」' . $data['month'] . ' 的账单。');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 财务点「核对完成」/「撤销」:核对完成的厂家才能推送给厂家确认。 */
|
||||||
|
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']]);
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
|
||||||
$month = $data['month'];
|
$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'], 'summary' => ['nullable', 'boolean']]);
|
||||||
|
$month = $data['month'];
|
||||||
|
if ($request->boolean('summary')) {
|
||||||
|
$overview = $this->overviewData($month);
|
||||||
|
return response()->streamDownload(static function () use ($overview): void {
|
||||||
|
app(DropshipOverviewExporter::class)->write($overview, fopen('php://output', 'wb'));
|
||||||
|
}, '代发运费各厂家汇总_' . $month . '.xlsx');
|
||||||
|
}
|
||||||
$factories = collect($this->store->factories());
|
$factories = collect($this->store->factories());
|
||||||
if (! empty($data['factory'])) {
|
if (! empty($data['factory'])) {
|
||||||
$factories = $factories->where('id', (int) $data['factory'])->values();
|
$factories = $factories->where('id', (int) $data['factory'])->values();
|
||||||
@ -221,8 +416,8 @@ final class DropshipFreightController extends Controller
|
|||||||
|
|
||||||
return response()->streamDownload(function () use ($factories, $month, $own): void {
|
return response()->streamDownload(function () use ($factories, $month, $own): void {
|
||||||
$book = new StreamingWorkbook();
|
$book = new StreamingWorkbook();
|
||||||
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)',
|
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '最终结算运费',
|
||||||
'差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
'差额(厂家−最终结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
||||||
$details = [];
|
$details = [];
|
||||||
foreach ($factories as $factory) {
|
foreach ($factories as $factory) {
|
||||||
$result = $this->reconciler->factoryMonth($factory, $month, $own);
|
$result = $this->reconciler->factoryMonth($factory, $month, $own);
|
||||||
@ -233,10 +428,10 @@ final class DropshipFreightController extends Controller
|
|||||||
}
|
}
|
||||||
foreach ($details as [$factory, $rows]) {
|
foreach ($details as [$factory, $rows]) {
|
||||||
$sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28);
|
$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) {
|
foreach ($rows as $r) {
|
||||||
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'],
|
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settlement_weight'], $r['settle'],
|
||||||
$r['diff'], $r['label'], $r['note'], $r['formula']]);
|
$r['final'] ?? $r['settle'], $r['freight_diff'], $r['bill_weight'], $r['charge_weight'], $r['weight_diff'], $r['label'], $r['note'], $r['formula']]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$book->writeTo(fopen('php://output', 'wb'));
|
$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']);
|
||||||
|
}
|
||||||
|
}
|
||||||
128
app/Http/Controllers/Business/KukaPostingAmountPosting.php
Normal file
128
app/Http/Controllers/Business/KukaPostingAmountPosting.php
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Business;
|
||||||
|
|
||||||
|
use App\Business\KukaPostingBase\KukaPostingAmountPoster;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Routing\Controller;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class KukaPostingAmountPosting extends Controller
|
||||||
|
{
|
||||||
|
public function preview(
|
||||||
|
Request $request,
|
||||||
|
KukaPostingAmountPoster $poster,
|
||||||
|
): RedirectResponse {
|
||||||
|
$data = $this->validatePlan($request);
|
||||||
|
$companyId = (int) (company_id() ?: 1);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
|
||||||
|
} catch (InvalidArgumentException | RuntimeException $exception) {
|
||||||
|
return $this->redirectToPage($request, $data['period'])
|
||||||
|
->withInput()
|
||||||
|
->withErrors(['posting_amount' => $exception->getMessage()]);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
|
||||||
|
return $this->redirectToPage($request, $data['period'])
|
||||||
|
->withInput()
|
||||||
|
->withErrors(['posting_amount' => '过账金额暂时无法计算,请稍后重试。']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->redirectToPage($request, $data['period'])
|
||||||
|
->withInput()
|
||||||
|
->with('kuka_posting_amount_preview', $poster->previewSummary($plan));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function apply(
|
||||||
|
Request $request,
|
||||||
|
KukaPostingAmountPoster $poster,
|
||||||
|
): RedirectResponse {
|
||||||
|
$data = $request->validate([
|
||||||
|
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||||
|
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
|
||||||
|
'preview_hash' => ['required', 'string', 'size:64'],
|
||||||
|
], $this->messages());
|
||||||
|
$companyId = (int) (company_id() ?: 1);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
|
||||||
|
if (! hash_equals((string) $plan['preview_hash'], (string) $data['preview_hash'])) {
|
||||||
|
throw new InvalidArgumentException('发货明细或物料金额已经变化,请重新计算过账方案。');
|
||||||
|
}
|
||||||
|
if (($plan['is_exact'] ?? false) !== true) {
|
||||||
|
throw new InvalidArgumentException(sprintf(
|
||||||
|
'过账金额与选中发货金额仍有差额 %s,未写入过账标签。',
|
||||||
|
number_format((int) $plan['difference_cents'] / 100, 2, '.', ','),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $poster->apply($plan, auth()->id());
|
||||||
|
} catch (InvalidArgumentException | RuntimeException $exception) {
|
||||||
|
return $this->redirectToPage($request, $data['period'])
|
||||||
|
->withInput()
|
||||||
|
->withErrors(['posting_amount' => $exception->getMessage()]);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
|
||||||
|
return $this->redirectToPage($request, $data['period'])
|
||||||
|
->withInput()
|
||||||
|
->withErrors(['posting_amount' => '过账标签写入失败,原有标签已保留。']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->redirectToPage($request, $data['period'])->with(
|
||||||
|
'success',
|
||||||
|
sprintf(
|
||||||
|
'整月过账标签已更新:%s 行标记为“是”,其余标记为“补单(订单四组)”;本次变更 %s 行。',
|
||||||
|
number_format((int) $plan['selected_rows']),
|
||||||
|
number_format((int) $result['updated']),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{period:string,target_amount:string}
|
||||||
|
*/
|
||||||
|
private function validatePlan(Request $request): array
|
||||||
|
{
|
||||||
|
return $request->validate([
|
||||||
|
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||||
|
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
|
||||||
|
], $this->messages());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string,string>
|
||||||
|
*/
|
||||||
|
private function messages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'period.required' => '请选择需要过账的账期。',
|
||||||
|
'period.regex' => '账期格式必须为 YYYY-MM。',
|
||||||
|
'target_amount.required' => '请填写整月过账金额。',
|
||||||
|
'target_amount.regex' => '整月过账金额最多保留两位小数。',
|
||||||
|
'target_amount.not_in' => '整月过账金额必须大于 0。',
|
||||||
|
'preview_hash.required' => '请先计算过账方案。',
|
||||||
|
'preview_hash.size' => '过账方案已失效,请重新计算。',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function redirectToPage(Request $request, string $period): RedirectResponse
|
||||||
|
{
|
||||||
|
return redirect()->route('business.pages.show', [
|
||||||
|
'company_id' => company_id() ?: 1,
|
||||||
|
'section' => 'posting-data',
|
||||||
|
'page' => 'kuka-basic-data',
|
||||||
|
'submenu' => 'shipments',
|
||||||
|
'period' => $period,
|
||||||
|
'store_name' => mb_substr(trim((string) $request->input('store_name', '')), 0, 191),
|
||||||
|
'status' => mb_substr(trim((string) $request->input('status', '')), 0, 64),
|
||||||
|
'keyword' => mb_substr(trim((string) $request->input('keyword', '')), 0, 120),
|
||||||
|
'per_page' => max(1, min(200, (int) $request->input('per_page', 50))),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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'] ?? []);
|
$pages = collect($sectionConfig['pages'] ?? []);
|
||||||
|
|
||||||
if ($pages->isEmpty()) {
|
if ($pages->isEmpty()) {
|
||||||
@ -1769,7 +1777,7 @@ class Pages extends Controller
|
|||||||
// 数据按天同步,同一组筛选 5 分钟内复用结果,避免来回切换筛选项重复扫整月。
|
// 数据按天同步,同一组筛选 5 分钟内复用结果,避免来回切换筛选项重复扫整月。
|
||||||
$differenceMaterialized = DifferenceMaterialization::materialized($month);
|
$differenceMaterialized = DifferenceMaterialization::materialized($month);
|
||||||
$dataVersion = DifferenceMaterialization::dataVersion($month);
|
$dataVersion = DifferenceMaterialization::dataVersion($month);
|
||||||
$statsCacheKey = 'performance-details-aggregate-v2:' . md5(serialize([
|
$statsCacheKey = 'performance-details-aggregate-v3:' . md5(serialize([
|
||||||
$month,
|
$month,
|
||||||
[$platformFilter, $storeFilter, $companyFilter, $statusFilter, $remarkFilter, $unmatchedReasonFilter, $differenceState, $orderNo],
|
[$platformFilter, $storeFilter, $companyFilter, $statusFilter, $remarkFilter, $unmatchedReasonFilter, $differenceState, $orderNo],
|
||||||
$crossMonthOnly,
|
$crossMonthOnly,
|
||||||
@ -1881,7 +1889,7 @@ class Pages extends Controller
|
|||||||
$storeFilter,
|
$storeFilter,
|
||||||
array_map('strval', $filterOptions['stores'] ?? []),
|
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);
|
sort($companyOptions, SORT_NATURAL | SORT_FLAG_CASE);
|
||||||
$stats['company_options'] = array_values(array_unique(array_merge(
|
$stats['company_options'] = array_values(array_unique(array_merge(
|
||||||
$companyFilter,
|
$companyFilter,
|
||||||
@ -2400,16 +2408,15 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 当前账期的店铺 → 主体映射。
|
* 当前账期的店铺与主体期间映射。
|
||||||
*
|
*
|
||||||
* 主体字段由店铺当前存续主体派生,镜像表里没有可直接筛选的主体列;
|
* 业绩明细按发生日期匹配主体生效、失效区间;这里生成当月每天实际对应的
|
||||||
* 这里统一生成店铺名单、展示映射和“主体 → 店铺”关系,供页面、联动统计和导出共用。
|
* “主体 → 店铺日期窗口”,供页面、指标、联动统计和导出共用。
|
||||||
*
|
*
|
||||||
* @return array{
|
* @return array{
|
||||||
* store_names:list<string>,
|
* store_names:list<string>,
|
||||||
* subject_map:array<string,mixed>,
|
* subject_map:array<string,mixed>,
|
||||||
* companies_by_store:array<string,string>,
|
* company_windows:array<string,list<array{store_name:string,effective_at:string,expires_at:string}>>
|
||||||
* stores_by_company:array<string,list<string>>
|
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
private function receiptOrderMatchSubjectContext(string $month): array
|
private function receiptOrderMatchSubjectContext(string $month): array
|
||||||
@ -2417,7 +2424,7 @@ class Pages extends Controller
|
|||||||
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||||
$companyId = (int) (company_id() ?: 1);
|
$companyId = (int) (company_id() ?: 1);
|
||||||
$storeNames = cache()->remember(
|
$storeNames = cache()->remember(
|
||||||
'performance-details-subject-stores-v1:' . $companyId . ':' . $month,
|
'performance-details-subject-stores-v2:' . $companyId . ':' . $month,
|
||||||
now()->addHours(6),
|
now()->addHours(6),
|
||||||
static fn (): array => DB::connection($connection)->table('store_receipt_order_match_rows')
|
static fn (): array => DB::connection($connection)->table('store_receipt_order_match_rows')
|
||||||
->where('report_month', $month)
|
->where('report_month', $month)
|
||||||
@ -2434,30 +2441,61 @@ class Pages extends Controller
|
|||||||
->all(),
|
->all(),
|
||||||
);
|
);
|
||||||
|
|
||||||
$subjectMap = $this->currentStoreSubjectMap($storeNames);
|
$subjectMap = $this->performanceSubjectMap($storeNames);
|
||||||
$matcher = app(PerformanceDetailSubjectMatcher::class);
|
$matcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
$companiesByStore = [];
|
$companyWindows = cache()->remember(
|
||||||
$storesByCompany = [];
|
'performance-details-subject-windows-v1:'
|
||||||
foreach ($storeNames as $storeName) {
|
. $companyId . ':' . $month . ':' . sha1(serialize($subjectMap)),
|
||||||
$companyName = trim($matcher->companyForStore((string) $storeName, $subjectMap));
|
now()->addMinutes(5),
|
||||||
if ($companyName === '') {
|
static function () use ($matcher, $month, $storeNames, $subjectMap): array {
|
||||||
continue;
|
$companyWindows = [];
|
||||||
}
|
$monthStart = Carbon::parse($month)->startOfMonth();
|
||||||
$companiesByStore[(string) $storeName] = $companyName;
|
$monthEnd = $monthStart->copy()->endOfMonth();
|
||||||
$storesByCompany[$companyName][] = (string) $storeName;
|
foreach ($storeNames as $storeName) {
|
||||||
}
|
$cursor = $monthStart->copy();
|
||||||
ksort($storesByCompany, SORT_NATURAL | SORT_FLAG_CASE);
|
$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 [
|
return [
|
||||||
'store_names' => array_values($storeNames),
|
'store_names' => array_values($storeNames),
|
||||||
'subject_map' => $subjectMap,
|
'subject_map' => $subjectMap,
|
||||||
'companies_by_store' => $companiesByStore,
|
'company_windows' => $companyWindows,
|
||||||
'stores_by_company' => $storesByCompany,
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 主体筛选转换成镜像里的店铺条件;主体映射采用页面行展示的同一套当前主体口径。
|
* 主体筛选转换成镜像里的店铺与发生日期条件;与页面行展示使用同一套期间口径。
|
||||||
*
|
*
|
||||||
* @param \Illuminate\Database\Query\Builder $query
|
* @param \Illuminate\Database\Query\Builder $query
|
||||||
* @param list<string> $companyFilter
|
* @param list<string> $companyFilter
|
||||||
@ -2479,19 +2517,30 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$subjectContext ??= $this->receiptOrderMatchSubjectContext($month);
|
$subjectContext ??= $this->receiptOrderMatchSubjectContext($month);
|
||||||
$stores = [];
|
$windows = [];
|
||||||
foreach ($companyFilter as $companyName) {
|
foreach ($companyFilter as $companyName) {
|
||||||
foreach ($subjectContext['stores_by_company'][$companyName] ?? [] as $storeName) {
|
foreach ($subjectContext['company_windows'][$companyName] ?? [] as $window) {
|
||||||
$stores[(string) $storeName] = true;
|
$windows[] = $window;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($stores === []) {
|
if ($windows === []) {
|
||||||
$query->whereRaw('1 = 0');
|
$query->whereRaw('1 = 0');
|
||||||
|
|
||||||
return;
|
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,
|
$month,
|
||||||
$filters,
|
$filters,
|
||||||
$orderNo,
|
$orderNo,
|
||||||
@ -2683,6 +2732,7 @@ class Pages extends Controller
|
|||||||
$wantDifference = in_array('有差额', $differenceValues, true);
|
$wantDifference = in_array('有差额', $differenceValues, true);
|
||||||
$wantNoDifference = in_array('无差额', $differenceValues, true);
|
$wantNoDifference = in_array('无差额', $differenceValues, true);
|
||||||
$subjectContext = $this->receiptOrderMatchSubjectContext($month);
|
$subjectContext = $this->receiptOrderMatchSubjectContext($month);
|
||||||
|
$needsSubjectDate = in_array('company_name', $columns, true);
|
||||||
|
|
||||||
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||||
// 已物化的账期直接读规则序号列与默认差额列;未物化时回退实时规则表达式。
|
// 已物化的账期直接读规则序号列与默认差额列;未物化时回退实时规则表达式。
|
||||||
@ -2698,7 +2748,9 @@ class Pages extends Controller
|
|||||||
->table('store_receipt_order_match_rows')
|
->table('store_receipt_order_match_rows')
|
||||||
->where('report_month', $month)
|
->where('report_month', $month)
|
||||||
->whereNotIn('platform', self::RECEIPT_MATCH_EXCLUDED_PLATFORMS)
|
->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($baseDifferenceExpression . ' AS base_difference')
|
||||||
->selectRaw($reasonIndexExpression . ' AS reason_index');
|
->selectRaw($reasonIndexExpression . ' AS reason_index');
|
||||||
|
|
||||||
@ -2733,10 +2785,14 @@ class Pages extends Controller
|
|||||||
$outer->whereRaw('ABS(' . $effective . ')' . ($wantDifference ? ' > 0.005' : ' <= 0.005'));
|
$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
|
$rows = $outer
|
||||||
->select(['platform', 'store_name', 'match_status', 'remark', 'reason_index', 'base_difference'])
|
->select($select)
|
||||||
->selectRaw('COUNT(*) AS total')
|
->selectRaw('COUNT(*) AS total')
|
||||||
->groupBy(['platform', 'store_name', 'match_status', 'remark', 'reason_index', 'base_difference'])
|
->groupBy($select)
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
$counts = [
|
$counts = [
|
||||||
@ -2749,10 +2805,12 @@ class Pages extends Controller
|
|||||||
'difference_state' => [],
|
'difference_state' => [],
|
||||||
];
|
];
|
||||||
$wanted = array_fill_keys($columns, true);
|
$wanted = array_fill_keys($columns, true);
|
||||||
|
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$total = (int) ($row->total ?? 0);
|
$total = (int) ($row->total ?? 0);
|
||||||
$platform = (string) ($row->platform ?? '');
|
$platform = (string) ($row->platform ?? '');
|
||||||
$store = (string) ($row->store_name ?? '');
|
$store = (string) ($row->store_name ?? '');
|
||||||
|
$occurredDate = substr((string) ($row->occurred_date ?? ''), 0, 10);
|
||||||
$status = (string) ($row->match_status ?? '');
|
$status = (string) ($row->match_status ?? '');
|
||||||
$rawRemark = trim((string) ($row->remark ?? ''));
|
$rawRemark = trim((string) ($row->remark ?? ''));
|
||||||
$reasonIndex = (int) ($row->reason_index ?? 0);
|
$reasonIndex = (int) ($row->reason_index ?? 0);
|
||||||
@ -2765,7 +2823,11 @@ class Pages extends Controller
|
|||||||
$counts['store_name'][$store] = ($counts['store_name'][$store] ?? 0) + $total;
|
$counts['store_name'][$store] = ($counts['store_name'][$store] ?? 0) + $total;
|
||||||
}
|
}
|
||||||
if (isset($wanted['company_name']) && $store !== '') {
|
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 !== '') {
|
if ($companyName !== '') {
|
||||||
$counts['company_name'][$companyName] = ($counts['company_name'][$companyName] ?? 0) + $total;
|
$counts['company_name'][$companyName] = ($counts['company_name'][$companyName] ?? 0) + $total;
|
||||||
}
|
}
|
||||||
@ -2846,16 +2908,22 @@ class Pages extends Controller
|
|||||||
|
|
||||||
$counts = [];
|
$counts = [];
|
||||||
if ($column === 'company_name') {
|
if ($column === 'company_name') {
|
||||||
$rows = $query->select('store_name')
|
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
|
$rows = $query->select('store_name', 'occurred_date')
|
||||||
->selectRaw('COUNT(*) AS total')
|
->selectRaw('COUNT(*) AS total')
|
||||||
->whereNotNull('store_name')
|
->whereNotNull('store_name')
|
||||||
->where('store_name', '!=', '')
|
->where('store_name', '!=', '')
|
||||||
->groupBy('store_name')
|
->groupBy('store_name', 'occurred_date')
|
||||||
->pluck('total', 'store_name');
|
->get();
|
||||||
foreach ($rows as $store => $total) {
|
foreach ($rows as $row) {
|
||||||
$companyName = trim((string) ($subjectContext['companies_by_store'][(string) $store] ?? ''));
|
$total = (int) ($row->total ?? 0);
|
||||||
if ($companyName !== '' && (int) $total > 0) {
|
$companyName = trim($subjectMatcher->companyForStoreDate(
|
||||||
$counts[$companyName] = ($counts[$companyName] ?? 0) + (int) $total;
|
(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') {
|
} elseif ($column === 'remark') {
|
||||||
@ -3036,7 +3104,7 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
$subjectMap = $this->currentStoreSubjectMap(
|
$subjectMap = $this->performanceSubjectMap(
|
||||||
(clone $query)->whereNotNull('store_name')->where('store_name', '!=', '')
|
(clone $query)->whereNotNull('store_name')->where('store_name', '!=', '')
|
||||||
->distinct()->pluck('store_name')->all(),
|
->distinct()->pluck('store_name')->all(),
|
||||||
);
|
);
|
||||||
@ -3134,7 +3202,7 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @param list<string> $storeNames @return array<string,mixed> */
|
/** @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(
|
$names = array_values(array_unique(array_filter(array_map(
|
||||||
static fn (mixed $name): string => trim((string) $name),
|
static fn (mixed $name): string => trim((string) $name),
|
||||||
@ -3142,7 +3210,7 @@ class Pages extends Controller
|
|||||||
))));
|
))));
|
||||||
sort($names, SORT_NATURAL | SORT_FLAG_CASE);
|
sort($names, SORT_NATURAL | SORT_FLAG_CASE);
|
||||||
$companyId = (int) (company_id() ?: 1);
|
$companyId = (int) (company_id() ?: 1);
|
||||||
$cacheKey = 'current-store-subject-map-v2:'
|
$cacheKey = 'performance-details-subject-map-v3:'
|
||||||
. $companyId . ':' . sha1(implode("\n", $names));
|
. $companyId . ':' . sha1(implode("\n", $names));
|
||||||
|
|
||||||
return cache()->remember(
|
return cache()->remember(
|
||||||
@ -4970,17 +5038,14 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。
|
* 按表维护的页面数据:终版页签及快递记账明细使用各自的独立数据集。
|
||||||
*
|
*
|
||||||
* @return array<string,mixed>|null
|
* @return array<string,mixed>|null
|
||||||
*/
|
*/
|
||||||
protected function payablesFinalData(array $section, ?array $page): ?array
|
protected function payablesFinalData(array $section, ?array $page): ?array
|
||||||
{
|
{
|
||||||
$sectionSlug = (string) ($section['slug'] ?? '');
|
$sectionSlug = (string) ($section['slug'] ?? '');
|
||||||
if (empty($page) || ! in_array($sectionSlug, [
|
if (empty($page)) {
|
||||||
PayablesFinalRegistry::SECTION_SUPPLIER,
|
|
||||||
PayablesFinalRegistry::SECTION_COURIER,
|
|
||||||
], true)) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -4999,9 +5064,7 @@ class Pages extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$keyword = trim((string) request('keyword', ''));
|
$keyword = trim((string) request('keyword', ''));
|
||||||
$storeDataset = PayablesFinalActions::DATASET_PREFIX
|
$storeDataset = $registry->storeDataset($sectionSlug, $dataset);
|
||||||
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
|
|
||||||
. $dataset;
|
|
||||||
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
$isSupplierPayablesReport = $dataset === 'supplier-payables-report';
|
||||||
$requestedMonth = trim((string) request('month', ''));
|
$requestedMonth = trim((string) request('month', ''));
|
||||||
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
|
||||||
@ -5909,6 +5972,7 @@ class Pages extends Controller
|
|||||||
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
|
||||||
'shipping-data' => $this->contentForShippingData(),
|
'shipping-data' => $this->contentForShippingData(),
|
||||||
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
'return-pickup-management' => $this->contentForReturnPickupManagement(),
|
||||||
|
'returned-parcels' => app(ReturnedParcelController::class)->page(request()),
|
||||||
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
'withdrawal-management' => $this->contentForWithdrawalManagement(),
|
||||||
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
|
||||||
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
|
||||||
@ -5938,6 +6002,7 @@ class Pages extends Controller
|
|||||||
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
|
||||||
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
|
||||||
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
|
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
|
||||||
|
'raw-statements' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->rawStatementsData(),
|
||||||
'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
|
'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
|
||||||
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
|
||||||
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
'store-report-data-logic' => $this->prepareStoreReportLogic(),
|
||||||
@ -7199,6 +7264,9 @@ class Pages extends Controller
|
|||||||
['field' => 'barcode', 'label' => '条形码', 'type' => 'identifier'],
|
['field' => 'barcode', 'label' => '条形码', 'type' => 'identifier'],
|
||||||
['field' => 'product_name', 'label' => '商品名称', 'type' => 'text'],
|
['field' => 'product_name', 'label' => '商品名称', 'type' => 'text'],
|
||||||
['field' => 'qty', 'label' => '数量', 'type' => 'number'],
|
['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' => 'pkg_count', 'label' => '件数', 'type' => 'text'],
|
||||||
['field' => 'receiver_state', 'label' => '省', 'type' => 'text'],
|
['field' => 'receiver_state', 'label' => '省', 'type' => 'text'],
|
||||||
['field' => 'buyer_nick', 'label' => '买家昵称', 'type' => 'text'],
|
['field' => 'buyer_nick', 'label' => '买家昵称', 'type' => 'text'],
|
||||||
@ -7210,6 +7278,9 @@ class Pages extends Controller
|
|||||||
['field' => 'freight', 'label' => '运费', 'type' => 'number'],
|
['field' => 'freight', 'label' => '运费', 'type' => 'number'],
|
||||||
['field' => 'online_weight', 'label' => '线上重量', 'type' => 'number'],
|
['field' => 'online_weight', 'label' => '线上重量', 'type' => 'number'],
|
||||||
['field' => 'actual_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' => 'length_cm', 'label' => '长(cm)', 'type' => 'number'],
|
||||||
['field' => 'width_cm', 'label' => '宽(cm)', 'type' => 'number'],
|
['field' => 'width_cm', 'label' => '宽(cm)', 'type' => 'number'],
|
||||||
['field' => 'height_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' => 'settle_freight', 'label' => '结算运费', 'type' => 'number'],
|
||||||
['field' => 'front_no', 'label' => '换单前单号', 'type' => 'identifier'],
|
['field' => 'front_no', 'label' => '换单前单号', 'type' => 'identifier'],
|
||||||
// 报价核算(按报价管理里发货日生效的报价)
|
// 报价核算(按报价管理里发货日生效的报价)
|
||||||
['field' => 'qc_freight', 'label' => '核算运费', 'type' => 'number'],
|
|
||||||
['field' => 'qc_diff', 'label' => '核算-聚水潭运费', 'type' => 'number'],
|
['field' => 'qc_diff', 'label' => '核算-聚水潭运费', 'type' => 'number'],
|
||||||
['field' => 'qc_quote_version', 'label' => '报价版本', 'type' => 'identifier'],
|
['field' => 'qc_quote_version', 'label' => '报价版本', 'type' => 'identifier'],
|
||||||
['field' => 'qc_basis', 'label' => '结算重量依据', 'type' => 'text'],
|
['field' => 'qc_basis', 'label' => '结算重量依据', 'type' => 'text'],
|
||||||
['field' => 'qc_settle_weight', 'label' => '核算结算重量(kg)', 'type' => 'number'],
|
['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_flat_price', 'label' => '一口价(元)', 'type' => 'number'],
|
||||||
['field' => 'qc_extra_fee', 'label' => '多件/超长加收(元)', 'type' => 'number'],
|
['field' => 'qc_extra_fee', 'label' => '多件/超长加收(元)', 'type' => 'number'],
|
||||||
['field' => 'qc_formula', 'label' => '核算公式', 'type' => 'text'],
|
['field' => 'qc_formula', 'label' => '核算公式', 'type' => 'text'],
|
||||||
@ -8742,6 +8808,7 @@ class Pages extends Controller
|
|||||||
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
|
||||||
$pagePaymentAmount = '0.00';
|
$pagePaymentAmount = '0.00';
|
||||||
$filteredPaymentAmount = '0.00';
|
$filteredPaymentAmount = '0.00';
|
||||||
|
$storePaymentSummary = [];
|
||||||
$shopNames = [];
|
$shopNames = [];
|
||||||
$paymentReasons = [];
|
$paymentReasons = [];
|
||||||
$error = null;
|
$error = null;
|
||||||
@ -8764,7 +8831,7 @@ class Pages extends Controller
|
|||||||
$shopNames = $filterOptions['shops'];
|
$shopNames = $filterOptions['shops'];
|
||||||
$paymentReasons = $filterOptions['payment_reasons'];
|
$paymentReasons = $filterOptions['payment_reasons'];
|
||||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
$subjectMap = $this->currentStoreSubjectMap(array_values(array_unique(array_merge(
|
$subjectMap = $this->performanceSubjectMap(array_values(array_unique(array_merge(
|
||||||
$shopNames,
|
$shopNames,
|
||||||
array_map(
|
array_map(
|
||||||
static fn (mixed $row): string => trim((string) data_get($row, 'shop_name', '')),
|
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(
|
$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,
|
is_array($row) ? $row : (array) $row,
|
||||||
$subjectMap,
|
$subjectMap,
|
||||||
),
|
),
|
||||||
@ -8786,6 +8853,9 @@ class Pages extends Controller
|
|||||||
);
|
);
|
||||||
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
|
||||||
$filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00');
|
$filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00');
|
||||||
|
$storePaymentSummary = is_array($result['store_summary'] ?? null)
|
||||||
|
? $result['store_summary']
|
||||||
|
: [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
@ -8800,6 +8870,7 @@ class Pages extends Controller
|
|||||||
'smallPaymentSyncStatus' => $syncStatus,
|
'smallPaymentSyncStatus' => $syncStatus,
|
||||||
'smallPaymentPageAmount' => $pagePaymentAmount,
|
'smallPaymentPageAmount' => $pagePaymentAmount,
|
||||||
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
'smallPaymentFilteredAmount' => $filteredPaymentAmount,
|
||||||
|
'smallPaymentStoreSummary' => $storePaymentSummary,
|
||||||
'smallPaymentShops' => $shopNames,
|
'smallPaymentShops' => $shopNames,
|
||||||
'smallPaymentReasons' => $paymentReasons,
|
'smallPaymentReasons' => $paymentReasons,
|
||||||
'smallPaymentStatuses' => [
|
'smallPaymentStatuses' => [
|
||||||
@ -8837,7 +8908,7 @@ class Pages extends Controller
|
|||||||
|
|
||||||
$filterOptions = $this->smallPaymentWorkOrders->filterOptions();
|
$filterOptions = $this->smallPaymentWorkOrders->filterOptions();
|
||||||
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
$subjectMatcher = app(PerformanceDetailSubjectMatcher::class);
|
||||||
$subjectMap = $this->currentStoreSubjectMap($filterOptions['shops'] ?? []);
|
$subjectMap = $this->performanceSubjectMap($filterOptions['shops'] ?? []);
|
||||||
|
|
||||||
return $this->streamSmallPaymentWorkOrderCsv(
|
return $this->streamSmallPaymentWorkOrderCsv(
|
||||||
$this->smallPaymentWorkOrders->exportRows($filters),
|
$this->smallPaymentWorkOrders->exportRows($filters),
|
||||||
@ -8964,7 +9035,7 @@ class Pages extends Controller
|
|||||||
fputcsv($csv, array_column($columns, 'label'));
|
fputcsv($csv, array_column($columns, 'label'));
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
if ($subjectMatcher !== null) {
|
if ($subjectMatcher !== null) {
|
||||||
$row = $subjectMatcher->applyArray(
|
$row = $subjectMatcher->applyArrayCurrent(
|
||||||
is_array($row) ? $row : (array) $row,
|
is_array($row) ? $row : (array) $row,
|
||||||
$subjectMap,
|
$subjectMap,
|
||||||
);
|
);
|
||||||
|
|||||||
@ -16,8 +16,7 @@ use RuntimeException;
|
|||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「终版」目录的按表数据:界面与基础页面一致,数据独立存放
|
* 终版页签和快递记账明细的导入、导出及编辑,各入口使用独立数据集。
|
||||||
* (数据集键 final:<目录>:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。
|
|
||||||
*/
|
*/
|
||||||
class PayablesFinalActions extends Controller
|
class PayablesFinalActions extends Controller
|
||||||
{
|
{
|
||||||
@ -171,9 +170,7 @@ class PayablesFinalActions extends Controller
|
|||||||
|
|
||||||
private function storeDataset(Request $request): string
|
private function storeDataset(Request $request): string
|
||||||
{
|
{
|
||||||
$section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier';
|
return $this->registry->storeDataset($this->section($request), $this->dataset($request));
|
||||||
|
|
||||||
return self::DATASET_PREFIX . $section . ':' . $this->dataset($request);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private function csvText(mixed $value): string
|
private function csvText(mixed $value): string
|
||||||
|
|||||||
@ -19,6 +19,9 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|||||||
/** 种菜报销工作台:上传参考名单、维护种菜额度规则、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
|
/** 种菜报销工作台:上传参考名单、维护种菜额度规则、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
|
||||||
class PlantingReimbursementWorkbench extends Controller
|
class PlantingReimbursementWorkbench extends Controller
|
||||||
{
|
{
|
||||||
|
/** 需要放行检查通过才能导出的类型。 */
|
||||||
|
private const GATED_EXPORTS = ['import-template'];
|
||||||
|
|
||||||
public function upload(Request $request, string $kind, References $references)
|
public function upload(Request $request, string $kind, References $references)
|
||||||
{
|
{
|
||||||
abort_unless(isset(References::KINDS[$kind]), 404);
|
abort_unless(isset(References::KINDS[$kind]), 404);
|
||||||
@ -59,9 +62,12 @@ class PlantingReimbursementWorkbench extends Controller
|
|||||||
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
|
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
|
||||||
}
|
}
|
||||||
// 放行检查替代原来的「去聚工单人工核对、勾选已核对」。
|
// 放行检查替代原来的「去聚工单人工核对、勾选已核对」。
|
||||||
$gate = Gate::check($result);
|
// 对账、报销明细随时可导出核对(只读,不影响任何操作);导入模版会被导入聚工单,仍需放行检查通过。
|
||||||
if (! $gate['ok']) {
|
if (in_array($type, self::GATED_EXPORTS, true)) {
|
||||||
return $this->back(request())->with('error', '暂不能导出:' . implode(';', $gate['reasons']) . '。');
|
$gate = Gate::check($result);
|
||||||
|
if (! $gate['ok']) {
|
||||||
|
return $this->back(request())->with('error', '暂不能导出:' . implode(';', $gate['reasons']) . '。');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$spreadsheet = $exporter->build($type, $result);
|
$spreadsheet = $exporter->build($type, $result);
|
||||||
|
|
||||||
@ -82,14 +88,21 @@ class PlantingReimbursementWorkbench extends Controller
|
|||||||
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
||||||
'digest_secret' => (string) $request->input('digest_secret', ''),
|
'digest_secret' => (string) $request->input('digest_secret', ''),
|
||||||
'clear_digest' => $request->boolean('clear_digest'),
|
'clear_digest' => $request->boolean('clear_digest'),
|
||||||
|
'cancel_notices_enabled' => $request->has('cancel_notices_enabled')
|
||||||
|
? $request->boolean('cancel_notices_enabled')
|
||||||
|
: $robot->cancelNoticesEnabled(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
|
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */
|
/** 按发起人发送取消 / 待复查通知,须已启用逐单通知且放行检查通过。 */
|
||||||
public function notify(Request $request, PageData $page, Robot $robot)
|
public function notify(Request $request, PageData $page, Robot $robot)
|
||||||
{
|
{
|
||||||
|
if (! $robot->cancelNoticesEnabled()) {
|
||||||
|
return $this->back($request)->with('error', '取消 / 待复查工单通知已暂停,测试完成前不会发送。');
|
||||||
|
}
|
||||||
|
|
||||||
$filters = $page->filters();
|
$filters = $page->filters();
|
||||||
try {
|
try {
|
||||||
$result = $page->build($filters);
|
$result = $page->build($filters);
|
||||||
@ -158,7 +171,7 @@ class PlantingReimbursementWorkbench extends Controller
|
|||||||
|
|
||||||
return response()->streamDownload(static function () use ($csv): void {
|
return response()->streamDownload(static function () use ($csv): void {
|
||||||
echo $csv;
|
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('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)
|
public function exportCommission(CommissionPeople $people)
|
||||||
@ -204,7 +217,7 @@ class PlantingReimbursementWorkbench extends Controller
|
|||||||
|
|
||||||
return response()->streamDownload(static function () use ($csv): void {
|
return response()->streamDownload(static function () use ($csv): void {
|
||||||
echo $csv;
|
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 时读取钉钉表单结构并按本批填好展示,不上传、不发起。 */
|
/** 预览钉钉表单:页面带上 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
89
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
89
app/Http/Controllers/Business/ReturnedParcelController.php
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
<?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_kind' => '数据来源', '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, COALESCE(SUM(returned_qty),0) AS quantity')->first();
|
||||||
|
$data['summary']->orders_count = $db->query()->fromSub((clone $query)->select(['source_kind', 'after_sales_id'])->distinct(), 'returned_orders')->count();
|
||||||
|
$data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_kind')->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 (['regular', 'taobao'] as $source) foreach ((clone $query)->where('source_kind', $source)->orderBy('source_id')->lazyById(1000, 'source_id') as $row) {
|
||||||
|
fputcsv($file, array_map(function ($key) use ($row) {
|
||||||
|
$value = $key === 'source_kind' ? ($row->$key === 'taobao' ? '淘系' : '普通') : (string) ($row->$key ?? '');
|
||||||
|
if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value;
|
||||||
|
return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value;
|
||||||
|
}, $selected));
|
||||||
|
}
|
||||||
|
fclose($file);
|
||||||
|
}, '退回件明细.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function filters(Request $request): array
|
||||||
|
{
|
||||||
|
return validator($request->query(), [
|
||||||
|
'from' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:2026-10-01'],
|
||||||
|
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
|
||||||
|
'waybill' => ['nullable', 'string', 'max:255'], 'shop' => ['nullable', 'string', 'max:255'],
|
||||||
|
'warehouse' => ['nullable', 'string', 'max:255'], 'sku' => ['nullable', 'string', 'max:255'],
|
||||||
|
])->validate() + ['from' => Sync::START, 'to' => now('Asia/Shanghai')->toDateString(),
|
||||||
|
'waybill' => '', 'shop' => '', 'warehouse' => '', 'sku' => ''];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function query(array $filters)
|
||||||
|
{
|
||||||
|
$query = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(Sync::TABLE)
|
||||||
|
->where('received_at', '>=', $filters['from'] ?: Sync::START);
|
||||||
|
if ($filters['to']) $query->where('received_at', '<', Carbon::parse($filters['to'])->addDay()->toDateString());
|
||||||
|
foreach (['waybill', 'shop', 'warehouse', 'sku'] as $field) {
|
||||||
|
if (filled($filters[$field])) $query->where($field, trim($filters[$field]));
|
||||||
|
}
|
||||||
|
return $query;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -12,10 +12,11 @@ use Modules\EcommerceFinance\Services\SupplierComparisonCsvExporter;
|
|||||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
|
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierStatementWorkbookExporter;
|
||||||
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
@ -26,6 +27,8 @@ use Throwable;
|
|||||||
*/
|
*/
|
||||||
class SupplierReconciliation extends Controller
|
class SupplierReconciliation extends Controller
|
||||||
{
|
{
|
||||||
|
private const RAW_STATEMENT_PER_PAGE = 50;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly SupplierStatementTemplate $template,
|
private readonly SupplierStatementTemplate $template,
|
||||||
private readonly SupplierStatementStore $statements,
|
private readonly SupplierStatementStore $statements,
|
||||||
@ -36,6 +39,8 @@ class SupplierReconciliation extends Controller
|
|||||||
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
|
||||||
private readonly SupplierPortalAccess $supplierPortalAccess,
|
private readonly SupplierPortalAccess $supplierPortalAccess,
|
||||||
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
private readonly SupplierSummaryConfirmation $summaryConfirmations,
|
||||||
|
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||||
|
private readonly SupplierStatementWorkbookExporter $statementWorkbookExporter,
|
||||||
) {
|
) {
|
||||||
$this->middleware('auth');
|
$this->middleware('auth');
|
||||||
$this->middleware('company.identify');
|
$this->middleware('company.identify');
|
||||||
@ -58,18 +63,29 @@ class SupplierReconciliation extends Controller
|
|||||||
$supplierPortalUpload = $request->user()
|
$supplierPortalUpload = $request->user()
|
||||||
&& SupplierPortalAccess::isSupplierUser($request->user());
|
&& SupplierPortalAccess::isSupplierUser($request->user());
|
||||||
$supplier = $this->effectiveSupplier($request);
|
$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);
|
$records = $this->template->parse($request->file('import'), $supplier);
|
||||||
$rows = $this->statements->save(
|
$rows = $this->statements->save(
|
||||||
$supplier,
|
$supplier,
|
||||||
$records,
|
$records,
|
||||||
(string) $request->file('import')->getClientOriginalName(),
|
(string) $request->file('import')->getClientOriginalName(),
|
||||||
(int) (company_id() ?: 1),
|
$companyId,
|
||||||
user_id() ? (int) user_id() : null,
|
user_id() ? (int) user_id() : null,
|
||||||
);
|
);
|
||||||
|
|
||||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||||
$receiptNotice = '';
|
$notices = [];
|
||||||
|
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||||
if ($supplierPortalUpload) {
|
if ($supplierPortalUpload) {
|
||||||
try {
|
try {
|
||||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||||
@ -78,14 +94,30 @@ class SupplierReconciliation extends Controller
|
|||||||
$records,
|
$records,
|
||||||
);
|
);
|
||||||
if ($receiptSent) {
|
if ($receiptSent) {
|
||||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||||
}
|
}
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
report($exception);
|
report($exception);
|
||||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
|
||||||
|
$supplier,
|
||||||
|
$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()
|
return $request->expectsJson()
|
||||||
? response()->json(['message' => $message, 'rows' => $rows])
|
? 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
|
public function saveDingTalkRobot(Request $request): RedirectResponse
|
||||||
{
|
{
|
||||||
$request->validate([
|
$request->validate([
|
||||||
@ -283,7 +375,7 @@ class SupplierReconciliation extends Controller
|
|||||||
}
|
}
|
||||||
$differences = array_values(array_filter(
|
$differences = array_values(array_filter(
|
||||||
$detail['rows'],
|
$detail['rows'],
|
||||||
static fn (array $row): bool => ($row['type'] ?? '') !== SupplierStatementMatcher::TYPE_MATCH,
|
fn (array $row): bool => $this->pageData->requiresSupplierCorrection($row),
|
||||||
));
|
));
|
||||||
|
|
||||||
if ($request->input('scope') === 'row') {
|
if ($request->input('scope') === 'row') {
|
||||||
|
|||||||
@ -65,13 +65,17 @@ final class UnshippedWaybillController extends Controller
|
|||||||
public function export(Request $request)
|
public function export(Request $request)
|
||||||
{
|
{
|
||||||
$query = $this->filtered($request);
|
$query = $this->filtered($request);
|
||||||
return response()->streamDownload(function () use ($query): void {
|
$replacementOnly = (array) $request->input('sources', []) === ['replacement'];
|
||||||
|
return response()->streamDownload(function () use ($query, $replacementOnly): void {
|
||||||
$book = new Spreadsheet();
|
$book = new Spreadsheet();
|
||||||
$sheet = $book->getActiveSheet();
|
$sheet = $book->getActiveSheet();
|
||||||
$sheet->fromArray(['快递单号', '来源']);
|
$sheet->fromArray([$replacementOnly ? '换单前单号' : '快递单号', '来源',
|
||||||
|
$replacementOnly ? '换单前快递名称' : '快递名称', '换单后单号', '换单后快递名称', '依据时间']);
|
||||||
$line = 2;
|
$line = 2;
|
||||||
foreach ($query->orderBy('id')->lazyById(1000) as $row) {
|
foreach ($query->orderBy('id')->lazyById(1000) as $row) {
|
||||||
$values = [$row->waybill_no, UnshippedWaybills::label($row->source)];
|
$isReplacement = $row->source === 'replacement';
|
||||||
|
$values = [$row->waybill_no, UnshippedWaybills::label($row->source), $row->courier_name,
|
||||||
|
$isReplacement ? $row->new_waybill_no : null, $isReplacement ? $row->new_courier_name : null, $row->evidence_time];
|
||||||
foreach ($values as $column => $value) {
|
foreach ($values as $column => $value) {
|
||||||
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
|
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,12 +7,14 @@ use Illuminate\Http\JsonResponse;
|
|||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Routing\Controller;
|
use Illuminate\Routing\Controller;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Illuminate\View\View;
|
use Illuminate\View\View;
|
||||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
|
||||||
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
use Modules\EcommerceFinance\Services\SupplierStatementStore;
|
||||||
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
|
||||||
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
@ -30,6 +32,7 @@ class SupplierReconciliation extends Controller
|
|||||||
private readonly SupplierReconciliationPageData $pageData,
|
private readonly SupplierReconciliationPageData $pageData,
|
||||||
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
private readonly SupplierReturnCsvExporter $returnCsvExporter,
|
||||||
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
|
||||||
|
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -64,6 +67,15 @@ class SupplierReconciliation extends Controller
|
|||||||
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
|
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
|
||||||
]);
|
]);
|
||||||
[, $supplier, $companyId] = $this->supplierContext();
|
[, $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);
|
$records = $this->template->parse($request->file('import'), $supplier);
|
||||||
$rows = $this->statements->save(
|
$rows = $this->statements->save(
|
||||||
@ -74,7 +86,7 @@ class SupplierReconciliation extends Controller
|
|||||||
user_id() ? (int) user_id() : null,
|
user_id() ? (int) user_id() : null,
|
||||||
);
|
);
|
||||||
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
$message = "对账单已保存:{$supplier} 共 {$rows} 行";
|
||||||
$receiptNotice = '';
|
$notices = [];
|
||||||
try {
|
try {
|
||||||
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
|
||||||
$supplier,
|
$supplier,
|
||||||
@ -82,13 +94,30 @@ class SupplierReconciliation extends Controller
|
|||||||
$records,
|
$records,
|
||||||
);
|
);
|
||||||
if ($receiptSent) {
|
if ($receiptSent) {
|
||||||
$receiptNotice = ';上传回执已发送到该厂家钉钉群。';
|
$notices[] = '上传回执已发送到该厂家钉钉群';
|
||||||
}
|
}
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
report($exception);
|
report($exception);
|
||||||
$receiptNotice = ';上传回执发送失败,对账单已正常保存。';
|
$notices[] = '上传回执发送失败,对账单已正常保存';
|
||||||
}
|
}
|
||||||
$message .= $receiptNotice !== '' ? $receiptNotice : '。';
|
|
||||||
|
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
|
||||||
|
try {
|
||||||
|
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
|
||||||
|
$supplier,
|
||||||
|
$companyId,
|
||||||
|
$records,
|
||||||
|
user_id() ? (int) user_id() : null,
|
||||||
|
);
|
||||||
|
$autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush);
|
||||||
|
if ($autoPushNotice !== '') {
|
||||||
|
$notices[] = $autoPushNotice;
|
||||||
|
}
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
report($exception);
|
||||||
|
$notices[] = '零差异对账确认自动推送失败,对账单已正常保存';
|
||||||
|
}
|
||||||
|
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
|
||||||
|
|
||||||
return $request->expectsJson()
|
return $request->expectsJson()
|
||||||
? response()->json(['message' => $message, 'rows' => $rows])
|
? response()->json(['message' => $message, 'rows' => $rows])
|
||||||
@ -110,9 +139,10 @@ class SupplierReconciliation extends Controller
|
|||||||
public function confirmAllReturns(Request $request): RedirectResponse
|
public function confirmAllReturns(Request $request): RedirectResponse
|
||||||
{
|
{
|
||||||
[, $supplier, $companyId] = $this->supplierContext();
|
[, $supplier, $companyId] = $this->supplierContext();
|
||||||
|
$month = $this->pageData->accountingMonthKey();
|
||||||
$keys = array_values(array_map(
|
$keys = array_values(array_map(
|
||||||
static fn (array $row): string => (string) ($row['_action_key'] ?? ''),
|
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(
|
$confirmed = $this->returnConfirmations->confirmAll(
|
||||||
$supplier,
|
$supplier,
|
||||||
@ -127,7 +157,12 @@ class SupplierReconciliation extends Controller
|
|||||||
public function exportReturns(Request $request): StreamedResponse
|
public function exportReturns(Request $request): StreamedResponse
|
||||||
{
|
{
|
||||||
[, $supplier, $companyId] = $this->supplierContext();
|
[, $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);
|
return $this->returnCsvExporter->download($rows, $supplier);
|
||||||
}
|
}
|
||||||
@ -137,7 +172,11 @@ class SupplierReconciliation extends Controller
|
|||||||
$request->validate(['key' => ['required', 'string', 'max:191']]);
|
$request->validate(['key' => ['required', 'string', 'max:191']]);
|
||||||
[, $supplier, $companyId] = $this->supplierContext();
|
[, $supplier, $companyId] = $this->supplierContext();
|
||||||
$key = (string) $request->input('key');
|
$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);
|
->contains(static fn (array $row): bool => (string) ($row['_action_key'] ?? '') === $key);
|
||||||
abort_unless($owned, 403, '该退货明细不属于当前厂家账号。');
|
abort_unless($owned, 403, '该退货明细不属于当前厂家账号。');
|
||||||
|
|
||||||
|
|||||||
@ -13,11 +13,13 @@ class SupplierPortalSupplier extends Model
|
|||||||
'supplier_name',
|
'supplier_name',
|
||||||
'dingtalk_group_id',
|
'dingtalk_group_id',
|
||||||
'dingtalk_group_name',
|
'dingtalk_group_name',
|
||||||
|
'manually_bound',
|
||||||
'last_verified_at',
|
'last_verified_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
'dingtalk_group_id' => 'integer',
|
'dingtalk_group_id' => 'integer',
|
||||||
|
'manually_bound' => 'boolean',
|
||||||
'last_verified_at' => 'datetime',
|
'last_verified_at' => 'datetime',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@ -8,6 +8,7 @@ use App\Models\Auth\SupplierPortalSupplier;
|
|||||||
use App\Models\Auth\User;
|
use App\Models\Auth\User;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use InvalidArgumentException;
|
||||||
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
||||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
|
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
|
||||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||||
@ -129,6 +130,20 @@ class SupplierPortalAccess
|
|||||||
}
|
}
|
||||||
|
|
||||||
$resolved = [];
|
$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) {
|
foreach (array_keys($matchedSupplierNames) as $supplierName) {
|
||||||
$matchingRows = array_values(array_filter(
|
$matchingRows = array_values(array_filter(
|
||||||
$supplierRows,
|
$supplierRows,
|
||||||
@ -209,24 +224,27 @@ class SupplierPortalAccess
|
|||||||
);
|
);
|
||||||
|
|
||||||
foreach ($suppliers as $resolvedSupplier) {
|
foreach ($suppliers as $resolvedSupplier) {
|
||||||
SupplierPortalSupplier::query()->updateOrCreate(
|
$binding = SupplierPortalSupplier::query()->firstOrNew([
|
||||||
[
|
'company_id' => $companyId,
|
||||||
'company_id' => $companyId,
|
'user_id' => $user->id,
|
||||||
'user_id' => $user->id,
|
'supplier_name' => $resolvedSupplier['supplier_name'],
|
||||||
'supplier_name' => $resolvedSupplier['supplier_name'],
|
]);
|
||||||
],
|
$binding->fill([
|
||||||
[
|
'supplier_code' => $resolvedSupplier['supplier_code'] ?? null,
|
||||||
'supplier_code' => $resolvedSupplier['supplier_code'] ?? null,
|
'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'],
|
||||||
'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'],
|
'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'],
|
||||||
'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'],
|
'last_verified_at' => now(),
|
||||||
'last_verified_at' => now(),
|
]);
|
||||||
],
|
if (! $binding->exists) {
|
||||||
);
|
$binding->manually_bound = false;
|
||||||
|
}
|
||||||
|
$binding->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
SupplierPortalSupplier::query()
|
SupplierPortalSupplier::query()
|
||||||
->where('company_id', $companyId)
|
->where('company_id', $companyId)
|
||||||
->where('user_id', $user->id)
|
->where('user_id', $user->id)
|
||||||
|
->where('manually_bound', false)
|
||||||
->whereNotIn('supplier_name', $suppliers->pluck('supplier_name')->all())
|
->whereNotIn('supplier_name', $suppliers->pluck('supplier_name')->all())
|
||||||
->delete();
|
->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
|
public function mappingFor(User $user): ?SupplierPortalIdentity
|
||||||
{
|
{
|
||||||
if (! self::isSupplierUser($user)) {
|
if (! self::isSupplierUser($user)) {
|
||||||
|
|||||||
@ -21,7 +21,7 @@ final class BillParser
|
|||||||
/** 金额列名里出现这些字,整张表当附加费表,不读。 */
|
/** 金额列名里出现这些字,整张表当附加费表,不读。 */
|
||||||
public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价'];
|
public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价'];
|
||||||
/** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */
|
/** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */
|
||||||
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目'];
|
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目', '附加费类型'];
|
||||||
|
|
||||||
private const HEADER_SCAN_ROWS = 15;
|
private const HEADER_SCAN_ROWS = 15;
|
||||||
private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额'];
|
private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额'];
|
||||||
@ -169,7 +169,7 @@ final class BillParser
|
|||||||
}
|
}
|
||||||
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
|
||||||
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
|
||||||
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
$skip[$sheet] = ['附加费表:按单号和费用类型匹配结算', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
|
||||||
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
|
||||||
$freight[] = $sheet;
|
$freight[] = $sheet;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
355
app/Support/CourierBills/BillSurchargeQuoteCalculator.php
Normal file
355
app/Support/CourierBills/BillSurchargeQuoteCalculator.php
Normal file
@ -0,0 +1,355 @@
|
|||||||
|
<?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]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 发货、查件工单按账单当月及前两个月匹配;退回进仓不受此窗口限制。 */
|
||||||
|
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, $waybills) : [];
|
||||||
|
$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];
|
||||||
|
$feeReturns = $returns;
|
||||||
|
if (isset($returns['waybill:' . $wb])) $feeReturns['_waybill'] = $returns['waybill:' . $wb];
|
||||||
|
$result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? [],
|
||||||
|
$confirmations[$rule->id][$wb] ?? [], $feeReturns);
|
||||||
|
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 === '按尺寸/最长边') {
|
||||||
|
$combined = $this->sizeWeightRule($rule);
|
||||||
|
if ($combined !== null) {
|
||||||
|
$weight = $freight['charge_weight'] ?? null;
|
||||||
|
if (! is_numeric($weight) || (float) $weight <= 0) 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);
|
||||||
|
$eligible = $max > $combined['length_cm'] || (float) $weight > $combined['weight'];
|
||||||
|
$amount = $eligible ? round(max($combined['minimum'], (float) $weight * $combined['rate']), 2) : 0.0;
|
||||||
|
return [['settlement_amount' => $amount, 'evidence' =>
|
||||||
|
'最长边 ' . $max . 'cm,计费重量 ' . $weight . 'kg;报价条件:最长边>' . $combined['length_cm']
|
||||||
|
. 'cm 或计费重量>' . $combined['weight'] . 'kg;'
|
||||||
|
. ($eligible ? 'max(' . $weight . '×' . $combined['rate'] . '元/kg,最低' . $combined['minimum'] . '元)' : '未达到条件,不计费')
|
||||||
|
. ',按票计一次']];
|
||||||
|
}
|
||||||
|
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 sizeWeightRule(object $rule): ?array
|
||||||
|
{
|
||||||
|
$pattern = '/^最长边大于(\d+(?:\.\d+)?)米[;;]②?计费重量大于(\d+(?:\.\d+)?)KG[,,]即认定为超长超重货[,,]该单货物将在原收费基础上加收超长超重费[。.]加收标准按照计费重量[×*](\d+(?:\.\d+)?)元\/KG计算[,,]最低加收(\d+(?:\.\d+)?)元\/(?:票|单)[。.]?$/iu';
|
||||||
|
$condition = preg_replace('/\s+/u', '', $rule->condition);
|
||||||
|
$standard = preg_replace('/\s+/u', '', $rule->standard);
|
||||||
|
if (! preg_match($pattern, $condition, $c) || ! preg_match($pattern, $standard, $s)
|
||||||
|
|| array_map('floatval', array_slice($c, 1)) !== array_map('floatval', array_slice($s, 1))) return null;
|
||||||
|
if (min(array_map('floatval', array_slice($c, 1))) <= 0) return null;
|
||||||
|
|
||||||
|
return ['length_cm' => (float) $c[1] * 100, 'weight' => (float) $c[2],
|
||||||
|
'rate' => (float) $c[3], 'minimum' => (float) $c[4]];
|
||||||
|
}
|
||||||
|
|
||||||
|
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['_waybill'] ?? $returns[$reason['order_id']] ?? null;
|
||||||
|
if ($received === null) return '未找到对应订单的有效退回进仓明细,待核实';
|
||||||
|
$evidence .= ';退回进仓 ' . $received;
|
||||||
|
}
|
||||||
|
} elseif (preg_match('/^查件类型\/查件原因是([^\/]+)\/([^\/]+)$/u', $condition, $path)) {
|
||||||
|
$expected = trim($path[1]) . '/' . trim($path[2]);
|
||||||
|
$allowedReasons = array_map(static fn ($reason) => trim($path[1]) . '/' . trim($reason), explode('或', $path[2]));
|
||||||
|
$candidates = array_filter($orders, static function ($order) use ($rule): bool {
|
||||||
|
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
|
||||||
|
return ($fields['logisticsField'] ?? '') === $rule->courier
|
||||||
|
&& substr($order->created, 0, 10) >= substr($rule->effective_at, 0, 10)
|
||||||
|
&& ! in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true);
|
||||||
|
});
|
||||||
|
if ($candidates === []) return '未找到同快递的有效查件工单,无法核验查件类型和原因';
|
||||||
|
usort($candidates, static fn ($a, $b) => [$b->created, $b->source_id] <=> [$a->created, $a->source_id]);
|
||||||
|
$latest = $candidates[0];
|
||||||
|
$fields = array_column(json_decode($latest->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
|
||||||
|
$actual = trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''));
|
||||||
|
if ($actual === '') return '查件工单未填写查件类型和原因,待核实';
|
||||||
|
$evidence = '聚工单 ' . $latest->woNo . ' 查件类型/原因为“' . $actual . '”';
|
||||||
|
if (! in_array($actual, $allowedReasons, true)) return [['settlement_amount' => 0, 'evidence' => $evidence . ',不符合报价条件“' . $expected . '”,不计费']];
|
||||||
|
$evidence .= ',符合报价条件';
|
||||||
|
} 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, '.', '') . ' 元/单,按票计一次']];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按本批订单索引查询最新普通/淘系退回件,旧售后镜像补充历史;不限制进仓日期。 */
|
||||||
|
private function receivedReturns(array $orders, array $waybills): 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;
|
||||||
|
}
|
||||||
|
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
|
||||||
|
$schema = $db->getSchemaBuilder();
|
||||||
|
$hasReturnedParcels = $schema->hasTable('courier_returned_parcels');
|
||||||
|
$legacySources = array_filter([
|
||||||
|
['ops_jst_return_refund_info', 'ops_jst_return_refund_item'],
|
||||||
|
['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items'],
|
||||||
|
], fn ($tables) => $schema->hasTable($tables[0]) && $schema->hasTable($tables[1]));
|
||||||
|
$result = [];
|
||||||
|
foreach (array_chunk(array_keys($ids), 300) as $chunk) {
|
||||||
|
if ($hasReturnedParcels) {
|
||||||
|
$rows = $db->table('courier_returned_parcels')->whereIn('order_id', array_map('strval', $chunk))
|
||||||
|
->where('returned_qty', '>', 0)->whereNotNull('received_at')
|
||||||
|
->select('order_id', 'waybill')->selectRaw('MIN(received_at) AS received_at')
|
||||||
|
->groupBy('order_id', 'waybill')->orderBy('received_at')->get();
|
||||||
|
foreach ($rows as $row) $result[(string) $row->order_id] ??= $row->received_at
|
||||||
|
. (trim((string) $row->waybill) !== '' ? ';退回单号 ' . $row->waybill : '');
|
||||||
|
}
|
||||||
|
foreach ($legacySources as [$header, $items]) {
|
||||||
|
$remaining = array_values(array_filter($chunk, fn ($id) => ! isset($result[(string) $id])));
|
||||||
|
if ($remaining === []) break;
|
||||||
|
$rows = $db->table($header . ' as h')->join($items . ' as i', 'i.as_id', '=', 'h.as_id')
|
||||||
|
->whereIn('h.o_id', $remaining)->where('i.r_qty', '>', 0)->whereNotNull('i.receive_date')
|
||||||
|
->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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($hasReturnedParcels) {
|
||||||
|
$query = $db->table('courier_returned_parcels')->where('returned_qty', '>', 0)->whereNotNull('received_at');
|
||||||
|
foreach (WaybillMatch::find($query, 'waybill', $waybills, ['waybill', 'received_at']) as $number => $match) {
|
||||||
|
$records = $match['rows'];
|
||||||
|
usort($records, fn ($a, $b) => $a->received_at <=> $b->received_at);
|
||||||
|
$result['waybill:' . strtoupper($number)] = $records[0]->received_at . ';退回单号 ' . $records[0]->waybill
|
||||||
|
. ($match['exact'] ? '(精确匹配)' : '(模糊匹配:格式或T前缀)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -12,6 +12,9 @@ use RuntimeException;
|
|||||||
*/
|
*/
|
||||||
final class CourierBillMatcher
|
final class CourierBillMatcher
|
||||||
{
|
{
|
||||||
|
/** 这两家运费按我方核算结算,不能因合并分组而影响同组其他快递。 */
|
||||||
|
public const ACTUAL_FREIGHT_EXPRESSES = ['中铁物流', '武进安能'];
|
||||||
|
|
||||||
private ?AccessoryDeductions $deductions = null;
|
private ?AccessoryDeductions $deductions = null;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
@ -44,14 +47,20 @@ final class CourierBillMatcher
|
|||||||
|
|
||||||
$settled = [];
|
$settled = [];
|
||||||
foreach (array_chunk($waybills, 500) as $chunk) {
|
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) {
|
foreach ($db->table('courier_bill_ledger')->whereIn('waybill_no', $chunk)
|
||||||
$settled[strtoupper($row->waybill_no)] = $row->settle_month;
|
->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 = $this->unshipped->unshippedSources($waybills);
|
||||||
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
|
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
|
||||||
$shipping = $this->shipping->summaries($waybills);
|
$shipping = $this->shipping->summaries($waybills, $names);
|
||||||
|
foreach ($shipping as $key => $ship) {
|
||||||
|
if (($ship['data_source'] ?? null) !== '退件取件管理') continue;
|
||||||
|
unset($unshipped[$key]);
|
||||||
|
if (filled($ship['unshipped_source'] ?? null)) $unshipped[$key] = [$ship['unshipped_source']];
|
||||||
|
}
|
||||||
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
|
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
|
||||||
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
|
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
|
||||||
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
|
||||||
@ -77,7 +86,7 @@ final class CourierBillMatcher
|
|||||||
'calc_freight' => $ship['calc_freight'] ?? null,
|
'calc_freight' => $ship['calc_freight'] ?? null,
|
||||||
'charge_weight' => $ship['charge_weight'] ?? null,
|
'charge_weight' => $ship['charge_weight'] ?? null,
|
||||||
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
|
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
|
||||||
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution),
|
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution, $ship['express_name'] ?? null),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,7 +97,7 @@ final class CourierBillMatcher
|
|||||||
$unprovided[$row['waybill']] = $row;
|
$unprovided[$row['waybill']] = $row;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided));
|
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided), $names);
|
||||||
|
|
||||||
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
|
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
|
||||||
foreach ($updates as $id => $values) {
|
foreach ($updates as $id => $values) {
|
||||||
@ -147,13 +156,15 @@ final class CourierBillMatcher
|
|||||||
return [Category::DIFF, null];
|
return [Category::DIFF, null];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */
|
/** 人工处理优先;中铁物流、武进安能运费取核算值,其他正常应付取较低值,缺少核算依据保持空白。 */
|
||||||
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float
|
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution, ?string $expressName = null): ?float
|
||||||
{
|
{
|
||||||
return match ($resolution) {
|
return match ($resolution) {
|
||||||
'agree' => $billAmount === null ? null : (float) $billAmount,
|
'agree' => $billAmount === null ? null : (float) $billAmount,
|
||||||
'exclude', 'defer' => 0.0,
|
'exclude', 'defer' => 0.0,
|
||||||
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0,
|
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true)
|
||||||
|
? (in_array(trim((string) $expressName), self::ACTUAL_FREIGHT_EXPRESSES, true) ? $calcFreight
|
||||||
|
: ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight)) : 0.0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -168,14 +179,14 @@ final class CourierBillMatcher
|
|||||||
$db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void {
|
$db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void {
|
||||||
foreach (array_chunk($lineIds, 500) as $chunk) {
|
foreach (array_chunk($lineIds, 500) as $chunk) {
|
||||||
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk)
|
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk)
|
||||||
->get(['id', 'category', 'calc_freight', 'bill_amount']);
|
->get(['id', 'category', 'calc_freight', 'bill_amount', 'express_name']);
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
$db->table('courier_bill_lines')->where('id', $line->id)->update([
|
$db->table('courier_bill_lines')->where('id', $line->id)->update([
|
||||||
'resolution' => $resolution,
|
'resolution' => $resolution,
|
||||||
'resolved_by' => $resolution === null ? null : $user,
|
'resolved_by' => $resolution === null ? null : $user,
|
||||||
'resolved_at' => $resolution === null ? null : now(),
|
'resolved_at' => $resolution === null ? null : now(),
|
||||||
'self_amount' => self::selfAmount((string) $line->category,
|
'self_amount' => self::selfAmount((string) $line->category,
|
||||||
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution),
|
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution, $line->express_name),
|
||||||
]);
|
]);
|
||||||
$count++;
|
$count++;
|
||||||
}
|
}
|
||||||
@ -190,7 +201,7 @@ final class CourierBillMatcher
|
|||||||
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
|
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
|
||||||
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
|
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
|
||||||
*/
|
*/
|
||||||
public function refreshSummary(int $statementId): void
|
public function refreshSummary(int $statementId, bool $refreshSources = true): void
|
||||||
{
|
{
|
||||||
$db = self::db();
|
$db = self::db();
|
||||||
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
|
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
|
||||||
@ -249,17 +260,36 @@ final class CourierBillMatcher
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
|
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
|
||||||
$this->addAccessoryDeduction($statementId, $month, $items);
|
if ($refreshSources) {
|
||||||
|
$this->addAccessoryDeduction($statementId, $month, $items);
|
||||||
|
} else {
|
||||||
|
// 仅调整结算口径时,沿用已保存的配件扣款和补记账,不重新读取来源。
|
||||||
|
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->get() as $saved) {
|
||||||
|
if ($saved->label !== WeightDifferenceSubsidy::LABEL && in_array(SummaryMapper::classify($saved->label), ['AL', 'supplement'], true)) {
|
||||||
|
$items[$saved->label] = ['bill' => $saved->bill_amount, 'self' => $saved->self_amount, 'sort' => $saved->sort];
|
||||||
|
$kinds[$saved->label] = 'saved';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
|
||||||
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
|
||||||
|
$subsidy = app(WeightDifferenceSubsidy::class)->summary($statementId);
|
||||||
|
if ($subsidy['count'] > 0 && ! isset($manualLabels[WeightDifferenceSubsidy::LABEL])) {
|
||||||
|
$items[WeightDifferenceSubsidy::LABEL] = ['bill' => null, 'self' => $subsidy['amount'], 'sort' => 9200];
|
||||||
|
$kinds[WeightDifferenceSubsidy::LABEL] = 'weight-subsidy';
|
||||||
|
}
|
||||||
$kinds['配件补发扣款'] = 'accessory';
|
$kinds['配件补发扣款'] = 'accessory';
|
||||||
|
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
|
||||||
|
if ($refreshSources) $surchargeMatcher->courier($statementId);
|
||||||
|
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
|
||||||
|
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
|
||||||
$fees = $this->surchargeItems($statementId);
|
$fees = $this->surchargeItems($statementId);
|
||||||
$template = $this->templateFor($statementId);
|
$template = $this->templateFor($statementId);
|
||||||
|
if ($refreshSources) $this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
|
||||||
$sort = 8000;
|
$sort = 8000;
|
||||||
foreach ($fees as $item => $sum) {
|
foreach ($fees as $item => $sum) {
|
||||||
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
|
||||||
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填
|
$items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
|
||||||
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
|
|
||||||
$kinds[$item] = 'fee';
|
$kinds[$item] = 'fee';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -291,7 +321,7 @@ final class CourierBillMatcher
|
|||||||
foreach ($items as $name => $item) {
|
foreach ($items as $name => $item) {
|
||||||
$db->table('courier_bill_summary_items')->insert([
|
$db->table('courier_bill_summary_items')->insert([
|
||||||
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
|
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
|
||||||
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
|
'self_amount' => $item['self'] === null ? null : round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -301,6 +331,34 @@ final class CourierBillMatcher
|
|||||||
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 历史账单补接附加费时只更新费用行,保留原运费与手工小汇总。 */
|
||||||
|
public function refreshSurchargeSummary(int $statementId): void
|
||||||
|
{
|
||||||
|
$db=self::db();
|
||||||
|
$db->transaction(function()use($db,$statementId):void{
|
||||||
|
$statement=$db->table('courier_bill_statements')->where('id',$statementId)->lockForUpdate()->first();
|
||||||
|
if(!$statement||$statement->status==='confirmed')return;
|
||||||
|
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($statementId);
|
||||||
|
if(!$matcher->ready())return;
|
||||||
|
$sums=$matcher->query('courier',$statementId)->selectRaw('summary_label,SUM(bill_amount) AS bill,SUM(self_amount) AS self')
|
||||||
|
->groupBy('summary_label')->get();
|
||||||
|
$auto=[];foreach($sums as $sum)$auto[$sum->summary_label]=['bill'=>(float)$sum->bill,'self'=>(float)$sum->self,'kind'=>'fee'];
|
||||||
|
$template=$this->templateFor($statementId);
|
||||||
|
$rows=$template===null?array_map(fn($label,$v)=>['label'=>$label]+$v,array_keys($auto),array_values($auto))
|
||||||
|
:array_values(array_filter(SummaryTemplate::apply($template,$auto,(int)substr($statement->bill_month,5,2)),fn($r)=>$r['fee']));
|
||||||
|
foreach($rows as $row){
|
||||||
|
$existing=$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->where('label',$row['label'])->orderBy('id')->first();
|
||||||
|
if($existing){
|
||||||
|
if(!$existing->manual)$db->table('courier_bill_summary_items')->where('id',$existing->id)->update(['self_amount'=>round((float)$row['self'],2)]);
|
||||||
|
}else{
|
||||||
|
$sort=(int)$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->max('sort')+1;
|
||||||
|
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$statementId,'label'=>$row['label'],
|
||||||
|
'bill_amount'=>$row['bill'],'self_amount'=>round((float)$row['self'],2),'manual'=>false,'sort'=>$sort]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
|
||||||
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
|
||||||
@ -328,6 +386,38 @@ final class CourierBillMatcher
|
|||||||
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 补记账:按扣款月份各一行「补X月记账」(快递金额空、自算为补款金额),照模板落到「补9月记账」「2026.8-9月记账补款」「补记账」这类行。
|
||||||
|
* 已经手工加了补记账行时不再自动加,免得补两次;记账明细、复核还没导时不加。
|
||||||
|
*
|
||||||
|
* @param list<string>|null $template
|
||||||
|
* @param \Illuminate\Support\Collection<string,int> $manualLabels
|
||||||
|
* @param array<string,array{bill:?float,self:float,sort:int}> $items
|
||||||
|
* @param array<string,string> $kinds
|
||||||
|
*/
|
||||||
|
private function addRebooks(int $statementId, ?array $template, $manualLabels, array &$items, array &$kinds): void
|
||||||
|
{
|
||||||
|
foreach ($manualLabels->keys() as $label) {
|
||||||
|
if (Rebooks::isRebookLabel((string) $label)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$plan = app(Rebooks::class)->forStatement($statementId, $template);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$totals = Rebooks::totals($plan['rows']);
|
||||||
|
foreach (array_unique(array_column($plan['rows'], 'deduct_month')) as $deductMonth) {
|
||||||
|
$amount = $totals[$deductMonth] ?? 0.0;
|
||||||
|
$label = Rebooks::label($deductMonth);
|
||||||
|
$items[$label] = ['bill' => null, 'self' => $amount, 'sort' => 9100 + (int) substr($deductMonth, 5, 2)];
|
||||||
|
$kinds[$label] = 'rebook:' . (int) substr($deductMonth, 5, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */
|
/** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */
|
||||||
public function feeLabels(int $statementId): array
|
public function feeLabels(int $statementId): array
|
||||||
{
|
{
|
||||||
@ -379,7 +469,7 @@ final class CourierBillMatcher
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
|
||||||
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。
|
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
|
||||||
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
|
||||||
*
|
*
|
||||||
* @return array<string,float>
|
* @return array<string,float>
|
||||||
@ -394,9 +484,11 @@ final class CourierBillMatcher
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
$result = [];
|
$result = [];
|
||||||
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
|
$files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
|
||||||
foreach ($primaryIds as $fileId => $primaryId) {
|
foreach ($files as $file) {
|
||||||
$primary = (int) $primaryId;
|
$fileId = (int) $file->id;
|
||||||
|
$primary = (int) $file->statement_id;
|
||||||
|
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
|
||||||
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
|
||||||
if (! (clone $rows)->exists()) {
|
if (! (clone $rows)->exists()) {
|
||||||
continue;
|
continue;
|
||||||
@ -414,11 +506,14 @@ final class CourierBillMatcher
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void {
|
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
|
||||||
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
|
$assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId)
|
||||||
|
->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : [];
|
||||||
|
$shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all(), array_keys($names));
|
||||||
foreach ($chunk as $row) {
|
foreach ($chunk as $row) {
|
||||||
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
|
||||||
if (($names[$express] ?? $primary) !== $statementId) {
|
$owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary);
|
||||||
|
if ($owner !== $statementId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;
|
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;
|
||||||
|
|||||||
@ -54,6 +54,10 @@ final class CourierBillStore
|
|||||||
'weight_header' => self::blank($data['weight_header'] ?? null),
|
'weight_header' => self::blank($data['weight_header'] ?? null),
|
||||||
'updated_at' => now(),
|
'updated_at' => now(),
|
||||||
];
|
];
|
||||||
|
if (array_key_exists('rebook_months', $data)) {
|
||||||
|
// 补记账补几个月:空 = 按小汇总识别
|
||||||
|
$values['rebook_months'] = in_array($data['rebook_months'], [null, ''], true) ? null : min(max((int) $data['rebook_months'], 0), Rebooks::MAX_MONTHS);
|
||||||
|
}
|
||||||
if ($id === null) {
|
if ($id === null) {
|
||||||
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
|
||||||
}
|
}
|
||||||
@ -352,6 +356,41 @@ final class CourierBillStore
|
|||||||
return $ids;
|
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
|
public function assign(int $fileId, int $groupId): void
|
||||||
{
|
{
|
||||||
@ -384,6 +423,7 @@ final class CourierBillStore
|
|||||||
$db->transaction(function () use ($db, $file): void {
|
$db->transaction(function () use ($db, $file): void {
|
||||||
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
|
||||||
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
|
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
|
||||||
|
if(app(SurchargeSettlementMatcher::class)->ready())$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('file_id',$file->id)->delete();
|
||||||
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
$db->table('courier_bill_files')->where('id', $file->id)->delete();
|
||||||
});
|
});
|
||||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||||
@ -413,7 +453,7 @@ final class CourierBillStore
|
|||||||
* @param list<int> $groupIds
|
* @param list<int> $groupIds
|
||||||
* @param list<object> $groups
|
* @param list<object> $groups
|
||||||
*/
|
*/
|
||||||
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): int
|
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false, ?array $joint = null): int
|
||||||
{
|
{
|
||||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||||
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||||
@ -422,11 +462,11 @@ final class CourierBillStore
|
|||||||
$group = $groupIds !== []
|
$group = $groupIds !== []
|
||||||
? collect($groups)->firstWhere('id', $groupIds[0])
|
? collect($groups)->firstWhere('id', $groupIds[0])
|
||||||
: self::identify($name, $groups);
|
: 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([
|
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
|
||||||
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
|
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
|
||||||
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
|
||||||
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
|
'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
|
||||||
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
|
||||||
]);
|
]);
|
||||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||||
@ -435,17 +475,23 @@ final class CourierBillStore
|
|||||||
return $id;
|
return $id;
|
||||||
}
|
}
|
||||||
if ($group !== null) {
|
if ($group !== null) {
|
||||||
$this->ingest($id, $group);
|
$this->ingest($id, $group, false, $portal);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $id;
|
return $id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */
|
/** 读文件、写账单行到主分组的对账单,再按快递名称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();
|
$db = $this->db();
|
||||||
$file = $db->table('courier_bill_files')->find($fileId);
|
$file = $db->table('courier_bill_files')->find($fileId);
|
||||||
|
$joint = json_decode((string) $file->extra_group_ids, true)['joint_upload'] ?? null;
|
||||||
|
if ($joint !== null) {
|
||||||
|
$set = app(CourierJointUploads::class)->verify($joint);
|
||||||
|
$this->lockJointTargets($set['group_ids'], (string) $file->bill_month);
|
||||||
|
$portal = true;
|
||||||
|
}
|
||||||
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
|
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
|
||||||
if ($statement !== null && $statement->status === 'confirmed') {
|
if ($statement !== null && $statement->status === 'confirmed') {
|
||||||
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
|
||||||
@ -471,7 +517,7 @@ final class CourierBillStore
|
|||||||
$feeCount = 0;
|
$feeCount = 0;
|
||||||
$overlap = null;
|
$overlap = null;
|
||||||
try {
|
try {
|
||||||
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
|
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, $joint, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
|
||||||
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
|
||||||
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
|
||||||
}
|
}
|
||||||
@ -480,7 +526,9 @@ final class CourierBillStore
|
|||||||
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
|
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
|
||||||
}
|
}
|
||||||
$db->table('courier_bill_surcharges')->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) {
|
foreach ($this->parser->parse($path, $extension, $overrides) as $item) {
|
||||||
if ($item['type'] === 'sheet') {
|
if ($item['type'] === 'sheet') {
|
||||||
$sheets[] = isset($item['skipped'])
|
$sheets[] = isset($item['skipped'])
|
||||||
@ -550,7 +598,7 @@ final class CourierBillStore
|
|||||||
$db->table('courier_bill_surcharges')->insert($fees);
|
$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) {
|
} catch (Throwable $error) {
|
||||||
if ($reread) {
|
if ($reread) {
|
||||||
@ -581,7 +629,7 @@ final class CourierBillStore
|
|||||||
$notes[] = '没有找到含单号和运费列的工作表';
|
$notes[] = '没有找到含单号和运费列的工作表';
|
||||||
}
|
}
|
||||||
if ($feeCount > 0) {
|
if ($feeCount > 0) {
|
||||||
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2);
|
$notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
|
||||||
}
|
}
|
||||||
$unread = [];
|
$unread = [];
|
||||||
foreach ($sheets as $sheet) {
|
foreach ($sheets as $sheet) {
|
||||||
@ -629,6 +677,8 @@ final class CourierBillStore
|
|||||||
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
|
||||||
{
|
{
|
||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
|
$metadata = json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true);
|
||||||
|
if (isset($metadata['joint_upload'])) return $this->splitJoint($fileId, $month, $metadata['joint_upload']);
|
||||||
$groups = collect($this->groups());
|
$groups = collect($this->groups());
|
||||||
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
|
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
|
||||||
$bundle = trim((string) ($primary->bundle ?? ''));
|
$bundle = trim((string) ($primary->bundle ?? ''));
|
||||||
@ -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']);
|
$lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']);
|
||||||
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all());
|
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all(),
|
||||||
|
array_values(array_unique([...array_keys($own), ...array_keys($byName)])));
|
||||||
$moves = [];
|
$moves = [];
|
||||||
$strangers = [];
|
$strangers = [];
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
@ -709,6 +760,56 @@ final class CourierBillStore
|
|||||||
return implode(';', $parts);
|
return implode(';', $parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 只在签名授权范围内逐批归组;任何无法归属的行整份退回,避免留在错误的主分组。 */
|
||||||
|
private function splitJoint(int $fileId, string $month, array $scope): string
|
||||||
|
{
|
||||||
|
$db = $this->db();
|
||||||
|
$set = app(CourierJointUploads::class)->verify($scope);
|
||||||
|
$this->lockJointTargets($set['group_ids'], $month);
|
||||||
|
$owners = [];
|
||||||
|
$statements = [];
|
||||||
|
foreach ($set['groups'] as $g) {
|
||||||
|
foreach (array_intersect(array_unique([$g->name, ...$g->express_names]), $set['names']) as $name) {
|
||||||
|
if (isset($owners[$name]) && $owners[$name] !== (int) $g->id) throw new RuntimeException('联合上传快递名称重复,请联系财务。');
|
||||||
|
$owners[$name] = (int) $g->id;
|
||||||
|
}
|
||||||
|
$statement = $db->table('courier_bill_statements')->where('group_id', $g->id)->where('bill_month', $month)->first();
|
||||||
|
if ($statement !== null) $statements[(int) $g->id] = (int) $statement->id;
|
||||||
|
}
|
||||||
|
$counts = [];
|
||||||
|
$db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void {
|
||||||
|
$shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all(), array_keys($owners));
|
||||||
|
$moves = [];
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$raw = json_decode((string) $line->raw, true);
|
||||||
|
$declared = trim((string) ($raw[4] ?? ''));
|
||||||
|
if ($declared !== '' && ! isset($owners[$declared])) throw new RuntimeException('第 ' . $line->row_no . ' 行快递名称不在本链接范围内。整份文件未读入。');
|
||||||
|
$name = trim((string) ($shipping[strtoupper($line->waybill_no)]['express_name'] ?? ''));
|
||||||
|
if ($name === '') $name = $declared;
|
||||||
|
$groupId = $owners[$name] ?? null;
|
||||||
|
if ($groupId === null) throw new RuntimeException('第 ' . $line->row_no . ' 行单号 ' . $line->waybill_no . ' 无法归到本链接范围;系统查不到时请填写范围内的快递名称。整份文件未读入。');
|
||||||
|
$statements[$groupId] ??= (int) $db->table('courier_bill_statements')->insertGetId([
|
||||||
|
'group_id' => $groupId, 'bill_month' => $month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
$moves[$statements[$groupId]][] = (int) $line->id;
|
||||||
|
$counts[$groupId] = ($counts[$groupId] ?? 0) + 1;
|
||||||
|
}
|
||||||
|
foreach ($moves as $statementId => $ids) $db->table('courier_bill_lines')->whereIn('id', $ids)->update(['statement_id' => $statementId]);
|
||||||
|
});
|
||||||
|
// 附加费沿用同单号的运费归属,不把找不到归属的费用默认塞给主分组。
|
||||||
|
$missingFee = $db->table('courier_bill_surcharges as fee')->where('fee.file_id', $fileId)
|
||||||
|
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('courier_bill_lines as line')
|
||||||
|
->whereColumn('line.file_id', 'fee.file_id')->whereColumn('line.waybill_no', 'fee.waybill_no'))->first();
|
||||||
|
if ($missingFee !== null) throw new RuntimeException('附加费单号 ' . $missingFee->waybill_no . ' 缺少对应运费明细,无法确定分组。整份文件未读入。');
|
||||||
|
$ambiguous = $db->table('courier_bill_lines')->where('file_id', $fileId)->groupBy('waybill_no')
|
||||||
|
->havingRaw('COUNT(DISTINCT statement_id) > 1')->first(['waybill_no']);
|
||||||
|
if ($ambiguous !== null) throw new RuntimeException('单号 ' . $ambiguous->waybill_no . ' 填写了不同快递名称,请核对。整份文件未读入。');
|
||||||
|
$notes = [];
|
||||||
|
foreach ($set['groups'] as $g) if (isset($counts[$g->id])) $notes[] = $g->name . ' ' . $counts[$g->id] . ' 行';
|
||||||
|
|
||||||
|
return '联合上传已归组:' . implode('、', $notes);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
|
||||||
* 涉及的对账单有已确认结算的就不动。
|
* 涉及的对账单有已确认结算的就不动。
|
||||||
@ -914,7 +1015,7 @@ final class CourierBillStore
|
|||||||
return $files;
|
return $files;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 确认结算:锁定对账单,结算台账记下这批单号。 */
|
/** 确认结算:锁定对账单,结算台账记下这批单号;这期补记账补的单记进补记账台账(补过的不再补)。 */
|
||||||
public function confirm(int $statementId, string $user): void
|
public function confirm(int $statementId, string $user): void
|
||||||
{
|
{
|
||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
@ -947,6 +1048,9 @@ final class CourierBillStore
|
|||||||
if ($buffer !== []) {
|
if ($buffer !== []) {
|
||||||
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
|
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
|
||||||
}
|
}
|
||||||
|
$rebooks = app(Rebooks::class);
|
||||||
|
$rebooks->forget((int) $statement->id);
|
||||||
|
$rebooks->record((int) $statement->id);
|
||||||
$db->table('courier_bill_statements')->where('id', $statement->id)->update([
|
$db->table('courier_bill_statements')->where('id', $statement->id)->update([
|
||||||
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
|
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
@ -958,6 +1062,7 @@ final class CourierBillStore
|
|||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
$db->transaction(function () use ($db, $statementId): void {
|
$db->transaction(function () use ($db, $statementId): void {
|
||||||
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
|
||||||
|
app(Rebooks::class)->forget($statementId);
|
||||||
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
$db->table('courier_bill_statements')->where('id', $statementId)->update([
|
||||||
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
@ -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
|
public function importLedger(string $path, string $extension): array
|
||||||
{
|
{
|
||||||
$groups = collect($this->groups())->keyBy('name');
|
|
||||||
$reader = new BillWorkbookReader();
|
$reader = new BillWorkbookReader();
|
||||||
$rows = 0;
|
$rows = 0;
|
||||||
$inserted = 0;
|
$inserted = 0;
|
||||||
$rejected = 0;
|
$rejected = 0;
|
||||||
$unknown = [];
|
|
||||||
$buffer = [];
|
$buffer = [];
|
||||||
$flush = function () use (&$buffer, &$inserted): void {
|
$flush = function () use (&$buffer, &$inserted): void {
|
||||||
if ($buffer !== []) {
|
if ($buffer !== []) {
|
||||||
@ -1112,32 +1219,26 @@ final class CourierBillStore
|
|||||||
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
|
$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))
|
$find = static fn (array $names): ?int => collect($names)->map(static fn ($n) => array_search($n, $header, true))
|
||||||
->first(static fn ($i) => $i !== false);
|
->first(static fn ($i) => $i !== false);
|
||||||
$columns = ['group' => $find(['分组', '对账分组']), 'waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
$columns = ['waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
||||||
'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])];
|
'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])];
|
||||||
if ($columns['group'] === null || $columns['waybill'] === null || $columns['month'] === null) {
|
if ($columns['waybill'] === null || $columns['month'] === null) {
|
||||||
throw new RuntimeException('表头须含「分组」「单号」「结算月份」三列(金额可选)。');
|
throw new RuntimeException('表头须含「单号」「结算月份」两列(金额可选)。');
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$groupName = trim((string) ($row[$columns['group']] ?? ''));
|
|
||||||
$waybillRaw = trim((string) ($row[$columns['waybill']] ?? ''));
|
$waybillRaw = trim((string) ($row[$columns['waybill']] ?? ''));
|
||||||
if ($groupName === '' && $waybillRaw === '') {
|
$monthRaw = trim((string) ($row[$columns['month']] ?? ''));
|
||||||
|
if ($waybillRaw === '' && $monthRaw === '') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$rows++;
|
$rows++;
|
||||||
$group = $groups->get($groupName);
|
|
||||||
if ($group === null) {
|
|
||||||
$unknown[$groupName] = true;
|
|
||||||
$rejected++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$waybill = Waybill::normalize($waybillRaw);
|
$waybill = Waybill::normalize($waybillRaw);
|
||||||
$month = self::month((string) ($row[$columns['month']] ?? ''));
|
$month = self::month($monthRaw);
|
||||||
if ($waybill === null || $month === null) {
|
if ($waybill === null || $month === null) {
|
||||||
$rejected++;
|
$rejected++;
|
||||||
continue;
|
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),
|
'amount' => $columns['amount'] === null ? null : BillParser::number($row[$columns['amount']] ?? null),
|
||||||
'statement_id' => null, 'created_at' => now()];
|
'statement_id' => null, 'created_at' => now()];
|
||||||
if (count($buffer) >= 500) {
|
if (count($buffer) >= 500) {
|
||||||
@ -1148,7 +1249,7 @@ final class CourierBillStore
|
|||||||
}
|
}
|
||||||
$flush();
|
$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
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
294
app/Support/CourierBills/FreightConfirmation.php
Normal file
294
app/Support/CourierBills/FreightConfirmation.php
Normal file
@ -0,0 +1,294 @@
|
|||||||
|
<?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',
|
||||||
|
'warehouse', 'calc', 'bill_weight', 'charge_weight', 'settlement_weight', 'weight_diff',
|
||||||
|
'diff_kind', 'settle', 'freight_diff', 'diff', 'status_month', 'formula', 'ship_waybill',
|
||||||
|
'file_id', 'sheet', 'row_no',
|
||||||
|
]));
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Support\CourierBills;
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use App\Business\CourierContractPageData;
|
||||||
use Illuminate\Database\ConnectionInterface;
|
use Illuminate\Database\ConnectionInterface;
|
||||||
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
|
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
@ -38,7 +39,10 @@ final class PayableSummary
|
|||||||
/** 有对账单时由小汇总覆盖的列。 */
|
/** 有对账单时由小汇总覆盖的列。 */
|
||||||
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
|
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
|
||||||
|
|
||||||
public function __construct(private readonly CourierInformationMirrorRepository $couriers) {}
|
public function __construct(
|
||||||
|
private readonly CourierInformationMirrorRepository $couriers,
|
||||||
|
private readonly CourierContractPageData $contractDates,
|
||||||
|
) {}
|
||||||
|
|
||||||
public function db(): ConnectionInterface
|
public function db(): ConnectionInterface
|
||||||
{
|
{
|
||||||
@ -66,6 +70,7 @@ final class PayableSummary
|
|||||||
report($error);
|
report($error);
|
||||||
$contracts = [];
|
$contracts = [];
|
||||||
}
|
}
|
||||||
|
$contractDates = $this->contractDates->datesByCourierNames($stored->pluck('carrier')->all());
|
||||||
$today = now()->toDateString();
|
$today = now()->toDateString();
|
||||||
$rows = [];
|
$rows = [];
|
||||||
foreach ($stored as $row) {
|
foreach ($stored as $row) {
|
||||||
@ -77,6 +82,9 @@ final class PayableSummary
|
|||||||
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
|
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
|
||||||
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
|
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
|
||||||
}
|
}
|
||||||
|
$dates = $contractDates[$row->carrier] ?? [];
|
||||||
|
$cells['A'] = $dates['start_date'] ?? ($cells['A'] ?? null);
|
||||||
|
$cells['B'] = $dates['end_date'] ?? ($cells['B'] ?? null);
|
||||||
$mine = $statements[$row->carrier] ?? [];
|
$mine = $statements[$row->carrier] ?? [];
|
||||||
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
|
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
|
||||||
// 新建的月份金额是空的,才用对账单的小汇总填。
|
// 新建的月份金额是空的,才用对账单的小汇总填。
|
||||||
@ -189,6 +197,10 @@ final class PayableSummary
|
|||||||
throw new RuntimeException(self::COLUMNS[$column] . '须为数字。');
|
throw new RuntimeException(self::COLUMNS[$column] . '须为数字。');
|
||||||
}
|
}
|
||||||
$cells[$column] = $number;
|
$cells[$column] = $number;
|
||||||
|
if ($column === 'S') {
|
||||||
|
// 手工实付(含 0)优先保留;清空后恢复按应付金额自动带出。
|
||||||
|
$cells['_paid_manual'] = $number !== null;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
$cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500);
|
$cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500);
|
||||||
}
|
}
|
||||||
|
|||||||
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)];
|
||||||
|
}
|
||||||
|
}
|
||||||
138
app/Support/CourierBills/RebookReturns.php
Normal file
138
app/Support/CourierBills/RebookReturns.php
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
<?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[$number] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$db = Rebooks::db();
|
||||||
|
$available = $wanted !== [] && Schema::connection($db->getName())->hasTable('courier_returned_parcels');
|
||||||
|
$found = [];
|
||||||
|
if ($available) {
|
||||||
|
$found = WaybillMatch::find($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
|
||||||
|
->whereNotNull('received_at'), 'waybill', array_keys($wanted), ['waybill', 'received_at']);
|
||||||
|
}
|
||||||
|
$byOrder = [];
|
||||||
|
$orderIds = [];
|
||||||
|
$sourceOrders = [];
|
||||||
|
$fallbackNumbers = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$numbers = self::numbers($row);
|
||||||
|
if (!$available || empty($row['product_code']) || array_intersect($numbers, array_keys($found)) !== []) continue;
|
||||||
|
foreach ($numbers as $number) $fallbackNumbers[$number]=true;
|
||||||
|
$order = trim((string)($row['internal_order_id'] ?? $row['o_id'] ?? ''));
|
||||||
|
$online=trim((string)($row['online_order_no']??$row['trade_no']??''));
|
||||||
|
if ($order !== '' && $online !== '') $orderIds[$order.'|'.$online]=true;
|
||||||
|
}
|
||||||
|
// 通过原发货包裹明确的内部订单号匹配,不能把同一线上订单的补发包裹互相抵扣。
|
||||||
|
if ($fallbackNumbers !== [] && Schema::connection($db->getName())->hasTable('js_jst_order_express_details')) {
|
||||||
|
$packageKeys = [];
|
||||||
|
foreach (array_chunk(array_keys($fallbackNumbers),250) as $chunk) {
|
||||||
|
$aliases = [];
|
||||||
|
foreach ($chunk as $number) {
|
||||||
|
$key=self::key($number);
|
||||||
|
foreach ([$number, $key, '@'.$key, 'T'.$key, '@T'.$key] as $alias) $aliases[]=$alias;
|
||||||
|
}
|
||||||
|
$aliases = array_values(array_unique(array_map('strval', $aliases)));
|
||||||
|
// 运单索引定位包裹,随后只按主键读宽镜像,避免扫描数百万行 logistic_id。
|
||||||
|
foreach ($db->table('jst_oms_shipping')->whereIn('express_no',$aliases)
|
||||||
|
->distinct()->get(['source_id','express_no']) as $ship) {
|
||||||
|
$packageKeys[(int)$ship->source_id][self::key((string)$ship->express_no)]=true;
|
||||||
|
}
|
||||||
|
foreach ($db->table('courier_unshipped_waybills')->where('source','replacement')->whereIn('waybill_no',$aliases)
|
||||||
|
->get(['evidence_no','waybill_no']) as $replacement) {
|
||||||
|
if(preg_match('/^shipping:(\d+)$/',$replacement->evidence_no,$m))$packageKeys[(int)$m[1]][self::key($replacement->waybill_no)]=true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (array_chunk(array_keys($packageKeys),500) as $chunk) {
|
||||||
|
foreach ($db->table('js_jst_order_express_details')->whereIn('id',$chunk)->get(['id','inner_order_id','so_id']) as $source) {
|
||||||
|
if (!$source->inner_order_id || !$source->so_id) continue;
|
||||||
|
$orderKey=$source->inner_order_id.'|'.$source->so_id;
|
||||||
|
$orderIds[$orderKey]=true;
|
||||||
|
foreach ($packageKeys[(int)$source->id] as $key=>$_) $sourceOrders[$key][$orderKey]=true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($available && $orderIds !== [] && Schema::connection($db->getName())->hasColumns('courier_returned_parcels', ['order_id','online_order_no','sku'])) {
|
||||||
|
// 用内部订单索引缩小范围,两来源同数字键均参与,不全表扫描。
|
||||||
|
$ids=array_unique(array_map(fn($key)=>explode('|',$key,2)[0],array_keys($orderIds)));
|
||||||
|
foreach (array_chunk($ids,200) as $chunk) {
|
||||||
|
foreach ($db->table('courier_returned_parcels')->whereIn('order_id',$chunk)
|
||||||
|
->where('returned_qty','>',0)->whereNotNull('received_at')
|
||||||
|
->cursor(['waybill','received_at','order_id','online_order_no','sku']) as $record) {
|
||||||
|
$order=$record->order_id.'|'.$record->online_order_no;
|
||||||
|
$sku=trim((string)$record->sku);
|
||||||
|
if(isset($orderIds[$order]) && $sku!=='')$byOrder[$order][$sku][]=[
|
||||||
|
'waybill'=>trim((string)$record->waybill),'received_at'=>(string)$record->received_at];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($rows as &$row) {
|
||||||
|
$exact = $fuzzy = [];
|
||||||
|
foreach (self::numbers($row) as $number) {
|
||||||
|
$match = $found[$number] ?? [];
|
||||||
|
foreach ($match['rows'] ?? [] as $record) {
|
||||||
|
$value = ['waybill' => $record->waybill, 'received_at' => $record->received_at];
|
||||||
|
if ($match['exact']) $exact[] = $value;
|
||||||
|
else $fuzzy[] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$fuzzy = $exact === [] ? WaybillMatch::uniqueFuzzy($fuzzy) : [];
|
||||||
|
$matches = $exact ?: $fuzzy;
|
||||||
|
$orderMatches=[];
|
||||||
|
if($matches===[]){
|
||||||
|
$orders=[];$explicit=trim((string)($row['internal_order_id']??$row['o_id']??''));
|
||||||
|
$online=trim((string)($row['online_order_no']??$row['trade_no']??''));
|
||||||
|
if($explicit!=='' && $online!=='')$orders[$explicit.'|'.$online]=true;
|
||||||
|
foreach(self::numbers($row) as $number)foreach(array_keys($sourceOrders[self::key($number)]??[]) as $order)$orders[$order]=true;
|
||||||
|
$sku=trim((string)($row['product_code']??''));
|
||||||
|
if(count($orders)===1 && $sku!=='')$orderMatches=$byOrder[(string)array_key_first($orders)][$sku]??[];
|
||||||
|
$matches=$orderMatches;
|
||||||
|
}
|
||||||
|
$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前缀)' : ($orderMatches!==[]?'原内部订单及商品匹配':''));
|
||||||
|
$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
|
||||||
|
{
|
||||||
|
return WaybillMatch::key($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));
|
||||||
|
}
|
||||||
|
}
|
||||||
40
app/Support/CourierBills/SettlementComparison.php
Normal file
40
app/Support/CourierBills/SettlementComparison.php
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
/** 对账展示和导出统一使用最终结算口径,保留原核算字段。 */
|
||||||
|
final class SettlementComparison
|
||||||
|
{
|
||||||
|
public static function difference(mixed $billed, mixed $settled, int $precision = 2): ?float
|
||||||
|
{
|
||||||
|
return $billed === null || $settled === null ? null
|
||||||
|
: round(round((float) $billed, $precision) - round((float) $settled, $precision), $precision);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function weight(mixed $billFreight, mixed $calcFreight, mixed $billWeight, mixed $chargeWeight, mixed $settled): ?float
|
||||||
|
{
|
||||||
|
if ($settled === null) return null;
|
||||||
|
if ($billFreight !== null && $calcFreight !== null && (float) $billFreight < (float) $calcFreight
|
||||||
|
&& round((float) $settled, 2) === round((float) $billFreight, 2)) {
|
||||||
|
return $billWeight === null ? null : (float) $billWeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $chargeWeight === null ? null : (float) $chargeWeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{settlement_weight:?float,weight_diff:?float,freight_diff:?float} */
|
||||||
|
public static function courier(object $line): array
|
||||||
|
{
|
||||||
|
$weight = match ($line->resolution) {
|
||||||
|
'agree' => $line->bill_weight === null ? null : (float) $line->bill_weight,
|
||||||
|
'exclude', 'defer' => 0.0,
|
||||||
|
default => in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)
|
||||||
|
? (in_array(trim((string) ($line->express_name ?? '')), CourierBillMatcher::ACTUAL_FREIGHT_EXPRESSES, true)
|
||||||
|
? ($line->self_amount === null || $line->charge_weight === null ? null : (float) $line->charge_weight)
|
||||||
|
: self::weight($line->bill_amount, $line->calc_freight, $line->bill_weight, $line->charge_weight, $line->self_amount)) : null,
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['settlement_weight' => $weight, 'weight_diff' => self::difference($line->bill_weight, $weight, 4),
|
||||||
|
'freight_diff' => self::difference($line->bill_amount, $line->self_amount)];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -34,6 +34,8 @@ final class ShippingLookup
|
|||||||
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
|
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
|
||||||
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
|
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
|
||||||
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
|
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
|
||||||
|
'data_source' => '数据来源',
|
||||||
|
'origin_state' => '始发省', 'origin_city' => '始发市',
|
||||||
];
|
];
|
||||||
|
|
||||||
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
|
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
|
||||||
@ -56,7 +58,7 @@ final class ShippingLookup
|
|||||||
* @param list<string> $waybills
|
* @param list<string> $waybills
|
||||||
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
|
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
|
||||||
*/
|
*/
|
||||||
public function summaries(array $waybills): array
|
public function summaries(array $waybills, array $expressNames = []): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
||||||
@ -100,6 +102,11 @@ final class ShippingLookup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (app(ReturnPickupLookup::class)->details($waybills, $expressNames) as $key => $row) {
|
||||||
|
$result[$key] = ['ship_time' => $row['ship_time'], 'express_name' => $row['express_name1'],
|
||||||
|
'calc_freight' => $row['qc_freight'], 'charge_weight' => $row['qc_charge_weight'],
|
||||||
|
'data_source' => $row['data_source'], 'unshipped_source' => $row['_unshipped'] ?? null];
|
||||||
|
}
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,7 +116,7 @@ final class ShippingLookup
|
|||||||
* @param list<string> $waybills
|
* @param list<string> $waybills
|
||||||
* @return array<string,array<string,mixed>> 键为大写单号
|
* @return array<string,array<string,mixed>> 键为大写单号
|
||||||
*/
|
*/
|
||||||
public function details(array $waybills): array
|
public function details(array $waybills, array $expressNames = []): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
|
||||||
@ -189,7 +196,7 @@ final class ShippingLookup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $result;
|
return array_replace($result, app(ReturnPickupLookup::class)->details($waybills, $expressNames));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -203,6 +210,9 @@ final class ShippingLookup
|
|||||||
if ($expressNames === []) {
|
if ($expressNames === []) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
yield from app(ReturnPickupLookup::class)->monthWaybills($expressNames, $month);
|
||||||
|
$expressNames = array_values(array_diff($expressNames, array_values(ReturnPickupLookup::CARRIERS)));
|
||||||
|
if ($expressNames === []) return;
|
||||||
// 按天走 ship_time 索引,单次只扫一天的发货行。
|
// 按天走 ship_time 索引,单次只扫一天的发货行。
|
||||||
$day = strtotime($month . '-01');
|
$day = strtotime($month . '-01');
|
||||||
$end = strtotime($month . '-01 +1 month');
|
$end = strtotime($month . '-01 +1 month');
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
namespace App\Support\CourierBills;
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Modules\EcommerceFinance\Services\CourierBookkeepingRegistry;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
||||||
@ -10,15 +11,15 @@ use Illuminate\Support\Facades\Storage;
|
|||||||
* 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、
|
* 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、
|
||||||
* 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。
|
* 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。
|
||||||
*
|
*
|
||||||
* 对账类子表的列顺序:快递原始列 → 财务指定的 25 列 → 发货数据其余字段 → 处理结果。
|
* 对账类子表的列顺序:快递原始列 → 核算及结算对比列 → 发货数据其余字段 → 处理结果。
|
||||||
*/
|
*/
|
||||||
final class StatementExporter
|
final class StatementExporter
|
||||||
{
|
{
|
||||||
/** 财务指定的 25 列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */
|
/** 对账列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */
|
||||||
public const FRONT = [
|
public const FRONT = [
|
||||||
'称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no',
|
'称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no',
|
||||||
'交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty',
|
'交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty',
|
||||||
'计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '重量差' => '_weight_diff',
|
'计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '结算重量' => '_settlement_weight', '重量差' => '_weight_diff',
|
||||||
'运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name',
|
'运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name',
|
||||||
'店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time',
|
'店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time',
|
||||||
'未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight',
|
'未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight',
|
||||||
@ -64,6 +65,8 @@ final class StatementExporter
|
|||||||
{
|
{
|
||||||
$db = CourierBillMatcher::db();
|
$db = CourierBillMatcher::db();
|
||||||
$ids = $this->related($statementId);
|
$ids = $this->related($statementId);
|
||||||
|
$expressNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||||
|
->whereIn('s.id', $ids)->pluck('g.express_names')->flatMap(fn ($value) => (array) json_decode((string) $value, true))->unique()->values()->all();
|
||||||
$multi = count($ids) > 1;
|
$multi = count($ids) > 1;
|
||||||
$groupNames = [];
|
$groupNames = [];
|
||||||
$book = new StreamingWorkbook();
|
$book = new StreamingWorkbook();
|
||||||
@ -91,7 +94,8 @@ final class StatementExporter
|
|||||||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||||||
$bill = 0.0;
|
$bill = 0.0;
|
||||||
$self = 0.0;
|
$self = 0.0;
|
||||||
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
|
$items = app(SurchargeSettlementMatcher::class)->summaryItems($id,$db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get());
|
||||||
|
foreach (app(Rebooks::class)->summaryItems($id, $items) as $item) {
|
||||||
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
||||||
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
||||||
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
||||||
@ -104,8 +108,14 @@ final class StatementExporter
|
|||||||
$groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : [];
|
$groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : [];
|
||||||
|
|
||||||
[$sources, $original] = $this->originalHeaders($ids);
|
[$sources, $original] = $this->originalHeaders($ids);
|
||||||
|
$front = [];
|
||||||
|
foreach (self::FRONT as $label => $field) {
|
||||||
|
$front[$label] = $field;
|
||||||
|
if ($field === '_settlement_weight') $front['结算运费'] = '_settlement';
|
||||||
|
}
|
||||||
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
|
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
|
||||||
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail];
|
$rest['settle_freight'] = '发货数据结算运费';
|
||||||
|
$fullHeader = [...$original, ...array_keys($front), ...array_values($rest), '差异原因', '处理结果', ...$tail];
|
||||||
|
|
||||||
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
|
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
|
||||||
$originals = $this->writeOriginal($book, $files, $baseFileId);
|
$originals = $this->writeOriginal($book, $files, $baseFileId);
|
||||||
@ -119,16 +129,20 @@ final class StatementExporter
|
|||||||
}
|
}
|
||||||
foreach ($sheets as $name => $filter) {
|
foreach ($sheets as $name => $filter) {
|
||||||
$headerWritten = false;
|
$headerWritten = false;
|
||||||
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void {
|
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $front, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void {
|
||||||
if (! $headerWritten) {
|
if (! $headerWritten) {
|
||||||
$book->row($name, $fullHeader, true);
|
$book->row($name, $fullHeader, true);
|
||||||
$headerWritten = true;
|
$headerWritten = true;
|
||||||
}
|
}
|
||||||
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines));
|
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines), $expressNames);
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
||||||
$cells = $this->originalCells($line, $sources, $original);
|
$cells = $this->originalCells($line, $sources, $original);
|
||||||
foreach (self::FRONT as $field) {
|
foreach ($front as $field) {
|
||||||
|
if ($field === '_settlement') {
|
||||||
|
$cells[] = $line->self_amount === null ? null : (float) $line->self_amount;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$cells[] = $this->front($field, $line, $ship);
|
$cells[] = $this->front($field, $line, $ship);
|
||||||
}
|
}
|
||||||
foreach (array_keys($rest) as $field) {
|
foreach (array_keys($rest) as $field) {
|
||||||
@ -163,22 +177,158 @@ final class StatementExporter
|
|||||||
// 未提供:发货数据有、账单没有
|
// 未提供:发货数据有、账单没有
|
||||||
$headerWritten = false;
|
$headerWritten = false;
|
||||||
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
|
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
|
||||||
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void {
|
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, $expressNames, &$headerWritten): void {
|
||||||
if (! $headerWritten) {
|
if (! $headerWritten) {
|
||||||
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
|
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
|
||||||
$headerWritten = true;
|
$headerWritten = true;
|
||||||
}
|
}
|
||||||
$details = $this->shipping->details($rows->pluck('waybill_no')->all());
|
$details = $this->shipping->details($rows->pluck('waybill_no')->all(), $expressNames);
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
|
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
|
||||||
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
|
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
|
||||||
|
$subsidy = app(WeightDifferenceSubsidy::class);
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
if (! $db->table('courier_bill_summary_items')->where('statement_id', $id)->where('label', WeightDifferenceSubsidy::LABEL)->where('manual', false)->exists()) continue;
|
||||||
|
$summary = $subsidy->summary($id);
|
||||||
|
if ($summary['count'] === 0) continue;
|
||||||
|
$sheet = '重量差补款-' . $id;
|
||||||
|
$book->row($sheet, ['快递单号', '快递重量', '我方计费重量', '重量差(快递-我方)', '快递运费', '核算运费', '可补运费差额'], true);
|
||||||
|
foreach ($subsidy->query($id)->orderBy('id')->lazyById(500) as $line) {
|
||||||
|
$book->row($sheet, [$line->waybill_no, (float) $line->bill_weight, (float) $line->charge_weight,
|
||||||
|
round((float) $line->bill_weight - (float) $line->charge_weight, 4), (float) $line->bill_amount,
|
||||||
|
(float) $line->calc_freight, round((float) $line->bill_amount - (float) $line->calc_freight, 4)]);
|
||||||
|
}
|
||||||
|
$book->row($sheet, ['差额合计', null, null, null, null, null, $summary['difference']], true);
|
||||||
|
$book->row($sheet, ['差额合计×50%,补给快递', null, null, null, null, null, $summary['amount']], true);
|
||||||
|
}
|
||||||
|
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
|
||||||
$this->writeNotes($book, $ids, $originals);
|
$this->writeNotes($book, $ids, $originals);
|
||||||
$book->writeTo($output);
|
$book->writeTo($output);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 补记账子表:全部历史记账及本期差额(已补记录不重复计入),表名照手工版「补9月记账」「2026.8-9月记账补款」。
|
||||||
|
*
|
||||||
|
* @param list<int> $ids
|
||||||
|
* @param list<string> $tail
|
||||||
|
* @param array<int,string> $groupNames
|
||||||
|
*/
|
||||||
|
private function writeRebooks(StreamingWorkbook $book, array $ids, array $tail, array $groupNames, bool $multi): void
|
||||||
|
{
|
||||||
|
$plans = [];
|
||||||
|
$window = [];
|
||||||
|
foreach ($ids as $id) {
|
||||||
|
try {
|
||||||
|
$plan = app(Rebooks::class)->forStatement($id);
|
||||||
|
} catch (\Throwable $error) {
|
||||||
|
report($error);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($plan['window'] !== []) {
|
||||||
|
// 全部历史记账都展示,已补、未退回等仅供核对,不重复计入本期金额。
|
||||||
|
$plans[$id] = $plan['rows'];
|
||||||
|
$window = array_values(array_unique([...$window, ...$plan['window']]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($plans === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sort($window);
|
||||||
|
$name = Rebooks::sheetName($window);
|
||||||
|
$fields = ['summary_month' => ['label' => '月份', 'type' => 'text']];
|
||||||
|
foreach (app(CourierBookkeepingRegistry::class)->fields() as $field => $definition) {
|
||||||
|
$fields[$field] = $definition;
|
||||||
|
if ($field === 'settle_bookkeeping') {
|
||||||
|
$fields['current_bookkeeping'] = ['label' => '现结算记账金额', 'type' => 'number'];
|
||||||
|
$fields['rebook_amount'] = ['label' => '需补款记账金额', 'type' => 'number'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (['return_status' => '退回核对状态', 'return_match' => '退回匹配方式', 'matched_return' => '匹配退回单号',
|
||||||
|
'received_at' => '退回进仓时间', 'refund_status' => '补款状态'] as $field => $label) {
|
||||||
|
$fields[$field] = ['label' => $label, 'type' => 'text'];
|
||||||
|
}
|
||||||
|
$fields['refunded'] = ['label' => '历史已补金额', 'type' => 'number'];
|
||||||
|
$fields['payable_refund'] = ['label' => '本期补款金额', 'type' => 'number'];
|
||||||
|
$book->row($name, [...array_column($fields, 'label'), ...$tail], true);
|
||||||
|
$rowNumber = 1;
|
||||||
|
$settleColumn = array_search('settle_bookkeeping', array_keys($fields), true) + 1;
|
||||||
|
$currentColumn = $settleColumn + 1;
|
||||||
|
foreach ($plans as $id => $rows) {
|
||||||
|
foreach ($rows as $r) {
|
||||||
|
$sources = $r['info']['_rebook_sources'] ?? [$r['info']];
|
||||||
|
$remainingCurrent = (float) ($r['current'] ?? $r['deducted']);
|
||||||
|
$remainingRefund = (float) $r['amount'];
|
||||||
|
$last = array_key_last($sources);
|
||||||
|
$automatic = $r['info']['_automatic_current'] ?? false;
|
||||||
|
$weights = [];
|
||||||
|
foreach ($sources as $index => $source) {
|
||||||
|
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
|
||||||
|
$weights[$index] = $automatic ? max(0, round($old - (float) ($source['_return_current'] ?? $old), 2)) : max(0, $old);
|
||||||
|
}
|
||||||
|
$totalWeight = array_sum($weights);
|
||||||
|
$lastRefund = array_key_last(array_filter($weights, static fn ($weight) => $weight > 0));
|
||||||
|
$historyWritten = false;
|
||||||
|
foreach ($sources as $index => $source) {
|
||||||
|
$rowNumber++;
|
||||||
|
$values = $source;
|
||||||
|
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
|
||||||
|
$share = $r['deducted'] > 0 ? $old / $r['deducted'] : 0;
|
||||||
|
$current = $automatic || $r['current'] === null ? (float) ($source['_return_current'] ?? $old)
|
||||||
|
: ($index === $last ? $remainingCurrent : round((float) $r['current'] * $share, 2));
|
||||||
|
$payable = $weights[$index] <= 0 || $totalWeight <= 0 ? 0.0
|
||||||
|
: ($index === $lastRefund ? $remainingRefund : round((float) $r['amount'] * $weights[$index] / $totalWeight, 2));
|
||||||
|
$remainingCurrent = round($remainingCurrent - $current, 2);
|
||||||
|
$remainingRefund = round($remainingRefund - $payable, 2);
|
||||||
|
$values['summary_month'] = $r['deduct_month'];
|
||||||
|
$values['tracking_no'] = $values['tracking_no'] ?? $r['waybill'];
|
||||||
|
$values['tracking_no_clean'] = $r['waybill'];
|
||||||
|
$values['carrier'] = $source['carrier'] ?? $r['carrier'];
|
||||||
|
$values['settle_bookkeeping'] = $old;
|
||||||
|
$values['current_bookkeeping'] = $current;
|
||||||
|
if (isset($source['_return_analysis'])) {
|
||||||
|
$values['analysis'] = $source['_return_analysis'];
|
||||||
|
}
|
||||||
|
$values['rebook_amount'] = new XlsxFormula(
|
||||||
|
self::columnName($settleColumn) . $rowNumber . '-' . self::columnName($currentColumn) . $rowNumber,
|
||||||
|
round($old - $current, 2),
|
||||||
|
);
|
||||||
|
$values['return_status'] = $source['_return_status'] ?? '';
|
||||||
|
$values['return_match'] = $source['_return_method'] ?? '';
|
||||||
|
$values['matched_return'] = $source['_matched_return_no'] ?? '';
|
||||||
|
$values['received_at'] = $source['_return_received_at'] ?? '';
|
||||||
|
$values['refund_status'] = $r['status'];
|
||||||
|
$values['refunded'] = $historyWritten ? null : $r['refunded'];
|
||||||
|
$historyWritten = true;
|
||||||
|
$values['payable_refund'] = $payable;
|
||||||
|
$cells = [];
|
||||||
|
foreach ($fields as $field => $definition) {
|
||||||
|
$value = $values[$field] ?? null;
|
||||||
|
$cells[] = $value instanceof XlsxFormula ? $value : ($definition['type'] === 'number'
|
||||||
|
? ($value === null || $value === '' ? null : (float) $value)
|
||||||
|
: ($value === null || $value === '' ? null : (string) $value));
|
||||||
|
}
|
||||||
|
$book->row($name, [...$cells, ...($multi ? [$groupNames[$id] ?? ''] : [])]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function columnName(int $column): string
|
||||||
|
{
|
||||||
|
$name = '';
|
||||||
|
while ($column > 0) {
|
||||||
|
$column--;
|
||||||
|
$name = chr(65 + $column % 26) . $name;
|
||||||
|
$column = intdiv($column, 26);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $name;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
||||||
*
|
*
|
||||||
@ -248,7 +398,7 @@ final class StatementExporter
|
|||||||
}
|
}
|
||||||
$rows = [
|
$rows = [
|
||||||
...$rows,
|
...$rows,
|
||||||
[$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接我方核算的 25 列(称重重量、首重、面单、计费重量、续重/费率、核算运费、重量差、运费差……)和发货数据其余字段。', $count(Category::PAYABLE)],
|
[$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接核算与结算对比列;运费差为快递运费减结算运费,重量差为快递重量减结算重量。', $count(Category::PAYABLE)],
|
||||||
['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])],
|
['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])],
|
||||||
['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])],
|
['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])],
|
||||||
[$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])],
|
[$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])],
|
||||||
@ -338,10 +488,9 @@ final class StatementExporter
|
|||||||
return match ($field) {
|
return match ($field) {
|
||||||
'_measured' => $ship['qc_measured_weight'] ?? null,
|
'_measured' => $ship['qc_measured_weight'] ?? null,
|
||||||
'_unshipped' => $line->unshipped_sources,
|
'_unshipped' => $line->unshipped_sources,
|
||||||
'_weight_diff' => $line->bill_weight !== null && ($ship['qc_charge_weight'] ?? null) !== null
|
'_settlement_weight' => SettlementComparison::courier($line)['settlement_weight'],
|
||||||
? round((float) $line->bill_weight - (float) $ship['qc_charge_weight'], 4) : null,
|
'_weight_diff' => SettlementComparison::courier($line)['weight_diff'],
|
||||||
'_freight_diff' => $line->bill_amount !== null && ($ship['qc_freight'] ?? null) !== null
|
'_freight_diff' => SettlementComparison::courier($line)['freight_diff'],
|
||||||
? round((float) $line->bill_amount - (float) $ship['qc_freight'], 2) : null,
|
|
||||||
default => self::value($field, $ship[$field] ?? null),
|
default => self::value($field, $ship[$field] ?? null),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -126,12 +126,15 @@ final class SummaryMapper
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */
|
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;未手工填写时,R > 0 则实付 S = R。 */
|
||||||
public static function totals(array $cells): array
|
public static function totals(array $cells): array
|
||||||
{
|
{
|
||||||
$n = static fn (string $key): float => (float) ($cells[$key] ?? 0);
|
$n = static fn (string $key): float => (float) ($cells[$key] ?? 0);
|
||||||
$cells['M'] = round($n('K') - $n('L'), 2);
|
$cells['M'] = round($n('K') - $n('L'), 2);
|
||||||
$cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2);
|
$cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2);
|
||||||
|
if ($cells['R'] > 0 && empty($cells['_paid_manual'])) {
|
||||||
|
$cells['S'] = $cells['R'];
|
||||||
|
}
|
||||||
|
|
||||||
return $cells;
|
return $cells;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -52,7 +52,7 @@ final class SummaryTemplate
|
|||||||
$index = [];
|
$index = [];
|
||||||
foreach ($template as $label) {
|
foreach ($template as $label) {
|
||||||
$key = self::normalize($label);
|
$key = self::normalize($label);
|
||||||
if ($key === '') {
|
if ($key === '' || ($key === WeightDifferenceSubsidy::LABEL && ! isset($auto[$key]))) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行
|
// 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行
|
||||||
@ -74,7 +74,9 @@ final class SummaryTemplate
|
|||||||
unset($row);
|
unset($row);
|
||||||
}
|
}
|
||||||
|
|
||||||
return [...$rows, ...$extras];
|
// 这些费用已由账单附加费归集,不再沿用上月没有金额的占位类目;有实际费用的行仍保留。
|
||||||
|
return array_values(array_filter([...$rows, ...$extras], static fn (array $row): bool =>
|
||||||
|
! $row['blank'] || ! preg_match('/拦截|改地址|超长/u', $row['label'])));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list<string> $feeLabels @return list<string> */
|
/** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list<string> $feeLabels @return list<string> */
|
||||||
@ -95,7 +97,7 @@ final class SummaryTemplate
|
|||||||
$result = [];
|
$result = [];
|
||||||
foreach ($labels as $label) {
|
foreach ($labels as $label) {
|
||||||
$label = trim((string) $label);
|
$label = trim((string) $label);
|
||||||
if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) {
|
if ($label !== '' && $label !== WeightDifferenceSubsidy::LABEL && ! preg_match(self::TRANSIENT, $label)) {
|
||||||
$result[] = self::roll($label, $delta);
|
$result[] = self::roll($label, $delta);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -187,6 +189,7 @@ final class SummaryTemplate
|
|||||||
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
|
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
|
||||||
$kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
|
$kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
|
||||||
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
|
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
|
||||||
|
str_starts_with($kind, 'rebook:') => $find(static fn (string $n): bool => Rebooks::labelCovers($n, (int) substr($kind, 7))),
|
||||||
$kind === 'fee' => self::feeSlot($key, $find),
|
$kind === 'fee' => self::feeSlot($key, $find),
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
|
|||||||
259
app/Support/CourierBills/SurchargeSettlementMatcher.php
Normal file
259
app/Support/CourierBills/SurchargeSettlementMatcher.php
Normal file
@ -0,0 +1,259 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use RuntimeException;
|
||||||
|
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||||
|
|
||||||
|
/** 按账单月份归集,逐票/费用类型匹配结算表;不改来源报价和费用。 */
|
||||||
|
class SurchargeSettlementMatcher
|
||||||
|
{
|
||||||
|
public const TABLE = 'bill_surcharge_matches';
|
||||||
|
public const PAID_HISTORY = 'bill-surcharge-paid-history';
|
||||||
|
public const HEADERS = ['账单月份','来源工作表','原始行号','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'];
|
||||||
|
|
||||||
|
public function ready(): bool
|
||||||
|
{
|
||||||
|
return DB::connection('business_mirror')->getSchemaBuilder()->hasTable(self::TABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function paidHistoryKey(string $scope, int $owner, string $month, string $waybill, string $type): string
|
||||||
|
{
|
||||||
|
return implode('|', [$scope, $owner, $month, strtoupper(trim($waybill)), self::type($type)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
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)));
|
||||||
|
$historyRows = array_map(fn ($fee) => ['id' => self::paidHistoryKey($scope, $owner, $month, $fee['waybill_no'], $fee['item'])], $input);
|
||||||
|
$history = app(SupplierPayableOverrideStore::class)->decorate(self::PAID_HISTORY, $historyRows, (int) (company_id() ?: 1));
|
||||||
|
$output=[];
|
||||||
|
foreach($input as $index=>$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);
|
||||||
|
if ($scope === 'courier' && $row['bill_amount'] !== null && (float) $row['bill_amount'] < $row['self_amount']) {
|
||||||
|
$row['self_amount'] = round((float) $row['bill_amount'], 2);
|
||||||
|
$row['match_note'] .= ';快递提供金额较低,按快递金额结算';
|
||||||
|
}
|
||||||
|
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']='单号存在,但费用类型或快递归属不符';
|
||||||
|
$paid = $history[$index];
|
||||||
|
$settledMonth = (string) ($paid['settled_month'] ?? '');
|
||||||
|
if ($paid['_overridden'] && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D', $settledMonth)
|
||||||
|
&& $settledMonth < $month) {
|
||||||
|
$row['self_amount'] = 0;
|
||||||
|
$row['match_status'] = '历史已计入';
|
||||||
|
$row['match_note'] = '财务确认:' . $settledMonth . '已结算,本期不重复结算';
|
||||||
|
$seen[$identity] = true;
|
||||||
|
}
|
||||||
|
$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]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
71
app/Support/CourierBills/WaybillMatch.php
Normal file
71
app/Support/CourierBills/WaybillMatch.php
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
/** Only formatting and the established numeric T prefix may be treated as equivalent. */
|
||||||
|
final class WaybillMatch
|
||||||
|
{
|
||||||
|
/** Indexed exact lookup first; formatting fallback only receives unresolved numbers. */
|
||||||
|
public static function find($query, string $column, array $numbers, array $columns): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
$numbers = array_values(array_unique(array_map('strval', $numbers)));
|
||||||
|
foreach (array_chunk($numbers, 300) as $chunk) {
|
||||||
|
foreach ((clone $query)->whereIn($column, $chunk)->get($columns) as $row) {
|
||||||
|
$actual = (string) $row->{$column};
|
||||||
|
if (in_array($actual, $chunk, true)) {
|
||||||
|
$result[$actual]['exact'] = true;
|
||||||
|
$result[$actual]['rows'][] = $row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$pending = [];
|
||||||
|
foreach ($numbers as $number) if (! isset($result[$number]) && ($key = self::key($number)) !== null) $pending[$key][] = $number;
|
||||||
|
$expression = self::expression($query, $column);
|
||||||
|
foreach (array_chunk(array_keys($pending), 300) as $keys) {
|
||||||
|
$variants = $keys;
|
||||||
|
foreach ($keys as $key) {
|
||||||
|
if (ctype_digit((string) $key)) {
|
||||||
|
$variants[] = 'T' . $key;
|
||||||
|
$variants[] = $key . '.0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$found = [];
|
||||||
|
foreach ((clone $query)->whereIn($query->getConnection()->raw($expression), array_map('strval', $variants))->get($columns) as $row) {
|
||||||
|
$key = self::key((string) $row->{$column});
|
||||||
|
if ($key !== null && isset($pending[$key])) $found[$key][] = $row;
|
||||||
|
}
|
||||||
|
foreach ($found as $key => $rows) {
|
||||||
|
if (count(array_unique(array_map(fn ($r) => Waybill::normalize(mb_convert_kana((string) $r->{$column}, 'as')), $rows))) !== 1) continue;
|
||||||
|
foreach ($pending[$key] as $number) $result[$number] = ['exact' => false, 'rows' => $rows];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function expression($query, string $column): string
|
||||||
|
{
|
||||||
|
$expression = $query->getGrammar()->wrap($column);
|
||||||
|
foreach ([" ", "\t", "\r", "\n", "'", '@', '`', ''', ' '] as $remove) {
|
||||||
|
$literal = str_replace("'", "''", $remove);
|
||||||
|
$expression = "REPLACE({$expression}, '{$literal}', '')";
|
||||||
|
}
|
||||||
|
return 'UPPER(' . $expression . ')';
|
||||||
|
}
|
||||||
|
|
||||||
|
public 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function uniqueFuzzy(array $records): array
|
||||||
|
{
|
||||||
|
$keys = [];
|
||||||
|
foreach ($records as $record) {
|
||||||
|
$number = Waybill::normalize(mb_convert_kana((string) $record['waybill'], 'as'));
|
||||||
|
if ($number !== null) $keys[$number] = true;
|
||||||
|
}
|
||||||
|
return count($keys) === 1 ? $records : [];
|
||||||
|
}
|
||||||
|
}
|
||||||
29
app/Support/CourierBills/WeightDifferenceSubsidy.php
Normal file
29
app/Support/CourierBills/WeightDifferenceSubsidy.php
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\CourierBills;
|
||||||
|
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
|
||||||
|
/** 武进韵达重量多报超过1kg的运费差额,汇总后补给快递50%。 */
|
||||||
|
final class WeightDifferenceSubsidy
|
||||||
|
{
|
||||||
|
public const LABEL = '补武进韵达重量差运费(50%)';
|
||||||
|
|
||||||
|
public function query(int $statementId): Builder
|
||||||
|
{
|
||||||
|
return CourierBillMatcher::db()->table('courier_bill_lines')
|
||||||
|
->where('statement_id', $statementId)->where('express_name', '武进韵达')
|
||||||
|
->whereIn('category', [...Category::PAYABLE, Category::PRIOR])->whereNull('resolution')
|
||||||
|
->whereRaw('bill_weight - charge_weight > 1')
|
||||||
|
->whereColumn('bill_amount', '>', 'calc_freight');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按差额合计计算一半,再四舍五入到分,避免逐行四舍五入累积误差。 */
|
||||||
|
public function summary(int $statementId): array
|
||||||
|
{
|
||||||
|
$sum = $this->query($statementId)->selectRaw('COUNT(*) AS n, SUM(bill_amount - calc_freight) AS difference')->first();
|
||||||
|
|
||||||
|
return ['count' => (int) $sum->n, 'difference' => round((float) $sum->difference, 4),
|
||||||
|
'amount' => round((float) $sum->difference / 2, 2)];
|
||||||
|
}
|
||||||
|
}
|
||||||
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 => '厂家有异议'];
|
||||||
|
}
|
||||||
@ -17,10 +17,12 @@ use RuntimeException;
|
|||||||
* 代发运费对账单导出(内部版),和快递账单对账的导出一个样子:
|
* 代发运费对账单导出(内部版),和快递账单对账的导出一个样子:
|
||||||
* 和手工版一样:第一张是「汇总」(照这家上月手工汇总的样子),然后是厂家发来的原始账单(表名改叫「厂家账单」,内容原样不动),后面接 对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
|
* 和手工版一样:第一张是「汇总」(照这家上月手工汇总的样子),然后是厂家发来的原始账单(表名改叫「厂家账单」,内容原样不动),后面接 对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
|
||||||
* 厂家未提供、说明;没有数据的表不生成。
|
* 厂家未提供、说明;没有数据的表不生成。
|
||||||
* 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 财务指定的 25 列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。
|
* 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 核算及结算对比列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。
|
||||||
*/
|
*/
|
||||||
final class DropshipExporter
|
final class DropshipExporter
|
||||||
{
|
{
|
||||||
|
/** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */
|
||||||
|
public const FEE_LABEL = DropshipBillSummary::FEE_LABEL;
|
||||||
private const CHUNK = 500;
|
private const CHUNK = 500;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
@ -78,6 +80,7 @@ final class DropshipExporter
|
|||||||
$lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?');
|
$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] !== '_')));
|
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_')));
|
||||||
$tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
|
$tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
|
||||||
|
$front = self::frontColumns();
|
||||||
|
|
||||||
// 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张)
|
// 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张)
|
||||||
$sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)];
|
$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 === []) {
|
if ($picked === []) {
|
||||||
continue;
|
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) {
|
foreach (array_chunk($picked, self::CHUNK) as $chunk) {
|
||||||
$details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['ship_waybill'], $chunk));
|
$details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['ship_waybill'], $chunk));
|
||||||
foreach ($chunk as $r) {
|
foreach ($chunk as $r) {
|
||||||
$ship = $details[strtoupper((string) $r['ship_waybill'])] ?? [];
|
$ship = $details[strtoupper((string) $r['ship_waybill'])] ?? [];
|
||||||
$cells = $this->originalCells($r, $sources, $original, $lookup);
|
$cells = $this->originalCells($r, $sources, $original, $lookup);
|
||||||
foreach (StatementExporter::FRONT as $field) {
|
foreach ($front as $field) {
|
||||||
$cells[] = $this->front($field, $r, $ship);
|
$cells[] = $this->front($field, $r, $ship);
|
||||||
}
|
}
|
||||||
foreach (array_keys($rest) as $field) {
|
foreach (array_keys($rest) as $field) {
|
||||||
@ -135,46 +138,31 @@ final class DropshipExporter
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->writeNotes($book, $rows, $originals);
|
$this->writeNotes($book, $rows, $originals);
|
||||||
|
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
|
||||||
$book->writeTo($output);
|
$book->writeTo($output);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。运费行系统填(厂家开的运费合计 / 按我方核算的结算运费),
|
* 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。
|
||||||
* 货款、记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。
|
* - 运费行:原始 = 按我方结算的那些单(一致、运费有差、系统未核算、前月补提供)厂家开的运费,简尚核对 = 最终结算运费;
|
||||||
|
* - 厂家开了运费但这个月不付的,按分类各加一行(快递不符、重复、匹配不到、未发出、跨月订单-X月):原始 = 厂家开的运费,简尚核对 = 0;
|
||||||
|
* 这样「原始」合计 = 厂家账单运费合计。手工汇总里已有同名类目的就填在那一行,不重复加;
|
||||||
|
* - 记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。
|
||||||
*/
|
*/
|
||||||
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
|
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
|
||||||
{
|
{
|
||||||
$template = $this->store->summaryTemplate($factory, $month);
|
$summary = app(DropshipBillSummary::class)->build($factory, $month, $rows);
|
||||||
$billTotal = $settleTotal = null;
|
$book->row('汇总', [$summary['title'], ...$summary['headers']], true);
|
||||||
foreach ($rows as $r) {
|
foreach ($summary['rows'] as $index => $item) {
|
||||||
if ($r['bill'] !== null) {
|
$book->row('汇总', [$item['label'], $item['bill'], $item['settle'], self::diff($index + 2, $item['bill'], $item['settle'])]);
|
||||||
$billTotal = (float) $billTotal + (float) $r['bill'];
|
|
||||||
}
|
|
||||||
if ($r['settle'] !== null) {
|
|
||||||
$settleTotal = (float) $settleTotal + (float) $r['settle'];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
$labels = $template['labels'];
|
$last = count($summary['rows']) + 1;
|
||||||
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;
|
|
||||||
$n = $last + 1;
|
$n = $last + 1;
|
||||||
$book->row('汇总', [$template['total'], new XlsxFormula('SUM(B2:B' . $last . ')', round($sums[0], 2)),
|
$book->row('汇总', [$summary['total_label'], new XlsxFormula('SUM(B2:B' . $last . ')', $summary['totals']['bill']),
|
||||||
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);
|
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
|
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 . '))',
|
return new XlsxFormula('IF(COUNT(B' . $row . ':C' . $row . ')=0,"",N(B' . $row . ')-N(C' . $row . '))',
|
||||||
@ -270,7 +258,7 @@ final class DropshipExporter
|
|||||||
. ';' . ($read ? '读了这张表的运费。' : '这张表没读运费(货款、记账、退货等)。'), $lines]);
|
. ';' . ($read ? '读了这张表的运费。' : '这张表没读运费(货款、记账、退货等)。'), $lines]);
|
||||||
}
|
}
|
||||||
foreach ([
|
foreach ([
|
||||||
['对账', '本月发货、是这家代发单的单号(一致、运费有差、系统未核算),按我方核算运费结算。前面是厂家账单原始列,后面接我方核算的 25 列和发货数据其余字段。', [Category::MATCH, Category::DIFF, Category::UNCALCULATED]],
|
['对账', '本月发货、是这家代发单的单号(一致、运费有差、系统未核算)。运费差为厂家运费减最终结算运费,重量差为厂家重量减结算重量。前面是厂家账单原始列,后面接核算及结算对比列和发货数据其余字段。', [Category::MATCH, Category::DIFF, Category::UNCALCULATED]],
|
||||||
['前月补提供-X月', '上月及以前发货、厂家这次才开的单,按我方核算运费结算。', [Category::PRIOR]],
|
['前月补提供-X月', '上月及以前发货、厂家这次才开的单,按我方核算运费结算。', [Category::PRIOR]],
|
||||||
['跨月订单-X月', '下个月才发货的单,本月不付,留到发货那个月。', [Category::LATER]],
|
['跨月订单-X月', '下个月才发货的单,本月不付,留到发货那个月。', [Category::LATER]],
|
||||||
['快递不符', '发货数据查得到,但不是这家代发单(不是这家代发仓发的、快递名称1 不含关键字,或是自有快递),不付。', [Category::MISMATCH]],
|
['快递不符', '发货数据查得到,但不是这家代发单(不是这家代发仓发的、快递名称1 不含关键字,或是自有快递),不付。', [Category::MISMATCH]],
|
||||||
@ -327,13 +315,34 @@ final class DropshipExporter
|
|||||||
}, $original);
|
}, $original);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 对账表前面几列:核算运费、结算重量、最终结算运费依次相邻。 @return array<string,string> */
|
||||||
|
private static function frontColumns(): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
foreach (StatementExporter::FRONT as $label => $field) {
|
||||||
|
if ($field === 'qc_charge_weight') $result['厂家重量(kg)'] = '_bill_weight';
|
||||||
|
$result[$label] = $field;
|
||||||
|
if ($field === '_settlement_weight') {
|
||||||
|
$result['最终结算运费'] = '_final';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
private function front(string $field, array $r, array $ship): string|float|null
|
private function front(string $field, array $r, array $ship): string|float|null
|
||||||
{
|
{
|
||||||
return match ($field) {
|
return match ($field) {
|
||||||
'_measured' => $ship['qc_measured_weight'] ?? null,
|
'_measured' => $ship['qc_measured_weight'] ?? null,
|
||||||
'_unshipped' => null,
|
'_unshipped' => null,
|
||||||
'_weight_diff' => null,
|
'_bill_weight' => $r['bill_weight'],
|
||||||
'_freight_diff' => $r['bill'] !== null && ($ship['qc_freight'] ?? null) !== null ? round((float) $r['bill'] - (float) $ship['qc_freight'], 2) : null,
|
'qc_charge_weight' => $r['charge_weight'],
|
||||||
|
'_settlement_weight' => $r['settlement_weight'],
|
||||||
|
'_weight_diff' => $r['weight_diff'],
|
||||||
|
'_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),
|
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\BillWorkbookReader;
|
||||||
use App\Support\CourierBills\CourierBillStore;
|
use App\Support\CourierBills\CourierBillStore;
|
||||||
|
use App\Support\CourierBills\FreightBillTemplate;
|
||||||
use App\Support\CourierBills\ShippingLookup;
|
use App\Support\CourierBills\ShippingLookup;
|
||||||
|
use App\Support\CourierBills\SurchargeSettlementMatcher;
|
||||||
use Illuminate\Database\ConnectionInterface;
|
use Illuminate\Database\ConnectionInterface;
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@ -31,6 +33,73 @@ final class DropshipFreightStore
|
|||||||
private readonly CourierBillStore $courierBills,
|
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
|
public function db(): ConnectionInterface
|
||||||
{
|
{
|
||||||
return DB::connection('business_mirror');
|
return DB::connection('business_mirror');
|
||||||
@ -174,6 +243,17 @@ final class DropshipFreightStore
|
|||||||
return $ids;
|
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
|
public function assign(int $fileId, int $factoryId): void
|
||||||
{
|
{
|
||||||
$file = $this->db()->table('dropship_bill_files')->find($fileId);
|
$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()->transaction(function () use ($file): void {
|
||||||
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
|
||||||
|
if(app(SurchargeSettlementMatcher::class)->ready()){
|
||||||
|
$this->db()->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
|
||||||
|
$this->db()->table(SurchargeSettlementMatcher::TABLE)->where('scope','dropship')->where('file_id',$file->id)->delete();
|
||||||
|
}
|
||||||
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
|
||||||
});
|
});
|
||||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||||
|
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -209,14 +294,14 @@ final class DropshipFreightStore
|
|||||||
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
|
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
|
||||||
->orderByDesc('bill_month')->first();
|
->orderByDesc('bill_month')->first();
|
||||||
if ($row === null) {
|
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
|
$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);
|
+ (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)),
|
$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);
|
'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 */
|
/** @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));
|
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||||
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
|
||||||
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
|
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([
|
$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',
|
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory',
|
||||||
'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null,
|
'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null,
|
||||||
@ -320,6 +405,10 @@ final class DropshipFreightStore
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$lines = $result['lines'];
|
$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 = [];
|
$notes = [];
|
||||||
if ($lines === []) {
|
if ($lines === []) {
|
||||||
$notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空';
|
$notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空';
|
||||||
@ -341,12 +430,13 @@ final class DropshipFreightStore
|
|||||||
$lines = array_diff_key($lines, array_flip($others));
|
$lines = array_diff_key($lines, array_flip($others));
|
||||||
}
|
}
|
||||||
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
|
||||||
|
$this->storeSurchargeRows($file,$factoryId);
|
||||||
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
|
||||||
foreach (array_chunk($lines, 500, true) as $chunk) {
|
foreach (array_chunk($lines, 500, true) as $chunk) {
|
||||||
$insert = [];
|
$insert = [];
|
||||||
foreach ($chunk as $waybill => $line) {
|
foreach ($chunk as $waybill => $line) {
|
||||||
$insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill,
|
$insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill,
|
||||||
'amount' => $line['amount'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']];
|
'amount' => $line['amount'], 'bill_weight' => $line['weight'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']];
|
||||||
}
|
}
|
||||||
$db->table('dropship_bill_lines')->insert($insert);
|
$db->table('dropship_bill_lines')->insert($insert);
|
||||||
}
|
}
|
||||||
@ -359,6 +449,7 @@ final class DropshipFreightStore
|
|||||||
'updated_at' => now(),
|
'updated_at' => now(),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */
|
||||||
|
|||||||
50
app/Support/DropshipFreight/DropshipOverviewExporter.php
Normal file
50
app/Support/DropshipFreight/DropshipOverviewExporter.php
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support\DropshipFreight;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\StreamingWorkbook;
|
||||||
|
|
||||||
|
/** 导出各厂家汇总,数据直接复用页面汇总结果,不导出逐单明细。 */
|
||||||
|
final class DropshipOverviewExporter
|
||||||
|
{
|
||||||
|
public static function headers(): array
|
||||||
|
{
|
||||||
|
return ['厂家', ...array_values(DropshipFees::COLUMNS), '合计运费', '备注', '代发仓', '关键字',
|
||||||
|
'厂家开运费单数', '厂家运费', '结算运费', '差额', '运费有差·厂家多开', '运费有差·厂家少开',
|
||||||
|
'厂家未提供(不付)', '其他要看的', '厂家确认'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param resource $output */
|
||||||
|
public function write(array $data, $output): void
|
||||||
|
{
|
||||||
|
$book = new StreamingWorkbook();
|
||||||
|
$book->row('各厂家汇总', self::headers(), true);
|
||||||
|
foreach ($data['dfRows'] as $row) {
|
||||||
|
$fee = $data['dfFees'][$row['factory_id']];
|
||||||
|
$amounts = [];
|
||||||
|
foreach (array_keys(DropshipFees::COLUMNS) as $key) {
|
||||||
|
$value = (float) $fee['values'][$key];
|
||||||
|
$amounts[] = $value == 0 ? null : ($key === 'booking' ? -$value : $value);
|
||||||
|
}
|
||||||
|
$notes = $fee['note'];
|
||||||
|
if ($fee['other'] !== []) {
|
||||||
|
$other = [];
|
||||||
|
foreach ($fee['other'] as $type => $amount) $other[] = $type . ' ' . number_format($amount, 2);
|
||||||
|
$notes .= ($notes !== '' ? "\n" : '') . '未归类附加费(不计入合计):' . implode('、', $other);
|
||||||
|
}
|
||||||
|
$book->row('各厂家汇总', [$row['factory'], ...$amounts, $fee['total'], $notes, $row['warehouse'], $row['keywords'],
|
||||||
|
$row['billed'], $row['bill'], $row['settle'], $row['diff'], $row['over'], $row['under'],
|
||||||
|
$row['counts']['unprovided'], $row['attention'] - $row['counts']['diff'],
|
||||||
|
DropshipConfirmation::label($data['dfStates'][$row['factory_id']] ?? null)]);
|
||||||
|
}
|
||||||
|
if ($data['dfRows'] !== []) {
|
||||||
|
$totals = [];
|
||||||
|
foreach (array_keys(DropshipFees::COLUMNS) as $key) {
|
||||||
|
$value = (float) ($data['dfFeeTotals'][$key] ?? 0);
|
||||||
|
$totals[] = $value == 0 ? null : ($key === 'booking' ? -$value : $value);
|
||||||
|
}
|
||||||
|
$book->row('各厂家汇总', ['合计', ...$totals, $data['dfFeeTotals']['total'], ...array_fill(0, 12, null)], true);
|
||||||
|
}
|
||||||
|
$book->writeTo($output);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5,6 +5,7 @@ namespace App\Support\DropshipFreight;
|
|||||||
use App\Support\CourierBills\Category;
|
use App\Support\CourierBills\Category;
|
||||||
use App\Support\CourierBills\CourierBillMatcher;
|
use App\Support\CourierBills\CourierBillMatcher;
|
||||||
use App\Support\CourierBills\ShippingLookup;
|
use App\Support\CourierBills\ShippingLookup;
|
||||||
|
use App\Support\CourierBills\SettlementComparison;
|
||||||
use App\Support\UnshippedWaybills;
|
use App\Support\UnshippedWaybills;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -46,12 +47,33 @@ final class DropshipReconciler
|
|||||||
*/
|
*/
|
||||||
public function factoryMonth(object $factory, string $month, ?array $own = null, bool $withSources = false): array
|
public function factoryMonth(object $factory, string $month, ?array $own = null, bool $withSources = false): array
|
||||||
{
|
{
|
||||||
|
$confirmation = app(DropshipConfirmation::class);
|
||||||
|
$company = (int) company_id();
|
||||||
|
$state = $confirmation->state($month, (int)$factory->id, $company);
|
||||||
|
if (($state['status'] ?? '') === DropshipConfirmation::CONFIRMED) {
|
||||||
|
$version = (int)($state['version'] ?? 0);
|
||||||
|
$snapshot = $confirmation->snapshot($month, (int)$factory->id, $version, $company);
|
||||||
|
if ($snapshot !== null) {
|
||||||
|
$rows = [];
|
||||||
|
foreach ($confirmation->snapshotQuery($month, (int)$factory->id, $version, $company)->orderBy('id')->cursor() as $record) {
|
||||||
|
$row = json_decode($record->values, true);
|
||||||
|
// 旧版本快照仍锁定原金额;没有保存的核算字段留空,不拿当前镜像改写历史。
|
||||||
|
$rows[] = $row + array_fill_keys(['warehouse','calc','bill_weight','charge_weight','settlement_weight',
|
||||||
|
'weight_diff','diff_kind','settle','freight_diff','diff','status_month','formula'], null)
|
||||||
|
+ ['ship_waybill'=>$row['waybill']];
|
||||||
|
}
|
||||||
|
return ['rows'=>$rows, 'summary'=>$snapshot['summary']];
|
||||||
|
}
|
||||||
|
throw new \RuntimeException('已确认账单缺少确认快照,请核对历史记录。');
|
||||||
|
}
|
||||||
$own = array_flip($own ?? $this->store->ownExpressNames());
|
$own = array_flip($own ?? $this->store->ownExpressNames());
|
||||||
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
|
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
|
||||||
$columns = $withSources ? ['waybill_no', 'amount', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount'];
|
$columns = $withSources ? ['waybill_no', 'amount', 'bill_weight', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount', 'bill_weight'];
|
||||||
$lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
|
$lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
|
||||||
->orderBy('id')->get($columns)->groupBy('waybill_no');
|
->orderBy('id')->get($columns)->groupBy('waybill_no');
|
||||||
$bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
|
$bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
|
||||||
|
$weights = $lines->map(static fn ($rows): ?float => $rows->contains(fn ($r) => $r->bill_weight === null)
|
||||||
|
? null : round((float) $rows->sum('bill_weight'), 4))->all();
|
||||||
$sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id,
|
$sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id,
|
||||||
'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : [];
|
'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : [];
|
||||||
unset($lines);
|
unset($lines);
|
||||||
@ -114,7 +136,7 @@ final class DropshipReconciler
|
|||||||
$note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '')
|
$note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '')
|
||||||
. ($i === null ? ';新单号发货数据里也查不到' : '');
|
. ($i === null ? ';新单号发货数据里也查不到' : '');
|
||||||
}
|
}
|
||||||
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note) + ($sources[$waybill] ?? [])
|
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note, $weights[$waybill]) + ($sources[$waybill] ?? [])
|
||||||
+ ['ship_waybill' => $swap ?? $waybill];
|
+ ['ship_waybill' => $swap ?? $waybill];
|
||||||
}
|
}
|
||||||
$system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w])));
|
$system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w])));
|
||||||
@ -133,40 +155,63 @@ final class DropshipReconciler
|
|||||||
? Category::label($status, $month) : (self::LABELS[$status] ?? $status);
|
? Category::label($status, $month) : (self::LABELS[$status] ?? $status);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array
|
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note, ?float $billWeight = null): array
|
||||||
{
|
{
|
||||||
$calc = $i['calc'] ?? null;
|
$calc = $i['calc'] ?? null;
|
||||||
|
$settle = in_array($status, self::PAYABLE, true) ? $calc : null;
|
||||||
|
$chargeWeight = $i['charge_weight'] ?? null;
|
||||||
|
$weightDiff = $billWeight !== null && $chargeWeight !== null ? round($billWeight - $chargeWeight, 4) : null;
|
||||||
|
$final = self::final($billed, $settle);
|
||||||
|
$settlementWeight = SettlementComparison::weight($billed, $calc, $billWeight, $chargeWeight, $final);
|
||||||
|
|
||||||
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
|
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
|
||||||
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
|
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
|
||||||
'settle' => in_array($status, self::PAYABLE, true) ? $calc : null,
|
'bill_weight' => $billWeight, 'charge_weight' => $chargeWeight, 'settlement_weight' => $settlementWeight,
|
||||||
|
'weight_diff' => SettlementComparison::difference($billWeight, $settlementWeight, 4),
|
||||||
|
'diff_kind' => $status !== Category::DIFF ? null : ($weightDiff === null ? 'missing_weight' : (abs($weightDiff) > 0.005 ? 'weight_diff' : 'price_diff')),
|
||||||
|
'settle' => $settle, 'final' => $final, 'freight_diff' => SettlementComparison::difference($billed, $final),
|
||||||
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
|
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
|
||||||
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
|
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
|
||||||
'note' => $note, 'formula' => $i['formula'] ?? null];
|
'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 */
|
/** @param list<array<string,mixed>> $rows */
|
||||||
public static function summarize(object $factory, string $month, array $rows): array
|
public static function summarize(object $factory, string $month, array $rows): array
|
||||||
{
|
{
|
||||||
$counts = array_fill_keys(array_keys(self::LABELS), 0);
|
$counts = array_fill_keys(array_keys(self::LABELS), 0);
|
||||||
$bill = $settle = 0.0;
|
$bill = $settle = $calcSettle = 0.0;
|
||||||
$billedCount = $over = $under = 0;
|
$billedCount = $over = $under = $capped = 0;
|
||||||
|
$diffCounts = ['weight_diff' => 0, 'price_diff' => 0, 'missing_weight' => 0];
|
||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$counts[$row['status']]++;
|
$counts[$row['status']]++;
|
||||||
if ($row['bill'] !== null) {
|
if ($row['bill'] !== null) {
|
||||||
$billedCount++;
|
$billedCount++;
|
||||||
$bill += $row['bill'];
|
$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) {
|
if ($row['status'] === Category::DIFF) {
|
||||||
$row['diff'] > 0 ? $over++ : $under++;
|
$row['diff'] > 0 ? $over++ : $under++;
|
||||||
|
$diffCounts[$row['diff_kind'] ?? 'missing_weight']++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month,
|
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),
|
'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,
|
'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under,
|
||||||
'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
|
'diff_counts' => $diffCounts, 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function matches(string $express, array $keywords): bool
|
public static function matches(string $express, array $keywords): bool
|
||||||
@ -180,6 +225,14 @@ final class DropshipReconciler
|
|||||||
return false;
|
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> */
|
/** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list<string> */
|
||||||
private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array
|
private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array
|
||||||
{
|
{
|
||||||
@ -249,9 +302,15 @@ final class DropshipReconciler
|
|||||||
}
|
}
|
||||||
foreach ($sources as $key => $set) {
|
foreach ($sources as $key => $set) {
|
||||||
$total = 0.0;
|
$total = 0.0;
|
||||||
|
$weight = 0.0; $weightComplete = true;
|
||||||
$ok = true;
|
$ok = true;
|
||||||
$status = null;
|
$status = null;
|
||||||
$formulas = [];
|
$formulas = [];
|
||||||
|
foreach (array_keys($set) as $source) {
|
||||||
|
$freight = $freights[$source] ?? null;
|
||||||
|
if ($freight === null || $freight->charge_weight === null) $weightComplete = false;
|
||||||
|
else $weight += (float) $freight->charge_weight;
|
||||||
|
}
|
||||||
foreach (array_keys($set) as $source) {
|
foreach (array_keys($set) as $source) {
|
||||||
$freight = $freights[$source] ?? null;
|
$freight = $freights[$source] ?? null;
|
||||||
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
|
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
|
||||||
@ -265,6 +324,7 @@ final class DropshipReconciler
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$result[$key]['calc'] = $ok ? round($total, 2) : null;
|
$result[$key]['calc'] = $ok ? round($total, 2) : null;
|
||||||
|
$result[$key]['charge_weight'] = $weightComplete ? round($weight, 4) : null;
|
||||||
$result[$key]['calc_status'] = $ok ? null : $status;
|
$result[$key]['calc_status'] = $ok ? null : $status;
|
||||||
$result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas);
|
$result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas);
|
||||||
}
|
}
|
||||||
|
|||||||
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 TOTALS = ['合计', '汇总', '总计'];
|
||||||
|
|
||||||
/** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */
|
/** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */
|
||||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计'];
|
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账'], 'total' => '合计'];
|
||||||
|
/** 小汇总里不要的类目(手工汇总里带了也去掉)。 */
|
||||||
|
public const DROPPED = ['代发', '退货'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。
|
* 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。
|
||||||
@ -95,6 +97,15 @@ final class DropshipSummaryTemplate
|
|||||||
return $template;
|
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
|
public static function fallback(string $month, string $factory): array
|
||||||
{
|
{
|
||||||
$template = self::DEFAULT;
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -22,6 +22,7 @@ final class FactoryBillParser
|
|||||||
public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递'];
|
public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递'];
|
||||||
/** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */
|
/** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */
|
||||||
public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收'];
|
public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收'];
|
||||||
|
public const WEIGHT_HEADERS = ['计费重量', '结算重量', '厂家重量', '重量', '实际重量'];
|
||||||
/** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */
|
/** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */
|
||||||
public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账',
|
public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账',
|
||||||
'我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔'];
|
'我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔'];
|
||||||
@ -32,7 +33,7 @@ final class FactoryBillParser
|
|||||||
public function __construct(private readonly BillWorkbookReader $reader) {}
|
public function __construct(private readonly BillWorkbookReader $reader) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array{lines:array<string,array{amount:float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>}
|
* @return array{lines:array<string,array{amount:float,weight:?float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>}
|
||||||
*/
|
*/
|
||||||
public function parse(string $path, string $extension): array
|
public function parse(string $path, string $extension): array
|
||||||
{
|
{
|
||||||
@ -71,8 +72,11 @@ final class FactoryBillParser
|
|||||||
if ($waybill === null || $amount === null) {
|
if ($waybill === null || $amount === null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$mine[$waybill] ??= ['amount' => 0.0, 'sheet' => $sheet, 'row' => (int) $rowNumber];
|
$mine[$waybill] ??= ['amount' => 0.0, 'weight' => 0.0, 'weight_complete' => true, 'sheet' => $sheet, 'row' => (int) $rowNumber];
|
||||||
$mine[$waybill]['amount'] += $amount;
|
$mine[$waybill]['amount'] += $amount;
|
||||||
|
$weight = $columns['weight'] === null ? null : BillParser::number($row[$columns['weight']] ?? null);
|
||||||
|
if ($weight === null || $weight < 0) $mine[$waybill]['weight_complete'] = false;
|
||||||
|
else $mine[$waybill]['weight'] += $weight;
|
||||||
}
|
}
|
||||||
if ($columns === null) {
|
if ($columns === null) {
|
||||||
$sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列'];
|
$sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列'];
|
||||||
@ -83,6 +87,8 @@ final class FactoryBillParser
|
|||||||
$repeated = 0;
|
$repeated = 0;
|
||||||
foreach ($mine as $waybill => $line) {
|
foreach ($mine as $waybill => $line) {
|
||||||
$line['amount'] = round($line['amount'], 2);
|
$line['amount'] = round($line['amount'], 2);
|
||||||
|
$line['weight'] = $line['weight_complete'] ? round($line['weight'], 4) : null;
|
||||||
|
unset($line['weight_complete']);
|
||||||
if (abs($line['amount']) < 0.005) {
|
if (abs($line['amount']) < 0.005) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -97,6 +103,7 @@ final class FactoryBillParser
|
|||||||
$sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2),
|
$sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2),
|
||||||
'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」'
|
'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」'
|
||||||
. ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '')
|
. ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '')
|
||||||
|
. ($columns['weight'] !== null ? ';重量列「' . $columns['headers'][$columns['weight']] . '」' : ';未提供重量列')
|
||||||
. ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')];
|
. ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,7 +123,7 @@ final class FactoryBillParser
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<int,string> $row
|
* @param array<int,string> $row
|
||||||
* @return array{waybill:int,amount:int,extra:list<int>,headers:list<string>,waybill_header:string,amount_header:string}|null
|
* @return array{waybill:int,amount:int,weight:?int,extra:list<int>,headers:list<string>,waybill_header:string,amount_header:string}|null
|
||||||
*/
|
*/
|
||||||
public static function findColumns(array $row): ?array
|
public static function findColumns(array $row): ?array
|
||||||
{
|
{
|
||||||
@ -169,7 +176,14 @@ final class FactoryBillParser
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['waybill' => $waybill, 'amount' => $amount, 'extra' => $extra, 'headers' => array_values($headers),
|
$weight = null;
|
||||||
|
foreach (self::WEIGHT_HEADERS as $candidate) {
|
||||||
|
foreach ($headers as $index => $header) {
|
||||||
|
$base = preg_replace('/[((]?(?:kg|公斤|千克)[))]?$/iu', '', $header);
|
||||||
|
if ($base === $candidate) { $weight = (int) $index; break 2; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight, 'extra' => $extra, 'headers' => array_values($headers),
|
||||||
'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]];
|
'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -11,10 +11,14 @@ namespace App\Support;
|
|||||||
class ReturnPickupFreightCalculator
|
class ReturnPickupFreightCalculator
|
||||||
{
|
{
|
||||||
private const CARRIER_MAP = [
|
private const CARRIER_MAP = [
|
||||||
'速寄递' => '申通',
|
'速寄递' => '申通退货',
|
||||||
'申通' => '申通',
|
'申通' => '申通退货',
|
||||||
'德邦' => '德邦',
|
'申通退货' => '申通退货',
|
||||||
'中通快运' => '中通快运',
|
'德邦' => '常州德邦逆向',
|
||||||
|
'常州德邦' => '常州德邦逆向',
|
||||||
|
'常州德邦逆向' => '常州德邦逆向',
|
||||||
|
'中通快运' => '中通快运逆向',
|
||||||
|
'中通快运逆向' => '中通快运逆向',
|
||||||
];
|
];
|
||||||
|
|
||||||
private const PROVINCES = [
|
private const PROVINCES = [
|
||||||
@ -49,6 +53,8 @@ class ReturnPickupFreightCalculator
|
|||||||
?float $length = null,
|
?float $length = null,
|
||||||
?float $width = null,
|
?float $width = null,
|
||||||
?float $height = null,
|
?float $height = null,
|
||||||
|
?string $pickupDate = null,
|
||||||
|
?float $volumeCm3 = null,
|
||||||
): array {
|
): array {
|
||||||
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
|
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
|
||||||
|
|
||||||
@ -59,8 +65,8 @@ class ReturnPickupFreightCalculator
|
|||||||
$length = max((float) $length, 0);
|
$length = max((float) $length, 0);
|
||||||
$width = max((float) $width, 0);
|
$width = max((float) $width, 0);
|
||||||
$height = max((float) $height, 0);
|
$height = max((float) $height, 0);
|
||||||
$volumeWeight = ($length > 0 && $width > 0 && $height > 0)
|
$volumeWeight = ($volumeCm3 !== null || ($length > 0 && $width > 0 && $height > 0))
|
||||||
? round($length * $width * $height / 6000, 4)
|
? round(max(0, $volumeCm3 ?? ($length * $width * $height)) / 6000, 4)
|
||||||
: 0.0;
|
: 0.0;
|
||||||
$settlement = round(max($grossWeight, $volumeWeight), 4);
|
$settlement = round(max($grossWeight, $volumeWeight), 4);
|
||||||
|
|
||||||
@ -78,6 +84,9 @@ class ReturnPickupFreightCalculator
|
|||||||
}
|
}
|
||||||
|
|
||||||
$rule = $this->rules[$carrier] ?? [];
|
$rule = $this->rules[$carrier] ?? [];
|
||||||
|
if ($pickupDate !== null && ! empty($rule['effective_date']) && $pickupDate < $rule['effective_date']) {
|
||||||
|
return $this->missing('取件日期早于该逆向物流报价执行日期');
|
||||||
|
}
|
||||||
$mode = (string) ($rule['pricing_mode'] ?? '');
|
$mode = (string) ($rule['pricing_mode'] ?? '');
|
||||||
$maxSide = max($length, $width, $height);
|
$maxSide = max($length, $width, $height);
|
||||||
$sideSum = $length + $width + $height;
|
$sideSum = $length + $width + $height;
|
||||||
|
|||||||
@ -11,7 +11,7 @@ namespace App\Support;
|
|||||||
* - 到达:报价「到达地」可写完整名称(如「兰考华兰家具」)、省份(如「江苏」)、
|
* - 到达:报价「到达地」可写完整名称(如「兰考华兰家具」)、省份(如「江苏」)、
|
||||||
* 「省份+地名」(如「河南兰考」)或城市(如「青岛」),多个用 / 分隔。
|
* 「省份+地名」(如「河南兰考」)或城市(如「青岛」),多个用 / 分隔。
|
||||||
* 传入的到达地可以是厂家名或收货地址;完整名称 > 城市/地名 > 省份,取最具体的一条。
|
* 传入的到达地可以是厂家名或收货地址;完整名称 > 城市/地名 > 省份,取最具体的一条。
|
||||||
* 运费 = max(按吨, 按方)(各自四舍五入到分)+ 派送费(门槛与金额按报价行设置)。
|
* 运费 = max(按吨, 按方)(各自四舍五入到分)+ 派送费 + 提货费(门槛与金额按报价行设置,提货费只在该行填写时收)。
|
||||||
*/
|
*/
|
||||||
final class ReturnRouteFreightCalculator
|
final class ReturnRouteFreightCalculator
|
||||||
{
|
{
|
||||||
@ -52,11 +52,16 @@ final class ReturnRouteFreightCalculator
|
|||||||
|
|
||||||
$best = [];
|
$best = [];
|
||||||
$bestScore = 0;
|
$bestScore = 0;
|
||||||
|
$matchedRoute = false;
|
||||||
|
$pricingDate = $shipDate ?? now()->toDateString();
|
||||||
foreach ($this->rates ??= $this->snapshot->load()['rates'] as $rate) {
|
foreach ($this->rates ??= $this->snapshot->load()['rates'] as $rate) {
|
||||||
if (($rate['layout'] ?? null) !== ReverseLogisticsQuoteSnapshot::LAYOUT_ROUTE_TON_VOLUME || $rate['carrier'] !== $carrier) continue;
|
if (($rate['layout'] ?? null) !== ReverseLogisticsQuoteSnapshot::LAYOUT_ROUTE_TON_VOLUME || $rate['carrier'] !== $carrier) continue;
|
||||||
$originScore = self::originScore((string) $rate['origin'], $origin, $warehouse, $originProvince);
|
$originScore = self::originScore((string) $rate['origin'], $origin, $warehouse, $originProvince);
|
||||||
$destinationScore = self::destinationScore((string) $rate['destination'], $destination, $destinationName);
|
$destinationScore = self::destinationScore((string) $rate['destination'], $destination, $destinationName);
|
||||||
if ($originScore === 0 || $destinationScore === 0) continue;
|
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;
|
$score = $originScore * 10 + $destinationScore;
|
||||||
if ($score > $bestScore) {
|
if ($score > $bestScore) {
|
||||||
$best = [$rate];
|
$best = [$rate];
|
||||||
@ -65,12 +70,9 @@ final class ReturnRouteFreightCalculator
|
|||||||
$best[] = $rate;
|
$best[] = $rate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($best === []) return $this->missing('报价未覆盖该路线');
|
if ($best === []) return $this->missing($matchedRoute ? '发货日没有生效的逆向物流报价' : '报价未覆盖该路线');
|
||||||
if (count($best) !== 1) return $this->missing('该路线存在多条报价,请核对报价版本');
|
if (count($best) !== 1) return $this->missing('该路线存在多条报价,请核对报价版本');
|
||||||
$rate = $best[0];
|
$rate = $best[0];
|
||||||
if ($shipDate !== null && $rate['effective_date'] !== null && $shipDate < $rate['effective_date']) {
|
|
||||||
return $this->missing('发货日没有生效的逆向物流报价');
|
|
||||||
}
|
|
||||||
if (!$rate['available']) return $this->missing('该线路缺少有效吨价或方价');
|
if (!$rate['available']) return $this->missing('该线路缺少有效吨价或方价');
|
||||||
|
|
||||||
$tons = $weightKg / 1000;
|
$tons = $weightKg / 1000;
|
||||||
@ -79,11 +81,12 @@ final class ReturnRouteFreightCalculator
|
|||||||
$byVolume = round($cubicMeters * $rate['volume_price'], 2);
|
$byVolume = round($cubicMeters * $rate['volume_price'], 2);
|
||||||
$freight = max($byTon, $byVolume);
|
$freight = max($byTon, $byVolume);
|
||||||
$delivery = ReverseLogisticsQuoteSnapshot::deliveryFeeFor($rate, $cubicMeters);
|
$delivery = ReverseLogisticsQuoteSnapshot::deliveryFeeFor($rate, $cubicMeters);
|
||||||
|
$pickup = ReverseLogisticsQuoteSnapshot::pickupFeeFor($rate, $cubicMeters);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'covered' => true, 'reason' => null, 'carrier' => $carrier, 'origin' => $rate['origin'], 'destination' => $rate['destination'],
|
'covered' => true, 'reason' => null, 'carrier' => $carrier, 'origin' => $rate['origin'], 'destination' => $rate['destination'],
|
||||||
'tons' => $tons, 'cubic_meters' => $cubicMeters, 'by_ton' => $byTon, 'by_volume' => $byVolume,
|
'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'],
|
'pending_confirmation' => $rate['pending_confirmation'], 'effective_date' => $rate['effective_date'],
|
||||||
'quote_id' => 'RL-' . substr(hash('sha256', $rate['sheet_name'] . '|' . $rate['effective_date']), 0, 20),
|
'quote_id' => 'RL-' . substr(hash('sha256', $rate['sheet_name'] . '|' . $rate['effective_date']), 0, 20),
|
||||||
'ton_price' => $rate['ton_price'], 'volume_price' => $rate['volume_price'],
|
'ton_price' => $rate['ton_price'], 'volume_price' => $rate['volume_price'],
|
||||||
|
|||||||
@ -200,6 +200,12 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
$volume = $this->amount($row[5] ?? null);
|
$volume = $this->amount($row[5] ?? null);
|
||||||
$source = trim((string) ($row[6] ?? ''));
|
$source = trim((string) ($row[6] ?? ''));
|
||||||
$delivery = $this->deliveryRule($row);
|
$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, [
|
$rates[] = array_replace($this->rateRow($context, count($rates) + 1, [
|
||||||
'origin' => $origin,
|
'origin' => $origin,
|
||||||
'destination' => $destination,
|
'destination' => $destination,
|
||||||
@ -209,7 +215,8 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
'source' => $source,
|
'source' => $source,
|
||||||
]), [
|
]), [
|
||||||
'layout' => self::LAYOUT_ROUTE_TON_VOLUME,
|
'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,
|
'origin_key' => $origin,
|
||||||
'destination_key' => $destination,
|
'destination_key' => $destination,
|
||||||
'origin_province' => trim((string) ($row[1] ?? '')),
|
'origin_province' => trim((string) ($row[1] ?? '')),
|
||||||
@ -221,15 +228,20 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
'pending_confirmation' => $source === '待物流确认',
|
'pending_confirmation' => $source === '待物流确认',
|
||||||
'remark' => trim((string) ($row[7] ?? '')),
|
'remark' => trim((string) ($row[7] ?? '')),
|
||||||
'source_cells' => $this->cellRef(4, $index).':'.$this->cellRef(5, $index),
|
'source_cells' => $this->cellRef(4, $index).':'.$this->cellRef(5, $index),
|
||||||
'available' => $ton !== null && $ton >= 0 && $volume !== null && $volume >= 0,
|
'available' => $ton !== null && $ton >= 0 && $volume !== null && $volume >= 0
|
||||||
] + $delivery);
|
&& ($start === '' || $validDate($start)) && ($end === '' || $validDate($end))
|
||||||
|
&& ($start === '' || $end === '' || $start <= $end),
|
||||||
|
] + $delivery + ['surcharge_label' => self::surchargeLabel($delivery)]);
|
||||||
}
|
}
|
||||||
$first = $rates[0] ?? $this->deliveryRule([]);
|
$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 [
|
return [
|
||||||
'rule' => array_replace($this->rateRule($context, [
|
'rule' => array_replace($this->rateRule($context, [
|
||||||
'pricing_mode' => self::LAYOUT_ROUTE_TON_VOLUME,
|
'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' => '吨价',
|
'base_label' => '吨价',
|
||||||
'increment_label' => '方价',
|
'increment_label' => '方价',
|
||||||
'route_label' => '出发仓 → 到达地;到达地可写完整名称、省份或「省份/城市」,多个用 / 分隔',
|
'route_label' => '出发仓 → 到达地;到达地可写完整名称、省份或「省份/城市」,多个用 / 分隔',
|
||||||
@ -502,22 +514,56 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
/**
|
/**
|
||||||
* 返货线路派送费:可选列 I 派送费门槛(方)、J 门槛含等于(是/否)、K 派送费(元/票)。
|
* 返货线路派送费:可选列 I 派送费门槛(方)、J 门槛含等于(是/否)、K 派送费(元/票)。
|
||||||
* 缺省沿用中铁客退口径:不足 15 方加收 50 元/票。
|
* 缺省沿用中铁客退口径:不足 15 方加收 50 元/票。
|
||||||
|
* 提货费(叠加在派送费之外,只有填了才收):可选列 L 提货费门槛(方)、M 门槛含等于(是/否)、N 提货费(元/票)。
|
||||||
*
|
*
|
||||||
* @param array<int,mixed> $row
|
* @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
|
private function deliveryRule(array $row): array
|
||||||
{
|
{
|
||||||
$threshold = $this->amount($row[8] ?? null);
|
$threshold = $this->amount($row[8] ?? null);
|
||||||
$fee = $this->amount($row[10] ?? 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 [
|
return [
|
||||||
'delivery_threshold' => $threshold ?? 15.0,
|
'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,
|
'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 */
|
/** @param array{delivery_threshold:float,delivery_inclusive:bool,delivery_fee:float} $rule */
|
||||||
public static function deliveryLabel(array $rule): string
|
public static function deliveryLabel(array $rule): string
|
||||||
{
|
{
|
||||||
@ -689,6 +735,12 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
|
|
||||||
private function inferCompanyName(string $name): string
|
private function inferCompanyName(string $name): string
|
||||||
{
|
{
|
||||||
|
foreach (['申通' => '申通退货', '常州德邦' => '常州德邦逆向', '中通快运' => '中通快运逆向',
|
||||||
|
'中铁' => '中铁客退', '常州松宇货运' => '常州松宇货运'] as $match => $displayName) {
|
||||||
|
if (str_contains($name, $match)) {
|
||||||
|
return $displayName;
|
||||||
|
}
|
||||||
|
}
|
||||||
$companyName = trim((string) preg_replace('/(?:逆向|退货|报价表|报价)$/u', '', $name));
|
$companyName = trim((string) preg_replace('/(?:逆向|退货|报价表|报价)$/u', '', $name));
|
||||||
|
|
||||||
return $companyName !== '' ? $companyName : $name;
|
return $companyName !== '' ? $companyName : $name;
|
||||||
@ -696,6 +748,11 @@ final class ReverseLogisticsQuoteSnapshot
|
|||||||
|
|
||||||
private function inferCarrier(string $name): string
|
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 '中铁客退';
|
||||||
if (str_contains($name, '松宇')) return '常州松宇货运';
|
if (str_contains($name, '松宇')) return '常州松宇货运';
|
||||||
|
|
||||||
|
|||||||
181
app/Support/ShippingTrackingRefresh.php
Normal file
181
app/Support/ShippingTrackingRefresh.php
Normal file
@ -0,0 +1,181 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
/** 只校准现有包裹的运单标识,不重算商品、重量或运费。 */
|
||||||
|
class ShippingTrackingRefresh
|
||||||
|
{
|
||||||
|
public const DATASET = 'derived.shipping-tracking-refresh';
|
||||||
|
private ?bool $hasDetailsMirror = null;
|
||||||
|
|
||||||
|
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
|
||||||
|
|
||||||
|
public function sync(array $ids = [], int $maxBatches = 4): array
|
||||||
|
{
|
||||||
|
$db = DB::connection('business_mirror');
|
||||||
|
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
|
||||||
|
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
|
||||||
|
$targeted = $ids !== [];
|
||||||
|
$resume = !$targeted && is_array($cursor) && in_array($state->status, ['running', 'failed'], true);
|
||||||
|
$watermark = $state ? json_decode($state->high_watermark ?? 'null', true) : null;
|
||||||
|
$from = $resume ? $cursor['from'] : (isset($watermark['until'])
|
||||||
|
? \Illuminate\Support\Carbon::parse($watermark['until'])->subHours(48)->format('Y-m-d H:i:s')
|
||||||
|
: now()->subHours(48)->format('Y-m-d H:i:s'));
|
||||||
|
$until = $resume ? $cursor['until'] : now()->addSecond()->format('Y-m-d H:i:s');
|
||||||
|
$last = $resume ? (int) $cursor['last_id'] : 0;
|
||||||
|
$generation = $resume ? $state->generation : (string) Str::uuid();
|
||||||
|
$scanned = $resume ? (int)($cursor['scanned']??0) : 0;
|
||||||
|
$changed = $resume ? (int)($cursor['changed']??0) : 0;
|
||||||
|
$base = ['source_key'=>'operations_replica','source_object'=>'rpt.jst_order_express_details',
|
||||||
|
'target_table'=>'jst_oms_shipping','run_mode'=>'incremental','generation'=>$generation,
|
||||||
|
'status'=>'running','last_attempted_at'=>now(),'last_error_code'=>null,'updated_at'=>now()];
|
||||||
|
if (!$targeted) $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::DATASET], $base + [
|
||||||
|
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),
|
||||||
|
'created_at'=>$state->created_at??now()]);
|
||||||
|
try {
|
||||||
|
$names = $this->repairMissingCourierNames($generation);
|
||||||
|
for ($batch=0; $batch<max(1,$maxBatches); $batch++) {
|
||||||
|
$keys = $targeted ? array_values(array_unique(array_map('intval',$ids))) : $this->keys($last,$from,$until);
|
||||||
|
$scanned += count($keys);
|
||||||
|
$existing = $keys === [] ? [] : $db->table('jst_oms_shipping')->whereIn('source_id',$keys)->distinct()->pluck('source_id')->all();
|
||||||
|
foreach (array_chunk($existing,200) as $part) {
|
||||||
|
$current = $db->table('jst_oms_shipping')->whereIn('source_id',$part)
|
||||||
|
->distinct()->get(['source_id','express_no','express_name1'])->groupBy('source_id');
|
||||||
|
foreach ($this->details($part) as $row) {
|
||||||
|
$new = UnshippedWaybills::normalize($row['logistic_id']??null);
|
||||||
|
$name = trim((string)($row['logistic_company_name']??''));
|
||||||
|
$same = ($current[$row['id']]??collect())->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
|
||||||
|
&& ($name==='' || (string)$r->express_name1===$name));
|
||||||
|
if ($same) continue;
|
||||||
|
$changed += $this->apply($row, $generation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($targeted || count($keys)<5000) {
|
||||||
|
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
|
||||||
|
'status'=>'succeeded','cursor'=>null,'high_watermark'=>json_encode(['until'=>$until]),'last_succeeded_at'=>now(),'initial_completed_at'=>$state->initial_completed_at??now(),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
|
||||||
|
return ['status'=>'succeeded','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
|
||||||
|
}
|
||||||
|
$next = (int) end($keys);
|
||||||
|
if ($next <= $last) throw new RuntimeException('tracking_cursor_not_advanced');
|
||||||
|
$last=$next;
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
|
||||||
|
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
|
||||||
|
}
|
||||||
|
return ['status'=>'running','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function keys(int $last,string $from,string $until): array
|
||||||
|
{
|
||||||
|
// 先取窄键,再按明确主键读详情,避免宽行加日期过滤扫描超时。
|
||||||
|
return array_column($this->queries->forSourceWithTimeout('operations_replica',30)->select(
|
||||||
|
'SELECT TOP (5000) id FROM rpt.jst_order_express_details WHERE id > CAST(? AS int) AND updatedAt >= CAST(? AS datetime) AND updatedAt < CAST(? AS datetime) ORDER BY id',
|
||||||
|
[$last,$from,$until]),'id');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function details(array $ids): array
|
||||||
|
{
|
||||||
|
return $this->queries->forSourceWithTimeout('operations_replica',30)->select(
|
||||||
|
'SELECT id,updatedAt,inner_order_id,so_id,logistic_id,logistic_company_name FROM rpt.jst_order_express_details WHERE id IN ('
|
||||||
|
.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).') ORDER BY id',$ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function apply(array $source, string $generation): int
|
||||||
|
{
|
||||||
|
$db=DB::connection('business_mirror');$new=UnshippedWaybills::normalize($source['logistic_id']??null);
|
||||||
|
if ($new==='' || strcasecmp($new,'OuterWMS')===0) return 0;
|
||||||
|
return $db->transaction(function() use($db,$source,$new,$generation): int {
|
||||||
|
$rows=$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->lockForUpdate()->get();
|
||||||
|
if($rows->isEmpty()) return 0;
|
||||||
|
$old=UnshippedWaybills::normalize($rows->first()->express_no);
|
||||||
|
$courier=trim((string)($source['logistic_company_name']??''));
|
||||||
|
$mirror = $this->hasDetailsMirror()
|
||||||
|
? $db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->first() : null;
|
||||||
|
$sameMirror = !$mirror || (UnshippedWaybills::normalize($mirror->logistic_id)===$new
|
||||||
|
&& ($courier==='' || (string)$mirror->logistic_company_name===$courier));
|
||||||
|
if($sameMirror && $rows->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
|
||||||
|
&& ($courier==='' || (string)$r->express_name1===$courier))) return 0;
|
||||||
|
if(!$rows->every(fn($r)=>(string)$r->trade_no===trim((string)($source['so_id']??'')))) throw new RuntimeException('tracking_order_mismatch');
|
||||||
|
$this->backup($generation, (string)$source['id'], ['before'=>$rows->all(),'mirror_before'=>$mirror,'source'=>$source]);
|
||||||
|
$set=['express_no'=>$new];if($courier!=='')$set['express_name1']=$courier;
|
||||||
|
if($old!=='' && $old!==$new && strcasecmp($old,'OuterWMS')!==0){
|
||||||
|
$set['front_no']=$old;
|
||||||
|
self::recordChange((int)$source['id'],$old,(string)$rows->first()->express_name1,$new,$courier,
|
||||||
|
(string)($source['updatedAt']??now()),(string)$rows->first()->trade_no);
|
||||||
|
}
|
||||||
|
$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->update($set);
|
||||||
|
if ($mirror !== null) {
|
||||||
|
$db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->update([
|
||||||
|
'logistic_id'=>$new, 'logistic_company_name'=>$courier?:$mirror->logistic_company_name,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasDetailsMirror(): bool
|
||||||
|
{
|
||||||
|
return $this->hasDetailsMirror ??= DB::connection('business_mirror')->getSchemaBuilder()->hasTable('js_jst_order_express_details');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只补已有换单记录中有同源、同旧单号证据的空名称;每轮有界读取。 */
|
||||||
|
private function repairMissingCourierNames(string $generation): int
|
||||||
|
{
|
||||||
|
$db = DB::connection('business_mirror');
|
||||||
|
if (!$this->hasDetailsMirror()) return 0;
|
||||||
|
$rows = $db->table('courier_unshipped_waybills')->where('source','replacement')
|
||||||
|
->whereNull('courier_name')->where('evidence_no','like','shipping:%')->orderBy('id')->limit(500)->get();
|
||||||
|
$ids = $rows->map(fn($r)=>(int)substr($r->evidence_no,9))->all();
|
||||||
|
$details = $db->table('js_jst_order_express_details')->whereIn('id',$ids)
|
||||||
|
->get(['id','logistic_id','logistic_company_name'])->keyBy('id');
|
||||||
|
$changed = 0;
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$source = $details[(int)substr($row->evidence_no,9)] ?? null;
|
||||||
|
$name = trim((string)($source->logistic_company_name ?? ''));
|
||||||
|
if (!$source || $name==='' || UnshippedWaybills::normalize($source->logistic_id)!==$row->waybill_no) continue;
|
||||||
|
$this->backup($generation, 'name-'.$row->id, ['before'=>$row,'source'=>$source]);
|
||||||
|
$changed += $db->table('courier_unshipped_waybills')->where('id',$row->id)->whereNull('courier_name')->update(['courier_name'=>$name]);
|
||||||
|
}
|
||||||
|
return $changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function backup(string $generation, string $key, array $data): void
|
||||||
|
{
|
||||||
|
$dir=storage_path('app/private/maintenance/tracking-refresh/'.$generation);
|
||||||
|
if(!is_dir($dir) && !mkdir($dir,0700,true) && !is_dir($dir)) throw new RuntimeException('tracking_backup_failed');
|
||||||
|
$payload=json_encode($data,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
|
||||||
|
$path=$dir.'/'.$key.'-'.bin2hex(random_bytes(4)).'.json';
|
||||||
|
if(file_put_contents($path,$payload,LOCK_EX)!==strlen($payload)) throw new RuntimeException('tracking_backup_failed');
|
||||||
|
chmod($path,0600);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function recordChange(int $sourceId,string $old,string $oldCourier,string $new,string $newCourier,string $time,string $trade): void
|
||||||
|
{
|
||||||
|
$old=UnshippedWaybills::normalize($old);$new=UnshippedWaybills::normalize($new);
|
||||||
|
if($old===''||$new===''||$old===$new||strcasecmp($old,'OuterWMS')===0||strcasecmp($new,'OuterWMS')===0)return;
|
||||||
|
$db=DB::connection('business_mirror');$order='shipping:'.$sourceId;
|
||||||
|
$log=['old_waybill'=>$old,'new_waybill'=>$new,'old_courier'=>$oldCourier,'new_courier'=>$newCourier,
|
||||||
|
'operator'=>'系统同步','remark'=>$oldCourier.':'.$old.'->'.$newCourier.':'.$new];
|
||||||
|
$db->table('courier_unshipped_order_logs')->updateOrInsert(['order_no'=>$order,'operated_at'=>$time,'old_waybill'=>$old],$log);
|
||||||
|
if (!$db->table('jst_oms_shipping')->where('source_id','<>',$sourceId)->whereIn('express_no',[$old,'@'.$old])->exists()) {
|
||||||
|
$db->table('courier_unshipped_waybills')->updateOrInsert(['source'=>'replacement','evidence_no'=>$order,'waybill_no'=>$old],
|
||||||
|
['courier_name'=>$oldCourier?:null,'new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null,'trade_no'=>$trade,
|
||||||
|
'evidence_time'=>$time,'evidence_text'=>'按同一包裹源键核实换单前后信息','operator'=>'系统同步']);
|
||||||
|
}
|
||||||
|
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)
|
||||||
|
->update(['new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null]);
|
||||||
|
// A→B→A 时,最终正在使用的号码不再作为未发出旧号。
|
||||||
|
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)->where('waybill_no',$new)->delete();
|
||||||
|
$db->table('courier_unshipped_sync')->where('source','replacement')->update([
|
||||||
|
'row_count'=>$db->table('courier_unshipped_waybills')->where('source','replacement')->count(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
136
app/Support/UnshippedSourceSynchronizer.php
Normal file
136
app/Support/UnshippedSourceSynchronizer.php
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Support;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
|
||||||
|
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||||
|
use RuntimeException;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
/** 未发出名单的受控刷新:先完成来源快照,再原子发布,网页不查询上游。 */
|
||||||
|
class UnshippedSourceSynchronizer
|
||||||
|
{
|
||||||
|
public const WAREHOUSE_DATASET = 'derived.courier-unshipped-warehouse';
|
||||||
|
|
||||||
|
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries, private readonly UnshippedWaybills $waybills) {}
|
||||||
|
|
||||||
|
public function intercept(string $source): int
|
||||||
|
{
|
||||||
|
$db = $this->waybills->connection();
|
||||||
|
$state = $db->table('business_mirror_table_states')->where('dataset_key', ReturnedParcelSynchronizer::DATASET)->first();
|
||||||
|
if (!$state || $state->status !== 'succeeded' || !$state->last_succeeded_at) throw new RuntimeException('退回件明细尚未完成刷新,保留上次结果。');
|
||||||
|
$history = $this->waybills->results()->where('source', 'intercept')->where('evidence_no', 'like', 'history:%')->max('evidence_time');
|
||||||
|
$from = $history ? substr($history, 0, 10) : UnshippedWaybills::START;
|
||||||
|
if (substr((string)$state->window_started_at, 0, 10) > $from) throw new RuntimeException('退回件来源覆盖不足,保留上次结果。');
|
||||||
|
$kind = $source === 'intercept_taobao' ? 'taobao' : 'regular';
|
||||||
|
$generation = (string) Str::uuid(); $missing = 0;
|
||||||
|
$db->table('courier_unshipped_stage')->where('source', $source)->delete();
|
||||||
|
$candidates = $db->table(ReturnedParcelSynchronizer::TABLE)->where('source_kind', $kind)
|
||||||
|
->where('reason', UnshippedWaybills::SOURCES['intercept'])->where('received_at', '>=', $from)
|
||||||
|
->selectRaw('after_sales_id,order_id,online_order_no,shop,MIN(received_at) AS received_at')
|
||||||
|
->groupBy('after_sales_id','order_id','online_order_no','shop')->orderBy('after_sales_id');
|
||||||
|
$candidates->chunk(100, function ($batch) use ($source, $generation, $kind, &$missing): void {
|
||||||
|
$ids = $batch->pluck('order_id')->filter(fn($id)=>ctype_digit((string)$id) && (int)$id > 0)->unique()->values()->all();
|
||||||
|
$orders = $ids === [] ? [] : $this->originalOrders($kind, $ids);
|
||||||
|
$byOrder = [];
|
||||||
|
foreach ($orders as $order) {
|
||||||
|
$number = UnshippedWaybills::normalize($order['l_id'] ?? null);
|
||||||
|
if ($number !== '' && (!isset($byOrder[$order['o_id']]) || strcmp($number,$byOrder[$order['o_id']]['l_id'])<0)) $byOrder[$order['o_id']] = array_replace($order, ['l_id'=>$number]);
|
||||||
|
}
|
||||||
|
$rows = [];
|
||||||
|
foreach ($batch as $refund) {
|
||||||
|
$order = $byOrder[$refund->order_id] ?? null;
|
||||||
|
if (!$order) { $missing++; continue; }
|
||||||
|
$rows[] = ['source'=>$source,'waybill_no'=>UnshippedWaybills::normalize($order['l_id']),
|
||||||
|
'evidence_no'=>(string)$refund->after_sales_id,'evidence_time'=>$refund->received_at,
|
||||||
|
'courier_name'=>$order['logistics_company'],'o_id'=>$refund->order_id,'trade_no'=>$refund->online_order_no,
|
||||||
|
'shop_name'=>$refund->shop,'evidence_text'=>UnshippedWaybills::SOURCES['intercept']];
|
||||||
|
}
|
||||||
|
$this->stage($source,$generation,$rows);
|
||||||
|
});
|
||||||
|
return $this->waybills->publishStage($source,$generation,$missing);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function originalOrders(string $kind, array $ids): array
|
||||||
|
{
|
||||||
|
$table = $kind === 'taobao' ? 'jst_qmcust_orderlist' : 'jst_Orders';
|
||||||
|
return $this->queries->forSourceWithTimeout('operations_replica',15)->select(
|
||||||
|
'SELECT Id,o_id,l_id,logistics_company FROM rpt.'.$table.' WHERE o_id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function warehouse(int $maxBatches = 0, ?callable $progress = null): array
|
||||||
|
{
|
||||||
|
$db=$this->waybills->connection();$state=$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->first();
|
||||||
|
$cursor=$state?json_decode($state->cursor??'null',true):null;
|
||||||
|
$resume=$state && in_array($state->status,['running','failed'],true) && is_array($cursor);
|
||||||
|
$generation=$resume?$state->generation:(string)Str::uuid();$last=$resume?(int)$cursor['last_id']:0;
|
||||||
|
$high=$resume?(int)$cursor['high_id']:$this->warehouseHighId();$scanned=$resume?(int)$cursor['scanned']:0;
|
||||||
|
if(!$resume)$db->table('courier_unshipped_stage')->where('source','warehouse')->delete();
|
||||||
|
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::WAREHOUSE_DATASET],
|
||||||
|
['source_key'=>'operations_replica','source_object'=>'rpt.jst_workOrderInfo','target_table'=>'courier_unshipped_stage',
|
||||||
|
'status'=>'running','run_mode'=>'full','generation'=>$generation,'last_attempted_at'=>now(),'updated_at'=>now(),
|
||||||
|
'created_at'=>$state->created_at??now()]);
|
||||||
|
$batches=0;
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
$keys=$this->warehouseKeys($last,$high,5000);
|
||||||
|
if($keys===[])break;
|
||||||
|
$ids=[];foreach($keys as $key)if($key['woTypeId']===UnshippedWaybills::WAREHOUSE_WORK_TYPE)$ids[]=$key['Id'];
|
||||||
|
foreach(array_chunk($ids,100) as $part){
|
||||||
|
$rows=[];foreach($this->warehouseDetails($part) as $order){
|
||||||
|
if(substr($order['created'],0,10)<UnshippedWaybills::START || in_array($order['status'],UnshippedWaybills::WAREHOUSE_EXCLUDED_STATUSES,true))continue;
|
||||||
|
$fields=array_column(json_decode($order['businessFieldList'],true,512,JSON_THROW_ON_ERROR)?:[],'value','fieldId');
|
||||||
|
$number=UnshippedWaybills::normalize($fields['lIdField']??null);if($number==='')continue;
|
||||||
|
$rows[]=['source'=>'warehouse','waybill_no'=>$number,'evidence_no'=>$order['woNo'],'evidence_time'=>$order['created'],
|
||||||
|
'o_id'=>$fields['o_id']??null,'courier_name'=>$fields['logisticsField']??null,'evidence_text'=>trim($order['status'].' '.$order['title'])];
|
||||||
|
}
|
||||||
|
$this->stage('warehouse',$generation,$rows);
|
||||||
|
}
|
||||||
|
$next=(int)end($keys)['Id'];
|
||||||
|
if ($next <= $last) throw new RuntimeException('warehouse_cursor_not_advanced');
|
||||||
|
$last=$next;$scanned+=count($keys);$batches++;
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([
|
||||||
|
'cursor'=>json_encode(['last_id'=>$last,'high_id'=>$high,'scanned'=>$scanned]),'last_upserted_rows'=>$scanned,'updated_at'=>now()]);
|
||||||
|
$progress && $progress($scanned,$last,$high);
|
||||||
|
if($maxBatches>0 && $batches>=$maxBatches && $last<$high)return ['status'=>'running','scanned'=>$scanned];
|
||||||
|
} while($last<$high);
|
||||||
|
$rows=$this->waybills->publishStage('warehouse',$generation,0);
|
||||||
|
$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([
|
||||||
|
'status'=>'succeeded','cursor'=>null,'initial_completed_at'=>now(),'last_succeeded_at'=>now(),'last_full_succeeded_at'=>now(),
|
||||||
|
'mirror_row_count'=>$rows,'last_error_code'=>null,'updated_at'=>now()]);
|
||||||
|
return ['status'=>'succeeded','scanned'=>$scanned,'rows'=>$rows];
|
||||||
|
}catch(Throwable $e){$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);throw $e;}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function warehouseHighId(): int
|
||||||
|
{
|
||||||
|
return (int)$this->queries->forSourceWithTimeout('operations_replica',15)->scalar('SELECT MAX(Id) FROM rpt.jst_workOrderInfo');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function warehouseKeys(int $last,int $high,int $limit): array
|
||||||
|
{
|
||||||
|
return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT TOP ('.$limit.') Id,woTypeId FROM rpt.jst_workOrderInfo WHERE Id > ? AND Id <= ? ORDER BY Id',[$last,$high]);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function warehouseDetails(array $ids): array
|
||||||
|
{
|
||||||
|
return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT Id,woNo,created,status,title,businessFieldList FROM rpt.jst_workOrderInfo WHERE Id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function stage(string $source,string $generation,array $rows): void
|
||||||
|
{
|
||||||
|
if($rows===[])return;
|
||||||
|
if ($source === 'warehouse') {
|
||||||
|
$numbers = array_column(array_filter($rows, fn ($row) => empty($row['courier_name'])), 'waybill_no');
|
||||||
|
$couriers = $numbers === [] ? [] : $this->waybills->connection()->table('jst_oms_shipping')->whereIn('express_no', $numbers)
|
||||||
|
->orderBy('id')->pluck('express_name1', 'express_no')->all();
|
||||||
|
foreach ($rows as &$row) $row['courier_name'] = $row['courier_name'] ?: ($couriers[$row['waybill_no']] ?? null);
|
||||||
|
unset($row);
|
||||||
|
}
|
||||||
|
$values=[];foreach($rows as $r)$values[]=$r+['generation'=>$generation,'row_key'=>hash('sha256',$r['evidence_no'].'|'.$r['waybill_no']),
|
||||||
|
'courier_name'=>null,'trade_no'=>null,'o_id'=>null,'shop_name'=>null,'new_courier_name'=>null,'new_waybill_no'=>null,'operator'=>null,'evidence_text'=>null];
|
||||||
|
DB::connection('business_mirror')->table('courier_unshipped_stage')->upsert($values,['source','row_key'],array_keys($values[0]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Support;
|
namespace App\Support;
|
||||||
|
|
||||||
|
use App\Support\CourierBills\WaybillMatch;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
@ -12,8 +13,8 @@ final class UnshippedWaybills
|
|||||||
public const HISTORY_PREFIX = 'history:';
|
public const HISTORY_PREFIX = 'history:';
|
||||||
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
|
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
|
||||||
|
|
||||||
private const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
|
public const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
|
||||||
private const WAREHOUSE_EXCLUDED_STATUSES = [
|
public const WAREHOUSE_EXCLUDED_STATUSES = [
|
||||||
'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消',
|
'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消',
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -53,6 +54,12 @@ final class UnshippedWaybills
|
|||||||
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
|
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static function isPlaceholder(?string $number): bool
|
||||||
|
{
|
||||||
|
// 外部仓占位标记不是运单号,不能作为未发出或换单依据。
|
||||||
|
return strcasecmp(self::normalize($number), 'OuterWMS') === 0;
|
||||||
|
}
|
||||||
|
|
||||||
public static function parseRemark(string $remark): ?array
|
public static function parseRemark(string $remark): ?array
|
||||||
{
|
{
|
||||||
if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) {
|
if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) {
|
||||||
@ -61,7 +68,7 @@ final class UnshippedWaybills
|
|||||||
$old = self::normalize($parts[2]);
|
$old = self::normalize($parts[2]);
|
||||||
$new = self::normalize($parts[4]);
|
$new = self::normalize($parts[4]);
|
||||||
foreach ([$old, $new] as $number) {
|
foreach ([$old, $new] as $number) {
|
||||||
if (!preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null;
|
if (self::isPlaceholder($number) || !preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])];
|
return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])];
|
||||||
@ -75,10 +82,12 @@ final class UnshippedWaybills
|
|||||||
public function unshippedSources(array $waybills): array
|
public function unshippedSources(array $waybills): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
foreach (array_chunk(array_unique(array_filter(array_map(self::normalize(...), $waybills))), 500) as $chunk) {
|
$numbers = array_values(array_unique(array_filter(array_map(self::normalize(...), $waybills),
|
||||||
foreach ($this->results()->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'source']) as $row) {
|
fn ($number) => $number !== '' && !self::isPlaceholder($number))));
|
||||||
|
foreach (WaybillMatch::find($this->results(), 'waybill_no', $numbers, ['waybill_no', 'source']) as $number => $match) {
|
||||||
|
foreach ($match['rows'] as $row) {
|
||||||
$label = self::label($row->source);
|
$label = self::label($row->source);
|
||||||
$result[$row->waybill_no][$label] = $label;
|
$result[$number][$label] = $label;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,7 +109,7 @@ final class UnshippedWaybills
|
|||||||
$cutoff = (clone $history)->max('evidence_time');
|
$cutoff = (clone $history)->max('evidence_time');
|
||||||
if ($cutoff !== null) {
|
if ($cutoff !== null) {
|
||||||
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
|
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
|
||||||
$rows = array_filter($rows, fn ($row) => substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10)
|
$rows = array_filter($rows, fn ($row) => (str_starts_with($row['evidence_no'], 'shipping:') || substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10))
|
||||||
&& !isset($covered[$row['waybill_no']]));
|
&& !isset($covered[$row['waybill_no']]));
|
||||||
}
|
}
|
||||||
$db->transaction(function () use ($db, $source, $rows, $missing): void {
|
$db->transaction(function () use ($db, $source, $rows, $missing): void {
|
||||||
@ -119,7 +128,7 @@ final class UnshippedWaybills
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (Throwable $error) {
|
} catch (Throwable $error) {
|
||||||
if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) {
|
if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '尚无订单操作日志或发货换单记录。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) {
|
||||||
report($error);
|
report($error);
|
||||||
$warning = '读取失败,保留上次同步结果。';
|
$warning = '读取失败,保留上次同步结果。';
|
||||||
} else {
|
} else {
|
||||||
@ -186,29 +195,104 @@ final class UnshippedWaybills
|
|||||||
private function replacements(): array
|
private function replacements(): array
|
||||||
{
|
{
|
||||||
$logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START)
|
$logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START)
|
||||||
->where('operated_at', '<', today())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor();
|
->where('operated_at', '<=', now())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor();
|
||||||
$rows = [];
|
$rows = [];
|
||||||
$currentOrder = null;
|
$currentOrder = null;
|
||||||
$finalNumber = null;
|
$finalNumber = null;
|
||||||
|
$finalCourier = null;
|
||||||
foreach ($logs as $log) {
|
foreach ($logs as $log) {
|
||||||
|
if (self::isPlaceholder($log->old_waybill) || self::isPlaceholder($log->new_waybill)) continue;
|
||||||
if ($currentOrder !== $log->order_no) {
|
if ($currentOrder !== $log->order_no) {
|
||||||
$currentOrder = $log->order_no;
|
$currentOrder = $log->order_no;
|
||||||
$finalNumber = $log->new_waybill;
|
$finalNumber = $log->new_waybill;
|
||||||
|
$finalCourier = $log->new_courier;
|
||||||
}
|
}
|
||||||
if ($log->old_waybill === $finalNumber) continue;
|
if ($log->old_waybill === $finalNumber) continue;
|
||||||
|
if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$log->old_waybill, '@'.$log->old_waybill])->exists()) continue;
|
||||||
$key = $log->order_no.'|'.$log->old_waybill;
|
$key = $log->order_no.'|'.$log->old_waybill;
|
||||||
$rows[$key] ??= [
|
$rows[$key] ??= [
|
||||||
'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier,
|
'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier,
|
||||||
'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at,
|
'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at,
|
||||||
'evidence_text' => $log->remark, 'operator' => $log->operator,
|
'evidence_text' => $log->remark, 'operator' => $log->operator,
|
||||||
'new_courier_name' => $log->new_courier, 'new_waybill_no' => $log->new_waybill,
|
'new_courier_name' => $finalCourier, 'new_waybill_no' => $finalNumber,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
if ($currentOrder === null) throw new RuntimeException('未导入订单操作日志。');
|
// 发货同步已明确保留的换单前单号也是证据;不是用订单商品或当前单号推断换单。
|
||||||
|
if ($this->connection()->getSchemaBuilder()->hasColumn('jst_oms_shipping', 'front_no')) {
|
||||||
|
$ships = $this->connection()->table('jst_oms_shipping')->where('ship_time', '>=', self::START)
|
||||||
|
->whereNotNull('front_no')->where('front_no', '<>', '')->whereColumn('front_no', '<>', 'express_no')
|
||||||
|
->select(['id', 'source_id', 'front_no', 'express_no', 'trade_no', 'ship_time', 'express_name1'])->lazyById(500);
|
||||||
|
foreach ($ships as $ship) {
|
||||||
|
$old = self::normalize($ship->front_no); $new = self::normalize($ship->express_no);
|
||||||
|
if ($old === '' || $new === '' || $old === $new || self::isPlaceholder($old) || self::isPlaceholder($new)) continue;
|
||||||
|
// 旧号码仍是现有发货包裹时,不因另一条换单记录把它排除。
|
||||||
|
if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$old, '@'.$old])->exists()) continue;
|
||||||
|
$key = 'shipping:'.$ship->source_id.'|'.$old;
|
||||||
|
$rows[$key] = [
|
||||||
|
'source' => 'replacement', 'waybill_no' => $old, 'courier_name' => $rows[$key]['courier_name'] ?? null,
|
||||||
|
'evidence_no' => 'shipping:'.$ship->source_id, 'trade_no' => $ship->trade_no,
|
||||||
|
'evidence_time' => $rows[$key]['evidence_time'] ?? $ship->ship_time, 'new_courier_name' => $ship->express_name1,
|
||||||
|
'new_waybill_no' => $new, 'evidence_text' => $rows[$key]['evidence_text'] ?? '发货镜像明确记录换单前单号;依据时间为发货时间,非换单操作时间',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($currentOrder === null && $rows === []) throw new RuntimeException('尚无订单操作日志或发货换单记录。');
|
||||||
|
|
||||||
|
// 已核实保存的历史旧名在上游镜像更新后仍需保留。
|
||||||
|
foreach ($this->results()->where('source','replacement')->whereNotNull('courier_name')
|
||||||
|
->get(['evidence_no','waybill_no','courier_name']) as $saved) {
|
||||||
|
$key=$saved->evidence_no.'|'.$saved->waybill_no;
|
||||||
|
if (isset($rows[$key]) && empty($rows[$key]['courier_name'])) $rows[$key]['courier_name']=$saved->courier_name;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 历史镜像只有仍明确保留同一个旧单号时,才能用它的快递名称补空。
|
||||||
|
$sourceIds = [];
|
||||||
|
foreach ($rows as $key => $row) {
|
||||||
|
if (empty($row['courier_name']) && preg_match('/^shipping:(\d+)$/', $row['evidence_no'], $m)) $sourceIds[$key]=(int)$m[1];
|
||||||
|
}
|
||||||
|
if ($sourceIds !== [] && $this->connection()->getSchemaBuilder()->hasTable('js_jst_order_express_details')) {
|
||||||
|
foreach (array_chunk(array_values(array_unique($sourceIds)),500) as $ids) {
|
||||||
|
$oldRecords=$this->connection()->table('js_jst_order_express_details')->whereIn('id',$ids)
|
||||||
|
->get(['id','logistic_id','logistic_company_name'])->keyBy('id');
|
||||||
|
foreach ($sourceIds as $key=>$id) {
|
||||||
|
$record=$oldRecords[$id]??null;
|
||||||
|
if($record && self::normalize($record->logistic_id)===$rows[$key]['waybill_no']) {
|
||||||
|
$rows[$key]['courier_name']=trim((string)$record->logistic_company_name)?:null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return [$rows, 0];
|
return [$rows, 0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 完整批次才发布;失败/中断保留上一版及历史导入。 */
|
||||||
|
public function publishStage(string $source, string $generation, int $missing): int
|
||||||
|
{
|
||||||
|
$db = $this->connection();
|
||||||
|
return $db->transaction(function () use ($db, $source, $generation, $missing): int {
|
||||||
|
$historySource = in_array($source, ['intercept_regular', 'intercept_taobao'], true) ? 'intercept' : $source;
|
||||||
|
$history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%');
|
||||||
|
$cutoff = (clone $history)->max('evidence_time');
|
||||||
|
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
|
||||||
|
$this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
|
||||||
|
$count = 0;
|
||||||
|
$db->table('courier_unshipped_stage')->where('source', $source)->where('generation', $generation)
|
||||||
|
->orderBy('row_key')->chunkById(300, function ($batch) use ($cutoff, $covered, &$count): void {
|
||||||
|
$rows = [];
|
||||||
|
foreach ($batch as $row) {
|
||||||
|
if ($cutoff !== null && (substr($row->evidence_time, 0, 10) <= substr($cutoff, 0, 10) || isset($covered[$row->waybill_no]))) continue;
|
||||||
|
$values = (array) $row; unset($values['generation'], $values['row_key']); $rows[] = $values;
|
||||||
|
}
|
||||||
|
if ($rows !== []) { $this->results()->insert($rows); $count += count($rows); }
|
||||||
|
}, 'row_key');
|
||||||
|
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [
|
||||||
|
'last_success_at' => now(), 'row_count' => $count, 'missing_count' => $missing, 'warning' => null,
|
||||||
|
]);
|
||||||
|
return $count;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private function warehouse(): array
|
private function warehouse(): array
|
||||||
{
|
{
|
||||||
$db = $this->connection();
|
$db = $this->connection();
|
||||||
|
|||||||
@ -127,6 +127,14 @@ class SidebarPermissions
|
|||||||
$allowed[] = 'process-data/invoice-data';
|
$allowed[] = 'process-data/invoice-data';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (in_array('courier-payables/shipping-data', $allowed, true)) {
|
||||||
|
$allowed[] = 'courier-payables/returned-parcels';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array('supplier-reconciliation/finance-data', $allowed, true)) {
|
||||||
|
$allowed[] = 'supplier-reconciliation/raw-statements';
|
||||||
|
}
|
||||||
|
|
||||||
return array_values(array_unique($allowed));
|
return array_values(array_unique($allowed));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -43,6 +43,7 @@ return [
|
|||||||
* existing table, but do not keep querying the upstream source.
|
* existing table, but do not keep querying the upstream source.
|
||||||
*/
|
*/
|
||||||
'datasets' => [
|
'datasets' => [
|
||||||
|
'jiansun.dbo.jst_shipFreight_view' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货数据专线核算运费'],
|
||||||
// Small organization and catalog dimensions stay in MariaDB.
|
// Small organization and catalog dimensions stay in MariaDB.
|
||||||
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
|
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
|
||||||
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],
|
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],
|
||||||
@ -81,6 +82,9 @@ return [
|
|||||||
|
|
||||||
// 淘系(天猫/淘宝)订单与售后:聚水潭 qmcust 表族,订单售后费用明细页需要与
|
// 淘系(天猫/淘宝)订单与售后:聚水潭 qmcust 表族,订单售后费用明细页需要与
|
||||||
// jst_Orders 系列合并读取,因此保持常规同步(不等待列式库启用)。
|
// jst_Orders 系列合并读取,因此保持常规同步(不等待列式库启用)。
|
||||||
|
'operations_replica.rpt.jst_qmcust_salesoutbound' => [
|
||||||
|
'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货线上重量精度恢复', 'sync' => 'always',
|
||||||
|
],
|
||||||
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
'operations_replica.rpt.jst_qmcust_orderlist' => [
|
||||||
'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系订单',
|
'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系订单',
|
||||||
'partition_column' => 'order_date', 'sync' => 'always',
|
'partition_column' => 'order_date', 'sync' => 'always',
|
||||||
|
|||||||
@ -586,7 +586,6 @@ $navigation = [
|
|||||||
'title' => '账单流水数据',
|
'title' => '账单流水数据',
|
||||||
'icon' => 'receipt_long',
|
'icon' => 'receipt_long',
|
||||||
'pages' => [
|
'pages' => [
|
||||||
['slug' => 'bank-transactions', 'title' => '银行账户流水'],
|
|
||||||
[
|
[
|
||||||
'slug' => 'store-receiving-bills',
|
'slug' => 'store-receiving-bills',
|
||||||
'title' => '店铺收款账户账单',
|
'title' => '店铺收款账户账单',
|
||||||
@ -814,6 +813,7 @@ $navigation = [
|
|||||||
'icon' => 'fact_check',
|
'icon' => 'fact_check',
|
||||||
'pages' => [
|
'pages' => [
|
||||||
['slug' => 'finance-data', 'title' => '财务端数据'],
|
['slug' => 'finance-data', 'title' => '财务端数据'],
|
||||||
|
['slug' => 'raw-statements', 'title' => '原始账单'],
|
||||||
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
['slug' => 'supplier-data', 'title' => '厂家端数据'],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
@ -1043,7 +1043,7 @@ $navigation = [
|
|||||||
'title' => '安装明细',
|
'title' => '安装明细',
|
||||||
'tabs' => [
|
'tabs' => [
|
||||||
['slug' => 'details', 'title' => '安装明细', 'icon' => 'table_view'],
|
['slug' => 'details', 'title' => '安装明细', 'icon' => 'table_view'],
|
||||||
['slug' => 'fee-trend', 'title' => '安装费汇总', 'icon' => 'trending_up'],
|
['slug' => 'fee-trend', 'title' => '安装公司使用趋势', 'icon' => 'trending_up'],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
['slug' => 'promotion-expenses', 'title' => '推广费用'],
|
['slug' => 'promotion-expenses', 'title' => '推广费用'],
|
||||||
|
|||||||
@ -10,6 +10,9 @@ return [
|
|||||||
| Entries are appended to an existing section in configuration order.
|
| Entries are appended to an existing section in configuration order.
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
'courier-payables' => [
|
||||||
|
['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'],
|
||||||
|
],
|
||||||
'module_sections' => [
|
'module_sections' => [
|
||||||
[
|
[
|
||||||
'position_after' => 'inventory-management',
|
'position_after' => 'inventory-management',
|
||||||
|
|||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'dataset_key' => 'operations_replica.rpt.ding_invoices',
|
'dataset_key' => 'operations_replica.rpt.ding_invoices',
|
||||||
|
'first_supported_month' => '2026-10',
|
||||||
'document_types' => [
|
'document_types' => [
|
||||||
'公摊日常报销',
|
'公摊日常报销',
|
||||||
'店铺日常报销',
|
'店铺日常报销',
|
||||||
|
|||||||
@ -1,13 +1,48 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
return [
|
return [
|
||||||
// 上传入口不设截止时间;系统只在 1-14 日催办未上传厂家,15 日财务出上月终版。
|
// 系统在 1-14 日催办未上传厂家;15 日 12:00 后已确认厂家不能继续上传或覆盖。
|
||||||
'reminder_end_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_REMINDER_END_DAY', 14))),
|
'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))),
|
'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))),
|
'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))),
|
||||||
|
|
||||||
|
// 这些结算方式不依赖月度对账单,不进入未上传统计,也不发送群催办。
|
||||||
|
'statement_upload_exempt_settlement_methods' => ['订单合同', '现结'],
|
||||||
|
|
||||||
|
// 应付汇总镜像尚未覆盖完整,保留已确认的无需上传厂家作为兜底。
|
||||||
|
'statement_upload_exempt_suppliers' => [
|
||||||
|
'博曼特',
|
||||||
|
'常州安裕',
|
||||||
|
'格林家具',
|
||||||
|
'公牛电器',
|
||||||
|
'河北星沐橡胶制品',
|
||||||
|
'恒菏',
|
||||||
|
'简尚',
|
||||||
|
'兰考华兰家具',
|
||||||
|
'木町工艺品',
|
||||||
|
'青岛弢森',
|
||||||
|
'三环',
|
||||||
|
'三洋木业',
|
||||||
|
'沐野竹木',
|
||||||
|
'沭阳简华家具有限公司',
|
||||||
|
'沭阳勋雅泡沫',
|
||||||
|
'双爱家私',
|
||||||
|
'顺兴木业',
|
||||||
|
'苏州贝格迪派',
|
||||||
|
'腾云',
|
||||||
|
'橡润家',
|
||||||
|
'新奇维木艺',
|
||||||
|
'优创包装',
|
||||||
|
'众隆包装',
|
||||||
|
'帝富尼',
|
||||||
|
],
|
||||||
|
|
||||||
'reminder' => [
|
'reminder' => [
|
||||||
// 每天运行任务;仅在上传提醒窗口(默认 1-14 日)内执行,15 日不得再催办。
|
// 1-14 日每天 10:00、16:00 运行,15 日不得再催办。
|
||||||
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),
|
||||||
|
'starts_at' => env('SUPPLIER_STATEMENT_REMINDER_START_AT', '2026-12-03 00:00:00'),
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
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