277 lines
11 KiB
PHP
277 lines
11 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use InvalidArgumentException;
|
||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||
use RuntimeException;
|
||
|
||
class VipshopMpBillImporter
|
||
{
|
||
private const TABLE = 'ec_account_bills';
|
||
private const BILL_TYPE = 'vipshop';
|
||
private const CREATED_FROM = 'vip-mp-import';
|
||
|
||
private const REQUIRED_HEADERS = [
|
||
'全局ID',
|
||
'店铺ID',
|
||
'店铺名称',
|
||
'订单签收或退款时间',
|
||
'订单类型名称',
|
||
'订单编号',
|
||
'总金额(E=A-B-C-D)',
|
||
'技术服务费(F)',
|
||
'商家应收(G=E-F-G)',
|
||
];
|
||
|
||
private const PAYLOAD_HEADERS = [
|
||
'行类型名称' => 'vip_5',
|
||
'售后类型名称' => 'vip_6',
|
||
'售后单号' => 'vip_7',
|
||
'SKU' => 'vip_9',
|
||
'商品款号' => 'vip_10',
|
||
'商品SKU' => 'vip_11',
|
||
'商品描述' => 'vip_12',
|
||
'店铺协议编号' => 'vip_13',
|
||
'二级类目' => 'vip_14',
|
||
'三级类目' => 'vip_15',
|
||
'商品单价' => 'vip_16',
|
||
'商品数量' => 'vip_17',
|
||
'商品金额(A)' => 'vip_18',
|
||
'商家优惠(B)' => 'vip_19',
|
||
'调整金额(C)' => 'vip_20',
|
||
'无需退款金额(D)' => 'vip_21',
|
||
'总金额(E=A-B-C-D)' => 'vip_22',
|
||
'扣点' => 'vip_23',
|
||
'技术服务费(F)' => 'vip_24',
|
||
'海淘综合税(G)' => 'vip_25',
|
||
'分享金扣点' => 'vip_26',
|
||
'唯品仓分享金' => 'vip_27',
|
||
];
|
||
|
||
/**
|
||
* @param list<string> $paths
|
||
* @param array<string,string> $storeMap
|
||
* @return array{status:string,row_count:int,store_count:int,bill_count:int,income_total:string,expense_total:string,balance_total:string,period:string}
|
||
*/
|
||
public function import(
|
||
array $paths,
|
||
string $period,
|
||
array $storeMap,
|
||
int $companyId = 1,
|
||
bool $dryRun = false,
|
||
): array {
|
||
$period = $this->period($period);
|
||
if ($companyId <= 0) {
|
||
throw new InvalidArgumentException('公司 ID 必须大于零。');
|
||
}
|
||
if (! Schema::hasTable(self::TABLE)) {
|
||
throw new RuntimeException('通用账户账单表尚未完成迁移:' . self::TABLE);
|
||
}
|
||
|
||
$rows = [];
|
||
$seenCodes = [];
|
||
$stores = [];
|
||
$incomeTotal = '0.000000';
|
||
$expenseTotal = '0.000000';
|
||
$balanceTotal = '0.000000';
|
||
$billCodes = [];
|
||
|
||
foreach ($paths as $path) {
|
||
$realPath = realpath($path);
|
||
if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) {
|
||
throw new InvalidArgumentException('唯品会MP账单文件不存在或不可读。');
|
||
}
|
||
if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') {
|
||
throw new InvalidArgumentException('唯品会MP账单只支持 XLSX 文件。');
|
||
}
|
||
|
||
$sourceName = basename($realPath);
|
||
if (preg_match('/(MP-[A-Z]{2}\d{8}-\d{8}-\d{2}(?:-\d+)?)\.xlsx$/i', $sourceName, $matches) === 1) {
|
||
$billCodes[$matches[1]] = true;
|
||
}
|
||
|
||
$spreadsheet = IOFactory::load($realPath);
|
||
try {
|
||
$sheet = $spreadsheet->getActiveSheet();
|
||
$sheetTitle = $sheet->getTitle();
|
||
$matrix = $sheet->toArray(null, true, true, false);
|
||
} finally {
|
||
$spreadsheet->disconnectWorksheets();
|
||
}
|
||
if ($matrix === []) {
|
||
throw new InvalidArgumentException("{$sourceName} 为空。");
|
||
}
|
||
|
||
$headers = array_map(
|
||
static fn (mixed $value): string => trim((string) $value),
|
||
array_shift($matrix),
|
||
);
|
||
$indexes = array_flip($headers);
|
||
$missing = array_values(array_filter(
|
||
self::REQUIRED_HEADERS,
|
||
static fn (string $header): bool => ! array_key_exists($header, $indexes),
|
||
));
|
||
if ($missing !== []) {
|
||
throw new InvalidArgumentException(
|
||
"{$sourceName} 缺少唯品会MP字段:" . implode('、', $missing),
|
||
);
|
||
}
|
||
|
||
$sourceHash = hash_file('sha256', $realPath);
|
||
foreach ($matrix as $offset => $values) {
|
||
if (! is_array($values) || ! array_filter($values, static fn (mixed $value): bool => $value !== null && $value !== '')) {
|
||
continue;
|
||
}
|
||
$rowNumber = $offset + 2;
|
||
$sourceStore = trim((string) ($values[$indexes['店铺名称']] ?? ''));
|
||
$financeStore = trim((string) ($storeMap[$sourceStore] ?? ''));
|
||
if ($financeStore === '') {
|
||
throw new InvalidArgumentException(
|
||
"{$sourceName} 第 {$rowNumber} 行的店铺未配置财务系统名称:{$sourceStore}",
|
||
);
|
||
}
|
||
|
||
$recordCode = trim((string) ($values[$indexes['全局ID']] ?? ''));
|
||
if ($recordCode === '' || isset($seenCodes[$recordCode])) {
|
||
throw new InvalidArgumentException("全局ID为空或重复:{$recordCode}");
|
||
}
|
||
$seenCodes[$recordCode] = true;
|
||
|
||
$net = bcadd(
|
||
$this->decimal($values[$indexes['总金额(E=A-B-C-D)']] ?? null, $rowNumber, '总金额'),
|
||
$this->decimal($values[$indexes['技术服务费(F)']] ?? null, $rowNumber, '技术服务费'),
|
||
6,
|
||
);
|
||
$income = bccomp($net, '0', 6) > 0 ? $net : '0.000000';
|
||
$expense = bccomp($net, '0', 6) < 0 ? bcmul($net, '-1', 6) : '0.000000';
|
||
$balance = $this->decimal(
|
||
$values[$indexes['商家应收(G=E-F-G)']] ?? null,
|
||
$rowNumber,
|
||
'商家应收',
|
||
);
|
||
$payload = ['shop_id' => $this->text($values[$indexes['店铺ID']] ?? null)];
|
||
foreach (self::PAYLOAD_HEADERS as $header => $key) {
|
||
$payload[$key] = $this->text($values[$indexes[$header]] ?? null);
|
||
}
|
||
$payload += [
|
||
'settle_period' => $period,
|
||
'source_file' => $sourceName,
|
||
'source_sheet' => $sheetTitle,
|
||
'source_row' => $rowNumber,
|
||
'source_sha256' => $sourceHash,
|
||
'raw_headers' => $headers,
|
||
'raw_values' => array_map(fn (mixed $value): string => $this->text($value), $values),
|
||
];
|
||
|
||
$rows[] = [
|
||
'company_id' => $companyId,
|
||
'bill_type' => self::BILL_TYPE,
|
||
'record_code' => mb_substr($recordCode, 0, 64),
|
||
'store_name' => mb_substr($financeStore, 0, 255),
|
||
'finance_remark' => null,
|
||
'order_no' => mb_substr($this->text($values[$indexes['订单编号']] ?? null), 0, 64),
|
||
'amount' => $net,
|
||
'custom_remark' => null,
|
||
'bill_item' => mb_substr($this->text($values[$indexes['订单类型名称']] ?? null), 0, 64),
|
||
'occurred_at' => $this->dateTime($values[$indexes['订单签收或退款时间']] ?? null, $rowNumber),
|
||
'income' => $income,
|
||
'expense' => $expense,
|
||
'balance' => $balance,
|
||
'remark' => null,
|
||
'modifier' => '唯品会MP账单导出',
|
||
'payload' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
'created_by' => null,
|
||
'created_from' => self::CREATED_FROM,
|
||
];
|
||
$stores[$financeStore] = true;
|
||
$incomeTotal = bcadd($incomeTotal, $income, 6);
|
||
$expenseTotal = bcadd($expenseTotal, $expense, 6);
|
||
$balanceTotal = bcadd($balanceTotal, $balance, 6);
|
||
}
|
||
}
|
||
|
||
if ($rows === []) {
|
||
throw new InvalidArgumentException('唯品会MP账单文件中没有可导入的数据。');
|
||
}
|
||
|
||
if (! $dryRun) {
|
||
$now = now();
|
||
DB::transaction(function () use ($rows, $period, $stores, $now): void {
|
||
DB::table(self::TABLE)
|
||
->where('company_id', (int) $rows[0]['company_id'])
|
||
->where('bill_type', self::BILL_TYPE)
|
||
->whereIn('store_name', array_keys($stores))
|
||
->where('payload->settle_period', $period)
|
||
->delete();
|
||
|
||
foreach (array_chunk($rows, 500) as $chunk) {
|
||
DB::table(self::TABLE)->insert(array_map(
|
||
static fn (array $row): array => $row + [
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
'deleted_at' => null,
|
||
],
|
||
$chunk,
|
||
));
|
||
}
|
||
});
|
||
}
|
||
|
||
return [
|
||
'status' => $dryRun ? 'validated' : 'succeeded',
|
||
'row_count' => count($rows),
|
||
'store_count' => count($stores),
|
||
'bill_count' => count($billCodes),
|
||
'income_total' => $incomeTotal,
|
||
'expense_total' => $expenseTotal,
|
||
'balance_total' => $balanceTotal,
|
||
'period' => $period,
|
||
];
|
||
}
|
||
|
||
private function period(string $period): string
|
||
{
|
||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
|
||
}
|
||
|
||
return $period;
|
||
}
|
||
|
||
private function decimal(mixed $value, int $rowNumber, string $label): string
|
||
{
|
||
$raw = trim(str_replace([',', ',', '¥', '¥'], '', (string) $value));
|
||
if ($raw === '' || ! is_numeric($raw)) {
|
||
throw new InvalidArgumentException("第 {$rowNumber} 行的{$label}不是有效金额。");
|
||
}
|
||
|
||
return number_format((float) $raw, 6, '.', '');
|
||
}
|
||
|
||
private function dateTime(mixed $value, int $rowNumber): string
|
||
{
|
||
$raw = trim((string) $value);
|
||
if ($raw === '') {
|
||
throw new InvalidArgumentException("第 {$rowNumber} 行缺少订单签收或退款时间。");
|
||
}
|
||
$date = \DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $raw);
|
||
if ($date === false || $date->format('Y-m-d H:i:s') !== $raw) {
|
||
throw new InvalidArgumentException("第 {$rowNumber} 行订单签收或退款时间无效。");
|
||
}
|
||
|
||
return $raw;
|
||
}
|
||
|
||
private function text(mixed $value): string
|
||
{
|
||
if ($value instanceof \DateTimeInterface) {
|
||
return $value->format('Y-m-d H:i:s');
|
||
}
|
||
|
||
return trim((string) ($value ?? ''));
|
||
}
|
||
}
|