010-53388338

小象买菜系统:临期商品提示功能设计与多端实现

分类:IT频道 时间:2026-01-21 05:55 浏览:20
概述
    功能概述    临期商品提示功能旨在帮助用户识别即将过期的商品,减少食物浪费,提升购物体验。该功能可以显示商品剩余保质期天数,并对即将过期的商品进行特殊标记。    系统架构设计    1.数据库设计    商品表(products)新增字段:  ```sql  ALTERTABLEprod
内容
  
   功能概述
  
  临期商品提示功能旨在帮助用户识别即将过期的商品,减少食物浪费,提升购物体验。该功能可以显示商品剩余保质期天数,并对即将过期的商品进行特殊标记。
  
   系统架构设计
  
   1. 数据库设计
  
  商品表(products)新增字段:
  ```sql
  ALTER TABLE products ADD COLUMN
   production_date DATE NOT NULL COMMENT 生产日期,
   expiry_date DATE NOT NULL COMMENT 保质期截止日期,
   shelf_life_days INT COMMENT 保质期天数(可选);
  ```
  
  或采用更灵活的设计:
  ```sql
  CREATE TABLE product_expiry (
   id INT AUTO_INCREMENT PRIMARY KEY,
   product_id INT NOT NULL,
   batch_number VARCHAR(50) COMMENT 批次号,
   production_date DATE NOT NULL,
   expiry_date DATE NOT NULL,
   quantity INT DEFAULT 0,
   FOREIGN KEY (product_id) REFERENCES products(id)
  );
  ```
  
   2. 后端实现
  
  Java Spring Boot示例:
  
  ```java
  @Service
  public class ExpiryAlertService {
  
   @Value("${expiry.alert.threshold.days:3}") // 默认3天预警
   private int alertThresholdDays;
  
   public List getExpiringProducts(Long userId) {
   // 获取用户购物车或收藏中的商品
   List cartItems = cartService.getCartItems(userId);
  
   return cartItems.stream()
   .map(item -> {
   Product product = productService.getProductById(item.getProductId());
   long daysLeft = ChronoUnit.DAYS.between(LocalDate.now(), product.getExpiryDate());
  
   return new ProductExpiryAlert(
   product.getId(),
   product.getName(),
   daysLeft,
   daysLeft <= alertThresholdDays
   );
   })
   .filter(alert -> alert.isAlertNeeded())
   .collect(Collectors.toList());
   }
  
   // 计算剩余天数方法
   public long calculateDaysLeft(Date expiryDate) {
   LocalDate today = LocalDate.now();
   LocalDate expiry = expiryDate.toInstant()
   .atZone(ZoneId.systemDefault())
   .toLocalDate();
   return ChronoUnit.DAYS.between(today, expiry);
   }
  }
  
  @Data
  class ProductExpiryAlert {
   private Long productId;
   private String productName;
   private long daysLeft;
   private boolean alertNeeded;
  }
  ```
  
   3. 前端实现
  
  Vue.js示例:
  
  ```javascript
  // 商品列表组件中添加临期提示
  
  
  <script>
  export default {
   data() {
   return {
   products: []
   };
   },
   async created() {
   const response = await axios.get(/api/products/with-expiry);
   this.products = response.data.map(product => ({
   ...product,
   isExpiringSoon: product.daysLeft <= 3 // 3天内过期显示警告
   }));
   }
  };
  
  
  <style>
  .expiry-warning {
   color:   ff4d4f;
   font-weight: bold;
  }
  
  ```
  
   4. API设计
  
  获取带临期提示的商品列表:
  ```
  GET /api/products/with-expiry
  
  响应示例:
  [
   {
   "id": 123,
   "name": "新鲜牛奶",
   "price": 12.5,
   "daysLeft": 2,
   "isExpiringSoon": true
   },
   {
   "id": 124,
   "name": "全麦面包",
   "price": 8.0,
   "daysLeft": 5,
   "isExpiringSoon": false
   }
  ]
  ```
  
   高级功能实现
  
   1. 智能推荐系统
  
  根据用户历史购买记录和临期商品,推荐相关食谱或处理建议:
  
  ```java
  public List suggestRecipesForExpiring(Long userId) {
   List expiringProducts = getExpiringProducts(userId);
  
   return expiringProducts.stream()
   .flatMap(product -> {
   // 查询包含该商品的食谱
   List recipes = recipeService.findByIngredient(product.getProductId());
   return recipes.stream()
   .map(recipe -> new RecipeSuggestion(
   recipe.getId(),
   recipe.getName(),
   product.getDaysLeft(),
   "使用即将过期的" + product.getProductName() + "制作"
   ));
   })
   .collect(Collectors.toList());
  }
  ```
  
   2. 批量处理功能
  
  允许用户一键处理所有临期商品(如打折销售、捐赠等):
  
  ```javascript
  // 前端批量处理按钮
  
  
  methods: {
   async handleExpiringProducts() {
   try {
   const response = await axios.post(/api/products/handle-expiring, {
   userId: this.userId,
   action: discount // 或 donate
   });
   this.$message.success(临期商品处理成功);
   } catch (error) {
   this.$message.error(处理失败);
   }
   }
  }
  ```
  
   部署与监控
  
  1. 定时任务:设置每日任务检查所有商品保质期
   ```java
   @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
   public void checkAllProductsExpiry() {
   List allProducts = productRepository.findAll();
   allProducts.forEach(product -> {
   long daysLeft = expiryAlertService.calculateDaysLeft(product.getExpiryDate());
   if (daysLeft <= 3) {
   // 触发通知或标记
   }
   });
   }
   ```
  
  2. 监控面板:添加临期商品统计看板
   ```javascript
   // 管理员看板组件
   const expiryStats = ref({
   totalProducts: 0,
   expiringSoon: 0,
   expired: 0
   });
  
   onMounted(async () => {
   const res = await axios.get(/api/admin/expiry-stats);
   expiryStats.value = res.data;
   });
   ```
  
   测试策略
  
  1. 单元测试:验证保质期计算逻辑
   ```java
   @Test
   public void testCalculateDaysLeft() {
   // 测试不同日期情况
   Date tomorrow = Date.from(LocalDate.now().plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
   assertEquals(1, expiryAlertService.calculateDaysLeft(tomorrow));
  
   Date yesterday = Date.from(LocalDate.now().minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
   assertEquals(-1, expiryAlertService.calculateDaysLeft(yesterday));
   }
   ```
  
  2. 集成测试:验证端到端流程
   ```javascript
   test(临期商品提示流程, async ({ page }) => {
   await page.goto(/products);
   const expiringProduct = await page.getByText(新鲜牛奶);
   await expect(expiringProduct.getByText(2天)).toHaveClass(/expiry-warning/);
   });
   ```
  
   优化建议
  
  1. 缓存策略:对频繁访问的商品保质期信息进行缓存
  2. 推送通知:集成消息推送,提前提醒用户商品即将过期
  3. 多端同步:确保Web、App和小程序端提示一致
  4. 国际化:支持多语言环境下的日期显示
  
  通过以上实现,小象买菜系统可以有效帮助用户管理临期商品,减少食物浪费,同时提升用户购物体验和平台社会责任感。
评论