《仿盒马》app开发技术分享-- 领取优惠券(56)

简介: 在之前的功能开发中,我们有些功能只有展示的能力并没有与云端产生任何的交互,后续经过我们的迭代,更多的能力有了交互能力,这一节我们就要开始着手给那些静态展示的模块添加业务逻辑,我们现在要实现的是首页的新人优惠券的领取

技术栈

Appgallery connect

开发准备

在之前的功能开发中,我们有些功能只有展示的能力并没有与云端产生任何的交互,后续经过我们的迭代,更多的能力有了交互能力,这一节我们就要开始着手给那些静态展示的模块添加业务逻辑,我们现在要实现的是首页的新人优惠券的领取

功能分析

新人优惠券我们在创建的时候给他赋予了一些字段,分别对应了优惠券的id,面额,最小可用金额等,那我们既然需要跟用户进行绑定,还是需要新建一个优惠券的表,把优惠券已有的数据填充进去,并且添加上userid,方便我们按用户查

代码实现

首先我们创建对应的优惠券表,进行字段的定义

{
   
  "objectTypeName": "coupon_mall",
  "fields": [
    {
   "fieldName": "id", "fieldType": "Integer", "notNull": true, "belongPrimaryKey": true},
    {
   "fieldName": "user_id", "fieldType": "Integer"},
    {
   "fieldName": "coupon_id", "fieldType": "Integer", "notNull": true, "defaultValue": 0},
    {
   "fieldName": "price", "fieldType": "Double"},
    {
   "fieldName": "type", "fieldType": "Integer"},
    {
   "fieldName": "limit_amount", "fieldType": "Double"},
    {
   "fieldName": "start_time", "fieldType": "String"},
    {
   "fieldName": "end_time", "fieldType": "String"},
    {
   "fieldName": "type_str", "fieldType": "String"},
    {
   "fieldName": "txt", "fieldType": "String"}

  ],
  "indexes": [
    {
   "indexName": "field1Index", "indexList": [{
   "fieldName":"id","sortType":"ASC"}]}
  ],
  "permissions": [
    {
   "role": "World", "rights": ["Read", "Upsert", "Delete"]},
    {
   "role": "Authenticated", "rights": ["Read", "Upsert", "Delete"]},
    {
   "role": "Creator", "rights": ["Read", "Upsert", "Delete"]},
    {
   "role": "Administrator", "rights": ["Read", "Upsert", "Delete"]}
  ]
}

添加完我们需要的字段后,我们生成对应的实体和db类

import {
    cloudDatabase } from '@kit.CloudFoundationKit';

class coupon_mall extends cloudDatabase.DatabaseObject {
   
  public id: number;
  public user_id: number;
  public coupon_id = 0;
  public price: number;
  public type: number;
  public limit_amount: number;
  public start_time: string;
  public end_time: string;
  public type_str: string;
  public txt: string;

  public naturalbase_ClassName(): string {
   
    return 'coupon_mall';
  }
}

export {
    coupon_mall };



/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2023. All rights reserved.
 * Generated by the CloudDB ObjectType compiler. DO NOT EDIT!
 */

class CouponMall {
   
    id: number;
    user_id: number;
    coupon_id: number = 0;
    price: number;
    type: number;
    limit_amount: number;
    start_time: string;
    end_time: string;
    type_str: string;
    txt: string;

    constructor() {
   
    }


    setId(id: number): void {
   
        this.id = id;
    }

    getId(): number  {
   
        return this.id;
    }

    setUser_id(user_id: number): void {
   
        this.user_id = user_id;
    }

    getUser_id(): number  {
   
        return this.user_id;
    }

    setCoupon_id(coupon_id: number): void {
   
        this.coupon_id = coupon_id;
    }

    getCoupon_id(): number  {
   
        return this.coupon_id;
    }

    setPrice(price: number): void {
   
        this.price = price;
    }

    getPrice(): number  {
   
        return this.price;
    }

    setType(type: number): void {
   
        this.type = type;
    }

    getType(): number  {
   
        return this.type;
    }

    setLimit_amount(limit_amount: number): void {
   
        this.limit_amount = limit_amount;
    }

    getLimit_amount(): number  {
   
        return this.limit_amount;
    }

    setStart_time(start_time: string): void {
   
        this.start_time = start_time;
    }

