小程序导出账单接口

This commit is contained in:
liu
2026-08-14 20:28:07 +08:00
parent 9a0999742f
commit 398bb98356
9 changed files with 693 additions and 4 deletions
+226
View File
@@ -0,0 +1,226 @@
<?php
namespace App\Exports;
use App\Exceptions\RepositoryException;
use App\Models\BillModel;
use App\Models\ProductCategoryModel;
use App\Models\ProductModel;
use App\Services\BillDetailService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
/**
* 门店账单合并导出:勾选账单跨账单按商品合并明细(可按一级分类过滤),
* 表尾汇总商品金额/配送费/附加金额/总金额
*/
class BillExport implements FromCollection, WithStyles
{
private ?Collection $rows = null;
/** @var array<int, string> 特殊行索引(1 起)=> 类型(title/scope/header/summary/grand */
private array $specialRows = [];
/** @var array<int, int> 标签需左合并 A:G 的合计行索引 */
private array $mergeRows = [];
/** 列头所在行索引 */
private int $headerRow = 1;
/**
* @param Collection<int, BillModel> $bills 勾选账单(已按 bill_date/id 排序,with store
* @param int $categoryId 一级分类ID0=全部)
*/
public function __construct(
private readonly Collection $bills,
private readonly int $categoryId = 0,
) {
}
/**
* 导出行:标题/范围/列头/明细/合计全部手工构建(行位置不固定,不用 WithHeadings
*/
public function collection(): Collection
{
if ($this->rows !== null) {
return $this->rows;
}
$items = app(BillDetailService::class)->mergedItemsOfBills(
$this->bills->pluck('id')->map(static fn ($id): int => (int) $id)->all()
);
$categoryName = '全部';
if ($this->categoryId > 0) {
[$items, $categoryName] = $this->filterByRootCategory($items);
}
$rows = [];
$rowIndex = 0;
// 标题行
$rows[] = ['门店账单合并导出(共 ' . $this->bills->count() . ' 张)'];
$this->specialRows[++$rowIndex] = 'title';
// 范围行:账单号 / 门店 / 分类 / 导出时间
$billNos = $this->bills->pluck('bill_no')->all();
$billNoText = count($billNos) > 8
? implode('、', array_slice($billNos, 0, 8)) . ' 等 ' . count($billNos) . ' 张'
: implode('、', $billNos);
$storeNames = $this->bills
->map(static fn (BillModel $bill): string => $bill->store->name ?? ('门店#' . $bill->store_id))
->unique()
->values()
->all();
$rows[] = ['账单号:' . $billNoText];
$this->specialRows[++$rowIndex] = 'scope';
$rows[] = ['门店:' . implode('、', $storeNames) . ' 分类:' . $categoryName . ' 导出时间:' . now()->format('Y-m-d H:i:s')];
$this->specialRows[++$rowIndex] = 'scope';
// 空行
$rows[] = [''];
$rowIndex++;
// 列头
$rows[] = ['序号', '品名', '包规', '单位', '单价', '数量', '重量(斤)', '金额'];
$this->specialRows[++$rowIndex] = 'header';
$this->headerRow = $rowIndex;
// 明细行(跨账单同商品已合并,单价为加权平均)
$totalQuantity = 0;
$totalWeight = '0';
$totalAmount = '0';
foreach (array_values($items) as $sort => $item) {
$rows[] = [
$sort + 1,
$item['product_name'],
$item['product_spec'],
$item['unit'],
(float) $item['price'],
(int) $item['quantity'],
(float) $item['weight'],
(float) $item['amount'],
];
$rowIndex++;
$totalQuantity += (int) $item['quantity'];
$totalWeight = bcadd($totalWeight, $item['weight'], 3);
$totalAmount = bcadd($totalAmount, $item['amount'], 2);
}
// 商品合计行
$rows[] = ['', '合计', '', '', '', $totalQuantity, (float) $totalWeight, (float) $totalAmount];
$this->specialRows[++$rowIndex] = 'summary';
// 配送费/附加金额/总金额(账单级费用全额汇总,不受分类过滤影响)
$deliveryTotal = '0';
$addedTotal = '0';
$boxNum = 0;
$trayNum = 0;
foreach ($this->bills as $bill) {
$deliveryTotal = bcadd($deliveryTotal, (string) $bill->delivery_fee, 2);
$addedTotal = bcadd($addedTotal, (string) $bill->added_amount, 2);
$boxNum += (int) $bill->box_num;
$trayNum += (int) $bill->tray_num;
}
$grandTotal = bcadd(bcadd($totalAmount, $deliveryTotal, 2), $addedTotal, 2);
$rows[] = ['配送费合计', '', '', '', '', '', '', (float) $deliveryTotal];
$this->specialRows[++$rowIndex] = 'summary';
$this->mergeRows[] = $rowIndex;
$rows[] = ['附加金额合计(周转筐 ' . $boxNum . ' 个 / 周转托盘 ' . $trayNum . ' 个)', '', '', '', '', '', '', (float) $addedTotal];
$this->specialRows[++$rowIndex] = 'summary';
$this->mergeRows[] = $rowIndex;
$rows[] = ['总金额(商品金额+配送费+附加金额)', '', '', '', '', '', '', (float) $grandTotal];
$this->specialRows[++$rowIndex] = 'grand';
$this->mergeRows[] = $rowIndex;
return $this->rows = collect($rows);
}
/**
* 标题/列头/合计行加粗,合计行标签左合并 A:G,冻结列头
*/
public function styles(Worksheet $sheet): array
{
$this->collection();
$sheet->freezePane('A' . ($this->headerRow + 1));
$sheet->getColumnDimension('A')->setWidth(6);
$sheet->getColumnDimension('B')->setWidth(24);
$sheet->getColumnDimension('C')->setWidth(14);
$sheet->getColumnDimension('D')->setWidth(8);
$sheet->getColumnDimension('E')->setWidth(10);
$sheet->getColumnDimension('F')->setWidth(10);
$sheet->getColumnDimension('G')->setWidth(12);
$sheet->getColumnDimension('H')->setWidth(12);
foreach ($this->mergeRows as $row) {
$sheet->mergeCells('A' . $row . ':G' . $row);
}
$styles = [];
foreach ($this->specialRows as $row => $type) {
$style = match ($type) {
'title' => ['font' => ['bold' => true, 'size' => 14]],
'header', 'summary' => ['font' => ['bold' => true]],
'grand' => ['font' => ['bold' => true, 'size' => 12]],
default => [],
};
if ($style !== []) {
$styles[$row] = $style;
}
}
return $styles;
}
/**
* 按一级分类过滤明细:沿 parent_id 上溯取根分类(商品含软删除,保证历史账单可导出),
* 仅保留根分类为所选分类的行
*
* @param array<int, array> $items 合并后的商品明细
* @return array{0: array<int, array>, 1: string} [过滤后明细, 一级分类名]
*/
private function filterByRootCategory(array $items): array
{
$categories = ProductCategoryModel::all()->keyBy('id');
$categoryName = $categories->get($this->categoryId)->name ?? ('分类#' . $this->categoryId);
$productCategoryIds = ProductModel::withTrashed()
->whereIn('id', array_column($items, 'product_id'))
->pluck('category_id', 'id');
// 商品ID => 根分类ID(与采购单导出同口径的上溯解析)
$rootIds = [];
foreach ($productCategoryIds as $productId => $categoryId) {
$rootId = 0;
$cursor = (int) $categoryId;
$guard = 0;
while ($cursor > 0 && $guard++ < 20) {
$category = $categories->get($cursor);
if ($category === null) {
break;
}
$rootId = (int) $category->id;
$cursor = (int) $category->parent_id;
}
$rootIds[(int) $productId] = $rootId;
}
$categoryId = $this->categoryId;
$filtered = array_values(array_filter(
$items,
static fn (array $row): bool => ($rootIds[$row['product_id']] ?? 0) === $categoryId
));
if ($filtered === []) {
throw new RepositoryException('所选账单在「' . $categoryName . '」分类下无商品明细');
}
return [$filtered, $categoryName];
}
}
@@ -3,12 +3,15 @@
namespace App\Http\Controllers\Mini;
use App\Exceptions\RepositoryException;
use App\Exports\BillExport;
use App\Models\BillModel;
use App\Services\BillDetailService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Modules\AnnoRoute\Attribute\GetRoute;
use Modules\AnnoRoute\Attribute\RequestAttribute;
use Symfony\Component\HttpFoundation\Response;
/**
* 小程序门店账单(采购单完成后由后台生成,门店端只读)
@@ -84,6 +87,46 @@ class BillController extends BaseMiniController
return $this->success($data);
}
/**
* 合并导出账单(静态路由放在 /bill/{id} 之前声明)
* 仅可导出本店账单(强制 store_id 过滤,张数不匹配说明混入无效账单整批拒绝);
* ?ids=1,2,3 必选(1~100 张);?category_id= 一级分类过滤(0/缺省=全部)
*/
#[GetRoute('/bill/export', authorize: true)]
public function export(Request $request): Response
{
$data = $request->validate([
'ids' => 'required|string',
'category_id' => 'nullable|integer|min:0',
]);
$user = $this->currentUser($request);
$store = $this->ensureStoreBound($user);
$ids = array_values(array_unique(array_filter(array_map('intval', explode(',', (string) $data['ids'])))));
if ($ids === [] || count($ids) > 100) {
throw new RepositoryException('请选择 1~100 张账单');
}
$bills = BillModel::with('store:id,name')
->where('store_id', $store->id)
->whereIn('id', $ids)
->orderBy('bill_date')
->orderBy('id')
->get();
if ($bills->isEmpty()) {
throw new RepositoryException('账单不存在');
}
if ($bills->count() !== count($ids)) {
throw new RepositoryException('存在无效账单,请刷新后重试');
}
return Excel::download(
new BillExport($bills, (int) ($data['category_id'] ?? 0)),
'门店账单_' . now()->format('Ymd_His') . '.xlsx'
);
}
/** 账单详情(校验归属:仅能查看本店账单;含合并后的商品明细与关联订单) */
#[GetRoute('/bill/{id}', authorize: true, where: ['id' => '[0-9]+'])]
public function detail(int $id, Request $request): JsonResponse
@@ -3,14 +3,17 @@
namespace App\Http\Controllers\Recon;
use App\Exceptions\RepositoryException;
use App\Exports\BillExport;
use App\Models\BillModel;
use App\Services\BillDetailService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Modules\AnnoRoute\Attribute\GetRoute;
use Modules\AnnoRoute\Attribute\PutRoute;
use Modules\AnnoRoute\Attribute\RequestAttribute;
use Modules\Common\Http\Controllers\BaseController;
use Symfony\Component\HttpFoundation\Response;
/**
* 门店账单管理(采购单完成后按门店生成,后台查看 + 线下收款登记)
@@ -55,6 +58,38 @@ class BillController extends BaseController
return $this->success($data);
}
/**
* 合并导出:勾选账单跨账单按商品合并明细(可按一级分类过滤),
* 表尾汇总商品金额/配送费/附加金额/总金额
*/
#[GetRoute(route: '/export', authorize: 'export')]
public function export(Request $request): Response
{
$data = $request->validate([
'ids' => 'required|string',
'category_id' => 'nullable|integer|min:0',
]);
$ids = array_values(array_filter(array_map('intval', explode(',', (string) $data['ids']))));
if ($ids === [] || count($ids) > 100) {
throw new RepositoryException('请选择 1~100 张账单');
}
$bills = BillModel::with('store:id,name')
->whereIn('id', $ids)
->orderBy('bill_date')
->orderBy('id')
->get();
if ($bills->isEmpty()) {
throw new RepositoryException('账单不存在');
}
return Excel::download(
new BillExport($bills, (int) ($data['category_id'] ?? 0)),
'门店账单_' . now()->format('Ymd_His') . '.xlsx'
);
}
/**
* 账单详情:账单信息 + 合并后的商品明细(按商品聚合)+ 关联订单
*/
+30
View File
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Models\BillModel;
use App\Models\ProductModel;
use App\Models\StoreOrderItemModel;
use Illuminate\Support\Collection;
/**
* 账单详情数据组装(后台门店账单页与小程序账单详情共用)
@@ -24,6 +25,35 @@ class BillDetailService
->orderBy('id')
->get();
return $this->aggregateItems($items);
}
/**
* 合并后的商品明细(跨账单口径):按商品聚合多张账单的全部订单明细
* 用于账单合并导出,单价同为加权平均口径
*
* @param array<int, int> $billIds 账单ID列表
* @return array<int, array{product_id: int, product_name: string, product_spec: string, unit: string, price: string, quantity: int, weight: string, amount: string}>
*/
public function mergedItemsOfBills(array $billIds): array
{
$items = StoreOrderItemModel::query()
->whereIn('bill_id', $billIds)
->orderBy('id')
->get();
return $this->aggregateItems($items);
}
/**
* 按商品聚合订单明细:数量累加、重量/金额 bc 累加、单价加权平均,
* 按「分类sort → 商品sort」排序
*
* @param Collection<int, StoreOrderItemModel> $items
* @return array<int, array{product_id: int, product_name: string, product_spec: string, unit: string, price: string, quantity: int, weight: string, amount: string}>
*/
private function aggregateItems(Collection $items): array
{
// 排序键:分类 sort → 商品 sort(与采购单明细矩阵同序)
$products = ProductModel::withTrashed()
->with('category:id,sort')