All files / src/app/admin/promotions/new page.tsx

0% Statements 0/381
100% Branches 0/0
0% Functions 0/1
0% Lines 0/381

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Card, Input } from "@/components/ui";
import { Icon } from "@/components/ui/icons";
import { clientLogger } from "@/lib/logging/clientLogger";
import type { PromotionType, DiscountType, PromotionTargetType } from "@prisma/client";

const promotionTypes: { value: PromotionType; label: string }[] = [
  { value: "PERCENTAGE_OFF", label: "Percentage Off" },
  { value: "FIXED_AMOUNT_OFF", label: "Fixed Amount Off" },
  { value: "BOGO", label: "Buy One Get One" },
  { value: "FREE_SHIPPING", label: "Free Shipping" },
  { value: "BUNDLE", label: "Bundle Discount" },
  { value: "FREE_GIFT", label: "Free Gift" },
  { value: "TIERED", label: "Tiered Discount" },
  { value: "FLASH_SALE", label: "Flash Sale" },
  { value: "SEASONAL", label: "Seasonal" },
  { value: "FIRST_PURCHASE", label: "First Purchase" },
];

const discountTypes: { value: DiscountType; label: string }[] = [
  { value: "PERCENTAGE", label: "Percentage" },
  { value: "FIXED_AMOUNT", label: "Fixed Amount" },
];

const targetTypes: { value: PromotionTargetType; label: string }[] = [
  { value: "ALL_PRODUCTS", label: "All Products" },
  { value: "SPECIFIC_PRODUCTS", label: "Specific Products" },
  { value: "SPECIFIC_CATEGORIES", label: "Specific Categories" },
  { value: "CART_TOTAL", label: "Cart Total" },
  { value: "SHIPPING", label: "Shipping" },
];

