*/ use HasFactory; public const string PERCENT = 'percent'; public const string FIXED = 'fixed'; /** Letters, digits and dashes, 3 to 30 long. */ public const string CODE_PATTERN = '/^[A-Z0-9-]{3,30}$/'; /** * Shoppers may type " raya10 "; we store and compare "RAYA10". */ public static function normalize(string $code): string { return strtoupper(trim($code)); } /** * @return BelongsTo */ public function store(): BelongsTo { return $this->belongsTo(Store::class); } /** * Why this code cannot be used right now for products adding up to $subtotal (in sen), * as a key for StorefrontText. Null when it can be used. */ public function problemFor(int $subtotal): ?string { return match (true) { ! $this->active => 'discount_invalid', $this->starts_at !== null && $this->starts_at->isFuture() => 'discount_not_started', $this->ends_at !== null && $this->ends_at->isPast() => 'discount_expired', $this->usage_limit !== null && $this->times_used >= $this->usage_limit => 'discount_used_up', $this->minimum_subtotal !== null && $subtotal < $this->minimum_subtotal => 'discount_minimum', default => null, }; } /** * How much comes off products adding up to $subtotal, in sen. Never more than the subtotal. * Percentages are rounded down to the sen, so the shopper never gets less than promised by more than a sen. */ public function amountFor(int $subtotal): int { $amount = $this->type === self::PERCENT ? intdiv($subtotal * min(100, $this->value), 100) : $this->value; return max(0, min($amount, $subtotal)); } /** * "10% off" or "RM 5.00 off", in the store's language. */ public function label(string $language = 'en'): string { $amount = $this->type === self::PERCENT ? $this->value.'%' : 'RM '.number_format($this->value / 100, 2); return $language === 'ms' ? 'Diskaun '.$amount : $amount.' off'; } /** * The state a merchant sees in the list. */ public function status(): string { return match (true) { ! $this->active => 'off', $this->starts_at !== null && $this->starts_at->isFuture() => 'scheduled', $this->ends_at !== null && $this->ends_at->isPast() => 'expired', $this->usage_limit !== null && $this->times_used >= $this->usage_limit => 'used_up', default => 'active', }; } /** * @return array */ protected function casts(): array { return [ 'value' => 'integer', 'minimum_subtotal' => 'integer', 'starts_at' => 'datetime', 'ends_at' => 'datetime', 'usage_limit' => 'integer', 'times_used' => 'integer', 'active' => 'boolean', ]; } }