feat(运费对账): 合入补丁 29 至 32 (#1681)
This commit is contained in:
parent
f9417702a2
commit
2bfbd1fc92
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;
|
||||
}
|
||||
}
|
||||
@ -103,6 +103,14 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 代发运费:每月 1–14 日 10:00 提醒还没上传上月代发运费账单的厂家(14 日截止,逾期本月货款和运费不予结算)。
|
||||
$schedule->command('dropship-freight:remind-upload')
|
||||
->cron('0 10 1-14 * *')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(60)
|
||||
->appendOutputTo(storage_path('logs/dropship-upload-reminder.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。
|
||||
$schedule->command('inventory:sync-warehouse-mapping-alert')
|
||||
->dailyAt('10:15')
|
||||
|
||||
@ -37,8 +37,10 @@ final class CourierBillController extends Controller
|
||||
$db = $this->store->db();
|
||||
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
|
||||
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
|
||||
// 推送上传链接默认推上个月(新月份还没有对账单时,$month 会停在最近有对账单的月份)
|
||||
$pushMonth = self::monthParam($request->query('month')) ?? max($month, now()->subMonthNoOverflow()->format('Y-m'));
|
||||
$groups = $this->store->groups();
|
||||
$data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups,
|
||||
$data += ['cbMonth' => $month, 'cbPushMonth' => $pushMonth, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups,
|
||||
'cbRobots' => app(SupplierDingTalkNotifier::class)->configurationMap(array_map(static fn ($g): string => (string) $g->name, $groups))];
|
||||
$data += match ($view) {
|
||||
'statement' => $this->statementData($request),
|
||||
@ -199,10 +201,11 @@ final class CourierBillController extends Controller
|
||||
$search = Waybill::normalize((string) $request->query('waybill'));
|
||||
|
||||
return [
|
||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported')
|
||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->groupBy('g.name', 'l.settle_month')->selectRaw(sprintf('%s as group_name, %s as settle_month, COUNT(*) as n, SUM(%s) as amount, SUM(CASE WHEN %s IS NULL THEN 1 ELSE 0 END) as imported',
|
||||
...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['g.name', 'l.settle_month', 'l.amount', 'l.statement_id'])))
|
||||
->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(),
|
||||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||||
'cbSearch' => $search,
|
||||
];
|
||||
@ -428,7 +431,7 @@ final class CourierBillController extends Controller
|
||||
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
||||
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
||||
if ($result['rejected'] > 0) {
|
||||
$message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : '');
|
||||
$message .= ',' . $result['rejected'] . ' 行单号或结算月份认不出,未导入';
|
||||
}
|
||||
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
|
||||
@ -6,9 +6,11 @@ use App\Support\CourierBills\Category;
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\DropshipFreight\DropshipConfirmation;
|
||||
use App\Support\DropshipFreight\DropshipExporter;
|
||||
use App\Support\DropshipFreight\DropshipFees;
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use App\Support\DropshipFreight\DropshipReconciler;
|
||||
use App\Support\DropshipFreight\DropshipShareLink;
|
||||
use App\Support\DropshipFreight\DropshipUploadReminder;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
@ -70,7 +72,14 @@ final class DropshipFreightController extends Controller
|
||||
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
|
||||
$fees = app(DropshipFees::class)->rows($month, array_column($rows, 'settle', 'factory_id'), self::companyId());
|
||||
$feeTotals = [];
|
||||
foreach ([...array_keys(DropshipFees::COLUMNS), 'total'] as $key) {
|
||||
$feeTotals[$key] = round(array_sum(array_map(static fn (array $f): float => $key === 'total' ? $f['total'] : $f['values'][$key], $fees)), 2);
|
||||
}
|
||||
|
||||
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfStates' => $this->confirmations->states($month, self::companyId()),
|
||||
'dfFees' => $fees, 'dfFeeTotals' => $feeTotals,
|
||||
'dfRobots' => $notifier->configurationMap(array_column($rows, 'factory')), 'dfTotals' => [
|
||||
'bill' => array_sum(array_column($rows, 'bill')), 'settle' => array_sum(array_column($rows, 'settle')),
|
||||
'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')),
|
||||
@ -107,7 +116,8 @@ final class DropshipFreightController extends Controller
|
||||
$files = $this->store->db()->table('dropship_bill_files as f')->leftJoin('dropship_factories as d', 'd.id', '=', 'f.factory_id')
|
||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'd.name as factory_name']);
|
||||
|
||||
return ['dfFiles' => $files];
|
||||
return ['dfFiles' => $files, 'dfAutoRemind' => DropshipUploadReminder::enabled(),
|
||||
'dfDeadline' => DropshipUploadReminder::deadline($month)->format('n月j日')];
|
||||
}
|
||||
|
||||
public function upload(Request $request)
|
||||
@ -205,6 +215,21 @@ final class DropshipFreightController extends Controller
|
||||
: '已撤销「' . $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)
|
||||
{
|
||||
@ -240,43 +265,39 @@ final class DropshipFreightController extends Controller
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
|
||||
$month = $data['month'];
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$factories = collect($this->store->factories());
|
||||
$single = ! empty($data['factory']);
|
||||
if ($single) {
|
||||
$factories = $factories->where('id', (int) $data['factory'])->values();
|
||||
abort_if($factories->isEmpty(), 404);
|
||||
abort_if(collect($this->store->factories())->where('id', (int) $data['factory'])->isEmpty(), 404);
|
||||
}
|
||||
$uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id')
|
||||
->distinct()->pluck('factory_id')->map('intval')->all());
|
||||
$robots = $notifier->configurationMap($factories->pluck('name')->map('strval')->all());
|
||||
$portal = route('business.supplier-portal.home', ['company_id' => self::companyId()]);
|
||||
$sent = $failed = [];
|
||||
$noRobot = $done = 0;
|
||||
foreach ($factories as $f) {
|
||||
if (! $single && isset($uploaded[(int) $f->id])) {
|
||||
$done++;
|
||||
continue;
|
||||
}
|
||||
if (! ($robots[$f->name]['configured'] ?? false)) {
|
||||
$noRobot++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$notifier->pushDropshipUploadReminder((string) $f->name, $month, $portal);
|
||||
$sent[] = $f->name;
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$failed[] = $f->name;
|
||||
}
|
||||
}
|
||||
if ($single && $noRobot > 0) {
|
||||
$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, [], '已通知 ' . count($sent) . ' 家上传 ' . $month . ' 代发运费账单' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 40)) : '')
|
||||
. ($done > 0 ? ';' . $done . ' 家已经上传,没再通知' : '') . ($noRobot > 0 ? ';' . $noRobot . ' 家没配钉钉群机器人' : '')
|
||||
. ($failed !== [] ? ';发送失败:' . implode('、', $failed) : '') . '。');
|
||||
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']) : '');
|
||||
}
|
||||
|
||||
/** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */
|
||||
@ -339,8 +360,8 @@ final class DropshipFreightController extends Controller
|
||||
|
||||
return response()->streamDownload(function () use ($factories, $month, $own): void {
|
||||
$book = new StreamingWorkbook();
|
||||
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)',
|
||||
'差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
||||
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '最终结算运费',
|
||||
'差额(厂家−最终结算)', ...array_values(DropshipReconciler::LABELS)], true);
|
||||
$details = [];
|
||||
foreach ($factories as $factory) {
|
||||
$result = $this->reconciler->factoryMonth($factory, $month, $own);
|
||||
@ -351,10 +372,10 @@ final class DropshipFreightController extends Controller
|
||||
}
|
||||
foreach ($details as [$factory, $rows]) {
|
||||
$sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28);
|
||||
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true);
|
||||
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '最终结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true);
|
||||
foreach ($rows as $r) {
|
||||
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'],
|
||||
$r['diff'], $r['label'], $r['note'], $r['formula']]);
|
||||
$r['final'] ?? $r['settle'], $r['diff'], $r['label'], $r['note'], $r['formula']]);
|
||||
}
|
||||
}
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
|
||||
@ -141,8 +141,8 @@ final class DropshipFreightShare extends Controller
|
||||
}
|
||||
$book->row('明细', ['快递单号', '发货时间', '快递名称', '厂家运费', '应结运费', '差额(厂家−应结)', '状态', '说明'], true);
|
||||
foreach ($t['rows'] as $r) {
|
||||
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['settle'] ?? 0,
|
||||
round((float) $r['bill'] - (float) ($r['settle'] ?? 0), 2), $r['label'], $r['note']]);
|
||||
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'] ?? $r['settle'] ?? 0,
|
||||
round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle'] ?? 0), 2), $r['label'], $r['note']]);
|
||||
}
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
}, $name);
|
||||
|
||||
@ -44,9 +44,10 @@ final class CourierBillMatcher
|
||||
|
||||
$settled = [];
|
||||
foreach (array_chunk($waybills, 500) as $chunk) {
|
||||
foreach ($db->table('courier_bill_ledger')->where('group_id', $statement->group_id)->whereIn('waybill_no', $chunk)
|
||||
->where('settle_month', '<>', $month)->get(['waybill_no', 'settle_month']) as $row) {
|
||||
$settled[strtoupper($row->waybill_no)] = $row->settle_month;
|
||||
// 查重按单号:别的月份结算过(不论哪个分组、系统确认还是历史导入)就算重复,取最早那个月
|
||||
foreach ($db->table('courier_bill_ledger')->whereIn('waybill_no', $chunk)
|
||||
->where('settle_month', '<>', $month)->orderBy('settle_month')->get(['waybill_no', 'settle_month']) as $row) {
|
||||
$settled[strtoupper($row->waybill_no)] ??= $row->settle_month;
|
||||
}
|
||||
}
|
||||
$unshipped = $this->unshipped->unshippedSources($waybills);
|
||||
|
||||
@ -1097,19 +1097,21 @@ final class CourierBillStore
|
||||
});
|
||||
}
|
||||
|
||||
/** 历史导入的已结算单号不分对账分组,group_id 记 0;查重按单号,不看分组。 */
|
||||
public const LEDGER_NO_GROUP = 0;
|
||||
|
||||
/**
|
||||
* 导入历史已结算单号:表头含 分组、单号、结算月份,可选 金额。
|
||||
* 导入系统上线前已结算的单号:只要「单号」「结算月份」两列(可带「金额」)。导入后这些单号再出现在任何一家的账单里,
|
||||
* 只要结算月份不是本月,就归「重复」。
|
||||
*
|
||||
* @return array{rows:int,inserted:int,unknown_groups:list<string>,rejected:int}
|
||||
* @return array{rows:int,inserted:int,rejected:int}
|
||||
*/
|
||||
public function importLedger(string $path, string $extension): array
|
||||
{
|
||||
$groups = collect($this->groups())->keyBy('name');
|
||||
$reader = new BillWorkbookReader();
|
||||
$rows = 0;
|
||||
$inserted = 0;
|
||||
$rejected = 0;
|
||||
$unknown = [];
|
||||
$buffer = [];
|
||||
$flush = function () use (&$buffer, &$inserted): void {
|
||||
if ($buffer !== []) {
|
||||
@ -1124,32 +1126,26 @@ final class CourierBillStore
|
||||
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
|
||||
$find = static fn (array $names): ?int => collect($names)->map(static fn ($n) => array_search($n, $header, true))
|
||||
->first(static fn ($i) => $i !== false);
|
||||
$columns = ['group' => $find(['分组', '对账分组']), 'waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
||||
$columns = ['waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
|
||||
'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])];
|
||||
if ($columns['group'] === null || $columns['waybill'] === null || $columns['month'] === null) {
|
||||
throw new RuntimeException('表头须含「分组」「单号」「结算月份」三列(金额可选)。');
|
||||
if ($columns['waybill'] === null || $columns['month'] === null) {
|
||||
throw new RuntimeException('表头须含「单号」「结算月份」两列(金额可选)。');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$groupName = trim((string) ($row[$columns['group']] ?? ''));
|
||||
$waybillRaw = trim((string) ($row[$columns['waybill']] ?? ''));
|
||||
if ($groupName === '' && $waybillRaw === '') {
|
||||
$monthRaw = trim((string) ($row[$columns['month']] ?? ''));
|
||||
if ($waybillRaw === '' && $monthRaw === '') {
|
||||
continue;
|
||||
}
|
||||
$rows++;
|
||||
$group = $groups->get($groupName);
|
||||
if ($group === null) {
|
||||
$unknown[$groupName] = true;
|
||||
$rejected++;
|
||||
continue;
|
||||
}
|
||||
$waybill = Waybill::normalize($waybillRaw);
|
||||
$month = self::month((string) ($row[$columns['month']] ?? ''));
|
||||
$month = self::month($monthRaw);
|
||||
if ($waybill === null || $month === null) {
|
||||
$rejected++;
|
||||
continue;
|
||||
}
|
||||
$buffer[] = ['group_id' => $group->id, 'waybill_no' => $waybill, 'settle_month' => $month,
|
||||
$buffer[] = ['group_id' => self::LEDGER_NO_GROUP, 'waybill_no' => $waybill, 'settle_month' => $month,
|
||||
'amount' => $columns['amount'] === null ? null : BillParser::number($row[$columns['amount']] ?? null),
|
||||
'statement_id' => null, 'created_at' => now()];
|
||||
if (count($buffer) >= 500) {
|
||||
@ -1160,7 +1156,7 @@ final class CourierBillStore
|
||||
}
|
||||
$flush();
|
||||
|
||||
return ['rows' => $rows, 'inserted' => $inserted, 'unknown_groups' => array_keys($unknown), 'rejected' => $rejected];
|
||||
return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected];
|
||||
}
|
||||
|
||||
private function assertOpen(int $statementId): void
|
||||
|
||||
@ -20,7 +20,7 @@ final class FreightBillTemplate
|
||||
public const SURCHARGE_SHEET = '附加费';
|
||||
public const SURCHARGE_HEADERS = ['快递单号', '附加费金额', '附加费类型'];
|
||||
/** 写在附加费表表头右边(空一列)的说明,校验时不算表头。 */
|
||||
public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可';
|
||||
public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可;附加费类型填:补运费、退回费、拦截费、改地址费、翻箱费、超长费';
|
||||
private const MAX_ERRORS = 10;
|
||||
private const TOTAL_WORDS = ['合计', '总计', '小计'];
|
||||
|
||||
@ -71,6 +71,47 @@ final class FreightBillTemplate
|
||||
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 (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;
|
||||
}
|
||||
|
||||
/** @return array{rows:int,waybills:int,amount:float} */
|
||||
private function validateBill(?iterable $rows): array
|
||||
{
|
||||
|
||||
@ -77,7 +77,7 @@ final class DropshipExporter
|
||||
[$originals, $sources, $original] = $this->writeOriginal($book, $files, $baseFileId, $index, $baseCount);
|
||||
$lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?');
|
||||
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_')));
|
||||
$tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
|
||||
$tail = ['厂家运费(这一单合计)', '结算运费', '最终结算运费', '分类', '说明'];
|
||||
|
||||
// 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张)
|
||||
$sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)];
|
||||
@ -103,7 +103,7 @@ final class DropshipExporter
|
||||
foreach (array_keys($rest) as $field) {
|
||||
$cells[] = self::value($field, $ship[$field] ?? null);
|
||||
}
|
||||
$book->row($name, [...$cells, $r['bill'], $r['settle'], $r['label'], $r['note']]);
|
||||
$book->row($name, [...$cells, $r['bill'], $r['settle'], $r['final'] ?? $r['settle'], $r['label'], $r['note']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -150,8 +150,9 @@ final class DropshipExporter
|
||||
if ($r['bill'] !== null) {
|
||||
$billTotal = (float) $billTotal + (float) $r['bill'];
|
||||
}
|
||||
if ($r['settle'] !== null) {
|
||||
$settleTotal = (float) $settleTotal + (float) $r['settle'];
|
||||
$final = $r['final'] ?? $r['settle'];
|
||||
if ($final !== null) {
|
||||
$settleTotal = (float) $settleTotal + (float) $final;
|
||||
}
|
||||
}
|
||||
$labels = $template['labels'];
|
||||
|
||||
133
app/Support/DropshipFreight/DropshipFees.php
Normal file
133
app/Support/DropshipFreight/DropshipFees.php
Normal file
@ -0,0 +1,133 @@
|
||||
<?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' => ['补运费', '补运'],
|
||||
'returned' => ['退回', '退件', '退货'], 'intercept' => ['拦截'], 'readdress' => ['改地址', '改址'], 'repack' => ['翻箱'], 'overlength' => ['超长']];
|
||||
|
||||
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 = [];
|
||||
$files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed')
|
||||
->whereNotNull('factory_id')->get(['factory_id', 'sheets']);
|
||||
foreach ($files as $file) {
|
||||
foreach ((array) json_decode((string) $file->sheets, true) as $sheet) {
|
||||
foreach ((array) ($sheet['fees'] ?? []) 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,6 +4,7 @@ namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\BillWorkbookReader;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\FreightBillTemplate;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@ -220,14 +221,14 @@ final class DropshipFreightStore
|
||||
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
|
||||
->orderByDesc('bill_month')->first();
|
||||
if ($row === null) {
|
||||
return DropshipSummaryTemplate::fallback($month, (string) $factory->name) + ['from' => null];
|
||||
return DropshipSummaryTemplate::withoutDropped(DropshipSummaryTemplate::fallback($month, (string) $factory->name)) + ['from' => null];
|
||||
}
|
||||
$delta = ((int) substr($month, 0, 4) - (int) substr((string) $row->bill_month, 0, 4)) * 12
|
||||
+ (int) substr($month, 5, 2) - (int) substr((string) $row->bill_month, 5, 2);
|
||||
$template = DropshipSummaryTemplate::roll(['title' => (string) $row->title, 'headers' => array_values((array) json_decode((string) $row->headers, true)),
|
||||
'labels' => array_values((array) json_decode((string) $row->labels, true)), 'total' => (string) $row->total_label], $delta);
|
||||
|
||||
return $template + ['from' => (string) $row->bill_month];
|
||||
return DropshipSummaryTemplate::withoutDropped($template) + ['from' => (string) $row->bill_month];
|
||||
}
|
||||
|
||||
/**
|
||||
@ -331,6 +332,23 @@ final class DropshipFreightStore
|
||||
return;
|
||||
}
|
||||
$lines = $result['lines'];
|
||||
// 按上传模板填的「附加费」表:按类型记下金额,各厂家汇总里自动带入退回费、拦截费等列
|
||||
$fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path($file->stored_path),
|
||||
pathinfo($file->stored_path, PATHINFO_EXTENSION));
|
||||
if ($fees !== []) {
|
||||
$found = false;
|
||||
foreach ($result['sheets'] as &$sheet) {
|
||||
if ($sheet['sheet'] === FreightBillTemplate::SURCHARGE_SHEET) {
|
||||
$sheet['fees'] = $fees;
|
||||
$sheet['note'] = '附加费按类型记入各厂家汇总';
|
||||
$found = true;
|
||||
}
|
||||
}
|
||||
unset($sheet);
|
||||
if (! $found) {
|
||||
$result['sheets'][] = ['sheet' => FreightBillTemplate::SURCHARGE_SHEET, 'read' => false, 'note' => '附加费按类型记入各厂家汇总', 'fees' => $fees];
|
||||
}
|
||||
}
|
||||
$notes = [];
|
||||
if ($lines === []) {
|
||||
$notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空';
|
||||
|
||||
@ -136,35 +136,49 @@ final class DropshipReconciler
|
||||
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array
|
||||
{
|
||||
$calc = $i['calc'] ?? null;
|
||||
$settle = in_array($status, self::PAYABLE, true) ? $calc : null;
|
||||
|
||||
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
|
||||
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
|
||||
'settle' => in_array($status, self::PAYABLE, true) ? $calc : null,
|
||||
'settle' => $settle, 'final' => self::final($billed, $settle),
|
||||
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
|
||||
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
|
||||
'note' => $note, 'formula' => $i['formula'] ?? null];
|
||||
}
|
||||
|
||||
/** 最终结算运费:按我方核算结算,但厂家开得比核算少(厂家运费 − 结算运费 < 0)就按厂家运费结。 */
|
||||
public static function final(?float $billed, ?float $settle): ?float
|
||||
{
|
||||
return $settle !== null && $billed !== null && $billed < $settle ? round($billed, 2) : $settle;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows */
|
||||
public static function summarize(object $factory, string $month, array $rows): array
|
||||
{
|
||||
$counts = array_fill_keys(array_keys(self::LABELS), 0);
|
||||
$bill = $settle = 0.0;
|
||||
$billedCount = $over = $under = 0;
|
||||
$bill = $settle = $calcSettle = 0.0;
|
||||
$billedCount = $over = $under = $capped = 0;
|
||||
foreach ($rows as $row) {
|
||||
$counts[$row['status']]++;
|
||||
if ($row['bill'] !== null) {
|
||||
$billedCount++;
|
||||
$bill += $row['bill'];
|
||||
}
|
||||
$settle += (float) $row['settle'];
|
||||
$calcSettle += (float) $row['settle'];
|
||||
$final = array_key_exists('final', $row) ? $row['final'] : self::final($row['bill'], $row['settle']);
|
||||
$settle += (float) $final;
|
||||
if ($final !== null && $row['settle'] !== null && $final < $row['settle']) {
|
||||
$capped++;
|
||||
}
|
||||
if ($row['status'] === Category::DIFF) {
|
||||
$row['diff'] > 0 ? $over++ : $under++;
|
||||
}
|
||||
}
|
||||
|
||||
return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month,
|
||||
// settle = 最终结算运费(各厂家汇总、小汇总、推送厂家确认都用它);calc_settle = 按我方核算的结算运费;capped = 按厂家运费结的单数
|
||||
'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2),
|
||||
'calc_settle' => round($calcSettle, 2), 'capped' => $capped,
|
||||
'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under,
|
||||
'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
|
||||
}
|
||||
@ -180,6 +194,14 @@ final class DropshipReconciler
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 这家这个月有没有代发发货(批量催上传账单时,没有代发发货的厂家不催)。 @param list<string>|null $own 自有快递名称 */
|
||||
public function hasDropship(object $factory, string $month, ?array $own = null): bool
|
||||
{
|
||||
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
|
||||
|
||||
return $this->dropshipWaybills($factory, $keywords, array_flip($own ?? $this->store->ownExpressNames()), $month) !== [];
|
||||
}
|
||||
|
||||
/** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list<string> */
|
||||
private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array
|
||||
{
|
||||
|
||||
@ -17,7 +17,9 @@ final class DropshipSummaryTemplate
|
||||
public const TOTALS = ['合计', '汇总', '总计'];
|
||||
|
||||
/** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */
|
||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计'];
|
||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账'], 'total' => '合计'];
|
||||
/** 小汇总里不要的类目(手工汇总里带了也去掉)。 */
|
||||
public const DROPPED = ['代发', '退货'];
|
||||
|
||||
/**
|
||||
* 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。
|
||||
@ -95,6 +97,15 @@ final class DropshipSummaryTemplate
|
||||
return $template;
|
||||
}
|
||||
|
||||
/** 去掉「代发」「退货」这类不要的类目(带月份的如「10月退货」也算)。 */
|
||||
public static function withoutDropped(array $template): array
|
||||
{
|
||||
$template['labels'] = array_values(array_filter($template['labels'], static fn (string $l): bool => ! in_array(
|
||||
trim(preg_replace('/^\d{1,2}月|\d{1,2}月$/u', '', trim($l)) ?? ''), self::DROPPED, true)));
|
||||
|
||||
return $template;
|
||||
}
|
||||
|
||||
public static function fallback(string $month, string $factory): array
|
||||
{
|
||||
$template = self::DEFAULT;
|
||||
|
||||
124
app/Support/DropshipFreight/DropshipUploadReminder.php
Normal file
124
app/Support/DropshipFreight/DropshipUploadReminder.php
Normal file
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 代发运费账单上传提醒:往厂家钉钉对账群(和货款对账同一个群)发厂家对账入口链接。
|
||||
* - 手动:上传厂家账单页「通知厂家上传」、代发厂家设置里单家「通知上传」;
|
||||
* - 自动:每月 1–14 日 10:00(dropship-freight:remind-upload),提醒上个月的账单,14 日截止,逾期本月货款和运费不予结算。
|
||||
* 批量提醒只发给「这个月有代发发货、还没上传、配了机器人」的厂家;单家提醒照发。
|
||||
*/
|
||||
final class DropshipUploadReminder
|
||||
{
|
||||
public const DEADLINE_DAY = 14;
|
||||
public const SEND_TIME = '10:00';
|
||||
public const SETTING_KEY = 'dropship_freight.auto_upload_reminder';
|
||||
public const TIMEZONE = 'Asia/Shanghai';
|
||||
|
||||
public function __construct(
|
||||
private readonly DropshipFreightStore $store,
|
||||
private readonly DropshipReconciler $reconciler,
|
||||
private readonly SupplierDingTalkNotifier $notifier,
|
||||
) {}
|
||||
|
||||
/** 自动提醒开关(按公司),默认开。 */
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return (string) setting(self::SETTING_KEY, '1') !== '0';
|
||||
}
|
||||
|
||||
public static function setEnabled(bool $on): void
|
||||
{
|
||||
setting()->set(self::SETTING_KEY, $on ? '1' : '0');
|
||||
setting()->save();
|
||||
}
|
||||
|
||||
public static function today(): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::now(self::TIMEZONE)->startOfDay();
|
||||
}
|
||||
|
||||
/** 这天要催的账单月:上个月。 */
|
||||
public static function billMonth(CarbonInterface $day): string
|
||||
{
|
||||
return CarbonImmutable::parse($day->format('Y-m-d'), self::TIMEZONE)->startOfMonth()->subMonth()->format('Y-m');
|
||||
}
|
||||
|
||||
/** 账单月的上传截止日:次月 14 日。 */
|
||||
public static function deadline(string $month): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::createFromFormat('Y-m-d', $month . '-01', self::TIMEZONE)->startOfDay()->addMonth()->day(self::DEADLINE_DAY);
|
||||
}
|
||||
|
||||
/** 今天还在这个账单月的上传期(次月 1–14 日)里,就返回截止日,提醒里写明截止和逾期后果;否则 null。 */
|
||||
public static function deadlineFor(string $month, CarbonInterface $today): ?CarbonImmutable
|
||||
{
|
||||
$deadline = self::deadline($month);
|
||||
$day = CarbonImmutable::parse($today->format('Y-m-d'), self::TIMEZONE);
|
||||
|
||||
return $day->greaterThanOrEqualTo($deadline->startOfMonth()) && $day->lessThanOrEqualTo($deadline) ? $deadline : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个月要提醒的厂家。
|
||||
*
|
||||
* @return array{targets:list<object>,done:list<string>,no_shipment:list<string>,no_robot:list<string>}
|
||||
*/
|
||||
public function targets(string $month, ?int $factoryId = null): array
|
||||
{
|
||||
$factories = collect($this->store->factories());
|
||||
$single = $factoryId !== null;
|
||||
if ($single) {
|
||||
$factories = $factories->where('id', $factoryId)->values();
|
||||
}
|
||||
$uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id')
|
||||
->where('status', '!=', 'failed')->distinct()->pluck('factory_id')->map('intval')->all());
|
||||
$robots = $this->notifier->configurationMap($factories->pluck('name')->map('strval')->all());
|
||||
$own = $single ? [] : $this->store->ownExpressNames();
|
||||
$result = ['targets' => [], 'done' => [], 'no_shipment' => [], 'no_robot' => []];
|
||||
foreach ($factories as $factory) {
|
||||
$name = (string) $factory->name;
|
||||
if (! $single && isset($uploaded[(int) $factory->id])) {
|
||||
$result['done'][] = $name;
|
||||
} elseif (! ($robots[$name]['configured'] ?? false)) {
|
||||
$result['no_robot'][] = $name;
|
||||
} elseif (! $single && ! $this->reconciler->hasDropship($factory, $month, $own)) {
|
||||
$result['no_shipment'][] = $name;
|
||||
} else {
|
||||
$result['targets'][] = $factory;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发提醒。
|
||||
*
|
||||
* @return array{sent:list<string>,failed:list<string>,done:list<string>,no_shipment:list<string>,no_robot:list<string>,deadline:?CarbonImmutable}
|
||||
*/
|
||||
public function remind(string $month, string $portalUrl, ?int $factoryId = null, ?CarbonInterface $today = null): array
|
||||
{
|
||||
$today ??= self::today();
|
||||
$deadline = self::deadlineFor($month, $today);
|
||||
$plan = $this->targets($month, $factoryId);
|
||||
$sent = $failed = [];
|
||||
foreach ($plan['targets'] as $factory) {
|
||||
try {
|
||||
$this->notifier->pushDropshipUploadReminder((string) $factory->name, $month, $portalUrl, $deadline, $today);
|
||||
$sent[] = (string) $factory->name;
|
||||
} catch (Throwable $error) {
|
||||
report($error);
|
||||
$failed[] = (string) $factory->name;
|
||||
}
|
||||
}
|
||||
unset($plan['targets']);
|
||||
|
||||
return ['sent' => $sent, 'failed' => $failed, 'deadline' => $deadline] + $plan;
|
||||
}
|
||||
}
|
||||
@ -524,14 +524,29 @@ class SupplierDingTalkNotifier
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。 */
|
||||
public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl): void
|
||||
/**
|
||||
* 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。
|
||||
* 给了截止日(次月 14 日)就写明截止日、还剩几天,以及逾期本月货款和运费不予结算。
|
||||
*/
|
||||
public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl,
|
||||
?\Carbon\CarbonInterface $deadline = null, ?\Carbon\CarbonInterface $today = null): void
|
||||
{
|
||||
[$webhook, $config] = $this->robotFor($supplier, 'dropship_upload_reminder');
|
||||
$deadlineLines = [];
|
||||
$title = '代发运费账单上传提醒';
|
||||
if ($deadline !== null) {
|
||||
$left = $today === null ? null : (int) \Carbon\CarbonImmutable::parse($today->format('Y-m-d'))->diffInDays(\Carbon\CarbonImmutable::parse($deadline->format('Y-m-d')), false);
|
||||
$title .= $left === 0 ? '(今天截止)' : '';
|
||||
$deadlineLines = [
|
||||
'- 请于 **' . (int) $deadline->format('n') . '月' . (int) $deadline->format('j') . '日** 前上传 **' . $this->displayMonth($month) . '** 代发运费账单'
|
||||
. ($left === 0 ? ',**今天截止**' : ($left !== null && $left > 0 ? ',还剩 ' . $left . ' 天' : '')),
|
||||
'- **逾期未上传,本月货款和运费将不予结算**',
|
||||
];
|
||||
}
|
||||
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
|
||||
$supplier . ' · 代发运费账单上传提醒 · ' . $this->displayMonth($month), implode("\n", [
|
||||
'### 代发运费账单上传提醒 · ' . $supplier,
|
||||
'- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单',
|
||||
$supplier . ' · ' . $title . ' · ' . $this->displayMonth($month), implode("\n", [
|
||||
'### ' . $title . ' · ' . $supplier,
|
||||
...($deadlineLines ?: ['- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单']),
|
||||
'- 按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填',
|
||||
'- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着',
|
||||
'',
|
||||
|
||||
@ -99,6 +99,13 @@
|
||||
|
||||
<section class="cbr-panel" aria-label="对账分组列表">
|
||||
<h3>对账分组({{ count($cbGroups) }})</h3>
|
||||
@php($pushMonth = $cbPushMonth ?? $month)
|
||||
<form method="GET" action="{{ $pageUrl() }}" class="cbr-form cbr-panel-body" data-cbr-filter>
|
||||
<input type="hidden" name="cb_view" value="groups">
|
||||
<label>推送上传链接的账单月份<input type="month" name="month" value="{{ $pushMonth }}" required></label>
|
||||
<button type="submit">切换</button>
|
||||
<span class="cbr-muted">下面「推送上传链接」按钮推的是这个月份的账单,默认上个月。</span>
|
||||
</form>
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">分组名称</th><th scope="col">快递名称1</th><th scope="col">归到承运商</th><th scope="col">合并账单</th><th scope="col">负责人</th><th scope="col">文件名关键字</th><th scope="col">指定表头</th><th scope="col">钉钉对账群</th><th scope="col"></th></tr></thead>
|
||||
@ -134,9 +141,9 @@
|
||||
</details>
|
||||
@if ($robot['configured'] ?? false)
|
||||
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-form" style="margin-top:4px"
|
||||
onsubmit="return confirm('往「{{ $group->name }}」钉钉对账群推送 {{ $month }} 账单上传链接?')">@csrf
|
||||
<input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="group" value="{{ $group->id }}">
|
||||
<button type="submit">推送 {{ $month }} 上传链接</button></form>
|
||||
onsubmit="return confirm('往「{{ $group->name }}」钉钉对账群推送 {{ $pushMonth }} 账单上传链接?')">@csrf
|
||||
<input type="hidden" name="month" value="{{ $pushMonth }}"><input type="hidden" name="group" value="{{ $group->id }}">
|
||||
<button type="submit">推送 {{ $pushMonth }} 上传链接</button></form>
|
||||
@endif
|
||||
</td>
|
||||
<td class="cbr-form">
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
@if ($cbSearch)
|
||||
<div class="cbr-panel-body" style="padding-top:0">
|
||||
@forelse ($cbLedgerHits as $hit)
|
||||
<div>{{ $hit->group_name }} · {{ $hit->settle_month }} 已结算 {{ $money($hit->amount) }}{{ $hit->statement_id ? '' : '(历史导入)' }}</div>
|
||||
<div>{{ $hit->group_name ?? '历史导入(不分组)' }} · {{ $hit->settle_month }} 已结算 {{ $money($hit->amount) }}{{ $hit->statement_id ? '' : '(历史导入)' }}</div>
|
||||
@empty
|
||||
<div class="cbr-muted">{{ $cbSearch }} 没有结算记录。</div>
|
||||
@endforelse
|
||||
@ -22,7 +22,7 @@
|
||||
@csrf
|
||||
<label>台账文件(xlsx / csv)<input type="file" name="ledger" required accept=".xlsx,.xls,.csv"></label>
|
||||
<button type="submit">导入</button>
|
||||
<p class="cbr-muted" style="flex-basis:100%">表头须含「分组」「单号」「结算月份」,可带「金额」。分组名称要和「对账分组」里的一致。系统上线前的月份没有台账,导入后这些单号再出现在账单里会归为「重复」;不导入的话会归为「前月补提供」。</p>
|
||||
<p class="cbr-muted" style="flex-basis:100%">表头须含「单号」「结算月份」,可带「金额」,不用分组。按单号查重:导入后这些单号再出现在任何一家的账单里(结算月份不是本月),就归为「重复」;不导入的话会归为「前月补提供」。同一单号同一月份重复导入只记一次。</p>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
@ -34,7 +34,7 @@
|
||||
<thead><tr><th scope="col">结算月份</th><th scope="col">对账分组</th><th scope="col" class="num">单号数</th><th scope="col" class="num">其中历史导入</th><th scope="col" class="num">结算金额</th></tr></thead>
|
||||
<tbody>
|
||||
@forelse ($cbLedgerStats as $row)
|
||||
<tr><td>{{ $row->settle_month }}</td><td>{{ $row->group_name }}</td><td class="num">{{ number_format($row->n) }}</td><td class="num">{{ number_format($row->imported) }}</td><td class="num">{{ $money($row->amount) }}</td></tr>
|
||||
<tr><td>{{ $row->settle_month }}</td><td>{{ $row->group_name ?? '历史导入(不分组)' }}</td><td class="num">{{ number_format($row->n) }}</td><td class="num">{{ number_format($row->imported) }}</td><td class="num">{{ $money($row->amount) }}</td></tr>
|
||||
@empty
|
||||
<tr><td colspan="5" class="cbr-empty">还没有结算记录。对账单「确认结算」后,单号会记到这里。</td></tr>
|
||||
@endforelse
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-panel-body cbr-form"
|
||||
onsubmit="return confirm('往所有配了钉钉对账群机器人的快递群推送上传链接?')">
|
||||
@csrf
|
||||
<label>账单月份<input type="month" name="month" value="{{ $month }}" required></label>
|
||||
<label>账单月份<input type="month" name="month" value="{{ $cbPushMonth ?? $month }}" required></label>
|
||||
<button type="submit" class="cbr-primary">推送上传链接到快递群</button>
|
||||
<span class="cbr-muted">对账分组已复用工作平台「应付群机器人配置」中对应快递的群机器人;未匹配的可在「对账分组」里补充。这里一键往已配置的群推本月的免登录上传链接。
|
||||
快递点开链接、下载模板(单号、省、重量、运费、快递名称、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。</span>
|
||||
|
||||
@ -15,8 +15,9 @@
|
||||
<div class="cbr-metrics">
|
||||
<div><span>{{ $dfFactory->name }} · {{ $dfFactory->warehouse }}</span><strong style="font-size:14px">关键字:{{ $dfFactory->keywords }}</strong></div>
|
||||
<div><span>厂家开运费 {{ number_format($s['billed']) }} 单</span><strong>{{ $money($s['bill']) }}</strong></div>
|
||||
<div><span>结算运费(按我方核算)</span><strong>{{ $money($s['settle']) }}</strong></div>
|
||||
<div><span>差额(厂家 − 结算)</span><strong class="cbr-diff">{{ $money($s['diff']) }}</strong></div>
|
||||
<div><span>结算运费(按我方核算)</span><strong>{{ $money($s['calc_settle'] ?? $s['settle']) }}</strong></div>
|
||||
<div><span>最终结算运费@if (($s['capped'] ?? 0) > 0)({{ number_format($s['capped']) }} 单厂家开得少,按厂家运费)@endif</span><strong>{{ $money($s['settle']) }}</strong></div>
|
||||
<div><span>差额(厂家 − 最终结算)</span><strong class="cbr-diff">{{ $money($s['diff']) }}</strong></div>
|
||||
</div>
|
||||
|
||||
<section class="cbr-panel" aria-label="厂家确认">
|
||||
@ -51,7 +52,7 @@
|
||||
<section class="cbr-panel" aria-label="明细">
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">快递单号</th><th scope="col">发货时间</th><th scope="col">快递名称1</th><th scope="col" class="num">厂家运费</th><th scope="col" class="num">我方核算</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">差额</th><th scope="col">状态</th><th scope="col">说明</th></tr></thead>
|
||||
<thead><tr><th scope="col">快递单号</th><th scope="col">发货时间</th><th scope="col">快递名称1</th><th scope="col" class="num">厂家运费</th><th scope="col" class="num">我方核算</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">最终结算运费</th><th scope="col" class="num">差额</th><th scope="col">状态</th><th scope="col">说明</th></tr></thead>
|
||||
<tbody>
|
||||
@forelse ($dfLines as $r)
|
||||
<tr>
|
||||
@ -61,12 +62,14 @@
|
||||
<td class="num">{{ $money($r['bill']) }}</td>
|
||||
<td class="num" title="{{ $r['formula'] }}">{{ $money($r['calc']) }}</td>
|
||||
<td class="num">{{ $money($r['settle']) }}</td>
|
||||
@php $capped = $r['final'] !== null && $r['settle'] !== null && $r['final'] < $r['settle']; @endphp
|
||||
<td class="num" @if ($capped) title="厂家开得比核算少,按厂家运费结" style="font-weight:600" @endif>{{ $money($r['final']) }}</td>
|
||||
<td class="num {{ ($r['diff'] ?? 0) != 0 ? 'cbr-diff' : '' }}">{{ $money($r['diff']) }}</td>
|
||||
<td>@php $st = $r['status']; @endphp<span class="cbr-chip {{ $st === 'match' ? 'ok' : ($st === 'unprovided' ? '' : (in_array($st, ['diff', 'prior', 'uncalculated'], true) ? 'warn' : 'bad')) }}">{{ $r['label'] }}</span></td>
|
||||
<td class="wrap">{{ $r['note'] }}</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td colspan="9" class="cbr-empty">没有明细。</td></tr>
|
||||
<tr><td colspan="10" class="cbr-empty">没有明细。</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
<div class="cbr-metrics">
|
||||
<div><span>本月有账单的厂家</span><strong>{{ number_format(count($dfRows)) }}</strong></div>
|
||||
<div><span>厂家运费合计</span><strong>{{ $money($dfTotals['bill']) }}</strong></div>
|
||||
<div><span>结算运费(按我方核算)</span><strong>{{ $money($dfTotals['settle']) }}</strong></div>
|
||||
<div><span>结算运费(最终)</span><strong>{{ $money($dfTotals['settle']) }}</strong></div>
|
||||
<div><span>差额(厂家 − 结算)</span><strong class="cbr-diff">{{ $money($dfTotals['diff']) }}</strong></div>
|
||||
<div><span>要看一眼的单</span><strong>{{ number_format($dfTotals['attention']) }}</strong></div>
|
||||
</div>
|
||||
@ -17,15 +17,45 @@
|
||||
<div class="cbr-scroll">
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th scope="col">厂家</th><th scope="col">代发仓</th><th scope="col">关键字</th>
|
||||
<th scope="col">厂家</th>
|
||||
@foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $label)<th scope="col" class="num">{{ $label }}</th>@endforeach
|
||||
<th scope="col" class="num">合计运费</th><th scope="col">备注</th>
|
||||
<th scope="col">代发仓</th><th scope="col">关键字</th>
|
||||
<th scope="col" class="num">厂家开运费单数</th><th scope="col" class="num">厂家运费</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">差额</th>
|
||||
<th scope="col" class="num">运费有差·厂家多开</th><th scope="col" class="num">运费有差·厂家少开</th><th scope="col" class="num">厂家未提供(不付)</th><th scope="col" class="num">其他要看的</th><th scope="col">厂家确认</th><th scope="col">操作</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@forelse ($dfRows as $row)
|
||||
@php $other = $row['attention'] - $row['counts']['diff']; @endphp
|
||||
@php
|
||||
$other = $row['attention'] - $row['counts']['diff'];
|
||||
$fee = $dfFees[$row['factory_id']] ?? ['values' => [], 'auto' => [], 'manual' => [], 'other' => [], 'note' => '', 'total' => 0];
|
||||
@endphp
|
||||
<tr>
|
||||
<td>{{ $row['factory'] }}</td>
|
||||
@foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $key => $label)
|
||||
@php $v = (float) ($fee['values'][$key] ?? 0); @endphp
|
||||
<td class="num" @if ($fee['manual'][$key] ?? false) title="财务手工改过" style="font-weight:600" @endif>{{ $v == 0 ? '' : $money($key === 'booking' ? -$v : $v) }}</td>
|
||||
@endforeach
|
||||
<td class="num"><strong>{{ $money($fee['total']) }}</strong></td>
|
||||
<td class="wrap" style="min-width:160px">
|
||||
{{ $fee['note'] }}
|
||||
@if ($fee['other'] !== [])<div class="cbr-muted">未归类附加费(不计入合计):@foreach ($fee['other'] as $type => $amount){{ $type }} {{ $money($amount) }}@if (! $loop->last)、@endif @endforeach</div>@endif
|
||||
<details>
|
||||
<summary>改费用 / 备注</summary>
|
||||
<form method="POST" action="{{ $action('save-fees', ['factory' => $row['factory_id']]) }}" class="cbr-form" style="display:grid;gap:4px;margin-top:4px">
|
||||
@csrf
|
||||
<input type="hidden" name="month" value="{{ $month }}">
|
||||
@foreach (\App\Support\DropshipFreight\DropshipFees::EDITABLE as $key)
|
||||
<label>{{ \App\Support\DropshipFreight\DropshipFees::COLUMNS[$key] }}{{ $key === 'booking' ? '(扣款,填正数)' : '' }}
|
||||
<input type="number" step="0.01" name="fees[{{ $key }}]" value="{{ ($fee['manual'][$key] ?? false) ? $fee['values'][$key] : '' }}"
|
||||
placeholder="自动 {{ $fee['auto'][$key] ?? 0 }}" style="width:110px"></label>
|
||||
@endforeach
|
||||
<label>备注<input type="text" name="note" maxlength="255" value="{{ $fee['note'] }}"></label>
|
||||
<button type="submit">保存</button>
|
||||
<span class="cbr-muted">空着 = 用厂家附加费表自动带入的值。</span>
|
||||
</form>
|
||||
</details>
|
||||
</td>
|
||||
<td>{{ $row['warehouse'] }}</td>
|
||||
<td>{{ $row['keywords'] }}</td>
|
||||
<td class="num">{{ number_format($row['billed']) }}</td>
|
||||
@ -41,13 +71,25 @@
|
||||
<td><a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $row['factory_id'], 'month' => $month]) }}">打开明细</a></td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td colspan="13" class="cbr-empty">{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。</td></tr>
|
||||
<tr><td colspan="24" class="cbr-empty">{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。</td></tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
@if ($dfRows !== [])
|
||||
<tfoot><tr>
|
||||
<th scope="row">合计</th>
|
||||
@foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $key => $label)
|
||||
@php $t = (float) ($dfFeeTotals[$key] ?? 0); @endphp
|
||||
<td class="num">{{ $t == 0 ? '' : $money($key === 'booking' ? -$t : $t) }}</td>
|
||||
@endforeach
|
||||
<td class="num"><strong>{{ $money($dfFeeTotals['total'] ?? 0) }}</strong></td>
|
||||
<td colspan="13"></td>
|
||||
</tr></tfoot>
|
||||
@endif
|
||||
</table>
|
||||
</div>
|
||||
@if ($dfWithout !== [])
|
||||
<div class="cbr-footer">本月没收到账单的厂家({{ count($dfWithout) }},没账单就不付运费):{{ implode('、', $dfWithout) }}</div>
|
||||
@endif
|
||||
</section>
|
||||
<p class="cbr-muted">差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算;换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。厂家确认:核对完成后点「推送厂家确认」,推送到这家的钉钉对账群(和货款对账同一个群机器人),厂家在免登录确认页逐单确认,对某一单有异议可写原因,结果实时回到这里。</p>
|
||||
<p class="cbr-muted">结算运费 = 最终结算运费:逐单按我方核算,厂家开得比核算少(厂家运费 − 结算运费 < 0)的单按厂家运费结。费用列:快递运费 = 最终结算运费;快递记账、补运费、补记账、退回费、拦截费、改地址费、翻箱费、超长费先按厂家上传模板「附加费」表的附加费类型自动带入,可在「改费用 / 备注」里逐家改(加粗 = 手工改过,清空回到自动值);合计运费 = 快递运费 + 补运费 + 退回费 + 拦截费 + 改地址费 + 翻箱费 + 超长费 − 快递记账 + 补记账。</p>
|
||||
<p class="cbr-muted">差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算,厂家开得比核算少的按厂家运费结(最终结算运费);换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。厂家确认:核对完成后点「推送厂家确认」,推送到这家的钉钉对账群(和货款对账同一个群机器人),厂家在免登录确认页逐单确认,对某一单有异议可写原因,结果实时回到这里。</p>
|
||||
|
||||
@ -104,7 +104,7 @@
|
||||
<td>{{ $r['ship_time'] ? substr($r['ship_time'], 0, 16) : '—' }}</td>
|
||||
<td>{{ $r['express'] ?? '—' }}</td>
|
||||
<td class="num">{{ number_format((float) $r['bill'], 2) }}</td>
|
||||
<td class="num">{{ number_format((float) ($r['settle'] ?? 0), 2) }}</td>
|
||||
<td class="num">{{ number_format((float) ($r['final'] ?? $r['settle'] ?? 0), 2) }}</td>
|
||||
<td><span class="tag">{{ $r['label'] }}</span></td>
|
||||
<td>{{ $r['note'] }}</td>
|
||||
@if ($current && ! $submitted)
|
||||
|
||||
@ -5,7 +5,14 @@
|
||||
@csrf
|
||||
<label>账单月份<input type="month" name="month" value="{{ $month }}" required></label>
|
||||
<button type="submit" class="cbr-primary">通知厂家上传</button>
|
||||
<span class="cbr-muted">只通知这个月还没上传、且配了钉钉群机器人(供应商对账里配置,和货款对账同一个群)的厂家,已上传的不打扰。群里收到厂家对账入口链接,厂家钉钉登录后在「上传运费账单」里按模板上传。</span>
|
||||
<span class="cbr-muted">只通知这个月有代发发货、还没上传、且配了钉钉群机器人(供应商对账里配置,和货款对账同一个群)的厂家,已上传的不打扰。群里收到厂家对账入口链接,厂家钉钉登录后在「上传运费账单」里按模板上传。在次月 1–{{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日通知的,会写明 {{ $dfDeadline ?? '' }} 截止、逾期本月货款和运费不予结算。</span>
|
||||
</form>
|
||||
<form method="POST" action="{{ $action('auto-remind') }}" class="cbr-panel-body cbr-form">
|
||||
@csrf
|
||||
<input type="hidden" name="enabled" value="{{ ($dfAutoRemind ?? true) ? 0 : 1 }}">
|
||||
<span><strong>自动提醒:{{ ($dfAutoRemind ?? true) ? '已开启' : '已关闭' }}</strong></span>
|
||||
<button type="submit" class="cbr-button">{{ ($dfAutoRemind ?? true) ? '关闭自动提醒' : '开启自动提醒' }}</button>
|
||||
<span class="cbr-muted">每月 1–{{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日 {{ \App\Support\DropshipFreight\DropshipUploadReminder::SEND_TIME }} 自动往厂家群发提醒,催上个月的代发运费账单:只发给有代发发货、还没上传、配了机器人的厂家,写明 {{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日截止、逾期本月货款和运费不予结算;厂家一上传就不再提醒。</span>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
|
||||
@ -823,7 +823,9 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection)
|
||||
Route::post('factories/{factory}/delete', [$controller, 'deleteFactory'])->whereNumber('factory')->name('delete-factory')->defaults('section', $courierBillSection);
|
||||
Route::post('factories/{factory}/check', [$controller, 'check'])->whereNumber('factory')->name('check')->defaults('section', $courierBillSection);
|
||||
Route::post('factories/{factory}/push', [$controller, 'push'])->whereNumber('factory')->name('push')->defaults('section', $courierBillSection);
|
||||
Route::post('factories/{factory}/fees', [$controller, 'saveFees'])->whereNumber('factory')->name('save-fees')->defaults('section', $courierBillSection);
|
||||
Route::post('notify-upload', [$controller, 'notifyUpload'])->name('notify-upload')->defaults('section', $courierBillSection);
|
||||
Route::post('auto-remind', [$controller, 'autoRemind'])->name('auto-remind')->defaults('section', $courierBillSection);
|
||||
Route::get('export', [$controller, 'export'])->name('export')->defaults('section', $courierBillSection);
|
||||
});
|
||||
|
||||
|
||||
@ -28,11 +28,17 @@ final class CourierBillPagesTest extends FeatureTestCase
|
||||
$this->get($directory)->assertOk()->assertSeeText('快递应付汇总')->assertSeeText('快递账单对账');
|
||||
$page = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', ...$q]);
|
||||
foreach (['overview', 'details', 'upload', 'ledger', 'groups'] as $view) {
|
||||
$this->get($page(['cb_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false);
|
||||
$this->get($page(['cb_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false)->assertDontSeeText('快递账单对账暂不可用');
|
||||
}
|
||||
}
|
||||
|
||||
$section = 'courier-payables-final';
|
||||
// 历史已结算单号不分组:台账页、查单号都能显示
|
||||
$db->table('courier_bill_ledger')->insert(['group_id' => 0, 'waybill_no' => 'HIS001', 'settle_month' => '2026-08', 'amount' => 3]);
|
||||
$ledger = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'ledger', ...$q]);
|
||||
$this->get($ledger())->assertOk()->assertSeeText('历史导入(不分组)')->assertSeeText('「单号」「结算月份」');
|
||||
$this->get($ledger(['waybill' => 'his001']))->assertOk()->assertSeeText('历史导入(不分组) · 2026-08 已结算');
|
||||
$db->table('courier_bill_ledger')->where('waybill_no', 'HIS001')->delete();
|
||||
$this->post(route("business.$section.courier-bills.save-group"), ['name' => '河北中通-江三/小件', 'express_names' => "河北中通-江三\n河北中通小件-江三",
|
||||
'summary_carrier' => '河北中通', 'owner' => '张三'])->assertRedirect();
|
||||
$this->assertSame(1, $db->table('courier_bill_groups')->count());
|
||||
|
||||
@ -365,13 +365,24 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
$this->seedShipping();
|
||||
$store = app(CourierBillStore::class);
|
||||
$store->saveGroup(null, ['name' => '河北中通-江三/小件', 'express_names' => ['河北中通-江三'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
|
||||
$path = $this->workbook(['台账' => [['分组', '单号', '结算月份', '金额'], ['河北中通-江三/小件', 'ZT001', '2026年9月', 10], ['不存在', 'X1', '2026-09', 1]]]);
|
||||
// 只要单号和结算月份,不分组;同一单号同一月份只记一次;认不出的行不导入
|
||||
$path = $this->workbook(['台账' => [['单号', '结算月份'], ['ZT001', '2026年9月'], ['ZT001', '2026-09'], ['ZT002', '2026.9'], ['X1', '不知道']]]);
|
||||
$result = $store->importLedger($path, 'xlsx');
|
||||
$this->assertSame(1, $result['inserted']);
|
||||
$this->assertSame(['不存在'], $result['unknown_groups']);
|
||||
$ids = $store->upload([$this->upload('河北中通-江三.xlsx', [['运单号', '运费'], ['ZT001', 10]])], '2026-10', [], 'tester');
|
||||
$this->assertSame(['rows' => 4, 'inserted' => 2, 'rejected' => 1], $result);
|
||||
$this->assertSame([0], $store->db()->table('courier_bill_ledger')->distinct()->pluck('group_id')->map('intval')->all());
|
||||
try {
|
||||
$store->importLedger($this->workbook(['台账' => [['分组', '单号'], ['河北中通-江三/小件', 'ZT009']]]), 'xlsx');
|
||||
$this->fail('缺结算月份应当报错');
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->assertStringContainsString('「单号」「结算月份」', $e->getMessage());
|
||||
}
|
||||
// 按单号查重:哪家账单里出现、结算月份不是本月,就是重复
|
||||
$ids = $store->upload([$this->upload('河北中通-江三.xlsx', [['运单号', '运费'], ['ZT001', 10], ['ZT002', 5], ['ZT003', 6]])], '2026-10', [], 'tester');
|
||||
$statementId = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id');
|
||||
$this->assertSame(Category::DUPLICATE, $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->value('category'));
|
||||
$categories = $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->pluck('category', 'waybill_no')->all();
|
||||
$this->assertSame(Category::DUPLICATE, $categories['ZT001']);
|
||||
$this->assertSame(Category::DUPLICATE, $categories['ZT002']);
|
||||
$this->assertNotSame(Category::DUPLICATE, $categories['ZT003']);
|
||||
}
|
||||
|
||||
public function test_groups_can_be_generated_from_summary_imported_and_completed_from_shipping_names(): void
|
||||
|
||||
@ -6,6 +6,9 @@ use App\Models\Auth\Permission;
|
||||
use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use App\Support\DropshipFreight\DropshipConfirmation;
|
||||
use App\Support\DropshipFreight\DropshipUploadReminder;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
@ -133,39 +136,109 @@ final class DropshipFreightConfirmTest extends FeatureTestCase
|
||||
|
||||
public function test_notify_factories_that_have_not_uploaded_this_month(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$this->company->makeCurrent(true);
|
||||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
$this->loginAs()->withExceptionHandling();
|
||||
$db = CourierBillMatcher::db();
|
||||
foreach (['临沂卿德客' => '工厂-山东卿德客代发仓', '河北丽彪' => '工厂-河北丽彪代发仓', '没配群' => '工厂-没配群代发仓'] as $name => $wh) {
|
||||
$db->table('dropship_factories')->insert(['name' => $name, 'warehouse' => $wh, 'keywords' => mb_substr($name, -2),
|
||||
'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$notifier->save('临沂卿德客', 'https://oapi.dingtalk.com/robot/send?access_token=a', '', false);
|
||||
$notifier->save('河北丽彪', 'https://oapi.dingtalk.com/robot/send?access_token=b', '', false);
|
||||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id'),
|
||||
'original_name' => 'x.xlsx', 'stored_path' => 'x', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]);
|
||||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||||
Carbon::setTestNow(Carbon::parse('2026-12-03 10:00:00', 'Asia/Shanghai'));
|
||||
$db = $this->reminderFixture();
|
||||
$url = route('business.' . self::SECTION . '.dropship-freight.notify-upload');
|
||||
|
||||
$this->post($url, ['month' => '2026-11'])->assertSessionHas('dropship_message', '已通知 1 家上传 2026-11 代发运费账单:临沂卿德客;1 家已经上传,没再通知;1 家没配钉钉群机器人。');
|
||||
$this->post($url, ['month' => '2026-11'])->assertSessionHas('dropship_message', '已通知 1 家上传 2026-11 代发运费账单:临沂卿德客'
|
||||
. '(写明 12月14日 截止,逾期本月货款和运费不予结算);1 家已经上传,没再通知;1 家这个月没有代发发货,没通知;1 家没配钉钉群机器人:没配群。');
|
||||
$this->assertCount(1, Http::recorded());
|
||||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||||
$this->assertStringContainsString('代发运费账单上传提醒 · 临沂卿德客', $text);
|
||||
$this->assertStringContainsString('请上传 **2026年11月** 代发运费账单', $text);
|
||||
$this->assertStringContainsString('请于 **12月14日** 前上传 **2026年11月** 代发运费账单,还剩 11 天', $text);
|
||||
$this->assertStringContainsString('**逾期未上传,本月货款和运费将不予结算**', $text);
|
||||
$this->assertStringContainsString('[打开厂家对账入口](', $text);
|
||||
// 单独通知一家:已上传也照发;没配机器人报错
|
||||
// 不在上传期里的月份(比如单独补催 10 月):不写截止和后果;10 月没有代发发货,批量不发
|
||||
$this->post($url, ['month' => '2026-10'])->assertSessionHas('dropship_message', fn (string $m): bool => str_starts_with($m, '已通知 0 家'));
|
||||
$this->post($url, ['month' => '2026-10', 'factory' => $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id')]);
|
||||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||||
$this->assertStringContainsString('请上传 **2026年10月** 代发运费账单', $text);
|
||||
$this->assertStringNotContainsString('不予结算', $text);
|
||||
$count = count(Http::recorded());
|
||||
// 单独通知一家:已上传、没代发发货也照发;没配机器人报错
|
||||
$this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id')])
|
||||
->assertSessionHas('dropship_message');
|
||||
$this->assertCount(2, Http::recorded());
|
||||
$this->assertCount($count + 1, Http::recorded());
|
||||
$this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '没配群')->value('id')])
|
||||
->assertSessionHasErrors('dropship');
|
||||
$this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'factories', 'month' => '2026-11']))
|
||||
->assertOk()->assertSeeText('通知上传');
|
||||
$this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'upload', 'month' => '2026-11']))
|
||||
->assertOk()->assertSeeText('通知厂家上传');
|
||||
->assertOk()->assertSeeText('通知厂家上传')->assertSeeText('自动提醒:已开启')->assertSeeText('关闭自动提醒');
|
||||
Carbon::setTestNow();
|
||||
}
|
||||
|
||||
public function test_auto_reminder_runs_on_the_1st_to_14th_for_last_months_bill(): void
|
||||
{
|
||||
$db = $this->reminderFixture();
|
||||
$run = fn (string $date, array $options = []) => $this->artisan('dropship-freight:remind-upload', ['--date' => $date, ...$options]);
|
||||
|
||||
// 15 日以后不发
|
||||
$run('2026-12-15')->assertExitCode(0);
|
||||
$this->assertCount(0, Http::recorded());
|
||||
// 试运行只列名单
|
||||
$run('2026-12-04', ['--dry-run' => true])->expectsOutputToContain('会提醒 1 家:临沂卿德客')->assertExitCode(0);
|
||||
$this->assertCount(0, Http::recorded());
|
||||
|
||||
$run('2026-12-04')->expectsOutputToContain('已通知 1 家上传 2026-11 代发运费账单:临沂卿德客')->assertExitCode(0);
|
||||
$this->assertCount(1, Http::recorded());
|
||||
$this->assertStringContainsString('还剩 10 天', (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''));
|
||||
// 同一天不重复发
|
||||
$run('2026-12-04')->expectsOutputToContain('今天已经提醒过')->assertExitCode(0);
|
||||
$this->assertCount(1, Http::recorded());
|
||||
// 14 日:今天截止
|
||||
$run('2026-12-14')->assertExitCode(0);
|
||||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||||
$this->assertStringContainsString('代发运费账单上传提醒(今天截止) · 临沂卿德客', $text);
|
||||
$this->assertStringContainsString('**今天截止**', $text);
|
||||
// 厂家传了(解析失败的不算),第二天就不再催
|
||||
$factory = $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id');
|
||||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'bad.xlsx',
|
||||
'stored_path' => 'bad', 'status' => 'failed', 'created_at' => now(), 'updated_at' => now()]);
|
||||
$run('2026-12-05')->expectsOutputToContain('已通知 1 家')->assertExitCode(0);
|
||||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'ok.xlsx',
|
||||
'stored_path' => 'ok', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]);
|
||||
$sent = count(Http::recorded());
|
||||
$run('2026-12-06')->expectsOutputToContain('已通知 0 家')->assertExitCode(0);
|
||||
$this->assertCount($sent, Http::recorded());
|
||||
|
||||
// 关掉开关就不发
|
||||
$db->table('dropship_bill_files')->where('original_name', 'ok.xlsx')->delete();
|
||||
$this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 0])->assertSessionHas('dropship_message', '已关闭自动提醒。');
|
||||
$this->assertFalse(DropshipUploadReminder::enabled());
|
||||
$run('2026-12-07')->expectsOutputToContain('自动提醒已关闭')->assertExitCode(0);
|
||||
$this->assertCount($sent, Http::recorded());
|
||||
$this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 1]);
|
||||
$this->assertTrue(DropshipUploadReminder::enabled());
|
||||
}
|
||||
|
||||
private function reminderFixture()
|
||||
{
|
||||
Storage::fake('local');
|
||||
Cache::flush();
|
||||
$this->company->makeCurrent(true);
|
||||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
$this->loginAs()->withExceptionHandling();
|
||||
$db = CourierBillMatcher::db();
|
||||
$notifier = app(SupplierDingTalkNotifier::class);
|
||||
$source = 9100;
|
||||
foreach (['临沂卿德客' => '德客', '河北丽彪' => '丽彪', '没配群' => '配群', '无代发厂' => '代发厂'] as $name => $keyword) {
|
||||
$warehouse = '工厂-' . $name . '代发仓';
|
||||
$db->table('dropship_factories')->insert(['name' => $name, 'warehouse' => $warehouse, 'keywords' => $keyword,
|
||||
'created_at' => now(), 'updated_at' => now()]);
|
||||
if ($name !== '无代发厂') {
|
||||
$this->shipping()->table('jst_oms_shipping')->insert(['express_no' => 'DF' . $source, 'express_name1' => $keyword . '代发韵达',
|
||||
'warehouse_name' => $warehouse, 'ship_time' => '2026-11-20 10:00:00', 'source_id' => $source++]);
|
||||
}
|
||||
if ($name !== '没配群') {
|
||||
$notifier->save($name, 'https://oapi.dingtalk.com/robot/send?access_token=' . $source++, '', false);
|
||||
}
|
||||
}
|
||||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id'),
|
||||
'original_name' => 'x.xlsx', 'stored_path' => 'x', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]);
|
||||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||||
|
||||
return $db;
|
||||
}
|
||||
|
||||
private function shipping()
|
||||
|
||||
@ -121,8 +121,15 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$this->assertSame(11, $s['billed']);
|
||||
$this->assertEquals(63, $s['bill']);
|
||||
// 按我方核算:一致、运费有差、前月补提供、换单实际发出的代发单;跨月订单留到发货月
|
||||
$this->assertEquals(8 + 5 + 6 + 4 + 6, $s['settle']);
|
||||
$this->assertEquals(63 - 29, $s['diff']);
|
||||
$this->assertEquals(8 + 5 + 6 + 4 + 6, $s['calc_settle']);
|
||||
// 最终结算:厂家开得比核算少的(773444000003 厂家 5、核算 6)按厂家运费结
|
||||
$this->assertEquals(8 + 5 + 5 + 4 + 6, $s['settle']);
|
||||
$this->assertSame(1, $s['capped']);
|
||||
$this->assertEquals(63 - 28, $s['diff']);
|
||||
$under = collect($result['rows'])->firstWhere('waybill', '773444000003');
|
||||
$this->assertEquals([5, 6, 5], [$under['bill'], $under['settle'], $under['final']]);
|
||||
$over = collect($result['rows'])->firstWhere('waybill', '773444000002');
|
||||
$this->assertEquals([6, 5, 5], [$over['bill'], $over['settle'], $over['final']]);
|
||||
$swap = collect($result['rows'])->firstWhere('waybill', 'OLD0000001');
|
||||
$this->assertStringContainsString('换单:实际发出 773444000020(卿德客申通)', $swap['note']);
|
||||
$this->assertStringContainsString('自有快递「曹县韵达」', collect($result['rows'])->firstWhere('waybill', 'OLD0000002')['note']);
|
||||
@ -134,7 +141,7 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$this->assertStringContainsString('自有快递', (string) $own['note']);
|
||||
$this->assertNull($own['settle']);
|
||||
|
||||
$this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('29.00');
|
||||
$this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('28.00');
|
||||
$this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']))->assertOk()
|
||||
->assertSeeText('一致但运费有差')->assertSeeText('773444000004')->assertSeeText('厂家未提供(不付)')->assertSeeText('匹配不到')
|
||||
->assertSeeText('自有快递「曹县韵达」');
|
||||
@ -152,6 +159,10 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
->where('factory_id', $factory->id)->where('bill_month', '2026-10')->first(['title', 'labels', 'total_label'])));
|
||||
$november = app(DropshipFreightStore::class)->summaryTemplate($f, '2026-11');
|
||||
$this->assertSame(['11月', ['运费', '货款', '记账'], '2026-10'], [$november['title'], $november['labels'], $november['from']]);
|
||||
// 小汇总不要「代发」「退货」:默认样子没有,手工汇总里带了也去掉
|
||||
$this->assertSame(['运费', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::DEFAULT['labels']);
|
||||
$this->assertSame(['运费', '货款', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::withoutDropped(
|
||||
['labels' => ['运费', '货款', '代发', '记账', '10月退货']])['labels']);
|
||||
$before = $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson();
|
||||
$filesBefore = $db->table('dropship_bill_files')->orderBy('id')->get()->toJson();
|
||||
$export = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk();
|
||||
@ -175,12 +186,12 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$summary = $sheet->toArray(null, false, false);
|
||||
$this->assertSame(['10月', '厂家金额', '简尚金额', '差异'], array_slice($summary[0], 0, 4));
|
||||
$this->assertSame(['运费', '货款', '记账', '汇总'], [$summary[1][0], $summary[2][0], $summary[3][0], $summary[4][0]]);
|
||||
$this->assertEquals([63, 29], [$summary[1][1], $summary[1][2]]);
|
||||
$this->assertEquals([63, 28], [$summary[1][1], $summary[1][2]]);
|
||||
$this->assertNull($summary[2][1]); // 货款先空着手工填
|
||||
$this->assertSame('=SUM(B2:B4)', $sheet->getCell('B5')->getValue()); // 合计是公式,手工填了跟着算
|
||||
$sheet->setCellValue('C4', -100);
|
||||
$this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue());
|
||||
$this->assertEquals(-71, $sheet->getCell('C5')->getCalculatedValue());
|
||||
$this->assertEquals(-72, $sheet->getCell('C5')->getCalculatedValue());
|
||||
$this->assertSame(5, $sheet->getHighestDataRow()); // 汇总块下面不再附别的
|
||||
$this->assertSame([3, 1], [count($book->getSheetByName('快递不符')->toArray()) - 1, count($book->getSheetByName('匹配不到')->toArray()) - 1]);
|
||||
$book->disconnectWorksheets();
|
||||
@ -291,7 +302,8 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$data = $book->getSheetByName('对账')->toArray(null, false, false);
|
||||
$this->assertSame(['快递单号', '运费', '备注', '备注(2)'], array_slice($data[0], 0, 4));
|
||||
$this->assertSame(['00012345678901234567', 4, ' 保留空格 ', '=1+1'], array_slice($data[1], 0, 4));
|
||||
$this->assertEquals(11, $data[1][count($data[0]) - 4]);
|
||||
$this->assertEquals(11, $data[1][count($data[0]) - 5]);
|
||||
$this->assertSame(['厂家运费(这一单合计)', '结算运费', '最终结算运费'], array_slice($data[0], -5, 3));
|
||||
$this->assertContains($book->getSheetByName('对账')->getCell('D2')->getDataType(), [
|
||||
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE,
|
||||
]);
|
||||
@ -355,6 +367,51 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$this->assertSame('parsed', $store->db()->table('dropship_bill_files')->value('status'));
|
||||
}
|
||||
|
||||
public function test_overview_fee_columns_fill_from_the_surcharge_sheet_and_can_be_edited(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
$this->loginAs()->withExceptionHandling();
|
||||
$db = CourierBillMatcher::db();
|
||||
$id = $db->table('dropship_factories')->insertGetId(['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客',
|
||||
'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->ship('773444000001', '卿德客申通', self::WAREHOUSE, '2026-11-03 09:00:00', 1, 8);
|
||||
$this->ship('773444000002', '卿德客申通', self::WAREHOUSE, '2026-11-04 09:00:00', 2, 6); // 厂家开 5,比核算少,按 5 结
|
||||
$h = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率'];
|
||||
$path = $this->xlsx(['账单' => [$h, ['773444000001', '', 2, 8], ['773444000002', '', 1, 5]],
|
||||
'附加费' => [['快递单号', '附加费金额', '附加费类型'], ['773444000001', 3, '退回费'], ['773444000002', 2, '拦截费'], ['773444000002', 1.5, '上楼费']]]);
|
||||
app(DropshipFreightStore::class)->uploadFor('卿德客11月.xlsx', $path, '2026-11', $id, '测试');
|
||||
|
||||
$fees = app(\App\Support\DropshipFreight\DropshipFees::class);
|
||||
$row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id];
|
||||
$this->assertEquals(['freight' => 13, 'returned' => 3, 'intercept' => 2], array_filter($row['values']));
|
||||
$this->assertSame(['上楼费' => 1.5], $row['other']);
|
||||
$this->assertEquals(18, $row['total']);
|
||||
$this->assertSame('booking', \App\Support\DropshipFreight\DropshipFees::classify('快递记账'));
|
||||
$this->assertSame('extra_booking', \App\Support\DropshipFreight\DropshipFees::classify('补记账'));
|
||||
$this->assertSame('readdress', \App\Support\DropshipFreight\DropshipFees::classify('改址费'));
|
||||
|
||||
$section = 'courier-payables-final';
|
||||
$page = route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'overview', 'month' => '2026-11']);
|
||||
$this->get($page)->assertOk()->assertSeeTextInOrder(['厂家', '快递运费', '快递记账', '补运费', '补记账', '退回费', '拦截费', '改地址费', '翻箱费', '超长费', '合计运费', '备注', '代发仓'])
|
||||
->assertSeeText('18.00')->assertSeeText('上楼费');
|
||||
// 财务改:快递记账 4(扣款)、补记账 1、退回费改成 2.5,备注
|
||||
$save = route("business.$section.dropship-freight.save-fees", ['factory' => $id]);
|
||||
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '-4', 'extra_booking' => '1', 'returned' => '2.5'], 'note' => '已和厂家核对'])
|
||||
->assertSessionHas('dropship_message');
|
||||
$row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id];
|
||||
$this->assertEquals(13 + 2.5 + 2 - 4 + 1, $row['total']);
|
||||
$this->assertTrue($row['manual']['booking']);
|
||||
$this->assertEquals(3, $row['auto']['returned']);
|
||||
$this->get($page)->assertOk()->assertSeeText('-4.00')->assertSeeText('14.50')->assertSeeText('已和厂家核对');
|
||||
// 清空回到自动值
|
||||
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '', 'returned' => ''], 'note' => ''])->assertSessionHas('dropship_message');
|
||||
$this->assertEquals(18, $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id]['total']);
|
||||
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => 'abc']])->assertSessionHasErrors('fees.booking');
|
||||
// 页面上的快递运费 = 最终结算运费
|
||||
$this->assertEquals(13, app(DropshipReconciler::class)->factoryMonth(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11')['summary']['settle']);
|
||||
}
|
||||
|
||||
public function test_keyword_helpers(): void
|
||||
{
|
||||
$this->assertSame('卿德客', DropshipFreightStore::warehouseCore('工厂-山东卿德客代发仓'));
|
||||
|
||||
@ -274,6 +274,14 @@ final class PortalFreightBillTest extends FeatureTestCase
|
||||
$this->post($action('save-robot', ['group' => $groupId]), ['webhook' => 'https://oapi.dingtalk.com/robot/send?access_token=cx', 'secret' => 'SEC-cx'])
|
||||
->assertSessionHas('courier_bills_message');
|
||||
$this->get($groups)->assertOk()->assertSeeText('已配')->assertSeeText('推送 2026-11 上传链接');
|
||||
// 没指定月份:最近的对账单还停在上上个月(比如 10 月),推送默认上个月(11 月),对账单月份不变
|
||||
[$older, $last] = [now()->subMonthsNoOverflow(2)->format('Y-m'), now()->subMonthNoOverflow()->format('Y-m')];
|
||||
$db->table('courier_bill_statements')->insert(['group_id' => $groupId, 'bill_month' => $older, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->get(route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'groups']))
|
||||
->assertOk()->assertSeeText('推送 ' . $last . ' 上传链接')->assertSeeText('推送上传链接的账单月份');
|
||||
$this->get(route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'upload']))
|
||||
->assertOk()->assertSee('name="month" value="' . $last . '"', false)->assertSeeText('上传账单 · ' . $older);
|
||||
$db->table('courier_bill_statements')->where('bill_month', $older)->delete();
|
||||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||||
$this->post($action('push-upload-links'), ['month' => '2026-11'])->assertSessionHas('courier_bills_message');
|
||||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user