/
CheckoutPage.js
344 lines (314 loc) · 9.63 KB
/
CheckoutPage.js
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
// @flow
import React from "react"
import * as R from "ramda"
import { connect } from "react-redux"
import { mutateAsync, requestAsync } from "redux-query"
import { compose } from "redux"
import queryString from "query-string"
import queries from "../../lib/queries"
import {
calculateDiscount,
calculatePrice,
formatPrice,
formatRunTitle
} from "../../lib/ecommerce"
import { createCyberSourceForm, formatErrors } from "../../lib/form"
import type { Response } from "redux-query"
import type { Location } from "react-router"
import type {
BasketResponse,
BasketPayload,
CheckoutResponse,
BasketItem
} from "../../flow/ecommerceTypes"
export const calcSelectedRunIds = (item: BasketItem): { [number]: number } => {
if (item.type === "courserun") {
const course = item.courses[0]
return {
[course.id]: item.object_id
}
}
const courseLookup = {}
for (const course of item.courses) {
for (const run of course.courseruns) {
courseLookup[run.id] = course.id
}
}
const selectedRunIds = {}
for (const runId of item.run_ids) {
const courseId = courseLookup[runId]
// there should only be one run selected for a course
selectedRunIds[courseId] = runId
}
return selectedRunIds
}
type Props = {
basket: ?BasketResponse,
checkout: () => Promise<Response<CheckoutResponse>>,
fetchBasket: () => Promise<*>,
location: Location,
updateBasket: (payload: BasketPayload) => Promise<*>
}
type State = {
couponCode: string | null,
errors: string | Array<string> | null,
selectedRuns: { [number]: { [number]: number } } | null
}
export class CheckoutPage extends React.Component<Props, State> {
state = {
couponCode: null,
selectedRuns: null,
errors: null
}
componentDidMount = async () => {
const {
fetchBasket,
location: { search }
} = this.props
const params = queryString.parse(search)
const productId = parseInt(params.product)
if (!productId) {
await fetchBasket()
return
}
try {
await this.updateBasket({ items: [{ id: productId }] })
const couponCode = params.code
if (couponCode) {
await this.updateBasket({ coupons: [{ code: couponCode }] })
}
} catch (_) {
// prevent complaints about unresolved promises
}
}
handleErrors = async (responsePromise: Promise<*>) => {
const response = await responsePromise
if (response.body.errors) {
this.setState({ errors: response.body.errors })
throw new Error("Received error from request")
}
return response
}
getSelectedRunIds = (item: BasketItem): { [number]: number } => {
return {
...calcSelectedRunIds(item),
...this.state.selectedRuns
}
}
submit = async () => {
const { basket } = this.props
if (!basket) {
// if there is no basket there shouldn't be any submit button rendered
throw new Error("Expected basket to exist")
}
// update basket with selected runs
await this.updateBasket({
items: basket.items.map(item => ({
id: item.id,
// $FlowFixMe: flow doesn't understand that Object.values will return an array of number here
run_ids: Object.values(this.getSelectedRunIds(item))
}))
})
const {
body: { url, payload, method }
} = await this.checkout()
if (method === "GET") {
window.location = url
} else {
const form = createCyberSourceForm(url, payload)
const body: HTMLElement = (document.querySelector("body"): any)
body.appendChild(form)
form.submit()
}
}
updateCouponCode = (event: any) => {
this.setState({
couponCode: event.target.value
})
}
updateSelectedRun = R.curry((courseId: number, event: any) => {
const { selectedRuns } = this.state
const runId = parseInt(event.target.value)
this.setState({
selectedRuns: {
...selectedRuns,
[courseId]: runId
}
})
})
submitCoupon = async (e: Event) => {
const { updateBasket } = this.props
const { couponCode } = this.state
e.preventDefault()
const response = await updateBasket({
coupons: couponCode
? [
{
code: couponCode
}
]
: []
})
const errors = response.status !== 200 ? response.body.errors : null
this.setState({ errors })
}
// $FlowFixMe
updateBasket = (...args) =>
this.handleErrors(this.props.updateBasket(...args))
// $FlowFixMe
checkout = (...args) => this.handleErrors(this.props.checkout(...args))
renderBasketItem = (item: BasketItem) => {
const selectedRunIds = this.getSelectedRunIds(item)
if (item.type === "program") {
return (
<React.Fragment>
{item.courses.map(course => (
<div className="flex-row item-row" key={course.id}>
<div className="flex-row item-column">
<img src={course.thumbnail_url} alt={course.title} />
</div>
<div className="title-column">
<div className="title">{course.title}</div>
<select
className="run-selector"
onChange={this.updateSelectedRun(course.id)}
value={selectedRunIds[course.id] || ""}
>
<option value={null} key={"null"}>
Select a course run
</option>
{course.courseruns.map(run => (
<option value={run.id} key={run.id}>
{formatRunTitle(run)}
</option>
))}
</select>
</div>
</div>
))}
</React.Fragment>
)
} else {
return (
<div className="flex-row item-row">
<div className="flex-row item-column">
<img src={item.thumbnail_url} alt={item.description} />
</div>
<div className="title-column">
<div className="title">{item.description}</div>
</div>
</div>
)
}
}
render() {
const { basket } = this.props
const { couponCode, errors } = this.state
const item = basket && basket.items[0]
if (!basket || !item) {
return (
<div className="checkout-page">
No item in basket
{formatErrors(errors)}
</div>
)
}
const coupon = basket.coupons.find(coupon =>
coupon.targets.includes(item.id)
)
return (
<div className="checkout-page container">
<div className="row header">
<div className="col-12">
<div className="page-title">Checkout</div>
<div className="purchase-text">
You are about to purchase the following:
</div>
<div className="item-type">
{item.type === "program" ? "Program" : "Course"}
</div>
<hr />
{item.type === "program" ? (
<span className="description">{item.description}</span>
) : null}
</div>
</div>
<div className="row">
<div className="col-lg-7">
{this.renderBasketItem(item)}
<div className="enrollment-input">
<div className="enrollment-row">
Enrollment / Promotional Code
</div>
<form onSubmit={this.submitCoupon}>
<div className="flex-row coupon-code-row">
<input
type="text"
className={errors ? "error-border" : ""}
value={
(couponCode !== null
? couponCode
: coupon && coupon.code) || ""
}
onChange={this.updateCouponCode}
/>
<button
className="apply-button"
type="button"
onClick={this.submitCoupon}
>
Apply
</button>
</div>
{formatErrors(errors)}
</form>
</div>
</div>
<div className="col-lg-5 order-summary-container">
<div className="order-summary">
<div className="title">Order Summary</div>
<div className="flex-row price-row">
<span>Price:</span>
<span>{formatPrice(item.price)}</span>
</div>
{coupon ? (
<div className="flex-row discount-row">
<span>Discount:</span>
<span>{formatPrice(calculateDiscount(item, coupon))}</span>
</div>
) : null}
<div className="bar" />
<div className="flex-row total-row">
<span>Total:</span>
<span>{formatPrice(calculatePrice(item, coupon))}</span>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-lg-7" />
<div className="col-lg-5">
<button className="checkout-button" onClick={this.submit}>
Place your order
</button>
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
basket: state.entities.basket
})
const mapDispatchToProps = dispatch => ({
checkout: () => dispatch(mutateAsync(queries.ecommerce.checkoutMutation())),
fetchBasket: () => dispatch(requestAsync(queries.ecommerce.basketQuery())),
updateBasket: payload =>
dispatch(mutateAsync(queries.ecommerce.basketMutation(payload)))
})
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
)
)(CheckoutPage)