CaiWuXiTong/app/Business/TaobaoAlipayBillSpreadsheetImporter.php
chenxi 1751d8e062 接入淘系支付宝账单副本库全量数据 (#208)
使用经营分析副本库作为全量分页、筛选、汇总与导出主数据源;演示表仅按记录编码补充源表缺失字段。验证:47 项 PHP 测试、435 assertions;6 项账户账单脚本测试;真实页面全量及日期筛选验收通过。
2026-09-19 01:52:45 +08:00

156 lines
5.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Business;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use Modules\EcommerceFinance\Models\AlipayBill;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
class TaobaoAlipayBillSpreadsheetImporter
{
public const SHEET_NAME = '淘系支付宝账户';
public const HEADERS = [
'记录编码', '原始店铺', '自定义备注', '账单项目', '支付宝账号',
'账务订单号', '业务流水号', '商户订单号', '业务基础订单号', '商品名称',
'对方账号', '发生时间', '收入', '支出', '余额', '业务类型', '备注',
'线上单号', '线上单号对应实际店铺', '业务描述', '业务账单来源',
'业务订单号', '创建时间', '修改时间', '修改人',
];
private const FIELDS = [
'record_code', 'store_name', 'custom_remark', 'bill_item', 'alipay_account',
'account_order_no', 'business_serial_no', 'merchant_order_no',
'business_base_order_no', 'goods_name', 'counterparty_account', 'occurred_at',
'income', 'expense', 'balance', 'business_type', 'remark', 'online_order_no',
'online_real_store', 'business_description', 'business_bill_source',
'business_order_no', 'created_at', 'updated_at', 'modifier',
];
private const REQUIRED_TEXT_FIELDS = [
'store_name', 'bill_item', 'business_type', 'alipay_account',
'counterparty_account', 'account_order_no', 'business_serial_no', 'goods_name',
];
public function import(string $path, int $companyId, bool $replace = false): array
{
if (! is_file($path) || ! is_readable($path)) {
throw new InvalidArgumentException('导入文件不存在或不可读取。');
}
$spreadsheet = IOFactory::load($path);
$sheet = $spreadsheet->getSheetByName(self::SHEET_NAME);
if (! $sheet) {
throw new InvalidArgumentException('未找到工作表“' . self::SHEET_NAME . '”。');
}
$headers = $sheet->rangeToArray('A1:Y1', null, false, false)[0];
$headers = array_map(fn ($value) => trim((string) $value), $headers);
if ($headers !== self::HEADERS) {
throw new InvalidArgumentException('表头与淘系支付宝账户模板不一致。');
}
$rows = [];
$skipped = 0;
for ($rowNumber = 2; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) {
$values = $sheet->rangeToArray("A{$rowNumber}:Y{$rowNumber}", null, false, false)[0];
if (collect($values)->every(fn ($value) => $value === null || trim((string) $value) === '')) {
$skipped++;
continue;
}
$rows[] = $this->normalizeRow(array_combine(self::FIELDS, $values), $rowNumber);
}
$inserted = 0;
$updated = 0;
$replaced = 0;
DB::transaction(function () use ($rows, $companyId, $replace, &$inserted, &$updated, &$replaced) {
if ($replace) {
$replaced = DB::table('ec_alipay_bills')->where('company_id', $companyId)->delete();
}
foreach ($rows as $data) {
$record = AlipayBill::query()
->where('company_id', $companyId)
->where('record_code', $data['record_code'])
->first();
$record ??= new AlipayBill();
$wasExisting = $record->exists;
$record->timestamps = false;
$record->fill(array_merge($data, [
'company_id' => $companyId,
'platform' => 'taobao',
'created_from' => 'attachment-import',
]));
$record->created_at = $data['created_at'];
$record->updated_at = $data['updated_at'];
$record->save();
$wasExisting ? $updated++ : $inserted++;
}
});
$spreadsheet->disconnectWorksheets();
return compact('inserted', 'updated', 'skipped', 'replaced');
}
private function normalizeRow(array $data, int $rowNumber): array
{
foreach ($data as $field => $value) {
$data[$field] = is_string($value) ? trim($value) : $value;
}
if ($data['record_code'] === null || $data['record_code'] === '') {
throw new InvalidArgumentException("第 {$rowNumber} 行缺少记录编码。");
}
foreach (['occurred_at', 'created_at', 'updated_at'] as $field) {
$data[$field] = $this->normalizeDateTime($data[$field], $rowNumber);
}
foreach (['income', 'expense', 'balance'] as $field) {
$data[$field] = $this->normalizeDecimal($data[$field], $rowNumber);
}
foreach (self::REQUIRED_TEXT_FIELDS as $field) {
$data[$field] = $data[$field] ?? '';
}
return $data;
}
private function normalizeDateTime($value, int $rowNumber): ?string
{
if ($value === null || $value === '') {
return null;
}
try {
return is_numeric($value)
? ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d H:i:s')
: Carbon::parse((string) $value)->format('Y-m-d H:i:s');
} catch (\Throwable) {
throw new InvalidArgumentException("第 {$rowNumber} 行包含无效日期时间。");
}
}
private function normalizeDecimal($value, int $rowNumber): string
{
$value = str_replace([',', ',', '¥', '¥'], '', (string) ($value ?? '0'));
if (! is_numeric($value)) {
throw new InvalidArgumentException("第 {$rowNumber} 行包含无效金额。");
}
return number_format((float) $value, 6, '.', '');
}
}