    getStart_time(): string  {
   
        return this.start_time;
    }

    setEnd_time(end_time: string): void {
   
        this.end_time = end_time;
    }

    getEnd_time(): string  {
   
        return this.end_time;
    }

    setType_str(type_str: string): void {
   
        this.type_str = type_str;
    }

    getType_str(): string  {
   
        return this.type_str;
    }

    setTxt(txt: string): void {
   
        this.txt = txt;
    }

    getTxt(): string  {
   
        return this.txt;
    }

}

export {
    CouponMall };

都生成之后我们在首页的新人优惠券模块,立即领取按钮添加对应的逻辑,因为券有多张,所以我们需要循环获取,并且上传到云数据库

```css
import { coupon_mall } from "../clouddb/coupon_mall"
import { couponInfo } from "../entity/couponInfo"
import { homeNewPeopleCoupon } from "../entity/homeNewPeopleCoupon"
import { cloudDatabase } from "@kit.CloudFoundationKit"
import { hilog } from "@kit.PerformanceAnalysisKit"
import showToast from "../utils/ToastUtils"
import { StorageUtils } from "../utils/StorageUtils"
import { User } from "../entity/User"

@Component
@Preview
export struct CouponComponent {
@Link home_activity:homeNewPeopleCoupon|null
@Link couponList:couponInfo[]
@State user: User|null=null

async aboutToAppear(): Promise {
const value = await StorageUtils.getAll('user');
if (value!='') {
this.user=JSON.parse(value)
}
}

build() {
Column() {
Row() {
Text(this.home_activity?.title)
.fontSize(20)
.fontColor('#FF0000')

    Text(this.home_activity?.msg)
      .fontSize(14)
      .fontColor('#888888')
      .margin({left:10})
  }
  .width('100%')
  .padding(16)

  List({ space: 10 }) {
    ForEach(this.couponList, (item:couponInfo) => {
      ListItem() {
        Column() {
          Text(item.price)
            .fontSize(22)
            .fontColor('#FF4444')
            .margin({ bottom: 8 })

          Text(item.type)
            .fontSize(12)
            .fontColor('#FF4444')
        }
        .padding(10)
        .backgroundColor("#ffffff")
        .borderRadius(8)
      }
    })
  }
  .margin({left:50})
  .listDirection(Axis.Horizontal)
  .width('100%')
  .height(80)

  Button('立即领取', { type: ButtonType.Normal })
    .width(240)
    .height(40)
    .backgroundColor('#FF0000')
    .fontColor(Color.White)
    .borderRadius(20)
    .margin({ bottom: 16 })
    .onClick(async ()=>{
      for (let i = 0; i < this.couponList.length; i++) {
        let coupon=new coupon_mall()
        coupon.id=Math.floor(Math.random() * 1000000);
        coupon.user_id=this.user!.user_id
        coupon.coupon_id=this.couponList[i].coupon_id
        coupon.price=Number(this.couponList[i].price)
        coupon.type=0
        coupon.limit_amount=this.couponList[i].limit_amount
        coupon.start_time=this.creatTime()
        coupon.end_time=this.endTime()
        coupon.type_str=this.couponList[i].type
        coupon.txt="全场商品通用"
        let databaseZone = cloudDatabase.zone('default');
        let num = await databaseZone.upsert(coupon);
        hilog.info(0x0000, 'testTag', `Succeeded in upserting data, result: ${num}`);
        if (num>0) {
          showToast("优惠券领取成功")
        }
      }
    })
}
.backgroundColor("#fffce2be")
.width('95%')
.margin({top:10})
.borderRadius(20)

}

creatTime(): string {
const now = new Date();

const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

}

endTime(): string {
const now = new Date();

const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

return `${year}-${month}-${day+7} ${hours}:${minutes}:${seconds}`;

}
}

相关文章
|
5月前
|
人工智能 Java 测试技术
Codex与Claude Code 深度拆解:两代 AI编程智能体的技术本质与Java实战指南
本文深度对比OpenAI Codex与Anthropic Claude Code两大AI编程智能体:Codex走云端沙箱、异步委托路线,擅批量任务与开箱即用;Claude Code主打本地终端、实时结对,强在复杂重构与隐私可控。结合Java实战,剖析架构差异、能力边界与成本,并给出搭配选型与避坑指南。
1662 1
|
6月前
|
人工智能 前端开发 Java
AGENTS.md完整落地实践:一份文件翻倍AI编码效率实操指南
在AI编程工具广泛普及的当下,Cursor、Claude Code、Copilot、各类智能体工具各自使用独立规则文件,团队需要维护多套配置,切换工具时重复同步编码规范,AI对项目架构、私有组件、构建流程一无所知,产出代码大量不符合团队标准,反复人工修改大幅拉低开发效率。AGENTS.md作为统一行业标准,完美解决配置碎片化、AI缺少项目上下文的痛点,仅在仓库根目录放置一份Markdown文件,即可让全部AI编码工具统一读取项目规则、架构、构建命令,搭配配套工程脚本,实现「AI读懂项目、写完自动自检、自主验证功能」完整闭环,显著提升AI编码产出质量与整体研发效率。本文结合Spring Boot
1171 0
|
6月前
|
存储 运维 监控
《告别日志排查:OpenClaw如何修复工具错误指南》
传统工具调用系统依赖预先枚举的错误码,面对异构工具的指数级参数组合和隐蔽语义错误时彻底失效,只能靠人工排查海量日志救火。本文深入拆解OpenClaw的革命性设计,它彻底抛弃被动防御思路,构建了语法校验、语义验证、目标对齐三层递进的语义自愈体系。通过异常语义化建模、工具间协同纠错、动态粒度控制和自学习闭环,将异常转化为系统进化的养分,实现95%以上常见异常的自主修复。这套机制为通用智能体的鲁棒性提供了全新技术路径,重新定义了工具调用的可靠性标准。
383 9
|
6月前
|
前端开发 数据挖掘 API
2026年6月六大主流建站工具深度横评与选型指南
2026年6月六大主流建站工具深度横评与选型指南
1714 0
|
7月前
|
数据采集 人工智能 自然语言处理
淄博企业布局GEO(AI优化):技术层面的思考框架与落地指南
本文聚焦淄博制造业、本地服务及跨境企业,解析生成式引擎优化(GEO)落地路径:破除“GEO=AI版SEO”误区,强调语义理解、结构化呈现与权威信源建设;提供“基础搭建—核心优化—迭代升级”三步技术方案,并针对地域特性给出本地语义适配、多模态呈现等实操指南,助力企业抢占AI决策链“答案主权”。
368 1
|
9月前
|
SQL 人工智能 安全
Microsoft SQL Server 2025 RTM GDR & CU3 (2026 年 3 月安全更新 | 累计更新)
Microsoft SQL Server 2025 RTM GDR & CU3 (2026 年 3 月安全更新 | 累计更新)
778 2
Microsoft SQL Server 2025 RTM GDR & CU3 (2026 年 3 月安全更新 | 累计更新)
|
9月前
|
数据采集 JSON 网络协议
淘宝评论api调用常见问题以及解决方案?
淘宝评论 API(核心为taobao.item.reviews.get)调用常见问题集中在权限、签名、限流、参数、数据、网络、解析、合规八大类,以下按问题类型逐一说明现象、原因、解决方案与最佳实践,附错误码速查。
|
安全 C++ Windows
格式化电脑和重装系统有什么区别
本文详细解析了“格式化”与“重装系统”的区别。格式化是清空磁盘数据并重建文件系统,重装系统则是重新安装操作系统,解决系统故障。两者在操作原理、影响范围和适用场景上均有不同。了解它们有助于避免误操作,并根据实际情况选择最佳处理方式。
|
设计模式 Java uml
课时107:时序图
课时107介绍了时序图的描述与设计。时序图用于展示代码执行流程,如Java程序中接口IMessage、类MessageImpl及Factory的调用顺序。通过Power Designer创建UML Sequence Diagram,定义类操作结构并绘制消息传递路径,清晰呈现工厂模式下对象实例化和方法调用的过程。时序图帮助理解程序逻辑,适用于项目开发中的流程分析与文档记录。
830 1
|
存储 Windows
电脑d盘不见了怎么恢复?
在使用电脑的时候,我们可能会遇到这样一个问题,电脑里的D盘突然不见了,在“此电脑”中看不到D盘了。这这个情况可能会让人感到非常困惑甚至是头疼,因为D盘里面可能存放着非常重要的文件。今天的内容要和大家分析一下D盘不见的原因,并且介绍两个简单的方法,找回D盘。