CaiWuXiTong/tests/Feature/Business/PortalFreightBillTest.php

386 lines
25 KiB
PHP

<?php
namespace Tests\Feature\Business;
use App\Models\Auth\DingTalkIdentity;
use App\Models\Auth\Permission;
use App\Models\Auth\Role;
use App\Models\Auth\SupplierPortalIdentity;
use App\Models\Auth\SupplierPortalSupplier;
use App\Models\Auth\User;
use App\Services\Auth\SupplierPortalAccess;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBills;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use RuntimeException;
use Tests\Feature\FeatureTestCase;
final class PortalFreightBillTest extends FeatureTestCase
{
private const H = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率'];
private const S = ['快递单号', '附加费金额', '附加费类型'];
public function test_template_is_strict_about_headers_and_required_columns(): void
{
$t = new FreightBillTemplate(new BillWorkbookReader());
$ok = $t->validate($this->xlsx([self::H, ['773444000001', '江苏', 3.2, 8, null, 1, 2.1], ['773444000002', null, null, '6.5'], ['合计', null, null, 14.5]]), 'xlsx');
$this->assertSame(['rows' => 2, 'waybills' => 2, 'amount' => 14.5, 'surcharge_rows' => 0, 'surcharge_amount' => 0.0], $ok);
foreach ([
[[['快递单号', '运费'], ['1', 2]], '第一行必须依次是'],
[[self::H, ['773444000001', '江苏', 3, null]], '第 2 行运费没填'],
[[self::H, [null, '江苏', 3, 5]], '第 2 行没有单号'],
[[self::H, ['773444000001', '江苏', '三公斤', 5]], '重量「三公斤」不是数字'],
[[self::H, ['7.9E+13', '江苏', 3, 5]], '单号格式不对'],
[[self::H], '还没有填账单明细'],
] as [$rows, $message]) {
try {
$t->validate($this->xlsx($rows), 'xlsx');
$this->fail('应当拒收:' . $message);
} catch (RuntimeException $e) {
$this->assertStringContainsString($message, $e->getMessage());
}
}
}
public function test_template_has_a_surcharge_sheet_that_may_stay_empty(): void
{
$t = new FreightBillTemplate(new BillWorkbookReader());
$bill = [self::H, ['773444000001', '江苏', 3.2, 8, '曹县韵达', 1, 2.1]];
// 下载的模板:两张表,附加费表头右边带说明;直接填一行运费就能过
ob_start();
$t->download('模板.xlsx')->sendContent();
$path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx';
file_put_contents($path, ob_get_clean());
$sheets = [];
foreach ((new BillWorkbookReader())->sheets($path, 'xlsx') as $name => $rows) {
foreach ($rows as $row) {
$sheets[$name] = array_values(array_filter(array_map(static fn ($v): string => trim((string) $v), $row), static fn (string $v): bool => $v !== ''));
break;
}
}
$this->assertSame(['账单' => self::H, '附加费' => [...self::S, FreightBillTemplate::SURCHARGE_NOTE]], $sheets);
$this->assertStringContainsString('无附加费无需填写', FreightBillTemplate::SURCHARGE_NOTE);
// 附加费表空着、只有表头(带说明)、或者根本没有这张表,都照收
foreach ([['账单' => $bill], ['账单' => $bill, '附加费' => []], ['账单' => $bill, '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE]]]] as $book) {
$this->assertSame(0, $t->validate($this->xlsxBook($book), 'xlsx')['surcharge_rows']);
}
// 旧模板第 5 列「送货备注」也收
$old = self::H;
$old[4] = '送货备注';
$this->assertSame(1, $t->validate($this->xlsx([$old, ['773444000001', '江苏', 3, 8]]), 'xlsx')['rows']);
$ok = $t->validate($this->xlsxBook(['账单' => $bill, '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE],
['773444000001', 3, '上楼费'], ['773444000009', '2.5', '偏远加收'], ['合计', 5.5]]]), 'xlsx');
$this->assertSame(2, $ok['surcharge_rows']);
$this->assertSame(5.5, $ok['surcharge_amount']);
$this->assertSame(8.0, (float) $ok['amount']);
foreach ([
[[['单号', '金额', '类型'], ['1', 2, '上楼费']], '「附加费」表第一行必须依次是'],
[[self::S, ['773444000001', null, '上楼费']], '附加费第 2 行金额没填'],
[[self::S, ['773444000001', '两块', '上楼费']], '金额「两块」不是数字'],
[[self::S, ['773444000001', 2]], '附加费第 2 行没写附加费类型'],
[[self::S, [null, 2, '上楼费']], '附加费第 2 行没有快递单号'],
[[self::S, ['7.9E+13', 2, '上楼费']], '单号格式不对'],
[[self::S, ['773444000001', '1e999', '上楼费']], '不是数字'],
] as [$rows, $message]) {
try {
$t->validate($this->xlsxBook(['账单' => $bill, '附加费' => $rows]), 'xlsx');
$this->fail('应当拒收:' . $message);
} catch (RuntimeException $e) {
$this->assertStringContainsString($message, $e->getMessage());
}
}
}
public function test_dropship_factory_and_courier_upload_their_own_bills_in_the_supplier_portal(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$db = CourierBillMatcher::db();
$db->table('dropship_factories')->insert(['name' => '临沂卿德客', 'warehouse' => '工厂-山东卿德客代发仓', 'keywords' => '卿德客',
'created_at' => now(), 'updated_at' => now()]);
$db->table('courier_bill_groups')->insert(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE),
'summary_carrier' => '曹县韵达', 'created_at' => now(), 'updated_at' => now()]);
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
foreach (['临沂卿德客', '曹县韵达'] as $name) {
app(\Modules\EcommerceFinance\Services\SupplierDingTalkNotifier::class)->save($name, 'https://oapi.dingtalk.com/robot/send?access_token=template-test', 'SEC-test', false);
}
$this->assertSame(['曹县韵达'], PortalFreightBills::courierNames(['曹县韵达', '财务中心', '临沂卿德客']));
\Illuminate\Support\Facades\URL::defaults(['company_id' => $this->company->id]);
$page = route('business.pages.show', ['section' => 'supplier-reconciliation', 'page' => 'supplier-data']);
$upload = route('business.supplier-reconciliation.freight-bill.upload');
$file = fn (array $rows, string $name = '账单.xlsx') => new UploadedFile($this->xlsx($rows), $name, null, null, true);
// 代发厂家:厂家门户里多了「上传运费账单」,传代发运费账单
$factoryUser = $this->portalUser('临沂卿德客');
$this->actingAsPortal($factoryUser)->get($page)->assertOk()->assertSeeText('上传运费账单')->assertSeeText('代发运费账单');
$this->get(route('business.supplier-reconciliation.freight-bill.template'))->assertOk();
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([['快递单号', '运费'], ['773444000001', 8]])])
->assertSessionHas('success');
$imports = app(PortalFreightBillImports::class);
$this->assertSame(0, $db->table('dropship_bill_files')->count());
$this->assertTrue($imports->processNext());
$this->get($page)->assertOk()->assertSeeText('第一行必须依次是');
$dropship = new UploadedFile($this->xlsxBook(['账单' => [self::H, ['773444000001', '江苏', 3, 8], ['773444000002', '', '', 6]],
'附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE], ['773444000001', 2, '上楼费']]]), '账单.xlsx', null, null, true);
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $dropship])
->assertSessionHas('success');
$this->assertTrue($imports->processNext());
$f = $db->table('dropship_bill_files')->sole();
$this->assertSame('parsed', $f->status);
$this->assertSame(2, (int) $f->waybill_count);
$this->assertEquals(14, (float) $f->amount);
$this->assertStringContainsString('附加费 1 行,合计 2.00 元', $f->message);
$receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('运费合计 **¥14.00**', $receipt);
$this->assertStringContainsString('附加费:**1** 行,合计 **¥2.00**', $receipt);
$this->get($page)->assertOk()->assertSeeText('附加费 1 行,合计 2.00 元');
$this->assertStringContainsString('(门户)', (string) $f->uploaded_by);
// 不能替别的厂家传
$this->post($upload, ['kind' => 'dropship', 'supplier' => '别家', 'month' => '2026-11', 'import' => $file([self::H, ['1', '', '', 1]])])
->assertForbidden();
// 快递:钉钉部门名是承运商名,只看得到上传快递账单,看不到货款对账
$courierUser = $this->portalUser('曹县韵达');
$this->actingAsPortal($courierUser)->get($page)->assertOk()->assertSeeText('快递账单')->assertSeeText('当前快递')
->assertDontSeeText('代发运费账单');
$withFees = new UploadedFile($this->xlsxBook(['账单' => [self::H, ['YD0001', '山东', 1.2, 4.5, '曹县韵达', 1, 3]],
'附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE], ['YD0001', 2, '上楼费'], ['YD0001', 1.5, '超长费']]]), '账单.xlsx', null, null, true);
$this->post($upload, ['kind' => 'courier', 'month' => '2026-11', 'import' => $withFees])
->assertSessionHas('success');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$c = $db->table('courier_bill_files')->sole();
$this->assertSame('parsed', $c->status);
$this->assertEquals(8, (float) $c->amount); // 文件合计 = 运费 4.5 + 附加费 3.5
// 附加费表进小汇总(附加费),不逐单核对
$this->assertSame(2, $db->table('courier_bill_surcharges')->where('file_id', $c->id)->count());
$this->assertEquals(3.5, (float) $db->table('courier_bill_surcharges')->where('file_id', $c->id)->sum('amount'));
$this->assertSame(['上楼费', '超长费'], $db->table('courier_bill_surcharges')->where('file_id', $c->id)->orderBy('id')->pluck('item')->all());
$receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('运费合计 **¥4.50**', $receipt);
$this->assertStringContainsString('附加费:**2** 行,合计 **¥3.50**', $receipt);
$this->get($page)->assertOk()->assertSeeText('附加费 2 行,合计 3.50 元');
$this->assertSame(1, $db->table('courier_bill_statements')->where('bill_month', '2026-11')->count());
// 快递账号传代发运费账单:不是代发厂家
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['YD0002', '', '', 4]])])
->assertSessionHasErrors('freight_bill');
$this->assertFalse($imports->processNext());
}
public function test_queued_bill_is_rejected_if_binding_is_revoked_before_processing(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$db = CourierBillMatcher::db();
$id = $db->table('dropship_factories')->insertGetId(['name' => '测试厂家', 'warehouse' => '测试仓', 'keywords' => '测试', 'created_at' => now(), 'updated_at' => now()]);
$user = $this->portalUser('测试厂家');
$imports = app(PortalFreightBillImports::class);
$imports->submit(new UploadedFile($this->xlsx([self::H, ['SF12345678', '', 1, 8]]), '账单.xlsx', null, null, true), [
'name' => '测试厂家', 'kind' => 'dropship', 'month' => '2026-11', 'target_id' => $id,
'user_id' => (int) $user->id, 'company_id' => (int) $this->company->id, 'uploader' => '测试',
]);
$user->update(['enabled' => false]);
$this->assertTrue($imports->processNext());
$this->assertSame(0, $db->table('dropship_bill_files')->count());
$this->assertSame('failed', $imports->recent((int) $this->company->id, '测试厂家')[0]['status']);
$this->assertSame([], $imports->recent((int) $this->company->id, '别家'));
$this->assertSame([], $imports->recent((int) $this->company->id + 1, '测试厂家'));
}
public function test_multiple_worksheets_are_not_partially_accepted(): void
{
$path = $this->xlsx([self::H, ['SF12345678', '', 1, 8]]);
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$book->createSheet()->fromArray([self::H, ['SF87654321', '', 1, 99]]);
(new Xlsx($book))->save($path);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('只保留模板的「账单」和可选的「附加费」工作表');
app(FreightBillTemplate::class)->validate($path, 'xlsx');
}
public function test_portal_filename_cannot_add_another_courier_group(): void
{
Storage::fake('local');
$db = CourierBillMatcher::db();
$a = $db->table('courier_bill_groups')->insertGetId(['name' => '本家快递', 'express_names' => '["本家快递"]', 'bundle' => '同一合并账单', 'waybill_header' => '旧单号列', 'amount_header' => '旧金额列', 'weight_header' => '旧重量列', 'created_at' => now(), 'updated_at' => now()]);
$b = $db->table('courier_bill_groups')->insertGetId(['name' => '另一家快递', 'express_names' => '["另一家快递"]', 'bundle' => '同一合并账单', 'created_at' => now(), 'updated_at' => now()]);
$db->table('jst_oms_shipping')->insert(['source_id' => 888001, 'sku_source_id' => 1, 'express_no' => 'SF12345678', 'express_name1' => '另一家快递', 'ship_time' => '2026-11-10']);
$file = new UploadedFile($this->xlsx([self::H, ['SF12345678', '江苏', 1, 8]]), '本家快递与另一家快递.xlsx', null, null, true);
$id = app(\App\Support\CourierBills\CourierBillStore::class)->uploadFor($file, '2026-11', $a, '测试');
$this->assertSame('parsed', $db->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $db->table('courier_bill_statements')->where('group_id', $b)->count());
$this->assertNull($db->table('courier_bill_files')->find($id)->extra_group_ids);
}
public function test_finance_can_choose_a_courier_without_supplier_statements(): void
{
$db = CourierBillMatcher::db();
$db->table('courier_bill_groups')->insert(['name' => '测试财务快递', 'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->get(route('business.pages.show', ['section' => 'supplier-reconciliation', 'page' => 'supplier-data', 'supplier' => '测试财务快递']))
->assertOk()->assertSeeText('上传运费账单')->assertSeeText('快递账单');
}
public function test_courier_department_in_dingtalk_resolves_to_a_portal_binding(): void
{
CourierBillMatcher::db()->table('courier_bill_groups')->insert(['name' => '曹县韵达小件', 'summary_carrier' => '曹县韵达',
'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]);
$query = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery::class);
$query->shouldReceive('select')->andReturnUsing(static fn (string $sql): array => str_contains($sql, 'hr_employee')
? [['userid' => 'ding-c', 'unionid' => 'union-c', 'active' => 1, 'dept_id_list' => '77']]
: [['Id' => 77, 'parent_id' => 70, 'name' => '曹县韵达', 'depth' => 0], ['Id' => 70, 'parent_id' => 1, 'name' => '快递', 'depth' => 1]]);
$factory = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory::class);
$factory->shouldReceive('forSource')->andReturn($query);
$suppliers = \Mockery::mock(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class);
$suppliers->shouldReceive('suppliersByNames')->andReturn([]);
$resolved = (new SupplierPortalAccess($factory, $suppliers))->resolveAll('ding-c', 'union-c');
$this->assertSame([['supplier_name' => '曹县韵达', 'supplier_code' => '', 'dingtalk_group_id' => 77, 'dingtalk_group_name' => '曹县韵达']], $resolved);
}
public function test_finance_pushes_a_no_login_upload_link_to_the_courier_dingtalk_group(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$db = CourierBillMatcher::db();
$groupId = $db->table('courier_bill_groups')->insertGetId(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE),
'bundle' => '合并测试',
'created_at' => now(), 'updated_at' => now()]);
$otherGroupId = $db->table('courier_bill_groups')->insertGetId(['name' => '其他快递', 'express_names' => json_encode(['其他快递'], JSON_UNESCAPED_UNICODE),
'bundle' => '合并测试', 'keywords' => '其他快递', 'created_at' => now(), 'updated_at' => now()]);
$section = 'courier-payables-final';
$action = fn (string $name, array $p = []) => route('business.' . $section . '.courier-bills.' . $name, $p);
$groups = route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'groups', 'month' => '2026-11']);
$this->get($groups)->assertOk()->assertSeeText('钉钉对账群')->assertSeeText('未配');
$this->post($action('push-upload-links'), ['month' => '2026-11', 'group' => $groupId])->assertSessionHasErrors('courier_bills');
$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 上传链接');
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'] ?? '');
$this->assertStringContainsString('运费账单上传 · 曹县韵达', $text);
preg_match('/\[打开账单上传页\]\(([^)]+)\)/', $text, $m);
$link = $m[1];
auth()->logout();
$this->get($link . '&month=2026-10')->assertOk()->assertSeeText('2026年11月');
$this->get(preg_replace('/signature=[^&]+/', 'signature=' . str_repeat('0', 64), $link))->assertForbidden();
$this->get(app(\App\Support\CourierBills\CourierUploadLink::class)->signedRoute('signed.courier-bill-upload.show',
basename(parse_url($link, PHP_URL_PATH)), (int) $this->company->id, now()->subMinute()))->assertForbidden();
$page = $this->get($link)->assertOk()->assertHeader('X-Robots-Tag', 'noindex, nofollow, noarchive')
->assertSeeText('曹县韵达 · 2026年11月 运费账单上传')->assertSeeText('还没有上传');
$html = (string) $page->getContent();
preg_match('/action="([^"]*courier-bill-upload[^"]*\/upload[^"]*)"/', $html, $u);
$upload = html_entity_decode($u[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
preg_match('/href="([^"]*courier-bill-upload[^"]*\/template[^"]*)"/', $html, $tp);
$this->get(html_entity_decode($tp[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'))->assertOk();
$file = fn (array $rows) => new UploadedFile($this->xlsx($rows), '其他快递11月.xlsx', null, null, true);
$imports = app(PortalFreightBillImports::class);
$this->post($upload, ['import' => $file([['运单号', '运费'], ['YD1', 3]])])->assertSessionHas('success');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$this->get($link)->assertOk()->assertSeeText('第一行必须依次是');
$this->post($upload, ['group' => $otherGroupId, 'month' => '2026-10',
'import' => $file([self::H, ['YD0001', '山东', 1.2, 4.5], ['YD0002', '河北', 2, 5.5]])])
->assertRedirect()->assertSessionHas('success');
$this->get($link)->assertOk()->assertSeeText('等待处理');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$f = $db->table('courier_bill_files')->sole();
$this->assertSame('parsed', $f->status);
$this->assertSame($groupId, (int) $f->group_id);
$this->assertSame('2026-11', $f->bill_month);
$this->assertEquals(10, (float) $f->amount);
$this->assertStringContainsString('(快递上传链接)', (string) $f->uploaded_by);
$this->assertStringContainsString('快递账单上传回执 · 曹县韵达', (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''));
$this->get($link)->assertOk()->assertSeeText('其他快递11月.xlsx')->assertSeeText('已读入');
// 排队期间财务确认结算,也不能在后台继续写入。
$this->post($upload, ['import' => $file([self::H, ['YD0003', '', '', 1]])])->assertSessionHas('success');
$db->table('courier_bill_statements')->where('group_id', $groupId)->update(['status' => 'confirmed']);
$this->assertTrue($imports->processNext());
$this->assertSame(1, $db->table('courier_bill_files')->count());
$this->get($link)->assertOk()->assertSeeText('财务已确认结算');
$this->post($upload, ['import' => $file([self::H, ['YD0003', '', '', 1]])])->assertSessionHasErrors('upload');
}
private function portalUser(string $name): User
{
$user = User::create(['name' => $name . '对账员', 'email' => Str::lower(Str::random(12)) . '@portal.test', 'password' => Str::random(32),
'locale' => 'zh-CN', 'enabled' => true, 'created_from' => SupplierPortalAccess::CREATED_FROM,
'landing_page' => 'business.supplier-portal.home', 'created_by' => 0]);
$user->roles()->attach(Role::where('name', 'user')->firstOrFail()->id);
$user->permissions()->attach(Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
$user->companies()->attach($this->company->id);
DingTalkIdentity::create(['user_id' => $user->id, 'union_id' => 'union-' . $user->id, 'dingtalk_user_id' => 'ding-' . $user->id]);
SupplierPortalIdentity::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null,
'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]);
SupplierPortalSupplier::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null,
'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]);
return $user;
}
private function actingAsPortal(User $user): self
{
$identity = DingTalkIdentity::query()->where('user_id', $user->id)->firstOrFail();
return $this->withExceptionHandling()->loginAs($user)->withSession(['dingtalk_identity_id' => $identity->id, 'dingtalk_roster_checked_at' => now()->timestamp]);
}
/** @param list<list<mixed>> $rows */
private function xlsx(array $rows): string
{
return $this->xlsxBook(['Sheet1' => $rows]);
}
/** @param array<string,list<list<mixed>>> $sheets */
private function xlsxBook(array $sheets): string
{
$book = new Spreadsheet();
$book->removeSheetByIndex(0);
foreach ($sheets as $name => $rows) {
$sheet = $book->createSheet();
$sheet->setTitle($name);
$this->fill($sheet, $rows);
}
$path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx';
(new Xlsx($book))->save($path);
return $path;
}
/** @param list<list<mixed>> $rows */
private function fill(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, array $rows): void
{
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
if ($value !== null && $value !== '') {
$sheet->setCellValueExplicit([$c + 1, $r + 1], $value, is_string($value)
? \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING : \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC);
}
}
}
}
}