This commit is contained in:
fengjignqi
2026-11-17 10:49:52 +08:00
parent 30f272f1af
commit 05c114dbbd
69 changed files with 2360 additions and 623 deletions

View File

@@ -20,7 +20,6 @@ import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.utils.show.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
@@ -32,10 +31,7 @@ import butterknife.OnClick;
/** 新版购物车:普通与管理共用商品列表,底部切换结算和批量删除。 */
public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, CartPresenter>
implements CartContract.CartView {
/** 商城详情加购入口;仅首次创建时消费,旋转恢复不重复增加数量。 */
public static final String EXTRA_ADD_GOODS = "cart_add_goods";
private static final String STATE_MANAGING = "cart_managing";
private static final String STATE_GOODS = "cart_goods";
private boolean managing;
private CartGoodsAdapter adapter;
@@ -60,23 +56,15 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
.statusBarDarkFont(true)
.init();
initGoodsList();
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_GOODS)) {
managing = savedInstanceState.getBoolean(STATE_MANAGING);
// 保留旋转、折叠和进程重建前的草稿,空列表也不能重新填充演示商品。
ArrayList<CartGoodsEntity> goods = (ArrayList<CartGoodsEntity>)
savedInstanceState.getSerializable(STATE_GOODS);
mPresenter.restoreCart(goods);
} else {
Serializable extra = savedInstanceState == null
? getIntent().getSerializableExtra(EXTRA_ADD_GOODS) : null;
mPresenter.getCart(extra instanceof CartGoodsEntity ? (CartGoodsEntity) extra : null);
}
managing = savedInstanceState != null && savedInstanceState.getBoolean(STATE_MANAGING);
// 购物车以服务端状态为准,配置变化后重新查询,避免恢复未完成的修改请求。
showLoadingDialog();
mPresenter.getCart();
}
private void initGoodsList() {
adapter = new CartGoodsAdapter();
viewBinding.rvCartGoods.setLayoutManager(new LinearLayoutManager(this));
viewBinding.rvCartGoods.setItemAnimator(null);
viewBinding.rvCartGoods.setAdapter(adapter);
adapter.setOnItemChildClickListener((baseAdapter, view, position) -> {
if (position < 0 || position >= adapter.getData().size()) return;
@@ -105,7 +93,8 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
});
}
@OnClick({R.id.iv_cart_back, R.id.tv_cart_manage, R.id.ll_cart_select_all, R.id.tv_cart_action})
@OnClick({R.id.iv_cart_back, R.id.tv_cart_manage, R.id.ll_cart_select_all,
R.id.tv_cart_action, R.id.tv_cart_empty})
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_cart_back:
@@ -125,12 +114,18 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
handleCartAction();
break;
case R.id.tv_cart_empty:
showLoadingDialog();
mPresenter.getCart();
break;
default:
break;
}
}
private void handleCartAction() {
if (mPresenter.isCartBusy()) return;
List<String> selected = mPresenter.getSelectedIds();
if (selected.isEmpty()) {
ToastUtil.showShort(mContext, getString(R.string.cart_choose_first));
@@ -141,7 +136,7 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
} else {
ArrayList<CartGoodsEntity> goods = new ArrayList<>();
for (CartGoodsEntity item : mPresenter.getSnapshot()) {
if (item.selected) goods.add(item);
if (item.selected && item.isAvailable()) goods.add(item);
}
Bundle bundle = new Bundle();
bundle.putSerializable(CheckoutActivity.EXTRA_GOODS, goods);
@@ -165,22 +160,65 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
@Override
public void onConfirmClick() {
mPresenter.deleteItems(deleteIds);
// 多条删除用数组接口一次提交;单条删除仍走按 id 删除的接口。
if (deleteIds.size() > 1) {
mPresenter.clearCart(deleteIds);
} else {
mPresenter.deleteItems(deleteIds);
}
}
});
}
@Override
public void showCart(List<CartGoodsEntity> goods) {
hideDialogLoading();
adapter.setNewData(new ArrayList<>(goods));
viewBinding.tvCartEmpty.setText(R.string.cart_empty);
viewBinding.tvCartEmpty.setVisibility(goods.isEmpty() ? View.VISIBLE : View.GONE);
renderSummary();
}
@Override
public void removeCartItem(String id) {
int position = findAdapterPosition(id);
if (position < 0) return;
adapter.getData().remove(position);
adapter.notifyItemRemoved(position);
viewBinding.tvCartEmpty.setVisibility(adapter.getData().isEmpty()
? View.VISIBLE : View.GONE);
renderSummary();
}
@Override
public void refreshCartItem(CartGoodsEntity item) {
if (item == null) return;
int position = findAdapterPosition(item.id);
if (position < 0) return;
adapter.getData().set(position, item);
adapter.notifyItemChanged(position);
}
private int findAdapterPosition(String id) {
for (int position = 0; position < adapter.getData().size(); position++) {
if (TextUtils.equals(id, adapter.getData().get(position).id)) return position;
}
return -1;
}
@Override
public void onCartOperationFinished(String errorMessage) {
renderSummary();
if (!TextUtils.isEmpty(errorMessage)) {
ToastUtil.showShort(mContext, errorMessage);
}
}
/** 按选中商品数量计算现金合计,不照抄原稿与示例勾选数量不一致的静态金额。 */
private void renderSummary() {
int selected = mPresenter.getSelectedQuantity();
boolean allSelected = mPresenter.isAllSelected();
boolean busy = mPresenter.isCartBusy();
NumberFormat cash = NumberFormat.getNumberInstance(
getResources().getConfiguration().getLocales().get(0));
cash.setMinimumFractionDigits(2);
@@ -191,27 +229,39 @@ public class CartManageActivity extends BaseActivity<CartManageLayoutBinding, Ca
viewBinding.tvCartManage.setText(managing ? R.string.cart_done : R.string.cart_manage);
viewBinding.ivCartSelectAll.setSelected(allSelected);
viewBinding.llCartSelectAll.setSelected(allSelected);
viewBinding.llCartSelectAll.setEnabled(!busy);
viewBinding.tvCartAction.setText(getString(managing
? R.string.cart_delete_selected : R.string.cart_checkout, selected));
viewBinding.tvCartAction.setBackgroundResource(managing
? R.drawable.cart_delete_bg : R.drawable.cart_checkout_bg);
viewBinding.tvCartAction.setAlpha(selected > 0 ? 1f : 0.5f);
viewBinding.tvCartAction.setEnabled(!busy);
viewBinding.tvCartAction.setAlpha(selected > 0 && !busy ? 1f : 0.5f);
viewBinding.tvCartTotalPrice.setText(getString(R.string.cart_cash_price, amount));
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
outState.putBoolean(STATE_MANAGING, managing);
outState.putSerializable(STATE_GOODS, mPresenter.getSnapshot());
super.onSaveInstanceState(outState);
}
@Override
public void showError(String message) {
hideDialogLoading();
if (adapter != null && adapter.getData().isEmpty()) {
viewBinding.tvCartEmpty.setText(TextUtils.isEmpty(message)
? getString(R.string.cart_load_failed) : message);
viewBinding.tvCartEmpty.setVisibility(View.VISIBLE);
}
if (!TextUtils.isEmpty(message)) ToastUtil.showShort(mContext, message);
}
@Override
public void showCartUpdateError(String message) {
ToastUtil.showShort(mContext, TextUtils.isEmpty(message)
? getString(R.string.cart_update_failed) : message);
}
@Override
public void logOut(BaseBean bean) {
// 登录失效沿用父类统一处理。

View File

@@ -58,6 +58,9 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
private ShippingAddressEntity address;
private PickupPointEntity pickup;
private ArrayList<ShippingAddressEntity> addresses;
private boolean viewReady;
private boolean pendingCouponDialog;
private ArrayList<String> pendingCouponDraft;
private final ActivityResultLauncher<Intent> addressLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
@@ -92,6 +95,7 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
@Override
public void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
viewReady = true;
ImmersionBar.with(this).statusBarColor(R.color.cart_header_background)
.statusBarAlpha(0f).statusBarDarkFont(true).init();
adapter = new CheckoutGoodsAdapter();
@@ -121,6 +125,8 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
address = (ShippingAddressEntity) state.getSerializable(STATE_ADDRESS);
addresses = (ArrayList<ShippingAddressEntity>) state.getSerializable(STATE_ADDRESSES);
pickup = (PickupPointEntity) state.getSerializable(STATE_PICKUP);
pendingCouponDialog = state.getBoolean(STATE_COUPON_OPEN, false);
pendingCouponDraft = state.getStringArrayList(STATE_COUPON_DRAFT);
}
ArrayList<CartGoodsEntity> goods = (ArrayList<CartGoodsEntity>) (state == null
? getIntent().getSerializableExtra(EXTRA_GOODS) : state.getSerializable(EXTRA_GOODS));
@@ -132,9 +138,9 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
// 折叠屏切换导致页面重建时恢复未确认草稿,不提前抵扣金额。
if (paymentSucceeded) {
viewBinding.getRoot().post(this::showPaymentSuccess);
} else if (state != null && state.getBoolean(STATE_COUPON_OPEN)) {
ArrayList<String> draft = state.getStringArrayList(STATE_COUPON_DRAFT);
viewBinding.getRoot().post(() -> openCouponDialog(draft));
} else {
// 先查询当前账号的真实优惠券,页面重建时待返回后再恢复弹窗草稿。
mPresenter.loadCoupons();
}
}
@@ -230,11 +236,37 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
private void openCouponDialog(List<String> selectedIds) {
if (isFinishing() || isDestroyed()
|| (couponDialog != null && couponDialog.isShowing())) return;
if (!mPresenter.areCouponsLoaded()) {
pendingCouponDialog = true;
pendingCouponDraft = selectedIds == null ? new ArrayList<>() : new ArrayList<>(selectedIds);
mPresenter.loadCoupons();
return;
}
pendingCouponDialog = false;
pendingCouponDraft = null;
couponDialog = new CheckoutCouponDialog(this, mPresenter.getCoupons(), selectedIds,
mPresenter.getSubtotalCents(),
ids -> mPresenter.setSelectedCoupons(ids));
couponDialog.show();
}
@Override
public void onCouponsLoaded() {
if (!viewReady || paymentSucceeded) return;
if (pendingCouponDialog) {
openCouponDialog(pendingCouponDraft == null
? mPresenter.getSelectedCouponIds() : pendingCouponDraft);
}
}
@Override
public void showCouponsLoadError(String message) {
if (!viewReady) return;
pendingCouponDialog = false;
pendingCouponDraft = null;
showError(message);
}
private void submitOrder() {
if (paymentSucceeded) return;
if (mPresenter.isEmpty()) {
@@ -255,11 +287,23 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
@Override
public void showOrder(List<CartGoodsEntity> goods) {
if (!viewReady) return;
adapter.setNewData(new ArrayList<>(goods));
viewBinding.tvCheckoutGoodsEmpty.setVisibility(goods.isEmpty() ? View.VISIBLE : View.GONE);
String coupon = getString(R.string.checkout_discount, money(mPresenter.getCouponCents()));
String points = getString(R.string.checkout_discount, money(mPresenter.getPointsCents()));
viewBinding.tvCheckoutCouponValue.setText(coupon);
if (mPresenter.isCouponsLoading()) {
viewBinding.tvCheckoutCouponValue.setText(R.string.checkout_coupons_loading);
} else if (!mPresenter.areCouponsLoaded()) {
viewBinding.tvCheckoutCouponValue.setText(R.string.checkout_coupons_retry);
} else if (mPresenter.getSelectedCouponIds().isEmpty()) {
int count = mPresenter.getAvailableCouponCount();
viewBinding.tvCheckoutCouponValue.setText(count == 0
? getString(R.string.checkout_coupons_empty)
: getString(R.string.checkout_coupons_available, count));
} else {
viewBinding.tvCheckoutCouponValue.setText(coupon);
}
viewBinding.tvCheckoutCouponTotal.setText(coupon);
viewBinding.tvCheckoutPointsValue.setText(points);
viewBinding.tvCheckoutPointsTotal.setText(points);
@@ -305,8 +349,11 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
outState.putBoolean(STATE_CASH, cashPayment);
outState.putStringArrayList(STATE_COUPON, mPresenter.getSelectedCouponIds());
boolean couponOpen = couponDialog != null && couponDialog.isShowing();
outState.putBoolean(STATE_COUPON_OPEN, couponOpen);
if (couponOpen) outState.putStringArrayList(STATE_COUPON_DRAFT, couponDialog.getDraftIds());
outState.putBoolean(STATE_COUPON_OPEN, couponOpen || pendingCouponDialog);
if (couponOpen || pendingCouponDialog) {
outState.putStringArrayList(STATE_COUPON_DRAFT,
couponOpen ? couponDialog.getDraftIds() : pendingCouponDraft);
}
outState.putBoolean(STATE_POINTS, mPresenter.isPointsEnabled());
outState.putBoolean(STATE_PAYMENT_SUCCESS, paymentSucceeded);
outState.putSerializable(STATE_ADDRESS, address);
@@ -327,6 +374,7 @@ public class CheckoutActivity extends BaseActivity<CheckoutLayoutBinding, Checko
@Override
protected void onDestroy() {
viewReady = false;
if (successDialog != null) successDialog.dismiss();
if (couponDialog != null) couponDialog.dismiss();
if (dialog != null) dialog.dismiss();

View File

@@ -25,7 +25,12 @@ public class CartGoodsAdapter extends BaseQuickAdapter<CartGoodsEntity, BaseView
mContext.getResources().getConfiguration().getLocales().get(0));
cash.setMinimumFractionDigits(2);
cash.setMaximumFractionDigits(2);
helper.setText(R.id.tv_cart_item_name, mContext.getString(item.nameRes))
helper.setText(R.id.tv_cart_item_name, item.getName(mContext))
.setText(R.id.tv_cart_item_spec, item.isInvalid()
? (android.text.TextUtils.isEmpty(item.getInvalidReason())
? mContext.getString(R.string.cart_goods_invalid) : item.getInvalidReason())
: (android.text.TextUtils.isEmpty(item.getSpecModel())
? mContext.getString(R.string.cart_goods_spec_unknown) : item.getSpecModel()))
.setText(R.id.tv_cart_item_price, mContext.getString(R.string.cart_cash_price,
cash.format(BigDecimal.valueOf(item.cashCents, 2))))
.setText(R.id.tv_cart_item_quantity, String.valueOf(item.quantity))
@@ -33,16 +38,26 @@ public class CartGoodsAdapter extends BaseQuickAdapter<CartGoodsEntity, BaseView
.addOnClickListener(R.id.iv_cart_item_delete)
.addOnClickListener(R.id.tv_cart_item_minus)
.addOnClickListener(R.id.tv_cart_item_plus);
helper.getView(R.id.iv_cart_item_select).setSelected(item.selected);
helper.getView(R.id.tv_cart_item_minus).setEnabled(item.quantity > 1);
helper.getView(R.id.tv_cart_item_minus).setAlpha(item.quantity > 1 ? 1f : 0.35f);
boolean available = item.isAvailable();
boolean actionable = available && !item.updating;
helper.itemView.setAlpha(available ? (item.updating ? 0.7f : 1f) : 0.5f);
helper.getView(R.id.iv_cart_item_select).setEnabled(actionable);
helper.getView(R.id.iv_cart_item_select).setSelected(available && item.selected);
helper.getView(R.id.iv_cart_item_delete).setEnabled(!item.updating);
helper.getView(R.id.tv_cart_item_minus).setEnabled(actionable && item.quantity > 1);
helper.getView(R.id.tv_cart_item_minus).setAlpha(
actionable && item.quantity > 1 ? 1f : 0.35f);
helper.getView(R.id.tv_cart_item_plus).setEnabled(
item.quantity < CartGoodsEntity.MAX_QUANTITY);
actionable && item.quantity < item.getMaxQuantity());
helper.getView(R.id.tv_cart_item_plus).setAlpha(
item.quantity < CartGoodsEntity.MAX_QUANTITY ? 1f : 0.35f);
actionable && item.quantity < item.getMaxQuantity() ? 1f : 0.35f);
ImageView cover = helper.getView(R.id.iv_cart_item_cover);
int radius = Math.round(8 * mContext.getResources().getDisplayMetrics().density);
Glide.with(cover).load(item.coverRes)
cover.setContentDescription(item.getName(mContext));
Glide.with(cover).load(item.getCover())
.placeholder(R.drawable.shop_mall_card_bg)
.fallback(R.drawable.shop_mall_card_bg)
.error(R.drawable.shop_mall_card_bg)
.transform(new CenterCrop(), new RoundedCorners(radius)).into(cover);
}
}

