/
CheckoutPage.js
293 lines (263 loc) · 7.79 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
// @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
} from "../../lib/ecommerce"
import { createCyberSourceForm } from "../../lib/form"
import type { Response } from "redux-query"
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>>,
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) {
const payload = {
items: [{ id: productId }]
}
const couponCode = params.code
if (couponCode) {
payload.coupons = [{ code: couponCode }]
}
await this.updateBasket(payload)
} else {
await fetchBasket()
}
}
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>
<div className="row">
You are about to purchase the following program
</div>
{item.courses.map(course => (
<div className="row course-row" key={course.id}>
<img src={course.thumbnail_url} alt={course.title} />
<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}>
{run.title}
</option>
))}
</select>
</div>
</div>
))}
</React.Fragment>
)
} else {
return (
<React.Fragment>
<div className="row">
You are about to purchase the following course run
</div>
<div className="row course-row">
<img src={item.thumbnail_url} alt={item.description} />
<div className="title-column">
<div className="title">{item.description}</div>
</div>
</div>
</React.Fragment>
)
}
}
render() {
const { basket } = this.props
const { couponCode, errors } = this.state
if (!basket) {
return null
}
const item = basket.items[0]
if (!item) {
return <div>No item in basket</div>
}
const coupon = basket.coupons.find(coupon =>
coupon.targets.includes(item.id)
)
return (
<div className="checkout-page">
{this.renderBasketItem(item)}
<div className="row price-row">Price {formatPrice(item.price)}</div>
{coupon ? (
<div className="row discount-row">
Discount applied {formatPrice(calculateDiscount(item, coupon))}
</div>
) : null}
<div className="row">Coupon (optional)</div>
<div className="row coupon-code-row">
<form onSubmit={this.submitCoupon}>
<input
type="text"
value={
(couponCode !== null ? couponCode : coupon && coupon.code) || ""
}
onChange={this.updateCouponCode}
/>
<button type="submit">Update</button>
</form>
</div>
<div className="row total-row">
Total {formatPrice(calculatePrice(item, coupon))}
</div>
{errors ? <div className="error">Error: {errors}</div> : null}
<button className="checkout" onClick={this.submit}>
Place your order
</button>
</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)