购物车悬浮

This commit is contained in:
liu
2026-08-27 18:13:43 +08:00
parent 52dc6efadf
commit f3e190f460
9 changed files with 330 additions and 6 deletions
File diff suppressed because one or more lines are too long
@@ -7,6 +7,7 @@ use App\Http\Requests\Mini\MiniCartRequest;
use App\Models\CartModel; use App\Models\CartModel;
use App\Models\CustomerLevelModel; use App\Models\CustomerLevelModel;
use App\Models\ProductModel; use App\Models\ProductModel;
use App\Services\CartService;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -207,6 +208,15 @@ class CartController extends BaseMiniController
return $this->success([], '已删除'); return $this->success([], '已删除');
} }
/**
* 购物车悬浮球汇总(轻量接口):种数/总数量/总金额,供任意页面刷新右下角悬浮球
*/
#[GetRoute('/cart/summary', authorize: true)]
public function summary(Request $request): JsonResponse
{
return $this->success(app(CartService::class)->summary($this->currentStore($request)));
}
/** /**
* 清空购物车(仅当前用户) * 清空购物车(仅当前用户)
*/ */
+5 -1
View File
@@ -5,19 +5,22 @@ namespace App\Http\Controllers\Mini;
use App\Models\HomeBannerModel; use App\Models\HomeBannerModel;
use App\Models\HomeNavModel; use App\Models\HomeNavModel;
use App\Models\HomePromoModel; use App\Models\HomePromoModel;
use App\Services\CartService;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\AnnoRoute\Attribute\GetRoute; use Modules\AnnoRoute\Attribute\GetRoute;
use Modules\AnnoRoute\Attribute\RequestAttribute; use Modules\AnnoRoute\Attribute\RequestAttribute;
/** /**
* 小程序首页配置(轮播图 + 宫格导航 + 促销推荐卡片,仅返回启用项) * 小程序首页配置(轮播图 + 宫格导航 + 促销推荐卡片,仅返回启用项)
* 登录门店附加 cart 购物车悬浮球汇总(未登录返回零值结构)
*/ */
#[RequestAttribute('/mini', 'mini', authGuard: 'users')] #[RequestAttribute('/mini', 'mini', authGuard: 'users')]
class HomeController extends BaseMiniController class HomeController extends BaseMiniController
{ {
/** 首页配置聚合:banners / navs / promos,按 sort 升序 */ /** 首页配置聚合:banners / navs / promos,按 sort 升序 */
#[GetRoute('/home', authorize: false)] #[GetRoute('/home', authorize: false)]
public function index(): JsonResponse public function index(Request $request): JsonResponse
{ {
$banners = HomeBannerModel::query() $banners = HomeBannerModel::query()
->where('status', HomeBannerModel::STATUS_NORMAL) ->where('status', HomeBannerModel::STATUS_NORMAL)
@@ -41,6 +44,7 @@ class HomeController extends BaseMiniController
'banners' => $banners, 'banners' => $banners,
'navs' => $navs, 'navs' => $navs,
'promos' => $promos, 'promos' => $promos,
'cart' => app(CartService::class)->summary($this->optionalStore($request)),
]); ]);
} }
} }
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Mini;
use App\Exceptions\RepositoryException; use App\Exceptions\RepositoryException;
use App\Http\Requests\Mini\MiniOrderRequest; use App\Http\Requests\Mini\MiniOrderRequest;
use App\Models\BillModel;
use App\Models\CartModel; use App\Models\CartModel;
use App\Models\CustomerLevelModel; use App\Models\CustomerLevelModel;
use App\Models\ProductModel; use App\Models\ProductModel;
@@ -37,6 +38,26 @@ class OrderController extends BaseMiniController
throw new RepositoryException('门店未设置客户等级,无法下单,请联系客服'); throw new RepositoryException('门店未设置客户等级,无法下单,请联系客服');
} }
// 回款周期校验:存在逾期未回款账单(未支付即拦截,含审核中)时禁止下单
// 周期 0 天=立即结清:任何未回款账单(含当天)都拦截;周期 N≥1:账单日 + N 天 < 今天(超过回款周期)才拦截
$cycleDays = (int) $store->payment_cycle_days;
$overdueQuery = BillModel::query()
->where('store_id', $store->id)
->where('status', BillModel::STATUS_UNPAID);
if ($cycleDays > 0) {
$overdueQuery->whereDate('bill_date', '<', now()->subDays($cycleDays)->toDateString());
}
$overdue = $overdueQuery
->selectRaw('COUNT(*) as aggregate_count, COALESCE(SUM(total_amount), 0) as aggregate_amount')
->first();
if ((int) $overdue->aggregate_count > 0) {
$amountText = bcadd((string) $overdue->aggregate_amount, '0', 2);
throw new RepositoryException($cycleDays > 0
? '您有 ' . (int) $overdue->aggregate_count . ' 笔账单已超过回款周期未回款(合计 ¥' . $amountText . '),请先结清后再下单'
: '您有 ' . (int) $overdue->aggregate_count . ' 笔账单未回款(合计 ¥' . $amountText . '),回款周期为当日结清,请先结清后再下单'
);
}
$items = $request->validated('items'); $items = $request->validated('items');
$remark = (string) ($request->validated('remark') ?? ''); $remark = (string) ($request->validated('remark') ?? '');
@@ -6,6 +6,7 @@ use App\Exceptions\RepositoryException;
use App\Models\CustomerLevelModel; use App\Models\CustomerLevelModel;
use App\Models\ProductCategoryModel; use App\Models\ProductCategoryModel;
use App\Models\ProductModel; use App\Models\ProductModel;
use App\Services\CartService;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Modules\AnnoRoute\Attribute\GetRoute; use Modules\AnnoRoute\Attribute\GetRoute;
@@ -25,7 +26,8 @@ class ProductController extends BaseMiniController
} }
/** /**
* 商品列表 * 商品列表(登录门店附 cart_id/cart_quantity 供列表直接加减购物车;
* data.cart 为购物车悬浮球汇总,未登录返回零值结构)
*/ */
#[GetRoute('/product/list', authorize: false)] #[GetRoute('/product/list', authorize: false)]
public function products(Request $request): JsonResponse public function products(Request $request): JsonResponse
@@ -50,22 +52,30 @@ class ProductController extends BaseMiniController
->orderBy('id') ->orderBy('id')
->paginate($pageSize); ->paginate($pageSize);
// 当前门店的等级(售价 = 成本价 × (100 + 等级上浮比例) / 100 // 当前门店的等级(售价 = 成本价 × (100 + 等级上浮比例) / 100与购物车行
$store = $this->optionalStore($request); $store = $this->optionalStore($request);
$level = ($store !== null && $store->level_id > 0) ? $store->level : null; $level = ($store !== null && $store->level_id > 0) ? $store->level : null;
$cartService = app(CartService::class);
$cartRows = $store !== null ? $cartService->cartRowMap($store->id) : [];
$paginator->getCollection()->transform( $paginator->getCollection()->transform(
static function (ProductModel $product) use ($level): array { static function (ProductModel $product) use ($level, $cartRows): array {
$row = $product->toArray(); $row = $product->toArray();
// 实际价(按等级上浮比例换算;成本价不随序列化输出) // 实际价(按等级上浮比例换算;成本价不随序列化输出)
$row['price'] = $level !== null $row['price'] = $level !== null
? CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent) ? CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent)
: null; : null;
// 购物车数量(列表直接加减用;不在购物车为 0/'0.00'
$row['cart_id'] = $cartRows[$product->id]['id'] ?? 0;
$row['cart_quantity'] = $cartRows[$product->id]['quantity'] ?? '0.00';
return $row; return $row;
} }
); );
return $this->success($paginator->toArray()); $data = $paginator->toArray();
$data['cart'] = $cartService->summary($store);
return $this->success($data);
} }
/** /**
@@ -89,8 +99,12 @@ class ProductController extends BaseMiniController
$price = CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent); $price = CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent);
} }
$cartRows = $store !== null ? app(CartService::class)->cartRowMap($store->id) : [];
$data = $product->toArray(); $data = $product->toArray();
$data['price'] = $price; $data['price'] = $price;
$data['cart_id'] = $cartRows[$product->id]['id'] ?? 0;
$data['cart_quantity'] = $cartRows[$product->id]['quantity'] ?? '0.00';
return $this->success($data); return $this->success($data);
} }
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Services;
use App\Models\CartModel;
use App\Models\CustomerLevelModel;
use App\Models\ProductModel;
use App\Models\StoreModel;
/**
* 购物车共享服务:商品列表/详情附加购物车数量、悬浮球汇总(种数/总数量/总金额)
*
* 汇总口径(与 Mini/CartController::index 一致,勿偏离):
* - total_count = 购物车全部行数(含已下架等不可购项)
* - total_quantity / total_amount = 仅统计可购项(商品在上架且门店已设等级),
* 金额 = Σ 数量 × 等级上浮价(CustomerLevelModel::calcLevelPrice
*/
class CartService
{
/**
* 门店购物车行映射:product_id => ['id' => 购物车行ID, 'quantity' => 数量字符串]
* (商品列表/详情附加 cart_id/cart_quantity 用;行ID供直接加减/删除操作)
*
* @return array<int, array{id: int, quantity: string}>
*/
public function cartRowMap(int $storeId): array
{
return CartModel::query()
->where('store_id', $storeId)
->get(['id', 'product_id', 'quantity'])
->keyBy('product_id')
->map(static fn (CartModel $row): array => [
'id' => (int) $row->id,
'quantity' => (string) $row->quantity,
])
->all();
}
/**
* 购物车悬浮球汇总:种数/总数量/总金额(未登录或空购物车返回零值结构)
*
* @return array{total_count: int, total_quantity: string, total_amount: string}
*/
public function summary(?StoreModel $store): array
{
$empty = ['total_count' => 0, 'total_quantity' => '0.00', 'total_amount' => '0.00'];
if ($store === null) {
return $empty;
}
$rows = CartModel::query()
->where('store_id', $store->id)
->get(['id', 'product_id', 'quantity']);
if ($rows->isEmpty()) {
return $empty;
}
$products = ProductModel::query()
->where('status', ProductModel::STATUS_ON)
->whereIn('id', $rows->pluck('product_id')->all())
->get(['id', 'cost_price'])
->keyBy('id');
$level = $store->level_id > 0 ? $store->level : null;
$totalQuantity = '0.00';
$totalAmount = '0.00';
foreach ($rows as $row) {
$product = $products->get($row->product_id);
if ($product === null || $level === null) {
continue;
}
$price = CustomerLevelModel::calcLevelPrice($product->cost_price, $level->percent);
$totalQuantity = bcadd($totalQuantity, (string) $row->quantity, 2);
$totalAmount = bcadd($totalAmount, bcmul($price, (string) $row->quantity, 2), 2);
}
return [
'total_count' => $rows->count(),
'total_quantity' => $totalQuantity,
'total_amount' => $totalAmount,
];
}
}
+37
View File
@@ -265,6 +265,43 @@ class CartTest extends ProcurementTestCase
$this->getJson('/mini/cart')->assertStatus(401); $this->getJson('/mini/cart')->assertStatus(401);
} }
/** 悬浮球汇总:种数/总数量/总金额(下架商品不计入数量与金额但仍计种数) */
public function test_cart_summary_endpoint(): void
{
$level = CustomerLevelModel::factory()->create();
$store = StoreModel::factory()->create(['level_id' => $level->id]);
$p1 = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '5.00']);
$p2 = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '3.00']);
$this->actingAsMiniStore($store);
// 空购物车返回零值结构
$this->getJson('/mini/cart/summary')->assertOk()
->assertJsonPath('data.total_count', 0)
->assertJsonPath('data.total_quantity', '0.00')
->assertJsonPath('data.total_amount', '0.00');
$this->postJson('/mini/cart', ['product_id' => $p1->id, 'quantity' => 2]);
$this->postJson('/mini/cart', ['product_id' => $p2->id, 'quantity' => 1]);
$this->getJson('/mini/cart/summary')->assertOk()
->assertJsonPath('data.total_count', 2)
->assertJsonPath('data.total_quantity', '3.00')
->assertJsonPath('data.total_amount', '13.00');
// 下架商品:数量/金额不计入(与购物车列表口径一致),种数仍计
$p2->update(['status' => ProductModel::STATUS_OFF]);
$this->getJson('/mini/cart/summary')->assertOk()
->assertJsonPath('data.total_count', 2)
->assertJsonPath('data.total_quantity', '2.00')
->assertJsonPath('data.total_amount', '10.00');
}
/** 未登录访问悬浮球汇总 → 401 */
public function test_cart_summary_requires_login(): void
{
$this->getJson('/mini/cart/summary')->assertStatus(401);
}
/** 下单成功后自动清空购物车中已下单的商品(未下单商品保留) */ /** 下单成功后自动清空购物车中已下单的商品(未下单商品保留) */
public function test_place_order_clears_ordered_items_from_cart(): void public function test_place_order_clears_ordered_items_from_cart(): void
{ {
+82
View File
@@ -2,6 +2,7 @@
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\CartModel;
use App\Models\CustomerLevelModel; use App\Models\CustomerLevelModel;
use App\Models\ProductModel; use App\Models\ProductModel;
use App\Models\StoreModel; use App\Models\StoreModel;
@@ -103,4 +104,85 @@ class MiniProductTest extends ProcurementTestCase
$this->assertNotNull($row); $this->assertNotNull($row);
$this->assertNull($row['price']); $this->assertNull($row['price']);
} }
/** 商品列表:登录门店附加购物车行ID与数量,响应附悬浮球汇总 */
public function test_product_list_appends_cart_quantity_and_summary(): void
{
[$store, $product] = $this->makeStoreWithProduct('5.00');
$extra = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '3.00']);
$this->actingAsMiniStore($store);
$this->postJson('/mini/cart', ['product_id' => $product->id, 'quantity' => 2]);
$this->postJson('/mini/cart', ['product_id' => $extra->id, 'quantity' => 1]);
$cartId = CartModel::where('product_id', $product->id)->first()->id;
$data = $this->getJson('/mini/product/list')->assertOk()->json('data');
$row = collect($data['data'])->firstWhere('id', $product->id);
$this->assertSame($cartId, $row['cart_id'], '在购物车的商品应附购物车行ID');
$this->assertSame('2.00', $row['cart_quantity']);
// 不在购物车的商品:cart_id=0、cart_quantity='0.00'
$other = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '1.00']);
$otherRow = collect($this->getJson('/mini/product/list')->json('data.data'))->firstWhere('id', $other->id);
$this->assertSame(0, $otherRow['cart_id']);
$this->assertSame('0.00', $otherRow['cart_quantity']);
// 悬浮球汇总:2 种商品、总数量 3、总金额 5×2+3×1=13
$this->assertSame(2, $data['cart']['total_count']);
$this->assertSame('3.00', $data['cart']['total_quantity']);
$this->assertSame('13.00', $data['cart']['total_amount']);
}
/** 商品列表/详情:未登录时购物车字段为零值结构 */
public function test_product_list_guest_sees_zero_cart_fields(): void
{
[, $product] = $this->makeStoreWithProduct();
$data = $this->getJson('/mini/product/list')->assertOk()->json('data');
$row = collect($data['data'])->firstWhere('id', $product->id);
$this->assertSame(0, $row['cart_id']);
$this->assertSame('0.00', $row['cart_quantity']);
$this->assertSame(
['total_count' => 0, 'total_quantity' => '0.00', 'total_amount' => '0.00'],
$data['cart']
);
$detail = $this->getJson("/mini/product/{$product->id}")->assertOk()->json('data');
$this->assertSame(0, $detail['cart_id']);
$this->assertSame('0.00', $detail['cart_quantity']);
}
/** 商品详情:登录门店附加购物车行ID与数量 */
public function test_product_detail_appends_cart_quantity(): void
{
[$store, $product] = $this->makeStoreWithProduct();
$this->actingAsMiniStore($store);
$this->postJson('/mini/cart', ['product_id' => $product->id, 'quantity' => 4]);
$cartId = CartModel::first()->id;
$data = $this->getJson("/mini/product/{$product->id}")->assertOk()->json('data');
$this->assertSame($cartId, $data['cart_id']);
$this->assertSame('4.00', $data['cart_quantity']);
}
/** 首页:登录门店附购物车悬浮球汇总,未登录为零值结构 */
public function test_home_appends_cart_summary(): void
{
[$store, $product] = $this->makeStoreWithProduct('5.00');
// 未登录:零值结构
$guest = $this->getJson('/mini/home')->assertOk()->json('data');
$this->assertSame(
['total_count' => 0, 'total_quantity' => '0.00', 'total_amount' => '0.00'],
$guest['cart']
);
// 登录:汇总跟随购物车
$this->actingAsMiniStore($store);
$this->postJson('/mini/cart', ['product_id' => $product->id, 'quantity' => 3]);
$data = $this->getJson('/mini/home')->assertOk()->json('data');
$this->assertSame(1, $data['cart']['total_count']);
$this->assertSame('3.00', $data['cart']['total_quantity']);
$this->assertSame('15.00', $data['cart']['total_amount']);
}
} }
+73
View File
@@ -2,8 +2,10 @@
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\BillModel;
use App\Models\CustomerLevelModel; use App\Models\CustomerLevelModel;
use App\Models\ProductModel; use App\Models\ProductModel;
use App\Models\PurchaseOrderModel;
use App\Models\StoreModel; use App\Models\StoreModel;
use App\Models\StoreOrderModel; use App\Models\StoreOrderModel;
use Modules\SystemTool\Models\SysFileModel; use Modules\SystemTool\Models\SysFileModel;
@@ -112,6 +114,77 @@ class StoreOrderTest extends ProcurementTestCase
$this->assertSame(StoreOrderModel::STATUS_SUMMARIZED, $order->refresh()->status); $this->assertSame(StoreOrderModel::STATUS_SUMMARIZED, $order->refresh()->status);
} }
/** 造一笔指定账单日期/状态的门店账单(默认总额 100.00 未支付) */
private function makeStoreBill(StoreModel $store, string $billDate, array $attributes = []): BillModel
{
return BillModel::create(array_merge([
'bill_no' => 'ZD' . random_int(100000000000, 999999999999),
'purchase_id' => PurchaseOrderModel::factory()->create()->id,
'store_id' => $store->id,
'bill_date' => $billDate,
'total_amount' => '100.00',
'status' => BillModel::STATUS_UNPAID,
], $attributes));
}
/** 回款周期校验:存在逾期未回款账单(含审核中)时禁止下单,结清后恢复 */
public function test_place_order_blocked_by_overdue_unpaid_bill(): void
{
$level = CustomerLevelModel::factory()->create();
$store = StoreModel::factory()->paymentCycle(7)->create(['level_id' => $level->id]);
$product = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '5.00']);
// 账单日 10 天前(应结算日=3 天前,已逾期)且未支付 → 拒绝
$this->makeStoreBill($store, now()->subDays(10)->toDateString());
$this->actingAsMiniStore($store);
$response = $this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]]);
$response->assertOk()->assertJsonPath('success', false);
$this->assertStringContainsString('已超过回款周期未回款', (string) $response->json('msg'));
$this->assertStringContainsString('¥100.00', (string) $response->json('msg'));
$this->assertSame(0, StoreOrderModel::count(), '拦截时不应生成订单');
// 审核中(已提交付款凭证)同样拦截
$this->makeStoreBill($store, now()->subDays(10)->toDateString(), ['payment_id' => 999]);
$blocked = $this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]]);
$blocked->assertJsonPath('success', false);
$this->assertStringContainsString('2 笔', (string) $blocked->json('msg'));
// 全部结清后恢复下单
BillModel::where('store_id', $store->id)->update(['status' => BillModel::STATUS_PAID]);
$this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]])
->assertJsonPath('success', true);
}
/** 回款周期校验:周期内账单与到期日当天均不拦截;回款周期 0 天=任何未回款账单(含当天)都拦截 */
public function test_place_order_allowed_within_payment_cycle(): void
{
$level = CustomerLevelModel::factory()->create();
$store = StoreModel::factory()->paymentCycle(7)->create(['level_id' => $level->id]);
$product = ProductModel::factory()->create(['status' => ProductModel::STATUS_ON, 'cost_price' => '5.00']);
$this->actingAsMiniStore($store);
// 账单日 7 天前 → 应结算日=今天,尚未超过周期,允许下单
$this->makeStoreBill($store, now()->subDays(7)->toDateString());
$this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]])
->assertJsonPath('success', true);
// 回款周期 0 天:昨天的未回款账单拦截;当天的未回款账单同样拦截(立即结清口径)
$store->update(['payment_cycle_days' => 0]);
$this->makeStoreBill($store, now()->subDays(1)->toDateString());
$this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]])
->assertJsonPath('success', false);
BillModel::where('store_id', $store->id)->delete();
$this->makeStoreBill($store, now()->toDateString());
$response = $this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]]);
$response->assertJsonPath('success', false);
$this->assertStringContainsString('当日结清', (string) $response->json('msg'));
// 0 天周期下无未回款账单 → 正常下单
BillModel::where('store_id', $store->id)->update(['status' => BillModel::STATUS_PAID]);
$this->postJson('/mini/order', ['items' => [['product_id' => $product->id, 'quantity' => 1]]])
->assertJsonPath('success', true);
}
/** 门店数据隔离:只能查看本店订单 */ /** 门店数据隔离:只能查看本店订单 */
public function test_order_data_isolated_between_stores(): void public function test_order_data_isolated_between_stores(): void
{ {