summaryrefslogtreecommitdiff
path: root/storefront/pages/checkout.js
blob: 1970df4e8cdc73f75fddca2951d1448a9354416f (plain)
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
import { useEffect, useState } from "react"
import { useRouter } from "next/router"
import { medusaClient } from "../lib/medusa-client"
import { getStoredCartId, clearStoredCartId } from "../lib/storefront"

const initialForm = {
  email: "",
  first_name: "",
  last_name: "",
  address_1: "",
  postal_code: "",
  city: "",
  country_code: "fr",
}

export default function CheckoutPage() {
  const router = useRouter()
  const [form, setForm] = useState(initialForm)
  const [status, setStatus] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [cartId, setCartId] = useState(null)

  useEffect(() => {
    const storedCartId = getStoredCartId()
    setCartId(storedCartId)
  }, [])

  const handleChange = (event) => {
    const { name, value } = event.target
    setForm((prev) => ({ ...prev, [name]: value }))
  }

  const handleSubmit = async (event) => {
    event.preventDefault()
    setStatus("")
    setIsLoading(true)

    if (!cartId) {
      setStatus("Votre panier est vide.")
      setIsLoading(false)
      return
    }

    try {
      await medusaClient.carts.update(cartId, {
        email: form.email,
        shipping_address: {
          first_name: form.first_name,
          last_name: form.last_name,
          address_1: form.address_1,
          postal_code: form.postal_code,
          city: form.city,
          country_code: form.country_code,
        },
      })

      const { shipping_options: shippingOptions } =
        await medusaClient.shippingOptions.listCartOptions(cartId)

      if (!shippingOptions?.length) {
        throw new Error("Aucune option de livraison disponible.")
      }

      await medusaClient.carts.addShippingMethod(cartId, {
        option_id: shippingOptions[0].id,
      })

      const { cart: cartWithPayments } = await medusaClient.carts.createPaymentSessions(
        cartId
      )

      const manualSession = cartWithPayments?.payment_sessions?.find(
        (session) => session.provider_id === "manual"
      )
      const providerId =
        manualSession?.provider_id ||
        cartWithPayments?.payment_sessions?.[0]?.provider_id

      if (!providerId) {
        throw new Error("Aucun moyen de paiement disponible.")
      }

      await medusaClient.carts.setPaymentSession(cartId, { provider_id: providerId })

      const { type, data } = await medusaClient.carts.complete(cartId)
      if (type === "order" && data?.id) {
        clearStoredCartId()
        router.push(`/order-confirmation?order_id=${data.id}`)
        return
      }

      setStatus("Commande validée, mais sans numéro de commande.")
    } catch (error) {
      setStatus("Impossible de finaliser la commande.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div style={{ maxWidth: "520px", margin: "0 auto" }}>
      <h1>Finaliser la commande</h1>
      <form onSubmit={handleSubmit} style={{ display: "grid", gap: "1rem" }}>
        <label>
          Email
          <input
            name="email"
            type="email"
            value={form.email}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Prénom
          <input
            name="first_name"
            value={form.first_name}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Nom
          <input
            name="last_name"
            value={form.last_name}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Adresse
          <input
            name="address_1"
            value={form.address_1}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Code postal
          <input
            name="postal_code"
            value={form.postal_code}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Ville
          <input
            name="city"
            value={form.city}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <label>
          Pays
          <input
            name="country_code"
            value={form.country_code}
            onChange={handleChange}
            required
            style={{ width: "100%", padding: "0.5rem", marginTop: "0.5rem" }}
          />
        </label>
        <button
          type="submit"
          disabled={isLoading}
          style={{
            border: "1px solid #ccc",
            background: "#fff",
            borderRadius: "6px",
            padding: "0.6rem",
            cursor: "pointer",
          }}
        >
          {isLoading ? "Validation..." : "Passer la commande"}
        </button>
        {status && <p>{status}</p>}
      </form>
    </div>
  )
}