View File

@@ -4,6 +4,7 @@ import android.view.View;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.CheckBox;
@@ -21,9 +22,11 @@ import java.util.Set;
/** 每张优惠券独立勾选,展示弹窗草稿,不直接修改订单。 */
public class CheckoutCouponAdapter extends BaseQuickAdapter<CheckoutCouponEntity, BaseViewHolder> {
private final Set<String> selectedIds = new HashSet<>();
private final long subtotalCents;
public CheckoutCouponAdapter() {
public CheckoutCouponAdapter(long subtotalCents) {
super(R.layout.item_checkout_coupon);
this.subtotalCents = subtotalCents;
}
public void setSelectedIds(Collection<String> ids) {
@@ -34,18 +37,44 @@ public class CheckoutCouponAdapter extends BaseQuickAdapter<CheckoutCouponEntity
@Override
protected void convert(BaseViewHolder helper, CheckoutCouponEntity item) {
String amount = BigDecimal.valueOf(item.discountCents, 2).stripTrailingZeros().toPlainString();
boolean selected = selectedIds.contains(item.id);
String titleText = mContext.getString(R.string.checkout_coupon_title, amount);
String amount = item.getDeductAmount().stripTrailingZeros().toPlainString();
boolean eligible = item.isEligible(subtotalCents);
boolean selected = eligible && selectedIds.contains(item.getId());
boolean rateCoupon = item.getType() == CheckoutCouponEntity.TYPE_DISCOUNT;
String titleText = TextUtils.isEmpty(item.getName())
? (rateCoupon ? mContext.getString(R.string.checkout_coupon_rate_title)
: mContext.getString(R.string.checkout_coupon_title, amount)) : item.getName();
SpannableString title = new SpannableString(titleText);
int amountStart = titleText.indexOf(amount);
if (amountStart >= 0) {
if (!rateCoupon && amountStart >= 0) {
title.setSpan(new ForegroundColorSpan(Color.rgb(245, 68, 76)),
amountStart, amountStart + amount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
helper.setText(R.id.tv_coupon_amount, mContext.getString(R.string.checkout_coupon_amount, amount))
String benefit = mContext.getString(R.string.checkout_coupon_amount, amount);
if (rateCoupon) {
boolean chinese = "zh".equals(mContext.getResources().getConfiguration()
.getLocales().get(0).getLanguage());
BigDecimal rate = chinese ? item.getDiscountRate()
: BigDecimal.TEN.subtract(item.getDiscountRate()).multiply(BigDecimal.TEN);
benefit = mContext.getString(R.string.checkout_coupon_rate,
rate.stripTrailingZeros().toPlainString());
}
String threshold = item.getType() != CheckoutCouponEntity.TYPE_DIRECT
&& item.getThresholdAmount().signum() > 0
? mContext.getString(R.string.checkout_coupon_minimum,
item.getThresholdAmount().stripTrailingZeros().toPlainString())
: mContext.getString(R.string.checkout_coupon_threshold);
String rule = TextUtils.isEmpty(item.getRule()) ? threshold : item.getRule();
if (!eligible) rule = mContext.getString(R.string.checkout_coupon_unavailable);
String validity = TextUtils.isEmpty(item.getExpireTime())
? mContext.getString(R.string.checkout_coupon_long_term)
: mContext.getString(R.string.checkout_coupon_validity, item.getExpireTime());
helper.setText(R.id.tv_coupon_amount, benefit)
.setText(R.id.tv_coupon_threshold, threshold)
.setText(R.id.tv_coupon_description, rule)
.setText(R.id.tv_coupon_title, title)
.setText(R.id.tv_coupon_validity, mContext.getString(R.string.checkout_coupon_validity, item.validUntil));
.setText(R.id.tv_coupon_validity, validity);
helper.itemView.setAlpha(eligible ? 1f : 0.45f);
helper.getView(R.id.iv_coupon_check).setSelected(selected);
helper.itemView.setSelected(selected);
helper.itemView.setAccessibilityDelegate(new View.AccessibilityDelegate() {
@@ -55,6 +84,7 @@ public class CheckoutCouponAdapter extends BaseQuickAdapter<CheckoutCouponEntity
info.setClassName(CheckBox.class.getName());
info.setCheckable(true);
info.setChecked(selected);
info.setEnabled(eligible);
}
});
}

View File

@@ -25,7 +25,7 @@ public class CheckoutGoodsAdapter extends BaseQuickAdapter<CartGoodsEntity, Base
mContext.getResources().getConfiguration().getLocales().get(0));
cash.setMinimumFractionDigits(2);
cash.setMaximumFractionDigits(2);
helper.setText(R.id.tv_checkout_goods_name, mContext.getString(item.nameRes))
helper.setText(R.id.tv_checkout_goods_name, item.getName(mContext))
.setText(R.id.tv_checkout_goods_price, mContext.getString(R.string.cart_cash_price,
cash.format(BigDecimal.valueOf(item.cashCents, 2))))
.setText(R.id.tv_checkout_quantity, String.valueOf(item.quantity))
@@ -38,7 +38,11 @@ public class CheckoutGoodsAdapter extends BaseQuickAdapter<CartGoodsEntity, Base
helper.getView(R.id.tv_checkout_plus).setAlpha(canIncrease ? 1f : 0.35f);
ImageView cover = helper.getView(R.id.iv_checkout_goods_cover);
int radius = Math.round(8 * mContext.getResources().getDisplayMetrics().density);
Glide.with(cover).load(item.coverRes)
cover.setContentDescription(item.getName(mContext));
Glide.with(cover).load(item.getCover())
.placeholder(R.drawable.shop_mall_card_bg)
.fallback(R.drawable.shop_mall_card_bg)
.error(R.drawable.shop_mall_card_bg)
.transform(new CenterCrop(), new RoundedCorners(radius)).into(cover);
}
}

View File

@@ -1,5 +1,8 @@
package com.ckkj.griddle.cart.entity;
import android.content.Context;
import android.text.TextUtils;
import java.io.Serializable;
/** 购物车商品;积分使用整数,现金以分保存,避免浮点累计误差。 */
@@ -10,16 +13,59 @@ public class CartGoodsEntity implements Serializable {
public final String id;
public final int nameRes;
public final int coverRes;
/** 真实接口商品使用名称和网络图片;原有本地资源构造方式继续兼容。 */
private final String goodsName;
private final String goodsImg;
private final String goodsId;
private final String skuId;
private final String specModel;
private final long stock;
private final boolean invalid;
private final String invalidReason;
public final long points;
public final long cashCents;
public int quantity;
public boolean selected;
/** 单条修改请求进行中,用于屏蔽连续点击。 */
public boolean updating;
public CartGoodsEntity(String id, int nameRes, int coverRes, long points,
long cashCents, int quantity, boolean selected) {
this(id, nameRes, coverRes, null, null, null, null, null,
points, cashCents, quantity, selected, MAX_QUANTITY, false, null);
}
public CartGoodsEntity(String id, String goodsName, String goodsImg, long points,
long cashCents, int quantity, boolean selected) {
this(id, 0, 0, goodsName == null ? "" : goodsName, goodsImg,
null, null, null, points, cashCents, quantity, selected,
MAX_QUANTITY, false, null);
}
/** 服务端购物车条目,id 为购物车记录 ID,goodsId 和 skuId 用于后续结算。 */
public CartGoodsEntity(String id, String goodsId, String skuId, String goodsName,
String goodsImg, String specModel, long cashCents, int quantity,
long stock, boolean selected, boolean invalid, String invalidReason) {
this(id, 0, 0, goodsName == null ? "" : goodsName, goodsImg,
goodsId, skuId, specModel, 0, cashCents, quantity,
selected && !invalid && stock > 0, stock, invalid, invalidReason);
}
private CartGoodsEntity(String id, int nameRes, int coverRes, String goodsName,
String goodsImg, String goodsId, String skuId, String specModel,
long points, long cashCents, int quantity, boolean selected,
long stock, boolean invalid, String invalidReason) {
this.id = id;
this.nameRes = nameRes;
this.coverRes = coverRes;
this.goodsName = goodsName;
this.goodsImg = goodsImg;
this.goodsId = goodsId;
this.skuId = skuId;
this.specModel = specModel;
this.stock = stock;
this.invalid = invalid;
this.invalidReason = invalidReason;
this.points = points;
this.cashCents = cashCents;
this.quantity = quantity;
@@ -27,6 +73,38 @@ public class CartGoodsEntity implements Serializable {
}
public CartGoodsEntity copy() {
return new CartGoodsEntity(id, nameRes, coverRes, points, cashCents, quantity, selected);
CartGoodsEntity result = new CartGoodsEntity(id, nameRes, coverRes, goodsName, goodsImg,
goodsId, skuId, specModel, points, cashCents, quantity, selected,
stock, invalid, invalidReason);
result.updating = updating;
return result;
}
public String getName(Context context) {
return goodsName != null ? goodsName : nameRes == 0 ? "" : context.getString(nameRes);
}
/** Glide 同时支持网络地址和本地资源编号,空地址不回退成演示商品。 */
public Object getCover() {
if (goodsName != null) {
return TextUtils.isEmpty(goodsImg) ? null : goodsImg.trim();
}
return coverRes == 0 ? null : coverRes;
}
public String getGoodsId() { return goodsId; }
public String getSkuId() { return skuId; }
public String getSpecModel() { return specModel; }
public boolean isInvalid() { return invalid || stock <= 0; }
public boolean isAvailable() { return !invalid && stock > 0; }
public String getInvalidReason() { return invalidReason; }
public int getMaxQuantity() {
return (int) Math.max(1, Math.min(MAX_QUANTITY, stock));
}
}

View File

@@ -1,14 +1,75 @@
package com.ckkj.griddle.cart.entity;
/** 下单优惠券预览,金额单位为分,券编号用于保存独立勾选状态。 */
public class CheckoutCouponEntity {
public final String id;
public final long discountCents;
public final String validUntil;
import android.text.TextUtils;
public CheckoutCouponEntity(String id, long discountCents, String validUntil) {
this.id = id;
this.discountCents = discountCents;
this.validUntil = validUntil;
import java.math.BigDecimal;
import java.math.RoundingMode;
/** 当前账号可用的优惠券;使用领取记录 recordId 标识每张券。 */
public class CheckoutCouponEntity {
public static final int TYPE_THRESHOLD = 0;
public static final int TYPE_DIRECT = 1;
public static final int TYPE_DISCOUNT = 2;
private String recordId;
private String couponId;
private String couponName;
private Integer couponType;
private String couponRule;
private BigDecimal thresholdAmount;
private BigDecimal deductAmount;
private BigDecimal discountRate;
private String expireTime;
public String getId() { return recordId; }
public String getCouponId() { return couponId; }
public String getName() { return couponName; }
public String getRule() { return couponRule; }
public String getExpireTime() { return expireTime; }
public int getType() { return couponType == null ? -1 : couponType; }
public BigDecimal getThresholdAmount() {
return thresholdAmount == null ? BigDecimal.ZERO : thresholdAmount;
}
public BigDecimal getDeductAmount() {
return deductAmount == null ? BigDecimal.ZERO : deductAmount;
}
public BigDecimal getDiscountRate() {
return discountRate == null ? BigDecimal.ZERO : discountRate;
}
/** 有效期和账号资格由可用券接口筛选,本地只补充商品金额门槛与券规则校验。 */
public boolean isEligible(long subtotalCents) {
if (TextUtils.isEmpty(recordId) || subtotalCents <= 0) return false;
try {
if (getType() != TYPE_DIRECT
&& subtotalCents < toCents(getThresholdAmount())) return false;
if (getType() == TYPE_THRESHOLD || getType() == TYPE_DIRECT) {
return toCents(getDeductAmount()) > 0;
}
return getType() == TYPE_DISCOUNT && getDiscountRate().signum() > 0
&& getDiscountRate().compareTo(BigDecimal.TEN) < 0;
} catch (ArithmeticException exception) {
// 超出本地金额范围的异常券不参与预估,避免错误抵扣。
return false;
}
}
/** 基于剩余金额计算本张券的预估抵扣,例如 8.5 折表示减免 15%。 */
public long calculateDiscount(long remainingCents) {
if (remainingCents <= 0) return 0;
long discount;
if (getType() == TYPE_DISCOUNT) {
discount = BigDecimal.valueOf(remainingCents)
.multiply(BigDecimal.TEN.subtract(getDiscountRate()))
.divide(BigDecimal.TEN, 0, RoundingMode.HALF_UP).longValueExact();
} else {
discount = toCents(getDeductAmount());
}
return Math.min(remainingCents, Math.max(0, discount));
}
private long toCents(BigDecimal amount) {
return amount.max(BigDecimal.ZERO).movePointRight(2)
.setScale(0, RoundingMode.HALF_UP).longValueExact();
}
}

View File

@@ -0,0 +1,31 @@
package com.ckkj.griddle.cart.entity;
import java.math.BigDecimal;
import java.math.RoundingMode;
/** 我的购物车接口条目,仅负责把服务端元金额转换为页面使用的分单位。 */
public class MallCartItemEntity {
private String id;
private String goodsId;
private String skuId;
private String goodsName;
private String goodsImg;
private String specModel;
private BigDecimal unitPrice;
private int num;
private long stock;
private Integer selected;
private boolean invalid;
private String invalidReason;
public String getId() { return id; }
public CartGoodsEntity toCartGoods() {
BigDecimal price = unitPrice == null ? BigDecimal.ZERO : unitPrice;
long cashCents = price.max(BigDecimal.ZERO).movePointRight(2)
.setScale(0, RoundingMode.HALF_UP).longValueExact();
return new CartGoodsEntity(id, goodsId, skuId, goodsName, goodsImg, specModel,
cashCents, Math.max(1, Math.min(CartGoodsEntity.MAX_QUANTITY, num)),
stock, selected != null && selected == 1, invalid, invalidReason);
}
}

View File

@@ -15,9 +15,30 @@ public class CartContract {
public interface DataModel {
void getCart(CallBack<List<CartGoodsEntity>> callback);
void cancelCartRequest();
void updateCartItem(String id, Integer num, Integer selected, CallBack<Void> callback);
void selectAll(boolean selected, CallBack<Void> callback);
void deleteCartItem(String id, CallBack<Void> callback);
/** 批量清空购物车,ids 为待清除的购物车记录编号。 */
void clearCart(List<String> ids, CallBack<Void> callback);
void cancelCartUpdates();
}
public interface CartView extends IView {
void showCart(List<CartGoodsEntity> goods);
void showCartUpdateError(String message);
void removeCartItem(String id);
void refreshCartItem(CartGoodsEntity item);
void onCartOperationFinished(String errorMessage);
}
}

View File

@@ -1,21 +1,239 @@
package com.ckkj.griddle.cart.mvp;
import android.text.TextUtils;
import com.ckkj.griddle.MyApplication;
import com.ckkj.griddle.R;
import com.ckkj.griddle.cart.entity.CartGoodsEntity;
import com.ckkj.griddle.cart.entity.MallCartItemEntity;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.network.NetWorkManager;
import com.ckkj.griddle.utils.AppLanguageUtil;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
/** 购物车数据实现:当前使用设计稿演示数据,尚未接入服务端购物车。 */
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.SerialDisposable;
import io.reactivex.schedulers.Schedulers;
/** 购物车数据层,使用当前登录账号的真实购物车数据。 */
public class CartImpl implements CartContract.DataModel {
private final SerialDisposable cartRequest = new SerialDisposable();
private final CompositeDisposable cartUpdates = new CompositeDisposable();
@Override
public void getCart(CartContract.CallBack<List<CartGoodsEntity>> callback) {
try {
NetWorkManager.getRequest().getMallCart(NetWorkManager.getToken())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean<List<MallCartItemEntity>>>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
cartRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean<List<MallCartItemEntity>> response) {
if (response.isSuccess() || response.getCode() == 200) {
callback.success(toCartGoods(response.getData()));
} else {
callback.fail(errorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(errorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(errorMessage(exception.getMessage()));
}
}
/** 过滤缺少记录编号的条目后,把接口条目转换为页面使用的购物车模型。 */
private List<CartGoodsEntity> toCartGoods(List<MallCartItemEntity> items) {
List<CartGoodsEntity> goods = new ArrayList<>();
// 新稿使用现金商品,首项勾选、次项未勾选,数量与合计按实际数据计算。
goods.add(new CartGoodsEntity("demo_beef_1", R.string.cart_goods_name,
R.mipmap.icon_cart_goods_preview, 0, 20800, 1, true));
goods.add(new CartGoodsEntity("demo_beef_2", R.string.cart_goods_name_long,
R.mipmap.icon_cart_goods_preview, 0, 20800, 1, false));
callback.success(goods);
if (items == null) return goods;
for (MallCartItemEntity item : items) {
if (item != null && !TextUtils.isEmpty(item.getId())) goods.add(item.toCartGoods());
}
return goods;
}
private String errorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(R.string.cart_load_failed) : message;
}
@Override
public void cancelCartRequest() {
cartRequest.set(null);
}
@Override
public void updateCartItem(String id, Integer num, Integer selected,
CartContract.CallBack<Void> callback) {
if (TextUtils.isEmpty(id) || (num == null && selected == null)) {
callback.fail(updateErrorMessage(null));
return;
}
try {
NetWorkManager.getRequest().updateMallCartItem(
NetWorkManager.getToken(), id.trim(), num, selected)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
cartUpdates.add(disposable);
}
@Override
public void onNext(@NonNull BaseBean response) {
if (response.isSuccess() || response.getCode() == 200) {
callback.success(null);
} else {
callback.fail(updateErrorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(updateErrorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(updateErrorMessage(exception.getMessage()));
}
}
@Override
public void selectAll(boolean selected, CartContract.CallBack<Void> callback) {
try {
NetWorkManager.getRequest().selectAllMallCartItems(
NetWorkManager.getToken(), selected ? 1 : 0)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(createVoidObserver(callback, R.string.cart_update_failed));
} catch (Exception exception) {
callback.fail(updateErrorMessage(exception.getMessage()));
}
}
@Override
public void deleteCartItem(String id, CartContract.CallBack<Void> callback) {
if (TextUtils.isEmpty(id)) {
callback.fail(deleteErrorMessage(null));
return;
}
try {
NetWorkManager.getRequest().deleteMallCartItem(NetWorkManager.getToken(), id.trim())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(createVoidObserver(callback, R.string.cart_delete_failed));
} catch (Exception exception) {
callback.fail(deleteErrorMessage(exception.getMessage()));
}
}
@Override
public void clearCart(List<String> ids, CartContract.CallBack<Void> callback) {
if (ids == null || ids.isEmpty()) {
callback.fail(clearErrorMessage(null));
return;
}
// 文档约定请求体为购物车编号数组,编号本身是数字字符串,转成整数提交。
JSONArray body = new JSONArray();
for (String id : ids) {
if (TextUtils.isEmpty(id)) continue;
try {
body.put(Long.parseLong(id.trim()));
} catch (NumberFormatException exception) {
body.put(id.trim());
}
}
try {
NetWorkManager.getRequest().clearMallCart(NetWorkManager.getToken(),
NetWorkManager.toRequestBodyJSONArray(body))
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(createVoidObserver(callback, R.string.cart_clear_failed));
} catch (Exception exception) {
callback.fail(clearErrorMessage(exception.getMessage()));
}
}
private Observer<BaseBean> createVoidObserver(CartContract.CallBack<Void> callback,
int fallbackMessageRes) {
return new Observer<BaseBean>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
cartUpdates.add(disposable);
}
@Override
public void onNext(@NonNull BaseBean response) {
if (response.isSuccess() || response.getCode() == 200) {
callback.success(null);
} else {
callback.fail(operationErrorMessage(response.getMessage(), fallbackMessageRes));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(operationErrorMessage(throwable.getMessage(), fallbackMessageRes));
}
@Override
public void onComplete() {
}
};
}
private String operationErrorMessage(String message, int fallbackMessageRes) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(fallbackMessageRes) : message;
}
private String updateErrorMessage(String message) {
return operationErrorMessage(message, R.string.cart_update_failed);
}
private String deleteErrorMessage(String message) {
return operationErrorMessage(message, R.string.cart_delete_failed);
}
private String clearErrorMessage(String message) {
return operationErrorMessage(message, R.string.cart_clear_failed);
}
@Override
public void cancelCartUpdates() {
cartUpdates.clear();
}
}

View File

@@ -8,34 +8,40 @@ import java.util.List;
/** 购物车交互协调层,管理模式切换共用同一份商品、数量和勾选状态。 */
public class CartPresenter extends BasePresenter<CartContract.CartView> {
private final CartContract.DataModel impl;
private final CartImpl impl;
private final List<CartGoodsEntity> goods = new ArrayList<>();
private int cartRequestVersion;
private int bulkOperationVersion;
private boolean bulkOperating;
public CartPresenter(CartContract.DataModel impl) {
public CartPresenter(CartImpl impl) {
this.impl = impl;
}
public void getCart() {
getCart(null);
}
/** 等购物车数据加载完成后再合并带入商品,后续改为异步接口也不会被响应覆盖。 */
public void getCart(CartGoodsEntity incoming) {
final int requestVersion = ++cartRequestVersion;
impl.cancelCartRequest();
impl.cancelCartUpdates();
bulkOperationVersion++;
bulkOperating = false;
for (CartGoodsEntity item : goods) item.updating = false;
impl.getCart(new CartContract.CallBack<List<CartGoodsEntity>>() {
@Override
public void success(List<CartGoodsEntity> data) {
if (requestVersion != cartRequestVersion || getView() == null) return;
restoreCart(data);
if (incoming != null) addItem(incoming);
}
@Override
public void fail(String message) {
if (getView() != null) getView().showError(message);
if (requestVersion == cartRequestVersion && getView() != null) {
getView().showError(message);
}
}
});
}
/** 恢复旋转、折叠或进程重建前的页面草稿,包括已经清空的购物车。 */
/** 使用接口结果替换页面数据,包括服务端返回的空购物车。 */
public void restoreCart(List<CartGoodsEntity> data) {
goods.clear();
if (data != null) {
@@ -50,64 +56,201 @@ public class CartPresenter extends BasePresenter<CartContract.CartView> {
return result;
}
/** 合并商城带入的本地演示商品,同款累计数量,上限与购物车操作保持一致。 */
public void addItem(CartGoodsEntity incoming) {
if (incoming == null) return;
for (CartGoodsEntity item : goods) {
if (item.id.equals(incoming.id)) {
item.quantity = Math.min(CartGoodsEntity.MAX_QUANTITY,
item.quantity + Math.max(1, incoming.quantity));
item.selected = true;
renderCart();
return;
}
}
CartGoodsEntity added = incoming.copy();
added.quantity = Math.max(1, Math.min(CartGoodsEntity.MAX_QUANTITY, added.quantity));
added.selected = true;
goods.add(added);
renderCart();
}
public void toggleItem(String id) {
for (CartGoodsEntity item : goods) {
if (item.id.equals(id)) item.selected = !item.selected;
}
renderCart();
CartGoodsEntity item = findItem(id);
if (item == null || !item.isAvailable() || item.updating) return;
updateItem(item, null, item.selected ? 0 : 1);
}
public void selectAll(boolean selected) {
for (CartGoodsEntity item : goods) item.selected = selected;
if (isCartBusy() || goods.isEmpty()) return;
final int operationVersion = ++bulkOperationVersion;
bulkOperating = true;
for (CartGoodsEntity item : goods) if (item.isAvailable()) item.updating = true;
renderCart();
impl.selectAll(selected, new CartContract.CallBack<Void>() {
@Override
public void success(Void data) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
bulkOperating = false;
for (CartGoodsEntity item : goods) {
item.updating = false;
if (item.isAvailable()) item.selected = selected;
}
renderCart();
getView().onCartOperationFinished(null);
}
@Override
public void fail(String message) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
bulkOperating = false;
for (CartGoodsEntity item : goods) item.updating = false;
renderCart();
getView().onCartOperationFinished(message);
}
});
}
public void changeQuantity(String id, int delta) {
for (CartGoodsEntity item : goods) {
if (item.id.equals(id)) {
item.quantity = Math.max(1, Math.min(CartGoodsEntity.MAX_QUANTITY,
item.quantity + delta));
break;
}
}
renderCart();
CartGoodsEntity item = findItem(id);
if (item == null || !item.isAvailable() || item.updating) return;
int quantity = Math.max(1, Math.min(CartGoodsEntity.MAX_QUANTITY,
Math.min(item.getMaxQuantity(), item.quantity + delta)));
if (quantity == item.quantity) return;
updateItem(item, quantity, null);
}
/** 当前删除仅作用于演示数据,接口接入后应在服务端成功回调中更新列表。 */
public void deleteItems(List<String> ids) {
goods.removeIf(item -> ids.contains(item.id));
private void updateItem(CartGoodsEntity item, Integer quantity, Integer selected) {
item.updating = true;
renderCart();
impl.updateCartItem(item.id, quantity, selected, new CartContract.CallBack<Void>() {
@Override
public void success(Void data) {
CartGoodsEntity current = findItem(item.id);
if (current == null || getView() == null) return;
if (quantity != null) current.quantity = quantity;
if (selected != null) current.selected = selected == 1;
current.updating = false;
renderCart();
}
@Override
public void fail(String message) {
CartGoodsEntity current = findItem(item.id);
if (current == null || getView() == null) return;
current.updating = false;
renderCart();
getView().showCartUpdateError(message);
}
});
}
private CartGoodsEntity findItem(String id) {
if (id == null) return null;
for (CartGoodsEntity item : goods) {
if (id.equals(item.id)) return item;
}
return null;
}
public void deleteItems(List<String> ids) {
if (isCartBusy() || ids == null || ids.isEmpty()) return;
ArrayList<String> targets = new ArrayList<>();
for (CartGoodsEntity item : goods) {
if (ids.contains(item.id) && !targets.contains(item.id)) {
targets.add(item.id);
item.updating = true;
}
}
if (targets.isEmpty()) return;
final int operationVersion = ++bulkOperationVersion;
bulkOperating = true;
renderCart();
deleteNext(targets, 0, operationVersion, null);
}
private void deleteNext(List<String> ids, int index, int operationVersion,
String firstError) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
if (index >= ids.size()) {
bulkOperating = false;
for (String id : ids) {
CartGoodsEntity item = findItem(id);
if (item == null) continue;
item.updating = false;
getView().refreshCartItem(item.copy());
}
getView().onCartOperationFinished(firstError);
return;
}
String id = ids.get(index);
impl.deleteCartItem(id, new CartContract.CallBack<Void>() {
@Override
public void success(Void data) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
CartGoodsEntity item = findItem(id);
if (item != null) goods.remove(item);
getView().removeCartItem(id);
deleteNext(ids, index + 1, operationVersion, firstError);
}
@Override
public void fail(String message) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
CartGoodsEntity item = findItem(id);
if (item != null) {
item.updating = false;
getView().refreshCartItem(item.copy());
}
deleteNext(ids, index + 1, operationVersion,
firstError == null ? message : firstError);
}
});
}
/**
* 批量删除:调用清空购物车接口并提交待删除的编号数组,
* 多条删除只发一次请求,成功后就地移除条目并统一回调。
*/
public void clearCart(List<String> ids) {
if (isCartBusy() || ids == null || ids.isEmpty()) return;
ArrayList<String> targets = new ArrayList<>();
for (CartGoodsEntity item : goods) {
if (ids.contains(item.id) && !targets.contains(item.id)) {
targets.add(item.id);
item.updating = true;
}
}
if (targets.isEmpty()) return;
final int operationVersion = ++bulkOperationVersion;
bulkOperating = true;
renderCart();
impl.clearCart(targets, new CartContract.CallBack<Void>() {
@Override
public void success(Void data) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
bulkOperating = false;
for (String id : targets) {
CartGoodsEntity item = findItem(id);
if (item != null) goods.remove(item);
}
renderCart();
getView().onCartOperationFinished(null);
}
@Override
public void fail(String message) {
if (operationVersion != bulkOperationVersion || getView() == null) return;
bulkOperating = false;
// 清空失败时条目仍保留在购物车,恢复可操作状态并提示原因。
for (String id : targets) {
CartGoodsEntity item = findItem(id);
if (item != null) item.updating = false;
}
renderCart();
getView().onCartOperationFinished(message);
}
});
}
public List<String> getSelectedIds() {
List<String> ids = new ArrayList<>();
for (CartGoodsEntity item : goods) {
if (item.selected) ids.add(item.id);
if (item.selected && item.isAvailable()) ids.add(item.id);
}
return ids;
}
public boolean isAllSelected() {
return !goods.isEmpty() && getSelectedIds().size() == goods.size();
int available = 0;
int selected = 0;
for (CartGoodsEntity item : goods) {
if (!item.isAvailable()) continue;
available++;
if (item.selected) selected++;
}
return available > 0 && selected == available;
}
public int getTotalQuantity() {
@@ -119,7 +262,7 @@ public class CartPresenter extends BasePresenter<CartContract.CartView> {
public int getSelectedQuantity() {
int quantity = 0;
for (CartGoodsEntity item : goods) {
if (item.selected) quantity += item.quantity;
if (item.selected && item.isAvailable()) quantity += item.quantity;
}
return quantity;
}
@@ -127,7 +270,7 @@ public class CartPresenter extends BasePresenter<CartContract.CartView> {
public long getSelectedPoints() {
long points = 0;
for (CartGoodsEntity item : goods) {
if (item.selected) points += item.points * item.quantity;
if (item.selected && item.isAvailable()) points += item.points * item.quantity;
}
return points;
}
@@ -135,12 +278,30 @@ public class CartPresenter extends BasePresenter<CartContract.CartView> {
public long getSelectedCashCents() {
long cash = 0;
for (CartGoodsEntity item : goods) {
if (item.selected) cash += item.cashCents * item.quantity;
if (item.selected && item.isAvailable()) cash += item.cashCents * item.quantity;
}
return cash;
}
public boolean isCartBusy() {
if (bulkOperating) return true;
for (CartGoodsEntity item : goods) {
if (item.updating) return true;
}
return false;
}
private void renderCart() {
if (getView() != null) getView().showCart(getSnapshot());
}
@Override
public void onDestroy() {
cartRequestVersion++;
bulkOperationVersion++;
bulkOperating = false;
impl.cancelCartRequest();
impl.cancelCartUpdates();
super.onDestroy();
}
}

View File

@@ -8,8 +8,15 @@ import java.util.List;
/** 确认订单页面协议,金额统一使用分,避免浮点计算误差。 */
public class CheckoutContract {
public interface CallBack<T> {
void success(T data);
void fail(String message);
}
public interface DataModel {
List<CheckoutCouponEntity> getCoupons();
void getCoupons(CallBack<List<CheckoutCouponEntity>> callback);
void cancelCouponsRequest();
int getAvailablePoints();
int getRedeemPoints();
}
@@ -17,6 +24,10 @@ public class CheckoutContract {
public interface CheckoutView extends IView {
void showOrder(List<CartGoodsEntity> goods);
void onCouponsLoaded();
void showCouponsLoadError(String message);
/** 订单支付确认成功后展示结果,失败或取消时不得调用。 */
void showPaymentSuccess();
}

View File

@@ -1,16 +1,74 @@
package com.ckkj.griddle.cart.mvp;
import android.text.TextUtils;
import com.ckkj.griddle.MyApplication;
import com.ckkj.griddle.R;
import com.ckkj.griddle.cart.entity.CheckoutCouponEntity;
import java.util.Arrays;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.network.NetWorkManager;
import com.ckkj.griddle.utils.AppLanguageUtil;
import java.util.ArrayList;
import java.util.List;
/** 当前仅提供设计稿优惠预览值;订单、优惠资格及支付均需后续接入服务端校验。 */
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.SerialDisposable;
import io.reactivex.schedulers.Schedulers;
/** 可用优惠券使用真实接口;积分预览配置、订单和支付后续单独联调。 */
public class CheckoutImpl implements CheckoutContract.DataModel {
private final SerialDisposable couponsRequest = new SerialDisposable();
@Override
public List<CheckoutCouponEntity> getCoupons() {
return Arrays.asList(
new CheckoutCouponEntity("preview_coupon_1", 1000, "2026-12-31"),
new CheckoutCouponEntity("preview_coupon_2", 1000, "2026-12-31"));
public void getCoupons(CheckoutContract.CallBack<List<CheckoutCouponEntity>> callback) {
try {
NetWorkManager.getRequest().getMallCoupons(NetWorkManager.getToken())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean<List<CheckoutCouponEntity>>>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
couponsRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean<List<CheckoutCouponEntity>> response) {
if (response.isSuccess() || response.getCode() == 200) {
List<CheckoutCouponEntity> coupons = response.getData();
callback.success(coupons == null ? new ArrayList<>() : coupons);
} else {
callback.fail(errorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(errorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(errorMessage(exception.getMessage()));
}
}
private String errorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(R.string.checkout_coupons_load_failed) : message;
}
@Override
public void cancelCouponsRequest() {
couponsRequest.set(null);
}
@Override

View File

@@ -1,5 +1,7 @@
package com.ckkj.griddle.cart.mvp;
import android.text.TextUtils;
import com.ckkj.griddle.base.BasePresenter;
import com.ckkj.griddle.cart.entity.CartGoodsEntity;
import com.ckkj.griddle.cart.entity.CheckoutCouponEntity;
@@ -9,13 +11,17 @@ import java.util.List;
/** 下单预览协调层,独立保存数量,返回时不直接修改购物车草稿。 */
public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutView> {
private final CheckoutContract.DataModel impl;
private final CheckoutImpl impl;
private final ArrayList<CartGoodsEntity> goods = new ArrayList<>();
private final ArrayList<String> selectedCouponIds = new ArrayList<>();
private final ArrayList<CheckoutCouponEntity> coupons = new ArrayList<>();
private boolean couponsLoaded;
private boolean couponsLoading;
private int couponsRequestVersion;
// 积分抵扣由用户主动开启,首次进入不自动兑换。
private boolean pointsEnabled = false;
public CheckoutPresenter(CheckoutContract.DataModel impl) {
public CheckoutPresenter(CheckoutImpl impl) {
this.impl = impl;
}
@@ -30,16 +36,53 @@ public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutVi
}
}
selectedCouponIds.clear();
// 延续原页面首次使用第一张券的预览行为,空集合表示主动不使用。
if (couponIds == null && !getCoupons().isEmpty()) {
selectedCouponIds.add(getCoupons().get(0).id);
} else {
updateCouponSelection(couponIds);
}
// 首次进入不自动用券;页面重建时暂存领取记录 ID,接口返回后再校验。
updateCouponSelection(couponIds);
pointsEnabled = points;
renderOrder();
}
public void loadCoupons() {
if (couponsLoading) return;
final int requestVersion = ++couponsRequestVersion;
couponsLoading = true;
impl.cancelCouponsRequest();
renderOrder();
impl.getCoupons(new CheckoutContract.CallBack<List<CheckoutCouponEntity>>() {
@Override
public void success(List<CheckoutCouponEntity> data) {
if (requestVersion != couponsRequestVersion || getView() == null) return;
couponsLoading = false;
couponsLoaded = true;
coupons.clear();
if (data != null) {
for (CheckoutCouponEntity coupon : data) {
if (coupon == null || TextUtils.isEmpty(coupon.getId())) continue;
boolean duplicate = false;
for (CheckoutCouponEntity existing : coupons) {
if (existing.getId().equals(coupon.getId())) {
duplicate = true;
break;
}
}
if (!duplicate) coupons.add(coupon);
}
}
updateCouponSelection(new ArrayList<>(selectedCouponIds));
renderOrder();
getView().onCouponsLoaded();
}
@Override
public void fail(String message) {
if (requestVersion != couponsRequestVersion || getView() == null) return;
couponsLoading = false;
renderOrder();
getView().showCouponsLoadError(message);
}
});
}
public ArrayList<CartGoodsEntity> getSnapshot() {
ArrayList<CartGoodsEntity> result = new ArrayList<>();
for (CartGoodsEntity item : goods) result.add(item.copy());
@@ -54,6 +97,8 @@ public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutVi
break;
}
}
// 数量变化后不满足门槛的券自动取消,避免继续使用原来的抵扣额。
updateCouponSelection(new ArrayList<>(selectedCouponIds));
renderOrder();
}
@@ -65,14 +110,31 @@ public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutVi
private void updateCouponSelection(List<String> ids) {
selectedCouponIds.clear();
if (ids == null) return;
if (!couponsLoaded) {
for (String id : ids) {
if (!TextUtils.isEmpty(id) && !selectedCouponIds.contains(id)) selectedCouponIds.add(id);
}
return;
}
for (CheckoutCouponEntity coupon : getCoupons()) {
if (ids.contains(coupon.id) && !selectedCouponIds.contains(coupon.id)) {
selectedCouponIds.add(coupon.id);
if (ids.contains(coupon.getId()) && coupon.isEligible(getSubtotalCents())
&& !selectedCouponIds.contains(coupon.getId())) {
selectedCouponIds.add(coupon.getId());
}
}
}
public List<CheckoutCouponEntity> getCoupons() { return impl.getCoupons(); }
public List<CheckoutCouponEntity> getCoupons() { return new ArrayList<>(coupons); }
public boolean areCouponsLoaded() { return couponsLoaded; }
public boolean isCouponsLoading() { return couponsLoading; }
public int getAvailableCouponCount() {
int count = 0;
for (CheckoutCouponEntity coupon : coupons) {
if (coupon.isEligible(getSubtotalCents())) count++;
}
return count;
}
public ArrayList<String> getSelectedCouponIds() {
return new ArrayList<>(selectedCouponIds);
@@ -94,14 +156,21 @@ public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutVi
}
public long getCouponCents() {
long remaining = getSubtotalCents();
for (CheckoutCouponEntity coupon : getCoupons()) {
if (selectedCouponIds.contains(coupon.id)) {
remaining -= Math.min(Math.max(0, coupon.discountCents), remaining);
long subtotal = getSubtotalCents();
long remaining = subtotal;
// 本地叠加预估:门槛按商品小计判断,先减免券再折扣券,最后由积分抵扣。
// 当前服务端预览文档仅支持一个 couponRecordId,多券最终结算需以后端规则为准。
for (int pass = 0; pass < 2; pass++) {
for (CheckoutCouponEntity coupon : coupons) {
boolean discountCoupon = coupon.getType() == CheckoutCouponEntity.TYPE_DISCOUNT;
if ((pass == 1) == discountCoupon && selectedCouponIds.contains(coupon.getId())
&& coupon.isEligible(subtotal)) {
remaining -= coupon.calculateDiscount(remaining);
}
}
}
// 叠加优惠最多抵扣商品小计,积分在优惠券抵扣后继续计算。
return getSubtotalCents() - remaining;
return subtotal - remaining;
}
public long getPointsCents() {
@@ -117,4 +186,11 @@ public class CheckoutPresenter extends BasePresenter<CheckoutContract.CheckoutVi
private void renderOrder() {
if (getView() != null) getView().showOrder(getSnapshot());
}
@Override
public void onDestroy() {
couponsRequestVersion++;
impl.cancelCouponsRequest();
super.onDestroy();
}
}

View File

@@ -7,9 +7,9 @@ import java.util.List;
/** 优惠券协调层,页面不直接处理券源和领取校验。 */
public class CouponPresenter extends BasePresenter<CouponContract.CouponView> {
private final CouponContract.DataModel impl;
private final CouponImpl impl;
public CouponPresenter(CouponContract.DataModel impl) {
public CouponPresenter(CouponImpl impl) {
this.impl = impl;
}

View File

@@ -9,9 +9,9 @@ import com.ckkj.griddle.device.entity.BleScanDevice;
public class BltDeviceListPresenter
extends BasePresenter<BltDeviceListContract.BltDeviceListView> {
private final BltDeviceListContract.DataModel impl;
private final BltDeviceListImpl impl;
public BltDeviceListPresenter(BltDeviceListContract.DataModel impl) {
public BltDeviceListPresenter(BltDeviceListImpl impl) {
this.impl = impl;
}

View File

@@ -35,29 +35,33 @@ public class CheckoutCouponDialog implements View.OnClickListener {
private final OnConfirmListener listener;
public CheckoutCouponDialog(Activity context, List<CheckoutCouponEntity> coupons,
List<String> selectedIds, OnConfirmListener listener) {
List<String> selectedIds, long subtotalCents,
OnConfirmListener listener) {
this.context = context;
this.listener = listener;
// 仅恢复列表中存在的券,避免无效编号影响“不使用优惠券”状态。
for (CheckoutCouponEntity coupon : coupons) {
if (selectedIds != null && selectedIds.contains(coupon.id) && !draftIds.contains(coupon.id)) {
draftIds.add(coupon.id);
if (selectedIds != null && selectedIds.contains(coupon.getId())
&& coupon.isEligible(subtotalCents) && !draftIds.contains(coupon.getId())) {
draftIds.add(coupon.getId());
}
}
dialog = new Dialog(context, R.style.CheckoutCouponDialogStyle);
content = LayoutInflater.from(context).inflate(R.layout.dialog_checkout_coupon, null, false);
dialog.setContentView(content);
dialog.setCanceledOnTouchOutside(true);
adapter = new CheckoutCouponAdapter();
adapter = new CheckoutCouponAdapter(subtotalCents);
RecyclerView list = content.findViewById(R.id.rv_checkout_coupons);
list.setLayoutManager(new LinearLayoutManager(context));
list.setItemAnimator(null);
list.setAdapter(adapter);
adapter.setNewData(new ArrayList<>(coupons));
content.findViewById(R.id.tv_coupon_empty).setVisibility(coupons.isEmpty() ? View.VISIBLE : View.GONE);
adapter.setOnItemClickListener((baseAdapter, view, position) -> {
if (position < 0 || position >= adapter.getData().size()) return;
CheckoutCouponEntity coupon = adapter.getItem(position);
if (coupon == null) return;
if (!draftIds.remove(coupon.id)) draftIds.add(coupon.id);
if (coupon == null || !coupon.isEligible(subtotalCents)) return;
if (!draftIds.remove(coupon.getId())) draftIds.add(coupon.getId());
renderSelection();
});
content.findViewById(R.id.iv_coupon_close).setOnClickListener(this);

View File

@@ -7,10 +7,10 @@ import com.ckkj.griddle.food.entity.ShopGoodsEntity;
/** 美食详情协调层,页面沿用项目现有 MVP 关联方式。 */
public class FoodDetailPresenter extends BasePresenter<FoodDetailContract.DetailView> {
private final FoodDetailContract.DataModel impl;
private final FoodDetailImpl impl;
private int requestVersion;
public FoodDetailPresenter(FoodDetailContract.DataModel impl) {
public FoodDetailPresenter(FoodDetailImpl impl) {
this.impl = impl;
}

View File

@@ -117,7 +117,6 @@ public class MainActivity extends BaseActivity<MainActivityLayoutBinding, MainPr
@Override
public void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
mPresenter.checkNewVersion();
// 清空Fragment列表,避免状态恢复问题
mFragmentList.clear();
mFragmentList.add(new DeviceFragment());

View File

@@ -7,9 +7,9 @@ import java.util.List;
/** 消息中心协调层,加载、单条已读和全部已读共用列表回显。 */
public class MessagePresenter extends BasePresenter<MessageContract.MessageView> {
private final MessageContract.DataModel impl;
private final MessageImpl impl;
public MessagePresenter(MessageContract.DataModel impl) {
public MessagePresenter(MessageImpl impl) {
this.impl = impl;
}

View File

@@ -21,7 +21,6 @@ import com.ckkj.griddle.mine.mvp.MinePresenter;
import com.ckkj.griddle.mine.order.MyOrderActivity;
import com.ckkj.griddle.mine.share.ShareEarningsActivity;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.point.PointsOrderActivity;
import com.ckkj.griddle.review.MyReviewsActivity;
import com.ckkj.griddle.refund.MyRefundActivity;
import com.ckkj.griddle.utils.show.ToastUtil;
@@ -41,8 +40,8 @@ public class MineFragment extends BaseFragment<MineFragmentLayoutBinding, MinePr
return new MinePresenter(new MineImpl());
}
@OnClick({R.id.cv_mine_profile, R.id.ll_mine_devices, R.id.ll_credit_history,
R.id.ll_registration_order, R.id.ll_mine_addresses, R.id.ll_mine_shares,
@OnClick({R.id.cv_mine_profile, R.id.ll_mine_devices, R.id.btn_points_history,
R.id.ll_mine_addresses, R.id.ll_mine_shares,
R.id.ll_mine_repairs, R.id.ll_mine_cart, R.id.ll_mine_orders, R.id.ll_mine_reviews,
R.id.ll_mine_refunds, R.id.ll_mine_coupons, R.id.ll_mine_service})
public void onClick(View v) {
@@ -71,14 +70,10 @@ public class MineFragment extends BaseFragment<MineFragmentLayoutBinding, MinePr
goTo(mContext, MyDevicesActivity.class, null);
break;
case R.id.ll_credit_history:
case R.id.btn_points_history:
goTo(mContext, PointsHistoryActivity.class, null);
break;
case R.id.ll_registration_order:
goTo(mContext, PointsOrderActivity.class, null);
break;
case R.id.ll_mine_addresses:
// 个人中心进入收货地址管理,后续新增和编辑在列表页继续发起。
goTo(mContext, ShippingAddressActivity.class, null);

View File

@@ -2,31 +2,33 @@ package com.ckkj.griddle.mine.entity;
import java.io.Serializable;
/** 自提点信息;展示文案由页面按当前语言解析。 */
/** 自提点接口数据,agentId 为代理商编号,也是选择和下单时使用的自提点 ID。 */
public class PickupPointEntity implements Serializable {
private static final long serialVersionUID = 1L;
private final String id;
private final String name;
private final String englishName;
private final String phone;
private final String address;
private final String englishAddress;
private String agentId;
private String unitName;
private String contactName;
private String contactPhone;
private String address;
public PickupPointEntity(String id, String name, String englishName, String phone,
String address, String englishAddress) {
this.id = id;
this.name = name;
this.englishName = englishName;
this.phone = phone;
this.address = address;
this.englishAddress = englishAddress;
public String getId() {
return agentId;
}
public String getId() { return id; }
/** 保留现有页面调用方式;接口只返回一份门店资料,不再拼装中英文演示数据。 */
public String getName(boolean chinese) {
return unitName == null ? "" : unitName;
}
public String getName(boolean chinese) { return chinese ? name : englishName; }
public String getContactName() {
return contactName == null ? "" : contactName;
}
public String getPhone() { return phone; }
public String getPhone() {
return contactPhone == null ? "" : contactPhone;
}
public String getAddress(boolean chinese) { return chinese ? address : englishAddress; }
public String getAddress(boolean chinese) {
return address == null ? "" : address;
}
}

View File

@@ -20,9 +20,11 @@ public class MineContract {
}
public interface DataModel {
/** 自提点列表,目前沿用设计稿演示数据。 */
/** 获取服务端自提点列表。 */
void getPickupPoints(CallBack<List<PickupPointEntity>> callback);
void cancelPickupPointsRequest();
@Nullable
UserInfoEntity getCachedProfile();

View File

@@ -1,12 +1,19 @@
package com.ckkj.griddle.mine.mvp;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.ckkj.griddle.AppConfig;
import com.ckkj.griddle.MyApplication;
import com.ckkj.griddle.R;
import com.ckkj.griddle.base.entity.UserInfoEntity;
import com.ckkj.griddle.mine.entity.MyDevicesEntity;
import com.ckkj.griddle.mine.entity.PointsHistoryEntity;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.network.NetWorkManager;
import com.ckkj.griddle.utils.AppLanguageUtil;
import com.ckkj.griddle.utils.manager.MingDengUserInfoManager;
import java.util.ArrayList;
@@ -16,18 +23,72 @@ import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.SerialDisposable;
import io.reactivex.schedulers.Schedulers;
/** 读取已缓存的用户资料,后续在此接入新个人中心接口。 */
public class MineImpl implements MineContract.DataModel {
private final SerialDisposable pickupPointsRequest = new SerialDisposable();
@Override
public void getPickupPoints(MineContract.CallBack<List<PickupPointEntity>> callback) {
// 与其他个人中心页面保持一致,演示数据集中在 Model,后续替换为真实接口。
List<PickupPointEntity> points = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
points.add(new PickupPointEntity("demo-pickup-" + i,
"华东优选电器", "Huadong Youxuan Electrical", "+251123981908",
"亚的斯亚贝巴……", "Addis Ababa......"));
try {
NetWorkManager.getRequest().getMallPickupPoints(NetWorkManager.getToken())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean<List<PickupPointEntity>>>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
pickupPointsRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean<List<PickupPointEntity>> response) {
if (response.isSuccess() || response.getCode() == 200) {
callback.success(availablePickupPoints(response.getData()));
} else {
callback.fail(pickupErrorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(pickupErrorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(pickupErrorMessage(exception.getMessage()));
}
callback.success(points);
}
/** 无有效编号的自提点无法选择或用于下单,不加入可用列表。 */
private List<PickupPointEntity> availablePickupPoints(List<PickupPointEntity> points) {
List<PickupPointEntity> available = new ArrayList<>();
if (points == null) return available;
for (PickupPointEntity point : points) {
if (point != null && !TextUtils.isEmpty(point.getId())) available.add(point);
}
return available;
}
private String pickupErrorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext()).getString(R.string.pickup_load_failed)
: message;
}
@Override
public void cancelPickupPointsRequest() {
pickupPointsRequest.set(null);
}
@Override
public void getMyDevices(MineContract.CallBack<MyDevicesEntity> callback) {

View File

@@ -10,6 +10,7 @@ import java.util.List;
/** 个人中心业务协调层。 */
public class MinePresenter extends BasePresenter<MineContract.MineView> {
private final MineImpl impl;
private int pickupRequestVersion;
public MinePresenter(MineImpl impl) {
this.impl = impl;
@@ -22,19 +23,36 @@ public class MinePresenter extends BasePresenter<MineContract.MineView> {
}
public void getPickupPoints() {
final int requestVersion = ++pickupRequestVersion;
impl.cancelPickupPointsRequest();
impl.getPickupPoints(new MineContract.CallBack<List<PickupPointEntity>>() {
@Override
public void success(List<PickupPointEntity> points) {
if (getView() != null) getView().getPickupPointsSuccess(points);
if (getView() != null && requestVersion == pickupRequestVersion) {
getView().getPickupPointsSuccess(points);
}
}
@Override
public void fail(String message) {
if (getView() != null) getView().showError(message);
if (getView() != null && requestVersion == pickupRequestVersion) {
getView().showError(message);
}
}
});
}
public void cancelPickupPointsRequest() {
pickupRequestVersion++;
impl.cancelPickupPointsRequest();
}
@Override
public void onDestroy() {
cancelPickupPointsRequest();
super.onDestroy();
}
public void getMyDevices() {
impl.getMyDevices(new MineContract.CallBack<MyDevicesEntity>() {
@Override

View File

@@ -8,9 +8,9 @@ import java.util.List;
/** 订单筛选交由数据层处理,页面只负责状态及列表展示。 */
public class MyOrderPresenter extends BasePresenter<MyOrderContract.MyOrderView> {
private final MyOrderContract.DataModel impl;
private final MyOrderImpl impl;
public MyOrderPresenter(MyOrderContract.DataModel impl) {
public MyOrderPresenter(MyOrderImpl impl) {
this.impl = impl;
}

View File

@@ -44,6 +44,8 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
private final List<PickupPointEntity> points = new ArrayList<>();
private PickupPointAdapter adapter;
private String selectedId;
private boolean loading;
private boolean viewReady;
@Override
public MinePresenter createPresenter() {
@@ -52,12 +54,13 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
@Override
public int getLayoutResId(Bundle savedInstanceState) {
return 0;
return R.layout.pickup_manage_layout;
}
@Override
public void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
viewReady = true;
// 边到边显示时状态栏可能透明,根布局与标题栏同时使用白色,避免透出列表灰底。
ImmersionBar.with(this)
.statusBarColor(R.color.pickup_header_background)
@@ -97,10 +100,18 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
if (savedInstanceState != null) {
viewBinding.edPickupSearch.setText(savedInstanceState.getString(STATE_QUERY, ""));
}
loadPickupPoints();
}
private void loadPickupPoints() {
if (!viewReady || loading) return;
loading = true;
viewBinding.progressPickupPoints.setVisibility(View.VISIBLE);
viewBinding.tvPickupEmpty.setVisibility(View.GONE);
mPresenter.getPickupPoints();
}
@OnClick({R.id.iv_pickup_back, R.id.iv_pickup_search})
@OnClick({R.id.iv_pickup_back, R.id.iv_pickup_search, R.id.tv_pickup_empty})
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_pickup_back:
@@ -111,6 +122,10 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
searchPoints();
break;
case R.id.tv_pickup_empty:
loadPickupPoints();
break;
default:
break;
}
@@ -125,19 +140,22 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
viewBinding.edPickupSearch.clearFocus();
}
/** 搜索中英文门店名称、电话或地址,清空关键词即可恢复完整列表。 */
/** 在已请求的真实列表中搜索门店、联系人、电话或地址,清空关键词恢复完整列表。 */
private void filterPoints() {
String query = viewBinding.edPickupSearch.getText().toString().trim()
.toLowerCase(Locale.ROOT);
List<PickupPointEntity> filtered = new ArrayList<>();
for (PickupPointEntity point : points) {
String text = point.getName(true) + " " + point.getName(false) + " "
+ point.getPhone() + " " + point.getAddress(true) + " " + point.getAddress(false);
String text = point.getName(false) + " " + point.getContactName() + " "
+ point.getPhone() + " " + point.getAddress(false);
if (text.toLowerCase(Locale.ROOT).contains(query)) filtered.add(point);
}
adapter.setNewData(filtered);
adapter.setSelectedId(selectedId);
viewBinding.tvPickupEmpty.setVisibility(filtered.isEmpty() ? View.VISIBLE : View.GONE);
viewBinding.tvPickupEmpty.setText(points.isEmpty()
? R.string.pickup_no_points : R.string.pickup_empty);
viewBinding.tvPickupEmpty.setVisibility(!loading && filtered.isEmpty()
? View.VISIBLE : View.GONE);
}
private void selectPoint(PickupPointEntity point) {
@@ -152,17 +170,27 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
// 同时返回完整门店信息,原有只读取 ID、名称的调用方无需修改。
result.putExtra(EXTRA_POINT, point);
setResult(RESULT_OK, result);
// 购物车以选择模式进入时返回选中门店;独立管理模式仅更新选中边框。
// 商品详情和结算页以选择模式进入,点选即返回;独立管理模式仍只更新选中边框。
if (getIntent().getBooleanExtra(EXTRA_PICKER_MODE, false)) finish();
}
@Override
public void getPickupPointsSuccess(List<PickupPointEntity> data) {
if (!viewReady) return;
loading = false;
viewBinding.progressPickupPoints.setVisibility(View.GONE);
points.clear();
if (data != null) points.addAll(data);
// 未传入选择时沿用原稿第二项的演示选中状态,不覆盖用户已作出的选择。
if (TextUtils.isEmpty(selectedId) && !points.isEmpty()) {
selectedId = points.get(Math.min(1, points.size() - 1)).getId();
// 保留仍然有效的选中 ID;未选择或原自提点已移除时默认第一条。
boolean selectionExists = false;
for (PickupPointEntity point : points) {
if (TextUtils.equals(selectedId, point.getId())) {
selectionExists = true;
break;
}
}
if (!selectionExists) {
selectedId = points.isEmpty() ? null : points.get(0).getId();
}
filterPoints();
}
@@ -176,12 +204,27 @@ public class PickupManageActivity extends BaseActivity<PickupManageLayoutBinding
@Override
public void showError(String message) {
hideDialogLoading();
if (!TextUtils.isEmpty(message)) ToastUtil.showShort(mContext, message);
if (!viewReady) return;
loading = false;
viewBinding.progressPickupPoints.setVisibility(View.GONE);
if (points.isEmpty()) {
viewBinding.tvPickupEmpty.setText(R.string.pickup_retry);
viewBinding.tvPickupEmpty.setVisibility(View.VISIBLE);
}
ToastUtil.showShort(mContext, TextUtils.isEmpty(message)
? getString(R.string.pickup_load_failed) : message);
}
@Override
public void logOut(BaseBean bean) {
// 登录失效沿用父类统一处理。
}
@Override
protected void onDestroy() {
viewReady = false;
mPresenter.cancelPickupPointsRequest();
viewBinding.rvPickupPoints.setAdapter(null);
super.onDestroy();
}
}

View File

@@ -3,12 +3,17 @@ package com.ckkj.griddle.network;
import com.ckkj.griddle.base.entity.MineUserInfoBean;
import com.ckkj.griddle.cart.entity.CheckoutCouponEntity;
import com.ckkj.griddle.cart.entity.MallCartItemEntity;
import com.ckkj.griddle.login.entity.LoginEntity;
import com.ckkj.griddle.main.entity.CheckVersionEntity;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.food.entity.ShopBannerEntity;
import com.ckkj.griddle.food.entity.ShopCategoryEntity;
import com.ckkj.griddle.food.entity.ShopGoodsPageEntity;
import com.ckkj.griddle.food.entity.FoodDetailEntity;
import com.ckkj.griddle.shop.entity.MallGoodsDetailEntity;
import com.ckkj.griddle.shop.entity.MallGoodsPageEntity;
import java.util.List;
import java.util.Map;
@@ -16,9 +21,12 @@ import java.util.Map;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.HeaderMap;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
@@ -89,4 +97,62 @@ public interface Request {
Observable<BaseBean<FoodDetailEntity>> getFoodDetail(
@HeaderMap Map<String, String> headMap, @Path("id") String id);
/***************************钱包********************************/
/** 商城商品分页列表;data 为 {total, rows}。不传 sort、categoryId 时使用服务端默认排序查询全部商品。 */
@GET("app/mall/goods")
Observable<BaseBean<MallGoodsPageEntity>> getMallGoods(
@HeaderMap Map<String, String> headMap,
@Query("page") int page, @Query("size") int size);
/** 使用列表返回的真实商品编号获取详情。 */
@GET("app/mall/goods/{id}")
Observable<BaseBean<MallGoodsDetailEntity>> getMallGoodsDetail(
@HeaderMap Map<String, String> headMap, @Path("id") String id);
/** 加入购物车;同一商品规格由服务端累加购买数量。 */
@POST("app/cart/cart")
Observable<BaseBean> addMallGoodsToCart(
@HeaderMap Map<String, String> headMap, @Body RequestBody requestBody);
/** 当前登录账号的购物车商品。 */
@GET("app/cart/cart")
Observable<BaseBean<List<MallCartItemEntity>>> getMallCart(
@HeaderMap Map<String, String> headMap);
/** 修改单条购物车的数量或选中状态;传 null 的查询参数不会修改。 */
@PUT("app/cart/cart/{id}")
Observable<BaseBean> updateMallCartItem(
@HeaderMap Map<String, String> headMap,
@Path("id") String id,
@Query("num") Integer num,
@Query("selected") Integer selected);
/** 删除指定购物车记录。 */
@DELETE("app/cart/cart/{id}")
Observable<BaseBean> deleteMallCartItem(
@HeaderMap Map<String, String> headMap, @Path("id") String id);
/**
* 清空购物车;请求体为待清除的购物车记录编号数组。
* Retrofit 的 @DELETE 声明的请求不带 body,挂 @Body 会在调用时抛
* "Non-body HTTP method cannot contain @Body",因此改用 @HTTP 显式声明 hasBody。
*/
@HTTP(method = "DELETE", path = "app/cart/cart", hasBody = true)
Observable<BaseBean> clearMallCart(
@HeaderMap Map<String, String> headMap, @Body RequestBody requestBody);
/** 修改当前账号购物车中全部商品的选中状态。 */
@PUT("app/cart/cart/select-all")
Observable<BaseBean> selectAllMallCartItems(
@HeaderMap Map<String, String> headMap, @Query("selected") int selected);
/** 全部自提点,无分页参数;详情预览与自提点列表共用。 */
@GET("app/mall/pickup-points")
Observable<BaseBean<List<PickupPointEntity>>> getMallPickupPoints(
@HeaderMap Map<String, String> headMap);
/** 当前登录账号可用的优惠券,结算选择使用返回的 recordId。 */
@GET("app/mall/coupons")
Observable<BaseBean<List<CheckoutCouponEntity>>> getMallCoupons(
@HeaderMap Map<String, String> headMap);
}

View File

@@ -8,9 +8,9 @@ import java.util.List;
/** 退款协调层:转交筛选、取消申请及结果回调。 */
public class RefundPresenter extends BasePresenter<RefundContract.RefundView> {
private final RefundContract.DataModel impl;
private final RefundImpl impl;
public RefundPresenter(RefundContract.DataModel impl) {
public RefundPresenter(RefundImpl impl) {
this.impl = impl;
}

View File

@@ -10,9 +10,9 @@ import java.util.List;
/** 评价协调层:加载当前订单,统一转交评价草稿及校验结果。 */
public class ReviewPresenter extends BasePresenter<ReviewContract.ReviewView> {
public static final int MAX_IMAGE_COUNT = 6;
private final ReviewContract.DataModel impl;
private final ReviewImpl impl;
public ReviewPresenter(ReviewContract.DataModel impl) {
public ReviewPresenter(ReviewImpl impl) {
this.impl = impl;
}

View File

@@ -10,6 +10,8 @@ import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.core.widget.ImageViewCompat;
import androidx.viewpager2.widget.ViewPager2;
@@ -17,14 +19,15 @@ import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.ckkj.griddle.R;
import com.ckkj.griddle.base.BaseActivity;
import com.ckkj.griddle.base.BaseFragment;
import com.ckkj.griddle.cart.CartManageActivity;
import com.ckkj.griddle.cart.CheckoutActivity;
import com.ckkj.griddle.cart.entity.CartGoodsEntity;
import com.ckkj.griddle.databinding.ShopProductDetailLayoutBinding;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.mine.pickup.PickupManageActivity;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.shop.adapter.ProductImageAdapter;
import com.ckkj.griddle.shop.entity.ProductEntity;
import com.ckkj.griddle.shop.entity.MallGoodsDetailEntity;
import com.ckkj.griddle.shop.mvp.ShopContract;
import com.ckkj.griddle.shop.mvp.ShopImpl;
import com.ckkj.griddle.shop.mvp.ShopPresenter;
@@ -32,19 +35,42 @@ import com.ckkj.griddle.utils.show.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;
import java.util.ArrayList;
import java.util.List;
import butterknife.OnClick;
/** 商品详情:图片、商品说明和店铺信息共用一页,底部关联现有购物车及下单流程。 */
/** 商品详情使用真实商品数据展示,底部保留现有购物车及下单页面入口。 */
public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutBinding, ShopPresenter>
implements ShopContract.DetailView {
private static final String EXTRA_PRODUCT_ID = "shop_product_id";
private static final String STATE_IMAGE_INDEX = "shop_image_index";
private static final String STATE_PICKUP = "shop_selected_pickup";
private static final String STATE_PICKUP_CHOSEN = "shop_pickup_chosen";
private ProductEntity product;
private MallGoodsDetailEntity product;
private PickupPointEntity selectedPickupPoint;
private boolean pickupChosenByUser;
private boolean loading;
private boolean addingToCart;
private boolean viewReady;
private int imageCount;
private int restoredImageIndex;
private boolean toolbarCollapsed;
private final ActivityResultLauncher<Intent> pickupLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() != RESULT_OK || result.getData() == null) return;
Object value = result.getData().getSerializableExtra(PickupManageActivity.EXTRA_POINT);
if (!(value instanceof PickupPointEntity)) return;
PickupPointEntity point = (PickupPointEntity) value;
if (TextUtils.isEmpty(point.getId())) return;
selectedPickupPoint = point;
pickupChosenByUser = true;
// 用户选择优先,取消尚未结束的默认列表请求,避免回调覆盖新选择。
mPresenter.cancelPickupPointsRequest();
renderPickupPoint();
});
private final ViewPager2.OnPageChangeCallback imageCallback =
new ViewPager2.OnPageChangeCallback() {
@Override
@@ -72,6 +98,7 @@ public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutB
@Override
public void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
viewReady = true;
// 状态栏和标题栏覆盖在主图上;滚动离开主图后同步切换为白底深色文字。
ImmersionBar.with(this)
.transparentStatusBar()
@@ -81,53 +108,132 @@ public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutB
.init();
restoredImageIndex = savedInstanceState == null ? 0
: savedInstanceState.getInt(STATE_IMAGE_INDEX, 0);
if (savedInstanceState != null) {
selectedPickupPoint = (PickupPointEntity) savedInstanceState.getSerializable(STATE_PICKUP);
pickupChosenByUser = savedInstanceState.getBoolean(STATE_PICKUP_CHOSEN, false);
}
viewBinding.vpShopProductImages.registerOnPageChangeCallback(imageCallback);
viewBinding.scrollShopDetail.setOnScrollChangeListener(
(androidx.core.widget.NestedScrollView.OnScrollChangeListener)
(v, scrollX, scrollY, oldScrollX, oldScrollY) -> updateToolbar(scrollY));
loadProduct();
if (selectedPickupPoint != null) {
renderPickupPoint();
}
if (!pickupChosenByUser || selectedPickupPoint == null) {
mPresenter.getPickupPoints();
}
}
private void loadProduct() {
if (loading) return;
loading = true;
setProductActionsEnabled(false);
viewBinding.tvShopDetailState.setVisibility(View.GONE);
viewBinding.scrollShopDetail.setVisibility(View.GONE);
viewBinding.progressShopDetail.setVisibility(View.VISIBLE);
renderToolbar(true);
mPresenter.getProduct(getIntent().getStringExtra(EXTRA_PRODUCT_ID));
}
@Override
public void showProduct(ProductEntity data) {
public void showProduct(MallGoodsDetailEntity data) {
if (!viewReady) return;
if (data == null) {
showError(null);
return;
}
product = data;
viewBinding.tvShopDetailName.setText(data.nameRes);
viewBinding.tvShopDetailPrice.setText(ShopPriceFormatter.format(this, data.cashCents));
viewBinding.tvShopDetailSold.setText(getString(R.string.shop_mall_sold, data.sold));
viewBinding.tvShopDetailDescription.setText(data.descriptionRes);
int[] images = data.getImages();
loading = false;
viewBinding.progressShopDetail.setVisibility(View.GONE);
viewBinding.tvShopDetailName.setText(data.getGoodsName());
viewBinding.tvShopDetailPrice.setText(ShopPriceFormatter.format(this, data.getSalePrice()));
viewBinding.tvShopDetailSold.setText(getString(R.string.shop_mall_sold, data.getSalesVolume()));
String description = data.getGoodsDesc();
viewBinding.tvShopDetailDescription.setText(TextUtils.isEmpty(description)
? getString(R.string.shop_mall_description_empty) : description);
List<String> images = data.getImages();
imageCount = images.size();
viewBinding.vpShopProductImages.setAdapter(new ProductImageAdapter(Glide.with(this), images));
int page = Math.max(0, Math.min(restoredImageIndex, images.length - 1));
int page = Math.max(0, Math.min(restoredImageIndex, images.size() - 1));
viewBinding.vpShopProductImages.setCurrentItem(page, false);
renderImageCounter(page);
viewBinding.tvShopDetailState.setVisibility(View.GONE);
viewBinding.scrollShopDetail.setVisibility(View.VISIBLE);
setProductActionsEnabled(true);
viewBinding.scrollShopDetail.post(() -> updateToolbar(viewBinding.scrollShopDetail.getScrollY()));
setProductActionsEnabled(data.getStockNum() > 0);
viewBinding.scrollShopDetail.post(() -> {
if (viewReady) {
updateToolbar(viewBinding.scrollShopDetail.getScrollY());
}
});
}
private void renderImageCounter(int position) {
if (product == null) return;
viewBinding.tvShopImageCounter.setVisibility(imageCount == 0 ? View.GONE : View.VISIBLE);
if (imageCount == 0) return;
viewBinding.tvShopImageCounter.setText(getString(R.string.shop_mall_image_counter,
position + 1, product.getImages().length));
position + 1, imageCount));
}
@Override
public void showPickupPoints(List<PickupPointEntity> points) {
if (!viewReady) return;
// 尚未手动选择时默认第一条;选择返回后不再被默认数据覆盖。
if (!pickupChosenByUser) {
selectedPickupPoint = points == null || points.isEmpty() ? null : points.get(0);
}
renderPickupPoint();
}
private void renderPickupPoint() {
if (!viewReady) return;
if (selectedPickupPoint == null) {
viewBinding.llShopStore.setVisibility(View.GONE);
viewBinding.tvShopStoreState.setText(R.string.pickup_no_points);
viewBinding.tvShopStoreState.setVisibility(View.VISIBLE);
return;
}
viewBinding.tvShopStoreState.setVisibility(View.GONE);
viewBinding.llShopStore.setVisibility(View.VISIBLE);
viewBinding.tvShopStoreName.setText(selectedPickupPoint.getName(false));
viewBinding.tvShopStorePhone.setText(selectedPickupPoint.getPhone());
viewBinding.llShopStorePhone.setVisibility(TextUtils.isEmpty(selectedPickupPoint.getPhone())
? View.GONE : View.VISIBLE);
viewBinding.tvShopStoreAddress.setText(selectedPickupPoint.getAddress(false));
}
@Override
public void showPickupPointsError(String message) {
if (!viewReady) return;
if (selectedPickupPoint != null) {
renderPickupPoint();
return;
}
viewBinding.llShopStore.setVisibility(View.GONE);
viewBinding.tvShopStoreState.setText(R.string.shop_mall_pickup_failed);
viewBinding.tvShopStoreState.setVisibility(View.VISIBLE);
}
private void setProductActionsEnabled(boolean enabled) {
viewBinding.tvShopAddCart.setEnabled(enabled);
viewBinding.tvShopAddCart.setEnabled(enabled && !addingToCart);
viewBinding.tvShopBuyNow.setEnabled(enabled);
viewBinding.tvShopAddCart.setAlpha(enabled ? 1f : 0.5f);
viewBinding.tvShopAddCart.setAlpha(enabled && !addingToCart ? 1f : 0.5f);
viewBinding.tvShopBuyNow.setAlpha(enabled ? 1f : 0.5f);
viewBinding.tvShopAddCart.setText(addingToCart
? R.string.shop_mall_adding_cart : R.string.shop_mall_add_cart);
}
private void updateToolbar(int scrollY) {
boolean collapsed = viewBinding.shopDetailHero.getHeight() > 0
&& scrollY >= viewBinding.shopDetailHero.getHeight() - viewBinding.shopDetailToolbar.getHeight();
boolean collapsed = imageCount == 0 || (viewBinding.shopDetailHero.getHeight() > 0
&& scrollY >= viewBinding.shopDetailHero.getHeight()
- viewBinding.shopDetailToolbar.getHeight());
if (toolbarCollapsed == collapsed) return;
renderToolbar(collapsed);
}
/** 加载、失败和无图时使用白底;有主图时继续保留原来的透明标题栏。 */
private void renderToolbar(boolean collapsed) {
toolbarCollapsed = collapsed;
int foreground = collapsed ? ContextCompat.getColor(this, R.color.shop_mall_text) : Color.WHITE;
viewBinding.shopDetailToolbar.setBackgroundColor(collapsed ? Color.WHITE : Color.TRANSPARENT);
@@ -137,7 +243,8 @@ public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutB
}
@OnClick({R.id.iv_shop_detail_back, R.id.ll_shop_detail_cart, R.id.tv_shop_add_cart,
R.id.tv_shop_buy_now, R.id.ll_shop_store, R.id.ll_shop_store_phone, R.id.tv_shop_detail_state})
R.id.tv_shop_buy_now, R.id.tv_shop_detail_state, R.id.ll_shop_store_section,
R.id.ll_shop_store, R.id.tv_shop_store_state, R.id.ll_shop_store_phone})
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_shop_detail_back:
@@ -152,82 +259,109 @@ public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutB
case R.id.tv_shop_buy_now:
buyNow();
break;
case R.id.ll_shop_store_phone:
dialStore();
break;
case R.id.ll_shop_store:
showStoreInfo();
break;
case R.id.tv_shop_detail_state:
mPresenter.getProduct(getIntent().getStringExtra(EXTRA_PRODUCT_ID));
loadProduct();
break;
case R.id.ll_shop_store_section:
case R.id.ll_shop_store:
case R.id.tv_shop_store_state:
openPickupPoints();
break;
case R.id.ll_shop_store_phone:
dialPickupPoint();
break;
default:
break;
}
}
/** 本地演示阶段将所选商品传入购物车,正式加购接口联调时替换此入口。 */
private void addToCart() {
if (product == null) return;
private void openPickupPoints() {
Bundle bundle = new Bundle();
bundle.putSerializable(CartManageActivity.EXTRA_ADD_GOODS, product.toCartGoods());
goTo(mContext, CartManageActivity.class, bundle);
bundle.putBoolean(PickupManageActivity.EXTRA_PICKER_MODE, true);
if (selectedPickupPoint != null) {
bundle.putString(PickupManageActivity.EXTRA_SELECTED_ID, selectedPickupPoint.getId());
}
// 列表页进入后自行请求完整自提点列表,不依赖详情页缓存。
goTo(mContext, PickupManageActivity.class, bundle, pickupLauncher);
}
private void dialPickupPoint() {
if (selectedPickupPoint == null || TextUtils.isEmpty(selectedPickupPoint.getPhone())) return;
try {
startActivity(new Intent(Intent.ACTION_DIAL,
Uri.fromParts("tel", selectedPickupPoint.getPhone(), null)));
} catch (ActivityNotFoundException exception) {
ToastUtil.showShort(mContext, getString(R.string.pickup_no_dialer));
}
}
/** 当前页面尚未提供规格选择,默认加入第一条有库存的真实 SKU。 */
private void addToCart() {
if (product == null || loading || addingToCart || product.getStockNum() <= 0) return;
MallGoodsDetailEntity.SpecEntity sku = null;
for (MallGoodsDetailEntity.SpecEntity item : product.getSpecs()) {
if (item != null && !TextUtils.isEmpty(item.getId()) && item.getStock() > 0) {
sku = item;
break;
}
}
if (sku == null) {
ToastUtil.showShort(mContext, getString(R.string.shop_mall_no_available_sku));
return;
}
addingToCart = true;
setProductActionsEnabled(true);
mPresenter.addToCart(product.getId(), sku.getId(), 1);
}
@Override
public void onAddToCartSuccess() {
if (!viewReady) return;
addingToCart = false;
setProductActionsEnabled(product != null && product.getStockNum() > 0);
ToastUtil.showShort(mContext, getString(R.string.shop_mall_add_cart_success));
}
@Override
public void onAddToCartError(String message) {
if (!viewReady) return;
addingToCart = false;
setProductActionsEnabled(product != null && product.getStockNum() > 0);
ToastUtil.showShort(mContext, TextUtils.isEmpty(message)
? getString(R.string.shop_mall_add_cart_failed) : message);
}
private void buyNow() {
if (product == null) return;
CartGoodsEntity item = createCartGoods();
if (item == null) return;
ArrayList<CartGoodsEntity> goods = new ArrayList<>();
goods.add(product.toCartGoods());
goods.add(item);
Bundle bundle = new Bundle();
bundle.putSerializable(CheckoutActivity.EXTRA_GOODS, goods);
goTo(mContext, CheckoutActivity.class, bundle);
}
private void dialStore() {
// 调起系统拨号盘,不直接拨打,因此无需申请电话权限。
private CartGoodsEntity createCartGoods() {
if (product == null || loading || product.getStockNum() <= 0) return null;
try {
startActivity(new Intent(Intent.ACTION_DIAL,
Uri.fromParts("tel", getString(R.string.shop_mall_store_phone), null)));
} catch (ActivityNotFoundException e) {
ToastUtil.showShort(mContext, getString(R.string.shop_mall_no_dialer));
return product.toCartGoods();
} catch (ArithmeticException exception) {
ToastUtil.showShort(mContext, getString(R.string.shop_mall_amount_invalid));
return null;
}
}
private void showStoreInfo() {
if (dialog != null && dialog.isShowing()) return;
String content = getString(R.string.shop_mall_store_name) + "\n"
+ getString(R.string.shop_mall_store_phone) + "\n"
+ getString(R.string.shop_mall_store_address);
showDialogtext(null, false, false, false,
getString(R.string.shop_mall_store_title), content,
getString(android.R.string.cancel), getString(R.string.shop_mall_call),
new BaseFragment.OnDialogClick() {
@Override
public void onCancelClick() {
// 关闭后继续浏览商品。
}
@Override
public void onConfirmClick() {
dialStore();
}
});
}
@Override
public void showError(String message) {
if (!viewReady) return;
loading = false;
viewBinding.progressShopDetail.setVisibility(View.GONE);
setProductActionsEnabled(false);
viewBinding.scrollShopDetail.setVisibility(View.GONE);
viewBinding.tvShopDetailState.setText(TextUtils.isEmpty(message)
? getString(R.string.shop_mall_detail_failed) : message);
viewBinding.tvShopDetailState.setVisibility(View.VISIBLE);
// 异常页面没有主图承托标题,使用同一白色背景保证可读性。
toolbarCollapsed = true;
viewBinding.shopDetailToolbar.setBackgroundColor(Color.WHITE);
viewBinding.tvShopDetailTitle.setTextColor(ContextCompat.getColor(this, R.color.shop_mall_text));
ImageViewCompat.setImageTintList(viewBinding.ivShopDetailBack,
ColorStateList.valueOf(ContextCompat.getColor(this, R.color.shop_mall_text)));
ImmersionBar.with(this).statusBarDarkFont(true).init();
renderToolbar(true);
}
@Override
@@ -238,11 +372,17 @@ public class ProductDetailActivity extends BaseActivity<ShopProductDetailLayoutB
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
outState.putInt(STATE_IMAGE_INDEX, viewBinding.vpShopProductImages.getCurrentItem());
outState.putSerializable(STATE_PICKUP, selectedPickupPoint);
outState.putBoolean(STATE_PICKUP_CHOSEN, pickupChosenByUser);
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
viewReady = false;
mPresenter.cancelProductRequest();
mPresenter.cancelPickupPointsRequest();
mPresenter.cancelAddToCartRequest();
viewBinding.vpShopProductImages.unregisterOnPageChangeCallback(imageCallback);
viewBinding.vpShopProductImages.setAdapter(null);
viewBinding.scrollShopDetail.setOnScrollChangeListener(

View File

@@ -11,25 +11,35 @@ import androidx.recyclerview.widget.RecyclerView;
import com.ckkj.griddle.R;
import com.ckkj.griddle.base.BaseFragment;
import com.ckkj.griddle.custom.view.CustomRefreshHeader;
import com.ckkj.griddle.databinding.ShopMallFragmentBinding;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.shop.adapter.ShopProductAdapter;
import com.ckkj.griddle.shop.entity.ProductEntity;
import com.ckkj.griddle.shop.entity.MallGoodsEntity;
import com.ckkj.griddle.shop.entity.MallGoodsPageEntity;
import com.ckkj.griddle.shop.mvp.ShopContract;
import com.ckkj.griddle.shop.mvp.ShopImpl;
import com.ckkj.griddle.shop.mvp.ShopPresenter;
import com.ckkj.griddle.utils.show.ToastUtil;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import java.util.ArrayList;
import java.util.List;
import butterknife.OnClick;
/** 主页面商城入口,与美食模块分离;普通手机三列,宽窗口按可用宽度增加列数。 */
public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPresenter>
implements ShopContract.ListView {
private static final int PAGE_SIZE = 20;
private ShopProductAdapter adapter;
private GridLayoutManager layoutManager;
private boolean viewReady;
/** 仅成功后推进页码,失败重试不会跳过当前页。 */
private int loadedPage;
private int requestingPage;
private boolean loading;
private boolean noMoreData;
private final View.OnLayoutChangeListener widthListener =
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
@@ -44,6 +54,10 @@ public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPres
@Override
public void initData(Bundle savedInstanceState) {
viewReady = true;
loadedPage = 0;
requestingPage = 0;
loading = false;
noMoreData = false;
adapter = new ShopProductAdapter();
layoutManager = new GridLayoutManager(mContext, 3);
viewBinding.rvShopProducts.setLayoutManager(layoutManager);
@@ -66,7 +80,48 @@ public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPres
});
adapter.setOnItemClickListener((baseAdapter, view, position) -> openProduct(position));
adapter.setOnItemChildClickListener((baseAdapter, view, position) -> openProduct(position));
mPresenter.getProducts();
initRefresh();
requestProducts(1);
}
private void initRefresh() {
viewBinding.refreshShopProducts.setRefreshHeader(new CustomRefreshHeader(mContext));
viewBinding.refreshShopProducts.setRefreshFooter(new ClassicsFooter(mContext));
viewBinding.refreshShopProducts.setEnableLoadMore(false);
viewBinding.refreshShopProducts.setOnRefreshListener(refreshLayout -> {
if (loading && requestingPage == 1) {
refreshLayout.finishRefresh();
return;
}
// 刷新优先于分页,取消旧分页并使其回调失效。
if (loading) {
mPresenter.cancelProductsRequest();
viewBinding.refreshShopProducts.finishLoadMore();
}
requestProducts(1);
});
viewBinding.refreshShopProducts.setOnLoadMoreListener(refreshLayout -> {
if (!loading && !noMoreData) {
requestProducts(loadedPage + 1);
} else {
refreshLayout.finishLoadMore();
}
});
}
/** 列表按服务端默认排序查询全部商品,页面不额外传 sort 或 categoryId。 */
private void requestProducts(int page) {
if (!viewReady) return;
loading = true;
requestingPage = page;
viewBinding.tvShopMallState.setVisibility(View.GONE);
if (page == 1) {
viewBinding.refreshShopProducts.setEnableLoadMore(false);
viewBinding.refreshShopProducts.setNoMoreData(false);
}
viewBinding.progressShopProducts.setVisibility(
adapter.getData().isEmpty() ? View.VISIBLE : View.GONE);
mPresenter.getProducts(page, PAGE_SIZE);
}
/** 按列表实际宽度计算,折叠屏、分屏和旋转后重新排版,不依赖物理屏幕宽度。 */
@@ -87,25 +142,51 @@ public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPres
private void openProduct(int position) {
if (position < 0 || position >= adapter.getData().size()) return;
ProductEntity product = adapter.getItem(position);
if (product != null) {
goTo(mContext, ProductDetailActivity.class, ProductDetailActivity.createBundle(product.id));
MallGoodsEntity product = adapter.getItem(position);
if (product != null && !TextUtils.isEmpty(product.getId())) {
goTo(mContext, ProductDetailActivity.class,
ProductDetailActivity.createBundle(product.getId()));
}
}
@Override
public void showProducts(List<ProductEntity> products) {
public void showProducts(MallGoodsPageEntity products) {
if (!viewReady) return;
adapter.setNewData(products == null ? new ArrayList<>() : new ArrayList<>(products));
MallGoodsPageEntity result = products == null
? new MallGoodsPageEntity(null, null) : products;
if (requestingPage == 1) {
adapter.setNewData(new ArrayList<>(result.getRows()));
viewBinding.rvShopProducts.scrollToPosition(0);
} else {
adapter.addData(result.getRows());
}
loadedPage = requestingPage;
noMoreData = !result.hasMore(adapter.getData().size(), PAGE_SIZE);
viewBinding.tvShopMallState.setText(R.string.shop_mall_empty);
viewBinding.tvShopMallState.setVisibility(adapter.getData().isEmpty() ? View.VISIBLE : View.GONE);
}
@Override
public void onProductsRequestFinished(boolean success) {
if (!viewReady) return;
loading = false;
viewBinding.progressShopProducts.setVisibility(View.GONE);
if (requestingPage == 1) {
viewBinding.refreshShopProducts.finishRefresh(success);
} else {
viewBinding.refreshShopProducts.finishLoadMore(success);
}
viewBinding.refreshShopProducts.setEnableLoadMore(!adapter.getData().isEmpty());
viewBinding.refreshShopProducts.setNoMoreData(noMoreData);
}
@OnClick(R.id.tv_shop_mall_state)
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_shop_mall_state:
mPresenter.getProducts();
if (!loading) {
requestProducts(1);
}
break;
default:
break;
@@ -115,14 +196,18 @@ public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPres
@Override
public void showError(String message) {
if (!viewReady) return;
viewBinding.tvShopMallState.setText(TextUtils.isEmpty(message)
// 首屏错误提供点击重试;刷新或分页失败不覆盖已有商品。
if (adapter.getData().isEmpty()) {
viewBinding.tvShopMallState.setText(R.string.shop_mall_load_failed);
viewBinding.tvShopMallState.setVisibility(View.VISIBLE);
}
ToastUtil.showShort(mContext, TextUtils.isEmpty(message)
? getString(R.string.shop_mall_load_failed) : message);
viewBinding.tvShopMallState.setVisibility(View.VISIBLE);
}
@Override
public void onNetChange(int netModel) {
// 模拟阶段不因网络变化重新加载,避免打断列表浏览。
// 不打断用户浏览,网络恢复后可手动下拉刷新或点击重试。
}
@Override
@@ -133,6 +218,8 @@ public class ShopFragment extends BaseFragment<ShopMallFragmentBinding, ShopPres
@Override
public void onDestroyView() {
viewReady = false;
loading = false;
mPresenter.cancelProductsRequest();
viewBinding.rvShopProducts.removeOnLayoutChangeListener(widthListener);
viewBinding.rvShopProducts.setAdapter(null);
super.onDestroyView();

View File

@@ -12,11 +12,16 @@ public final class ShopPriceFormatter {
private ShopPriceFormatter() { }
public static String format(Context context, long cashCents) {
return format(context, BigDecimal.valueOf(cashCents, 2));
}
/** 接口商品售价使用金额值,避免误按分单位再除以 100。 */
public static String format(Context context, BigDecimal amount) {
NumberFormat format = NumberFormat.getNumberInstance(
context.getResources().getConfiguration().getLocales().get(0));
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
return context.getString(R.string.shop_mall_price,
format.format(BigDecimal.valueOf(cashCents, 2)));
format.format(amount == null ? BigDecimal.ZERO : amount));
}
}

View File

@@ -11,15 +11,19 @@ import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.RequestManager;
import com.ckkj.griddle.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** 详情图片轮播,页数来自真实图片集合,不固定显示设计稿中的五张。 */
public class ProductImageAdapter extends RecyclerView.Adapter<ProductImageAdapter.ImageHolder> {
private final RequestManager requestManager;
private final int[] images;
private final List<String> images;
public ProductImageAdapter(@NonNull RequestManager requestManager, int[] images) {
public ProductImageAdapter(@NonNull RequestManager requestManager, List<String> images) {
// 由页面在生命周期有效时传入,加载和回收始终复用同一个请求管理器。
this.requestManager = requestManager;
this.images = images.clone();
this.images = images == null ? Collections.emptyList() : new ArrayList<>(images);
}
@NonNull
@@ -32,13 +36,19 @@ public class ProductImageAdapter extends RecyclerView.Adapter<ProductImageAdapte
@Override
public void onBindViewHolder(@NonNull ImageHolder holder, int position) {
holder.image.setContentDescription(holder.itemView.getContext()
.getString(R.string.shop_mall_image_description, position + 1, images.length));
requestManager.load(images[position]).centerCrop().into(holder.image);
.getString(R.string.shop_mall_image_description, position + 1, getItemCount()));
// 无图时保留主图区域的中性占位,不显示虚构的商品照片。
requestManager.load(images.isEmpty() ? null : images.get(position))
.placeholder(R.drawable.shop_mall_card_bg)
.fallback(R.drawable.shop_mall_card_bg)
.error(R.drawable.shop_mall_card_bg)
.centerCrop()
.into(holder.image);
}
@Override
public int getItemCount() {
return images.length;
return Math.max(1, images.size());
}
@Override

View File

@@ -1,5 +1,6 @@
package com.ckkj.griddle.shop.adapter;
import android.text.TextUtils;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
@@ -7,23 +8,33 @@ import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ckkj.griddle.R;
import com.ckkj.griddle.shop.ShopPriceFormatter;
import com.ckkj.griddle.shop.entity.ProductEntity;
import com.ckkj.griddle.shop.entity.MallGoodsEntity;
/** 三列商品卡片;标题最多四行,长名称省略,按钮交由页面统一路由。 */
public class ShopProductAdapter extends BaseQuickAdapter<ProductEntity, BaseViewHolder> {
public class ShopProductAdapter extends BaseQuickAdapter<MallGoodsEntity, BaseViewHolder> {
public ShopProductAdapter() {
super(R.layout.item_shop_product);
}
@Override
protected void convert(BaseViewHolder helper, ProductEntity item) {
helper.setText(R.id.tv_shop_product_name, mContext.getString(item.nameRes));
helper.setText(R.id.tv_shop_product_sold, mContext.getString(R.string.shop_mall_sold, item.sold));
helper.setText(R.id.tv_shop_product_price, ShopPriceFormatter.format(mContext, item.cashCents));
protected void convert(BaseViewHolder helper, MallGoodsEntity item) {
helper.setText(R.id.tv_shop_product_name, item.getGoodsName());
helper.setText(R.id.tv_shop_product_sold,
mContext.getString(R.string.shop_mall_sold, item.getSalesVolume()));
helper.setText(R.id.tv_shop_product_price,
ShopPriceFormatter.format(mContext, item.getSalePrice()));
ImageView cover = helper.getView(R.id.iv_shop_product_cover);
cover.setContentDescription(mContext.getString(item.nameRes));
Glide.with(cover).load(item.coverRes).centerCrop().into(cover);
cover.setContentDescription(item.getGoodsName());
String imageUrl = item.getGoodsImg();
// 空链接也交给 Glide,防止复用时残留上一个商品的封面。
Glide.with(cover)
.load(TextUtils.isEmpty(imageUrl) ? null : imageUrl.trim())
.placeholder(R.drawable.shop_mall_card_bg)
.fallback(R.drawable.shop_mall_card_bg)
.error(R.drawable.shop_mall_card_bg)
.centerCrop()
.into(cover);
helper.addOnClickListener(R.id.tv_shop_product_redeem);
}
}

View File

@@ -0,0 +1,86 @@
package com.ckkj.griddle.shop.entity;
import android.text.TextUtils;
import com.ckkj.griddle.cart.entity.CartGoodsEntity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** 商品详情数据;基础字段与商品列表一致,额外包含轮播、描述和规格。 */
public class MallGoodsDetailEntity extends MallGoodsEntity {
private static final long serialVersionUID = 1L;
private List<String> banners;
private String goodsDesc;
private List<SpecEntity> specs;
public String getGoodsDesc() {
return goodsDesc;
}
public List<SpecEntity> getSpecs() {
return specs == null ? Collections.emptyList() : specs;
}
/** 过滤空轮播地址;没有轮播时使用商品主图,不再回退到本地演示图。 */
public List<String> getImages() {
List<String> images = new ArrayList<>();
if (banners != null) {
for (String image : banners) {
if (!TextUtils.isEmpty(image) && !image.trim().isEmpty()) {
images.add(image.trim());
}
}
}
String cover = getGoodsImg();
if (images.isEmpty() && !TextUtils.isEmpty(cover) && !cover.trim().isEmpty()) {
images.add(cover.trim());
}
return images;
}
/** 仅转换现有页面传参,不代表已调用服务端加购或下单接口。 */
public CartGoodsEntity toCartGoods() {
// 接口金额转为现有结算模型的分单位,使用十进制计算避免浮点误差。
long cashCents = getSalePrice().movePointRight(2)
.setScale(0, RoundingMode.HALF_UP).longValueExact();
String cover = getGoodsImg();
if (TextUtils.isEmpty(cover) || cover.trim().isEmpty()) {
List<String> images = getImages();
cover = images.isEmpty() ? null : images.get(0);
}
return new CartGoodsEntity(getId(), getGoodsName(), cover,
getPointsPrice().longValueExact(), cashCents, 1, true);
}
/** 规格列表按接口保存,后续规格选择和下单可直接使用真实规格 ID。 */
public static class SpecEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String specModel;
private BigDecimal salePrice;
private long stock;
public String getId() {
return id;
}
public String getSpecModel() {
return specModel;
}
public BigDecimal getSalePrice() {
return salePrice;
}
public long getStock() {
return stock;
}
}
}

View File

@@ -0,0 +1,52 @@
package com.ckkj.griddle.shop.entity;
import java.io.Serializable;
import java.math.BigDecimal;
/** 商城商品列表条目,对应 /app/mall/goods 返回的商品字段。 */
public class MallGoodsEntity implements Serializable {
private static final long serialVersionUID = 1L;
/** 编号按字符串接收,避免长整型商品 ID 丢失精度。 */
private String id;
private String goodsName;
private String goodsImg;
private String categoryId;
/** 接口销售价直接按金额显示,不沿用本地演示模型的分单位。 */
private BigDecimal salePrice;
private BigDecimal pointsPrice;
private long stockNum;
private long salesVolume;
public String getId() {
return id;
}
public String getGoodsName() {
return goodsName;
}
public String getGoodsImg() {
return goodsImg;
}
public String getCategoryId() {
return categoryId;
}
public BigDecimal getSalePrice() {
return salePrice == null ? BigDecimal.ZERO : salePrice;
}
public BigDecimal getPointsPrice() {
return pointsPrice == null ? BigDecimal.ZERO : pointsPrice;
}
public long getStockNum() {
return stockNum;
}
public long getSalesVolume() {
return salesVolume;
}
}

View File

@@ -0,0 +1,32 @@
package com.ckkj.griddle.shop.entity;
import java.util.Collections;
import java.util.List;
/** 列表分页结果;total 为空时,按本页条数判断是否还可以加载。 */
public class MallGoodsPageEntity {
private List<MallGoodsEntity> rows;
private Long total;
public MallGoodsPageEntity(List<MallGoodsEntity> rows, Long total) {
this.rows = rows;
this.total = total;
}
public List<MallGoodsEntity> getRows() {
return rows == null ? Collections.emptyList() : rows;
}
public Long getTotal() {
return total;
}
public boolean hasMore(int loadedCount, int pageSize) {
// 空页始终结束分页,避免服务端总数不准确时重复请求。
List<MallGoodsEntity> items = getRows();
if (items.isEmpty()) {
return false;
}
return total == null ? items.size() >= pageSize : loadedCount < total;
}
}

View File

@@ -1,38 +0,0 @@
package com.ckkj.griddle.shop.entity;
import com.ckkj.griddle.cart.entity.CartGoodsEntity;
import java.io.Serializable;
/** 商城商品演示模型;金额以分保存,商品 ID 在列表、详情和下单之间保持一致。 */
public class ProductEntity implements Serializable {
private static final long serialVersionUID = 1L;
public final String id;
public final int nameRes;
public final int coverRes;
public final int descriptionRes;
public final long cashCents;
public final int sold;
private final int[] images;
public ProductEntity(String id, int nameRes, int coverRes, int descriptionRes,
long cashCents, int sold, int[] images) {
this.id = id;
this.nameRes = nameRes;
this.coverRes = coverRes;
this.descriptionRes = descriptionRes;
this.cashCents = cashCents;
this.sold = sold;
this.images = images == null ? new int[0] : images.clone();
}
public int[] getImages() {
return images.length == 0 ? new int[]{coverRes} : images.clone();
}
/** 复用现有购物车与结算模型,不另外维护一套金额、数量计算。 */
public CartGoodsEntity toCartGoods() {
return new CartGoodsEntity(id, nameRes, coverRes, 0, cashCents, 1, true);
}
}

View File

@@ -1,7 +1,9 @@
package com.ckkj.griddle.shop.mvp;
import com.ckkj.griddle.base.IView;
import com.ckkj.griddle.shop.entity.ProductEntity;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.shop.entity.MallGoodsDetailEntity;
import com.ckkj.griddle.shop.entity.MallGoodsPageEntity;
import java.util.List;
@@ -16,18 +18,40 @@ public final class ShopContract {
}
public interface DataModel {
void getProducts(CallBack<List<ProductEntity>> callback);
void getProducts(int page, int size, CallBack<MallGoodsPageEntity> callback);
void getProduct(String productId, CallBack<ProductEntity> callback);
void cancelProductsRequest();
void getProduct(String productId, CallBack<MallGoodsDetailEntity> callback);
void cancelProductRequest();
void addToCart(String goodsId, String skuId, int num, CallBack<Void> callback);
void cancelAddToCartRequest();
void getPickupPoints(CallBack<List<PickupPointEntity>> callback);
void cancelPickupPointsRequest();
}
public interface ShopView extends IView { }
public interface ListView extends ShopView {
void showProducts(List<ProductEntity> products);
void showProducts(MallGoodsPageEntity products);
void onProductsRequestFinished(boolean success);
}
public interface DetailView extends ShopView {
void showProduct(ProductEntity product);
void showProduct(MallGoodsDetailEntity product);
void showPickupPoints(List<PickupPointEntity> points);
void showPickupPointsError(String message);
void onAddToCartSuccess();
void onAddToCartError(String message);
}
}

View File

@@ -1,39 +1,225 @@
package com.ckkj.griddle.shop.mvp;
import com.ckkj.griddle.R;
import com.ckkj.griddle.shop.entity.ProductEntity;
import android.text.TextUtils;
import com.ckkj.griddle.MyApplication;
import com.ckkj.griddle.R;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.mine.mvp.MineContract;
import com.ckkj.griddle.mine.mvp.MineImpl;
import com.ckkj.griddle.network.BaseBean;
import com.ckkj.griddle.network.NetWorkManager;
import com.ckkj.griddle.shop.entity.MallGoodsPageEntity;
import com.ckkj.griddle.shop.entity.MallGoodsDetailEntity;
import com.ckkj.griddle.utils.AppLanguageUtil;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
/** 商城数据层:暂用本地模拟数据,联调时统一替换此处,不在页面拼装接口数据。 */
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.SerialDisposable;
import io.reactivex.schedulers.Schedulers;
/** 商城数据层:列表和详情均使用真实接口,不在页面拼装模拟数据。 */
public class ShopImpl implements ShopContract.DataModel {
private List<ProductEntity> createProducts() {
List<ProductEntity> products = new ArrayList<>();
for (int i = 0; i < 12; i++) {
// 原稿沿用同款商品演示;每项 ID 独立,照片仅使用实际准备的本地预览图。
products.add(new ProductEntity("shop_demo_" + (i + 1),
R.string.shop_mall_product_name, R.drawable.shop_product_preview,
R.string.shop_mall_product_description, 20800, i == 0 ? 1000 : 0,
new int[]{R.drawable.shop_detail_preview, R.drawable.shop_product_preview}));
private final SerialDisposable productsRequest = new SerialDisposable();
private final SerialDisposable productRequest = new SerialDisposable();
private final SerialDisposable addCartRequest = new SerialDisposable();
/** 与自提点管理页共用同一接口解析,实例独立,取消时不影响其他页面。 */
private final MineImpl pickupImpl = new MineImpl();
@Override
public void getProducts(int page, int size,
ShopContract.CallBack<MallGoodsPageEntity> callback) {
try {
NetWorkManager.getRequest().getMallGoods(NetWorkManager.getToken(), page, size)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean<MallGoodsPageEntity>>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
productsRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean<MallGoodsPageEntity> response) {
if (response.isSuccess() || response.getCode() == 200) {
MallGoodsPageEntity data = response.getData();
callback.success(data == null
? new MallGoodsPageEntity(null, null) : data);
} else {
callback.fail(errorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(errorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(errorMessage(exception.getMessage()));
}
return products;
}
private String errorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(R.string.shop_mall_load_failed) : message;
}
@Override
public void getProducts(ShopContract.CallBack<List<ProductEntity>> callback) {
callback.success(createProducts());
public void cancelProductsRequest() {
// set(null) 取消当前请求,视图重建后仍可再次发起。
productsRequest.set(null);
}
@Override
public void getProduct(String productId, ShopContract.CallBack<ProductEntity> callback) {
for (ProductEntity product : createProducts()) {
if (product.id.equals(productId)) {
callback.success(product);
public void getProduct(String productId,
ShopContract.CallBack<MallGoodsDetailEntity> callback) {
if (TextUtils.isEmpty(productId) || TextUtils.isEmpty(productId.trim())) {
callback.fail(detailErrorMessage(null));
return;
}
try {
NetWorkManager.getRequest().getMallGoodsDetail(NetWorkManager.getToken(), productId.trim())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean<MallGoodsDetailEntity>>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
productRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean<MallGoodsDetailEntity> response) {
if ((response.isSuccess() || response.getCode() == 200)
&& response.getData() != null
&& !TextUtils.isEmpty(response.getData().getId())) {
callback.success(response.getData());
} else {
callback.fail(detailErrorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(detailErrorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(detailErrorMessage(exception.getMessage()));
}
}
@Override
public void cancelProductRequest() {
productRequest.set(null);
}
@Override
public void addToCart(String goodsId, String skuId, int num,
ShopContract.CallBack<Void> callback) {
if (TextUtils.isEmpty(goodsId) || TextUtils.isEmpty(skuId) || num <= 0) {
callback.fail(addCartErrorMessage(null));
return;
}
try {
long parsedGoodsId;
long parsedSkuId;
try {
parsedGoodsId = Long.parseLong(goodsId.trim());
parsedSkuId = Long.parseLong(skuId.trim());
} catch (NumberFormatException exception) {
callback.fail(addCartErrorMessage(null));
return;
}
JsonObject body = new JsonObject();
body.addProperty("goodsId", parsedGoodsId);
body.addProperty("skuId", parsedSkuId);
body.addProperty("num", num);
NetWorkManager.getRequest().addMallGoodsToCart(NetWorkManager.getToken(),
NetWorkManager.toRequestBody(body))
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseBean>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {
addCartRequest.set(disposable);
}
@Override
public void onNext(@NonNull BaseBean response) {
if (response.isSuccess() || response.getCode() == 200) {
callback.success(null);
} else {
callback.fail(addCartErrorMessage(response.getMessage()));
}
}
@Override
public void onError(@NonNull Throwable throwable) {
callback.fail(addCartErrorMessage(throwable.getMessage()));
}
@Override
public void onComplete() {
}
});
} catch (Exception exception) {
callback.fail(addCartErrorMessage(exception.getMessage()));
}
callback.fail(null);
}
@Override
public void cancelAddToCartRequest() {
addCartRequest.set(null);
}
private String addCartErrorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(R.string.shop_mall_add_cart_failed) : message;
}
private String detailErrorMessage(String message) {
return TextUtils.isEmpty(message)
? AppLanguageUtil.wrap(MyApplication.getContext())
.getString(R.string.shop_mall_detail_failed) : message;
}
@Override
public void getPickupPoints(ShopContract.CallBack<List<PickupPointEntity>> callback) {
pickupImpl.getPickupPoints(new MineContract.CallBack<List<PickupPointEntity>>() {
@Override
public void success(List<PickupPointEntity> data) {
callback.success(data);
}
@Override
public void fail(String message) {
callback.fail(message);
}
});
}
@Override
public void cancelPickupPointsRequest() {
pickupImpl.cancelPickupPointsRequest();
}
}

View File

@@ -1,47 +1,141 @@
package com.ckkj.griddle.shop.mvp;
import com.ckkj.griddle.base.BasePresenter;
import com.ckkj.griddle.shop.entity.ProductEntity;
import com.ckkj.griddle.mine.entity.PickupPointEntity;
import com.ckkj.griddle.shop.entity.MallGoodsDetailEntity;
import com.ckkj.griddle.shop.entity.MallGoodsPageEntity;
import java.util.List;
/** 商城协调层;分别向列表和详情派发数据,沿用项目 attachView 生命周期。 */
public class ShopPresenter extends BasePresenter<ShopContract.ShopView> {
private final ShopContract.DataModel impl;
private final ShopImpl impl;
private int productsRequestVersion;
private int productRequestVersion;
private int pickupRequestVersion;
private int addCartRequestVersion;
public ShopPresenter(ShopContract.DataModel impl) {
public ShopPresenter(ShopImpl impl) {
this.impl = impl;
}
public void getProducts() {
impl.getProducts(new ShopContract.CallBack<List<ProductEntity>>() {
public void getProducts(int page, int size) {
final int requestVersion = ++productsRequestVersion;
impl.getProducts(page, size, new ShopContract.CallBack<MallGoodsPageEntity>() {
@Override
public void success(List<ProductEntity> data) {
if (getView() instanceof ShopContract.ListView) {
((ShopContract.ListView) getView()).showProducts(data);
public void success(MallGoodsPageEntity data) {
if (requestVersion == productsRequestVersion
&& getView() instanceof ShopContract.ListView) {
ShopContract.ListView view = (ShopContract.ListView) getView();
view.showProducts(data);
view.onProductsRequestFinished(true);
}
}
@Override
public void fail(String message) {
if (getView() != null) getView().showError(message);
if (requestVersion == productsRequestVersion
&& getView() instanceof ShopContract.ListView) {
ShopContract.ListView view = (ShopContract.ListView) getView();
view.showError(message);
view.onProductsRequestFinished(false);
}
}
});
}
public void cancelProductsRequest() {
productsRequestVersion++;
impl.cancelProductsRequest();
}
@Override
public void onDestroy() {
cancelProductsRequest();
cancelProductRequest();
cancelPickupPointsRequest();
cancelAddToCartRequest();
super.onDestroy();
}
public void getProduct(String productId) {
impl.getProduct(productId, new ShopContract.CallBack<ProductEntity>() {
final int requestVersion = ++productRequestVersion;
impl.cancelProductRequest();
impl.getProduct(productId, new ShopContract.CallBack<MallGoodsDetailEntity>() {
@Override
public void success(ProductEntity data) {
if (getView() instanceof ShopContract.DetailView) {
public void success(MallGoodsDetailEntity data) {
if (requestVersion == productRequestVersion
&& getView() instanceof ShopContract.DetailView) {
((ShopContract.DetailView) getView()).showProduct(data);
}
}
@Override
public void fail(String message) {
if (getView() != null) getView().showError(message);
if (requestVersion == productRequestVersion && getView() != null) {
getView().showError(message);
}
}
});
}
public void cancelProductRequest() {
productRequestVersion++;
impl.cancelProductRequest();
}
public void addToCart(String goodsId, String skuId, int num) {
final int requestVersion = ++addCartRequestVersion;
impl.cancelAddToCartRequest();
impl.addToCart(goodsId, skuId, num, new ShopContract.CallBack<Void>() {
@Override
public void success(Void data) {
if (requestVersion == addCartRequestVersion
&& getView() instanceof ShopContract.DetailView) {
((ShopContract.DetailView) getView()).onAddToCartSuccess();
}
}
@Override
public void fail(String message) {
if (requestVersion == addCartRequestVersion
&& getView() instanceof ShopContract.DetailView) {
((ShopContract.DetailView) getView()).onAddToCartError(message);
}
}
});
}
public void cancelAddToCartRequest() {
addCartRequestVersion++;
impl.cancelAddToCartRequest();
}
/** 自提点失败单独回调,不覆盖商品详情的成功内容。 */
public void getPickupPoints() {
final int requestVersion = ++pickupRequestVersion;
impl.cancelPickupPointsRequest();
impl.getPickupPoints(new ShopContract.CallBack<List<PickupPointEntity>>() {
@Override
public void success(List<PickupPointEntity> data) {
if (requestVersion == pickupRequestVersion
&& getView() instanceof ShopContract.DetailView) {
((ShopContract.DetailView) getView()).showPickupPoints(data);
}
}
@Override
public void fail(String message) {
if (requestVersion == pickupRequestVersion
&& getView() instanceof ShopContract.DetailView) {
((ShopContract.DetailView) getView()).showPickupPointsError(message);
}
}
});
}
public void cancelPickupPointsRequest() {
pickupRequestVersion++;
impl.cancelPickupPointsRequest();
}
}