> */ public static function rules(Store $store, bool $percent, ?DiscountCode $existing = null): array { return [ 'code' => [ 'required', 'string', 'regex:'.DiscountCode::CODE_PATTERN, Rule::unique('discount_codes', 'code')->where('store_id', $store->id)->ignore($existing?->id), ], 'type' => ['required', Rule::in([DiscountCode::PERCENT, DiscountCode::FIXED])], 'value' => $percent ? ['required', 'integer', 'min:1', 'max:100'] : ['required', 'numeric', 'decimal:0,2', 'min:0.01', 'max:999999.99'], 'minimum_subtotal' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'], 'starts_on' => ['nullable', 'date_format:Y-m-d'], 'ends_on' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:starts_on'], 'usage_limit' => ['nullable', 'integer', 'min:1', 'max:1000000'], 'active' => ['boolean'], ]; } /** * @return array */ public static function messages(bool $percent): array { return [ 'code.regex' => __('Use 3 to 30 letters, numbers or dashes, such as RAYA10.'), 'code.unique' => __('This store already has that code.'), 'value.max' => $percent ? __('A percentage cannot be more than 100.') : __('The amount is too large.'), 'ends_on.after_or_equal' => __('The last day cannot be before the first day.'), ]; } /** * Copy checked data onto a code, converting ringgit to sen and Malaysian days to times. * * @param array $data */ public static function fill(DiscountCode $code, array $data): void { $percent = $data['type'] === DiscountCode::PERCENT; $code->code = $data['code']; $code->type = $data['type']; $code->value = $percent ? (int) $data['value'] : self::sen($data['value']); $code->minimum_subtotal = filled($data['minimum_subtotal'] ?? null) ? self::sen($data['minimum_subtotal']) : null; $code->starts_at = filled($data['starts_on'] ?? null) ? Carbon::parse($data['starts_on'], self::TIMEZONE)->startOfDay()->utc() : null; $code->ends_at = filled($data['ends_on'] ?? null) ? Carbon::parse($data['ends_on'], self::TIMEZONE)->endOfDay()->utc() : null; $code->usage_limit = filled($data['usage_limit'] ?? null) ? (int) $data['usage_limit'] : null; $code->active = (bool) ($data['active'] ?? false); } private static function sen(mixed $ringgit): int { return (int) round(((float) $ringgit) * 100); } }