159 lines
8.0 KiB
PHP
159 lines
8.0 KiB
PHP
<?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;
|
||
}
|
||
}
|