export default function NewPromotionPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    name: "",
    displayName: "",
    description: "",
    type: "PERCENTAGE_OFF" as PromotionType,
    discountType: "PERCENTAGE" as DiscountType,
    discountValue: 0,
    startDate: new Date().toISOString().split("T")[0],
    endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split("T")[0],
    isActive: true,
    usageLimit: "",
    perCustomerLimit: "",
    minimumPurchase: "",
    maximumDiscount: "",
    targetType: "ALL_PRODUCTS" as PromotionTargetType,
    stackable: false,
    priority: 0});

  const handleChange = (name: string, value: string | number | boolean) => {
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const payload = {
        name: formData.name,
        displayName: formData.displayName || undefined,
        description: formData.description || undefined,
        type: formData.type,
        discountType: formData.discountType,
        discountValue: Number(formData.discountValue),
        startDate: new Date(formData.startDate),
        endDate: new Date(formData.endDate),
        isActive: formData.isActive,
        usageLimit: formData.usageLimit ? Number(formData.usageLimit) : undefined,
        perCustomerLimit: formData.perCustomerLimit ? Number(formData.perCustomerLimit) : undefined,
        minimumPurchase: formData.minimumPurchase ? Number(formData.minimumPurchase) : undefined,
        maximumDiscount: formData.maximumDiscount ? Number(formData.maximumDiscount) : undefined,
        targetType: formData.targetType,
        stackable: formData.stackable,
        priority: Number(formData.priority)};

      const response = await fetch("/api/admin/promotions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)});

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to create promotion");
      }

      router.push(`/admin/promotions/${data.data.id}`);
    } catch (err) {
      clientLogger.error("Error creating promotion", err instanceof Error ? err : new Error(String(err)));
      setError(err instanceof Error ? err.message : "Failed to create promotion");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
      <div className="flex items-center gap-4 mb-6">
        <Button variant="ghost" onClick={() => router.back()}>
          <Icon name="arrow-left" size={20} />
        </Button>
        <div>
          <h1 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">Create Promotion</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400">Set up a new discount or promotional offer</p>
        </div>
      </div>

      {error && (
        <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-300">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit}>
        <Card className="p-6 mb-6">
          <h2 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Basic Information</h2>

          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Internal Name *
              </label>
              <Input
                value={formData.name}
                onChange={(e) => handleChange("name", e.target.value)}
                placeholder="e.g., Black Friday 2025"
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Display Name (shown to customers)
              </label>
              <Input
                value={formData.displayName}
                onChange={(e) => handleChange("displayName", e.target.value)}
                placeholder="e.g., 25% Off Everything!"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Description
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleChange("description", e.target.value)}
                placeholder="Internal notes about this promotion..."
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
                rows={3}
              />
            </div>
          </div>
        </Card>

        <Card className="p-6 mb-6">
          <h2 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Discount Settings</h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Promotion Type *
              </label>
              <select
                value={formData.type}
                onChange={(e: React.ChangeEvent<HTMLSelectElement>) => handleChange("type", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {promotionTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Discount Type *
              </label>
              <select
                value={formData.discountType}
                onChange={(e: React.ChangeEvent<HTMLSelectElement>) => handleChange("discountType", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {discountTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Discount Value *
              </label>
              <Input
                type="number"
                value={formData.discountValue}
                onChange={(e) => handleChange("discountValue", e.target.value)}
                min={0}
                max={formData.discountType === "PERCENTAGE" ? 100 : undefined}
                step={formData.discountType === "PERCENTAGE" ? 1 : 0.01}
                required
              />
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                {formData.discountType === "PERCENTAGE" ? "Percentage (0-100)" : "Dollar amount"}
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Target Type *
              </label>
              <select
                value={formData.targetType}
                onChange={(e: React.ChangeEvent<HTMLSelectElement>) => handleChange("targetType", e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {targetTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </Card>

        <Card className="p-6 mb-6">
          <h2 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Schedule</h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Start Date *
              </label>
              <Input
                type="date"
                value={formData.startDate}
                onChange={(e) => handleChange("startDate", e.target.value)}
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                End Date *
              </label>
              <Input
                type="date"
                value={formData.endDate}
                onChange={(e) => handleChange("endDate", e.target.value)}
                required
              />
            </div>
          </div>

          <div className="mt-4">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={formData.isActive}
                onChange={(e) => handleChange("isActive", e.target.checked)}
                className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500 dark:bg-gray-700"
              />
              <span className="text-sm text-gray-700 dark:text-gray-300">Active immediately</span>
            </label>
          </div>
        </Card>

        <Card className="p-6 mb-6">
          <h2 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Limits & Conditions</h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Total Usage Limit
              </label>
              <Input
                type="number"
                value={formData.usageLimit}
                onChange={(e) => handleChange("usageLimit", e.target.value)}
                placeholder="Unlimited"
                min={1}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Per Customer Limit
              </label>
              <Input
                type="number"
                value={formData.perCustomerLimit}
                onChange={(e) => handleChange("perCustomerLimit", e.target.value)}
                placeholder="Unlimited"
                min={1}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Minimum Purchase ($)
              </label>
              <Input
                type="number"
                value={formData.minimumPurchase}
                onChange={(e) => handleChange("minimumPurchase", e.target.value)}
                placeholder="No minimum"
                min={0}
                step={0.01}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Maximum Discount ($)
              </label>
              <Input
                type="number"
                value={formData.maximumDiscount}
                onChange={(e) => handleChange("maximumDiscount", e.target.value)}
                placeholder="No maximum"
                min={0}
                step={0.01}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Priority
              </label>
              <Input
                type="number"
                value={formData.priority}
                onChange={(e) => handleChange("priority", e.target.value)}
                placeholder="0"
              />
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Higher priority promotions are applied first</p>
            </div>

            <div className="flex items-center">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={formData.stackable}
                  onChange={(e) => handleChange("stackable", e.target.checked)}
                  className="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500 dark:bg-gray-700"
                />
                <span className="text-sm text-gray-700 dark:text-gray-300">Can stack with other promotions</span>
              </label>
            </div>
          </div>
        </Card>

        <div className="flex justify-end gap-4">
          <Button type="button" variant="ghost" onClick={() => router.back()}>
            Cancel
          </Button>
          <Button type="submit" disabled={loading}>
            {loading ? "Creating..." : "Create Promotion"}
          </Button>
        </div>
      </form>
    </div>
  );
}