'待使用', self::STATUS_USED => '已使用', self::STATUS_INVALID => '已失效']; } public function coupon(): HasOne { return $this->hasOne(Coupon::class, 'id', 'coupon_id')->bind( [ 'amount', 'name', 'cover', 'type', 'condition', 'begin_at', 'end_at', ] ); } public function account(): HasOne { return $this->hasOne(Account::class, 'id', 'account_id')->bind( [ 'nickname', 'mobile', ] ); } /** * 优惠券使用 * * @param int $accountId * @param int $id * @param string $orderCoding * @param string $checkBy * @return bool * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException * @throws RepositoryException */ public static function use(int $accountId, int $id, string $orderCoding = '',$checkBy =""): bool { $where = ['id' => $id]; if (!$accountCoupon = self::findOne($where)) { throw new RepositoryException('您的优惠券不存在'); } if ($accountCoupon['account_id'] != $accountId) { throw new RepositoryException('不是您的优惠券'); } if (!empty($accountCoupon['deleted_at'])) { throw new RepositoryException('您的优惠券不存在-2'); } if (!$coupon = Coupon::findById($accountCoupon['coupon_id'])) { throw new RepositoryException('此优惠券不存在或已下架'); } if (!empty($coupon['deleted_at'])) { throw new RepositoryException('此优惠券已下架'); } $now = date('Y-m-d H:i:s'); if ($now < $coupon['begin_at'] || $now > $coupon['end_at']) { throw new RepositoryException('此优惠券不在有效期'); } if($accountCoupon["status"] != AccountCoupon::STATUS_NORMAL){ throw new RepositoryException('优惠券已使用或已失效'); } return $accountCoupon->save([ 'used_at' => $now, 'status' => self::STATUS_USED, 'order_coding' => $orderCoding, 'check_by' => $checkBy, ]); } /** * 获取首页优惠券 * 没有或已领取则返回null * * @param int $accountId * @return Coupon|array|\think\Model|null * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ public static function homeCoupon(int $accountId) { if (!$coupon = Coupon::homeCoupon()) { return null; } if (self::where('account_id', $accountId)->where('coupon_id', $coupon['id'])->count() > 0) { return null; } return $coupon; } }