-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathAddEditCoupon.swift
456 lines (411 loc) · 23.6 KB
/
AddEditCoupon.swift
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import SwiftUI
import WordPressUI
import Yosemite
final class AddEditCouponHostingController: UIHostingController<AddEditCoupon> {
private let viewModel: AddEditCouponViewModel
init(viewModel: AddEditCouponViewModel, onDisappear: @escaping (_ success: Bool) -> Void) {
self.viewModel = viewModel
super.init(rootView: AddEditCoupon(viewModel))
rootView.onDisappear = onDisappear
rootView.dismissHandler = { [weak self] in
self?.dismiss(animated: true)
}
rootView.discountTypeHandler = { [weak self] viewProperties in
guard let self = self else { return }
let command = DiscountTypeBottomSheetListSelectorCommand(selected: self.viewModel.discountType) { [weak self] selectedType in
guard let self = self else { return }
viewModel.discountType = selectedType
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
let bottomSheet = BottomSheetListSelectorViewController(viewProperties: viewProperties, command: command, onDismiss: nil)
let bottomSheetViewController = BottomSheetViewController(childViewController: bottomSheet)
bottomSheetViewController.show(from: self)
}
}
required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
presentationController?.delegate = self
}
}
extension AddEditCouponHostingController: UIAdaptivePresentationControllerDelegate {
func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
return !viewModel.hasChangesMade
}
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
UIAlertController.presentDiscardChangesActionSheet(viewController: self) { [weak self] in
self?.dismiss(animated: true)
}
}
}
/// A view for Adding or Editing a Coupon.
///
struct AddEditCoupon: View {
/// Set this closure with UIKit dismiss code. Needed because we need access to the UIHostingController `dismiss` method.
///
var dismissHandler: () -> Void = {}
/// Set this closure with SwiftUI onDisappear code. Needed because we need to set this event from a UIKit object.
///
var onDisappear: (_ success: Bool) -> Void = { _ in }
/// Set this closure to display the bottom sheet for discount type selection the UIKit way.
///
var discountTypeHandler: (BottomSheetListSelectorViewProperties) -> Void = { _ in }
private let viewProperties = BottomSheetListSelectorViewProperties(subtitle: Localization.discountTypeSheetTitle)
@ObservedObject private var viewModel: AddEditCouponViewModel
@State private var showingEditDescription: Bool = false
@State private var showingCouponExpiryDate: Bool = false
@State private var showingCouponRestrictions: Bool = false
@State private var showingSelectProducts: Bool = false
@State private var showingSelectCategories: Bool = false
private let categorySelectorConfig = ProductCategorySelector.Configuration.categoriesForCoupons
private let categoryListConfig = ProductCategoryListViewController.Configuration(searchEnabled: true, clearSelectionEnabled: true)
init(_ viewModel: AddEditCouponViewModel) {
self.viewModel = viewModel
}
var body: some View {
NavigationView {
GeometryReader { geometry in
ScrollView {
VStack (alignment: .leading, spacing: 0) {
Group {
ListHeaderView(text: Localization.headerCouponDetails.uppercased(), alignment: .left)
Group {
TitleAndValueRow(title: Localization.discountType,
value: viewModel.discountTypeValue,
selectionStyle: .disclosure, action: {
discountTypeHandler(viewProperties)
})
Divider()
.padding(.leading, Constants.margin)
TitleAndTextFieldRow(title: viewModel.amountLabel,
placeholder: "0",
text: $viewModel.amountField,
editable: true,
fieldAlignment: .leading,
keyboardType: .decimalPad,
contentColor: viewModel.amountFieldColor,
inputFormatter: CouponAmountInputFormatter()) { beginningEditing in
if !beginningEditing {
viewModel.validatePercentageAmountInput(withWarning: true)
}
}
Divider()
.padding(.leading, Constants.margin)
Text(viewModel.amountSubtitleLabel)
.foregroundColor(viewModel.amountSubtitleColor)
.subheadlineStyle()
.padding(.horizontal, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
Group {
TitleAndTextFieldRow(title: Localization.couponCode,
placeholder: Localization.couponCodePlaceholder,
text: $viewModel.codeField,
editable: true,
fieldAlignment: .leading,
keyboardType: .default,
inputFormatter: CouponCodeInputFormatter())
Divider()
.padding(.leading, Constants.margin)
.padding(.bottom, Constants.verticalSpacing)
Text(Localization.footerCouponCode)
.subheadlineStyle()
.padding(.horizontal, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
Button {
viewModel.updateCodeFieldWithRandomCode()
} label: {
Text(Localization.regenerateCouponCodeButton)
}
.buttonStyle(LinkButtonStyle())
.fixedSize()
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, Constants.verticalSpacing)
Button {
showingEditDescription = true
} label: {
HStack {
Image(uiImage: viewModel.editDescriptionIcon)
.resizable()
.colorMultiply(Color(.text))
.frame(width: Constants.iconSize, height: Constants.iconSize)
Text(viewModel.editDescriptionLabel)
.bodyStyle()
}
}
.buttonStyle(SecondaryButtonStyle())
.padding(.horizontal, Constants.margin)
.padding(.bottom, Constants.verticalSpacing)
Group {
TitleAndValueRow(title: Localization.couponExpiryDate,
value: viewModel.expiryDateValue,
selectionStyle: .disclosure, action: {
showingCouponExpiryDate = true
})
Divider()
.padding(.leading, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
Group {
TitleAndToggleRow(title: Localization.includeFreeShipping, isOn: $viewModel.freeShipping)
.padding(.horizontal, Constants.margin)
Divider()
.padding(.leading, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
}
Group {
ListHeaderView(text: Localization.headerApplyCouponTo.uppercased(), alignment: .left)
.padding(.bottom, Constants.verticalSpacing)
Button {
showingSelectProducts = true
} label: {
HStack {
if viewModel.hasSelectedProducts {
Image(uiImage: .pencilImage)
.resizable()
.colorMultiply(Color(.text))
.frame(width: Constants.iconSize, height: Constants.iconSize)
Text(viewModel.editProductsButtonTitle)
.bodyStyle()
} else {
Text(Localization.allProductsButton)
.bodyStyle()
}
}
}
.buttonStyle(SecondaryButtonStyle())
.padding(.horizontal, Constants.margin)
.padding(.bottom, Constants.verticalSpacing)
Button {
showingSelectCategories = true
} label: {
HStack {
if viewModel.hasSelectedCategories {
Image(uiImage: .pencilImage)
.resizable()
.colorMultiply(Color(.text))
.frame(width: Constants.iconSize, height: Constants.iconSize)
Text(viewModel.editCategoriesButtonTitle)
.bodyStyle()
} else {
Image(uiImage: .plusImage)
.resizable()
.frame(width: Constants.iconSize, height: Constants.iconSize)
Text(Localization.selectCategoriesButton)
.bodyStyle()
}
}
}
.buttonStyle(SecondaryButtonStyle())
.padding(.horizontal, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
Group {
ListHeaderView(text: Localization.headerUsageDetails.uppercased(), alignment: .left)
TitleAndValueRow(title: Localization.usageRestrictions,
value: .placeholder(""),
selectionStyle: .disclosure, action: {
showingCouponRestrictions = true
})
Divider()
.padding(.leading, Constants.margin)
}
.padding(.bottom, Constants.verticalSpacing)
Button {
// TODO: This should be replaced with `@FocusState` when we drop support for iOS 14
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
viewModel.completeCouponAddEdit(coupon: viewModel.populatedCoupon, onUpdateFinished: {
dismissHandler()
})
} label: {
Text(viewModel.addEditCouponButtonText)
}
.buttonStyle(PrimaryLoadingButtonStyle(isLoading: viewModel.isLoading))
.padding(.horizontal, Constants.margin)
.padding([.top, .bottom], Constants.verticalSpacing)
.disabled(!viewModel.hasChangesMade)
LazyNavigationLink(destination: FullScreenTextView(title: Localization.titleEditDescriptionView,
text: $viewModel.descriptionField,
placeholder: Localization.addDescriptionPlaceholder),
isActive: $showingEditDescription) {
EmptyView()
}
LazyNavigationLink(destination: CouponExpiryDateView(date: viewModel.expiryDateField ?? Date(),
isRemovalEnabled: viewModel.expiryDateField != nil,
timezone: viewModel.timezone,
onCompletion: { updatedExpiryDate in
viewModel.expiryDateField = updatedExpiryDate
}), isActive: $showingCouponExpiryDate) {
EmptyView()
}
LazyNavigationLink(destination: CouponRestrictions(viewModel: viewModel.couponRestrictionsViewModel),
isActive: $showingCouponRestrictions) {
EmptyView()
}
}
}
}
.sheet(isPresented: $showingSelectProducts) {
ProductSelectorNavigationView(configuration: .productsForCoupons,
isPresented: $showingSelectProducts,
viewModel: viewModel.productSelectorViewModel)
.onDisappear {
viewModel.productSelectorViewModel.clearSearchAndFilters()
}
}
.sheet(isPresented: $showingSelectCategories) {
ProductCategorySelector(isPresented: $showingSelectCategories,
viewConfig: categorySelectorConfig,
categoryListConfig: categoryListConfig,
viewModel: viewModel.categorySelectorViewModel)
}
.sheet(isPresented: $viewModel.showingCouponCreationSuccess) {
let couponCode = viewModel.coupon?.code ?? ""
if couponCode.isEmpty {
let _ = DDLogError("⛔️ Error acquiring the coupon code after creation")
}
CouponCreationSuccess(couponCode: couponCode, shareMessage: viewModel.shareCouponMessage) {
onDisappear(true)
}
}
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button(Localization.cancelButton, action: {
dismissHandler()
})
}
}
.notice($viewModel.notice)
.navigationTitle(viewModel.title)
.navigationBarTitleDisplayMode(.large)
.wooNavigationBarStyle()
}
.navigationViewStyle(.stack)
.onDisappear {
onDisappear(false)
}
}
}
// MARK: - Constants
//
private extension AddEditCoupon {
enum Constants {
static let margin: CGFloat = 16
static let verticalSpacing: CGFloat = 8
static let iconSize: CGFloat = 16
}
enum Localization {
static let cancelButton = NSLocalizedString(
"Cancel",
comment: "Cancel button in the navigation bar of the view for adding or editing a coupon.")
static let headerCouponDetails = NSLocalizedString(
"Coupon details",
comment: "Header of the coupon details in the view for adding or editing a coupon.")
static let couponCode = NSLocalizedString(
"Coupon Code",
comment: "Text field coupon code in the view for adding or editing a coupon code.")
static let couponCodePlaceholder = NSLocalizedString(
"Enter a coupon",
comment: "Text field coupon code placeholder in the view for adding or editing a coupon.")
static let footerCouponCode = NSLocalizedString(
"Customers need to enter this code to use the coupon.",
comment: "The footer of the text field coupon code in the view for adding or editing a coupon.")
static let regenerateCouponCodeButton = NSLocalizedString(
"Regenerate Coupon Code",
comment: "Button in the view for adding or editing a coupon code.")
static let couponExpiryDate = NSLocalizedString(
"Coupon Expiry Date",
comment: "Field in the view for adding or editing a coupon's expiry date.")
static let discountType = NSLocalizedString(
"Discount Type",
comment: "Field in the view for adding or editing a coupon's discount type.")
static let includeFreeShipping = NSLocalizedString(
"Include Free Shipping?",
comment: "Toggle field in the view for adding or editing a coupon's free shipping support.")
static let headerApplyCouponTo = NSLocalizedString(
"Apply this coupon to",
comment: "Header of the section for applying a coupon to specific products or categories in the view " +
"for adding or editing a coupon's product and category restrictions.")
static let allProductsButton = NSLocalizedString(
"All Products",
comment: "Button indicating that coupon can be applied to all products in the view for adding or editing a coupon.")
static let selectCategoriesButton = NSLocalizedString(
"Select Product Categories",
comment: "Button to select specific categories applicable for a coupon in the view for adding or editing a coupon.")
static let headerUsageDetails = NSLocalizedString(
"Usage Details",
comment: "Header of the section usage details in the view for adding or editing a coupon.")
static let usageRestrictions = NSLocalizedString(
"Usage Restrictions",
comment: "Field in the view for adding or editing a coupon.")
static let addDescriptionPlaceholder = NSLocalizedString("Add the description of the coupon.",
comment: "Placeholder text that will be shown in the view" +
" for adding the description of a coupon.")
static let titleEditDescriptionView = NSLocalizedString("Coupon Description",
comment: "Title of the view for editing the coupon description.")
static let discountTypeSheetTitle = NSLocalizedString(
"Discount Type",
comment: "Title for the sheet to select discount type on the Add or Edit coupon screen."
)
}
}
#if DEBUG
struct AddEditCoupon_Previews: PreviewProvider {
static var previews: some View {
/// Edit Coupon
///
let editingViewModel = AddEditCouponViewModel(existingCoupon: Coupon.sampleCoupon, onSuccess: { _ in })
AddEditCoupon(editingViewModel)
}
}
#endif
private extension ProductSelectorView.Configuration {
static let productsForCoupons: Self =
.init(doneButtonTitleSingularFormat: Localization.doneButtonSingular,
doneButtonTitlePluralFormat: Localization.doneButtonPlural,
title: Localization.title,
cancelButtonTitle: Localization.cancel,
productRowAccessibilityHint: Localization.productRowAccessibilityHint,
variableProductRowAccessibilityHint: Localization.variableProductRowAccessibilityHint)
enum Localization {
static let title = NSLocalizedString("Select products", comment: "Title for the screen to select products for a coupon")
static let cancel = NSLocalizedString("Cancel", comment: "Text for the cancel button in the Select Products screen")
static let productRowAccessibilityHint = NSLocalizedString("Toggles selection for this product in a coupon.",
comment: "Accessibility hint for selecting a product in the Select Products screen")
static let variableProductRowAccessibilityHint = NSLocalizedString(
"Opens list of product variations.",
comment: "Accessibility hint for selecting a variable product in the Select Products screen"
)
static let doneButtonSingular = NSLocalizedString(
"Select 1 Product",
comment: "Title of the action button at the bottom of the Select Products screen when one product is selected"
)
static let doneButtonPlural = NSLocalizedString(
"Select %1$d Products",
comment: "Title of the action button at the bottom of the Select Products screen " +
"when more than 1 item is selected, reads like: Select 5 Products"
)
}
}
private extension ProductCategorySelector.Configuration {
static let categoriesForCoupons: Self = .init(
title: Localization.title,
doneButtonSingularFormat: Localization.doneSingularFormat,
doneButtonPluralFormat: Localization.donePluralFormat
)
enum Localization {
static let title = NSLocalizedString("Select categories", comment: "Title for the Select Categories screen")
static let doneSingularFormat = NSLocalizedString(
"Select %1$d Category",
comment: "Button to submit selection on the Select Categories screen when 1 item is selected")
static let donePluralFormat = NSLocalizedString(
"Select %1$d Categories",
comment: "Button to submit selection on the Select Categories screen " +
"when more than 1 item is selected. " +
"Reads like: Select 10 Categories")
}
}