-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathAddEditCouponViewModel.swift
697 lines (623 loc) · 30.5 KB
/
AddEditCouponViewModel.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
import Foundation
import Yosemite
import Combine
import UIKit
import WooFoundation
import protocol Storage.StorageManagerType
import SwiftUI
/// View model for `AddEditCoupon` view
///
final class AddEditCouponViewModel: ObservableObject {
private let siteID: Int64
/// Based on the Editing Option, the `AddEditCoupon` view can be in Creation or Editing mode.
///
private let editingOption: EditingOption
private let onSuccess: (Coupon) -> Void
/// Defines the current notice that should be shown.
/// Defaults to `nil`.
///
@Published var notice: Notice?
var title: String {
switch editingOption {
case .creation:
return Localization.createCouponTitle
case .editing:
return Localization.editCouponTitle
}
}
/// Defines the main action button text that should be shown.
/// Switching between `Create` or `Save` action.
///
var addEditCouponButtonText: String {
switch editingOption {
case .creation:
return Localization.createButton
case .editing:
return Localization.saveButton
}
}
/// The value for populating the coupon discount type field based on the `discountType`.
///
var discountTypeValue: TitleAndValueRow.Value {
return .content(discountType.localizedName)
}
/// Label representing the label of the amount field, localized based on discount type.
///
var amountLabel: String {
switch discountType {
case .percent:
return Localization.amountPercent
default:
let currencyCode = ServiceLocator.currencySettings.currencyCode
let unit = ServiceLocator.currencySettings.symbol(from: currencyCode)
return String.localizedStringWithFormat(Localization.amountFixedDiscount, unit)
}
}
/// Label representing the label of the amount textfield subtitle, localized based on discount type.
///
var amountSubtitleDefaultText: String {
switch discountType {
case .percent:
return Localization.amountPercentSubtitle
default:
return Localization.amountFixedDiscountSubtitle
}
}
/// Icon of the button for editing a coupon description, based on the field (populated or not).
///
var editDescriptionIcon: UIImage {
if descriptionField.isEmpty {
return .plusImage
}
return .pencilImage
}
/// Label of the button for editing a coupon description, based on the field (populated or not).
///
var editDescriptionLabel: String {
if descriptionField.isEmpty {
return Localization.addDescriptionButton
}
return Localization.editDescriptionButton
}
/// The value for populating the coupon expiry date field based on the `expiryDateField`.
///
var expiryDateValue: TitleAndValueRow.Value {
guard expiryDateField == nil else {
return .content(expiryDateField?.toString(dateStyle: .long, timeStyle: .none, timeZone: timezone) ?? "")
}
return .placeholder(Localization.couponExpiryDatePlaceholder)
}
/// View model for the product selector
///
var productSelectorViewModel: ProductSelectorViewModel {
ProductSelectorViewModel(siteID: siteID,
source: .couponForm,
selectedItemIDs: productOrVariationIDs,
onMultipleSelectionCompleted: { [weak self] ids in
self?.productOrVariationIDs = ids
})
}
/// Title for the Edit Products button with the number of selected products.
///
var editProductsButtonTitle: String {
String.localizedStringWithFormat(Localization.editProductsButton, productOrVariationIDs.count)
}
/// View model for the category selector
///
var categorySelectorViewModel: ProductCategorySelectorViewModel {
.init(siteID: siteID, selectedCategories: categoryIDs) { [weak self] categories in
self?.categoryIDs = categories.map { $0.categoryID }
}
}
/// Title for the Edit Categories button with the number of selected product categories.
///
var editCategoriesButtonTitle: String {
String.localizedStringWithFormat(Localization.editProductCategoriesButton, categoryIDs.count)
}
/// Whether the coupon is applicable to any specified products.
///
var hasSelectedProducts: Bool {
productOrVariationIDs.isNotEmpty
}
/// Whether the coupon is applicable to any specified product categories.
///
var hasSelectedCategories: Bool {
categoryIDs.isNotEmpty
}
var shareCouponMessage: String {
coupon?.generateShareMessage(currencySettings: currencySettings) ?? ""
}
var hasChangesMade: Bool {
let coupon = populatedCoupon
return checkDiscountTypeUpdated(for: coupon) ||
checkAmountUpdated(for: coupon) ||
checkDescriptionUpdated(for: coupon) ||
checkCouponCodeUpdated(for: coupon) ||
checkAllowedProductsAndCategoriesUpdated(for: coupon) ||
checkExpiryDateUpdated(for: coupon) ||
checkFreeShippingUpdated(for: coupon) ||
checkUsageRestrictionsUpdated(for: coupon)
}
private(set) var coupon: Coupon?
private let stores: StoresManager
private let storageManager: StorageManagerType
private let currencySettings: CurrencySettings
private let inputWarningDurationInSeconds: Double
let timezone: TimeZone
/// Sets the amount of time that an invalid amount percent input must stay
/// visible to the user before adjusting the value.
///
private let couponAmountInputFormatter: CouponAmountInputFormatter
/// When an invalid percentage amount is set a debouncing warning timer is triggered.
///
private var amountWarningTimer: Timer? = nil
/// When the view is updating or creating a new Coupon remotely.
///
@Published var isLoading: Bool = false
@Published private(set) var isDisplayingAmountWarning: Bool = false
// Fields
@Published var discountType: Coupon.DiscountType {
didSet {
validatePercentageAmountInput(withWarning: true)
couponRestrictionsViewModel.onDiscountTypeChanged(discountType: discountType)
}
}
@Published var amountField: String
@Published var amountFieldColor: Color
@Published var amountSubtitleLabel: String
@Published var amountSubtitleColor: Color
@Published var codeField: String
@Published var descriptionField: String
@Published var expiryDateField: Date?
@Published var freeShipping: Bool
@Published var couponRestrictionsViewModel: CouponRestrictionsViewModel
@Published var productOrVariationIDs: [Int64]
@Published var categoryIDs: [Int64]
@Published var showingCouponCreationSuccess: Bool = false
private var subscriptions: Set<AnyCancellable> = []
/// Keeping track of the initial discount type to check for changes
private let initialDiscountType: Coupon.DiscountType
/// Keeping track of the initial coupon code to check for changes
private let initialCouponCode: String
/// Init method for coupon creation
///
init(siteID: Int64 = ServiceLocator.stores.sessionManager.defaultStoreID ?? 0,
discountType: Coupon.DiscountType,
stores: StoresManager = ServiceLocator.stores,
storageManager: StorageManagerType = ServiceLocator.storageManager,
currencySettings: CurrencySettings = ServiceLocator.currencySettings,
couponAmountInputFormatter: CouponAmountInputFormatter = CouponAmountInputFormatter(),
inputWarningDurationInSeconds: Double = 3,
timezone: TimeZone = .siteTimezone,
onSuccess: @escaping (Coupon) -> Void) {
self.siteID = siteID
editingOption = .creation
self.discountType = discountType
self.stores = stores
self.storageManager = storageManager
self.currencySettings = currencySettings
self.couponAmountInputFormatter = couponAmountInputFormatter
self.inputWarningDurationInSeconds = inputWarningDurationInSeconds
self.timezone = timezone
self.onSuccess = onSuccess
amountField = String()
amountFieldColor = Color(.label)
amountSubtitleLabel = String()
amountSubtitleColor = Color(.textSubtle)
codeField = String()
descriptionField = String()
expiryDateField = nil
freeShipping = false
couponRestrictionsViewModel = CouponRestrictionsViewModel(siteID: siteID)
productOrVariationIDs = []
categoryIDs = []
initialCouponCode = Self.generateRandomCouponCode()
codeField = initialCouponCode
initialDiscountType = discountType
configureWarningBehavior()
}
/// Init method for coupon editing
///
init(existingCoupon: Coupon,
stores: StoresManager = ServiceLocator.stores,
storageManager: StorageManagerType = ServiceLocator.storageManager,
currencySettings: CurrencySettings = ServiceLocator.currencySettings,
couponAmountInputFormatter: CouponAmountInputFormatter = CouponAmountInputFormatter(),
inputWarningDurationInSeconds: Double = 3,
timezone: TimeZone = .siteTimezone,
onSuccess: @escaping (Coupon) -> Void) {
siteID = existingCoupon.siteID
coupon = existingCoupon
editingOption = .editing
discountType = existingCoupon.discountType
self.stores = stores
self.storageManager = storageManager
self.currencySettings = currencySettings
self.couponAmountInputFormatter = couponAmountInputFormatter
self.inputWarningDurationInSeconds = inputWarningDurationInSeconds
self.timezone = timezone
self.onSuccess = onSuccess
// Populate fields
amountField = existingCoupon.amount
amountFieldColor = Color(.label)
amountSubtitleLabel = String()
amountSubtitleColor = Color(.textSubtle)
codeField = existingCoupon.code
descriptionField = existingCoupon.description
expiryDateField = existingCoupon.dateExpires
freeShipping = existingCoupon.freeShipping
couponRestrictionsViewModel = CouponRestrictionsViewModel(coupon: existingCoupon)
productOrVariationIDs = existingCoupon.productIds
categoryIDs = existingCoupon.productCategories
initialCouponCode = existingCoupon.code
initialDiscountType = existingCoupon.discountType
configureWarningBehavior()
}
/// The method will generate a code in the same way as the existing admin website code does.
/// https://github.com/woocommerce/woocommerce/blob/23710744c01ded649d6a94a4eaea8745e543159f/assets/js/admin/meta-boxes-coupon.js#L53
/// We will loop to select 8 characters from the set `ABCDEFGHJKMNPQRSTUVWXYZ23456789` at random using `arc4random_uniform` for randomness.
/// https://github.com/woocommerce/woocommerce/blob/2e60d47a019a6e35f066f3ef43a56c0e761fc8e3/includes/admin/class-wc-admin-assets.php#L295
///
private static func generateRandomCouponCode() -> String {
let dictionary: [String] = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".map { String($0) }
let generatedCodeLength = 8
var code: String = ""
for _ in 0 ..< generatedCodeLength {
code += dictionary.randomElement() ?? ""
}
return code
}
private func configureWarningBehavior() {
let amountSubtitleDefaultText = amountSubtitleDefaultText
let warningColor = Color(.textWarning)
let labelColor = Color(.label)
let subtitleColor = Color(.textSubtle)
$isDisplayingAmountWarning
.removeDuplicates()
.sink { [weak self] isDisplaying in
if isDisplaying {
self?.amountFieldColor = warningColor
self?.amountSubtitleColor = warningColor
self?.amountSubtitleLabel = Localization.amountPercentWarningSubtitle
} else {
self?.amountFieldColor = labelColor
self?.amountSubtitleColor = subtitleColor
self?.amountSubtitleLabel = amountSubtitleDefaultText
}
}
.store(in: &subscriptions)
}
func updateCodeFieldWithRandomCode() {
codeField = Self.generateRandomCouponCode()
}
@discardableResult
func validatePercentageAmountInput(withWarning: Bool) -> CouponError? {
guard discountType == .percent else { return nil }
let formattedAmount = couponAmountInputFormatter.format(input: amountField)
guard let convertedAmount = couponAmountInputFormatter.value(from: formattedAmount)?.doubleValue else {
amountField = "0"
return .couponPercentAmountInvalid
}
if convertedAmount > 100 {
if withWarning {
debounceWarningState()
} else {
return .couponPercentAmountInvalid
}
}
return nil
}
private func debounceWarningState() {
isDisplayingAmountWarning = true
amountWarningTimer = Timer.scheduledTimer(
withTimeInterval: inputWarningDurationInSeconds,
repeats: false) { [weak self] timer in
timer.invalidate()
self?.amountWarningTimer = nil
self?.isDisplayingAmountWarning = false
self?.amountField = "100"
}
}
func completeCouponAddEdit(coupon: Coupon, onUpdateFinished: @escaping () -> Void) {
switch editingOption {
case .creation:
createCoupon(coupon: coupon)
case .editing:
updateCoupon(coupon: coupon, onUpdateFinished: onUpdateFinished)
}
}
private func createCoupon(coupon: Coupon) {
trackCouponCreateInitiated(with: coupon)
if let validationError = validateCouponLocally(coupon) {
notice = NoticeFactory.createCouponErrorNotice(validationError,
editingOption: editingOption)
return
}
isLoading = true
let action = CouponAction.createCoupon(coupon, siteTimezone: timezone) { [weak self] result in
guard let self = self else { return }
self.isLoading = false
switch result {
case .success(let coupon):
ServiceLocator.analytics.track(.couponCreationSuccess)
self.coupon = coupon
self.onSuccess(coupon)
self.showingCouponCreationSuccess = true
case .failure(let error):
DDLogError("⛔️ Error creating the coupon: \(error)")
ServiceLocator.analytics.track(.couponCreationFailed, withError: error)
self.notice = NoticeFactory.createCouponErrorNotice(.other(error: error),
editingOption: self.editingOption)
}
}
stores.dispatch(action)
}
private func updateCoupon(coupon: Coupon, onUpdateFinished: @escaping () -> Void) {
trackCouponUpdateInitiated(with: coupon)
if let validationError = validateCouponLocally(coupon) {
notice = NoticeFactory.createCouponErrorNotice(validationError,
editingOption: editingOption)
return
}
isLoading = true
let action = CouponAction.updateCoupon(coupon, siteTimezone: timezone) { [weak self] result in
guard let self = self else { return }
self.isLoading = false
switch result {
case .success(let updatedCoupon):
ServiceLocator.analytics.track(.couponUpdateSuccess)
self.onSuccess(updatedCoupon)
onUpdateFinished()
case .failure(let error):
DDLogError("⛔️ Error updating the coupon: \(error)")
ServiceLocator.analytics.track(.couponUpdateFailed, withError: error)
self.notice = NoticeFactory.createCouponErrorNotice(.other(error: error),
editingOption: self.editingOption)
}
}
stores.dispatch(action)
}
/// Default coupon when coupon creation is initiated
private lazy var defaultCoupon: Coupon = {
.init(siteID: siteID,
couponID: -1,
code: initialCouponCode,
amount: "0.00",
dateCreated: Date(),
dateModified: Date(),
discountType: initialDiscountType,
description: "",
dateExpires: nil,
usageCount: 0,
individualUse: false,
productIds: [],
excludedProductIds: [],
usageLimit: nil,
usageLimitPerUser: nil,
limitUsageToXItems: nil,
freeShipping: false,
productCategories: [],
excludedProductCategories: [],
excludeSaleItems: false,
minimumAmount: "",
maximumAmount: "",
emailRestrictions: [],
usedBy: [])
}()
/// Coupon generated from input
var populatedCoupon: Coupon {
let emailRestrictions: [String] = {
if couponRestrictionsViewModel.allowedEmails.isEmpty {
return []
}
return couponRestrictionsViewModel.allowedEmails.components(separatedBy: ", ")
}()
return Coupon(siteID: siteID,
couponID: coupon?.couponID ?? -1,
code: codeField,
amount: amountField,
dateCreated: coupon?.dateCreated ?? Date(),
dateModified: coupon?.dateModified ?? Date(),
discountType: discountType,
description: descriptionField,
dateExpires: expiryDateField?.startOfDay(timezone: timezone),
usageCount: coupon?.usageCount ?? 0,
individualUse: couponRestrictionsViewModel.individualUseOnly,
productIds: productOrVariationIDs,
excludedProductIds: couponRestrictionsViewModel.excludedProductOrVariationIDs,
usageLimit: Int64(couponRestrictionsViewModel.usageLimitPerCoupon),
usageLimitPerUser: Int64(couponRestrictionsViewModel.usageLimitPerUser),
limitUsageToXItems: Int64(couponRestrictionsViewModel.limitUsageToXItems),
freeShipping: freeShipping,
productCategories: categoryIDs,
excludedProductCategories: couponRestrictionsViewModel.excludedCategoryIDs,
excludeSaleItems: couponRestrictionsViewModel.excludeSaleItems,
minimumAmount: couponRestrictionsViewModel.minimumSpend,
maximumAmount: couponRestrictionsViewModel.maximumSpend,
emailRestrictions: emailRestrictions,
usedBy: coupon?.usedBy ?? [])
}
func validateCouponLocally(_ coupon: Coupon) -> CouponError? {
if coupon.code.isEmpty {
return .couponCodeEmpty
}
amountWarningTimer?.invalidate()
isDisplayingAmountWarning = false
return validatePercentageAmountInput(withWarning: false)
}
enum EditingOption {
case creation
case editing
}
enum CouponError: Error, Equatable {
case couponCodeEmpty
case couponPercentAmountInvalid
case other(error: Error)
static func ==(lhs: CouponError, rhs: CouponError) -> Bool {
return lhs.localizedDescription == rhs.localizedDescription
}
}
}
// MARK: - Helpers
//
private extension AddEditCouponViewModel {
func checkDiscountTypeUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
return coupon.discountType != initialCoupon.discountType
}
func checkUsageRestrictionsOnCreation(of coupon: Coupon) -> Bool {
coupon.maximumAmount.isNotEmpty ||
coupon.minimumAmount.isNotEmpty ||
(coupon.usageLimit ?? 0) > 0 ||
(coupon.usageLimitPerUser ?? 0) > 0 ||
(coupon.limitUsageToXItems ?? 0) > 0 ||
coupon.emailRestrictions.isNotEmpty ||
coupon.individualUse ||
coupon.excludeSaleItems ||
coupon.excludedProductIds.isNotEmpty ||
coupon.excludedProductCategories.isNotEmpty
}
func checkUsageRestrictionsUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
let amountFormatter = CouponAmountInputFormatter()
return amountFormatter.value(from: coupon.maximumAmount) != amountFormatter.value(from: initialCoupon.maximumAmount) ||
amountFormatter.value(from: coupon.minimumAmount) != amountFormatter.value(from: initialCoupon.minimumAmount) ||
coupon.usageLimit != initialCoupon.usageLimit ||
coupon.usageLimitPerUser != initialCoupon.usageLimitPerUser ||
coupon.limitUsageToXItems != initialCoupon.limitUsageToXItems ||
coupon.emailRestrictions != initialCoupon.emailRestrictions ||
coupon.individualUse != initialCoupon.individualUse ||
coupon.excludeSaleItems != initialCoupon.excludeSaleItems ||
coupon.excludedProductIds != initialCoupon.excludedProductIds ||
coupon.excludedProductCategories != initialCoupon.excludedProductCategories
}
func checkExpiryDateUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
// since we're trimming time on the new date, we should also trim the time on the old date
// as a workaround for the edge case where the date was created with different time zones.
guard let oldDate = initialCoupon.dateExpires?.startOfDay(timezone: timezone),
let newDate = coupon.dateExpires else {
return initialCoupon.dateExpires != coupon.dateExpires
}
return !oldDate.isSameDay(as: newDate)
}
func checkCouponCodeUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
return coupon.code.lowercased() != initialCoupon.code.lowercased()
}
func checkAmountUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
let amountFormatter = CouponAmountInputFormatter()
return amountFormatter.value(from: coupon.amount) != amountFormatter.value(from: initialCoupon.amount)
}
func checkDescriptionUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
return coupon.description != initialCoupon.description
}
func checkAllowedProductsAndCategoriesUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
return coupon.productIds != initialCoupon.productIds || coupon.productCategories != initialCoupon.productCategories
}
func checkFreeShippingUpdated(for coupon: Coupon) -> Bool {
let initialCoupon = self.coupon ?? defaultCoupon
return coupon.freeShipping != initialCoupon.freeShipping
}
func trackCouponCreateInitiated(with coupon: Coupon) {
ServiceLocator.analytics.track(.couponCreationInitiated, withProperties: [
"discount_type": coupon.discountType.rawValue,
"has_expiry_date": coupon.dateExpires != nil,
"includes_free_shipping": coupon.freeShipping,
"has_description": coupon.description.isNotEmpty,
"has_product_or_category_restrictions": coupon.excludedProductCategories.isNotEmpty || coupon.excludedProductIds.isNotEmpty,
"has_usage_restrictions": checkUsageRestrictionsOnCreation(of: coupon)
])
}
func trackCouponUpdateInitiated(with coupon: Coupon) {
ServiceLocator.analytics.track(.couponUpdateInitiated, withProperties: [
"discount_type_updated": checkDiscountTypeUpdated(for: coupon),
"coupon_code_updated": checkCouponCodeUpdated(for: coupon),
"amount_updated": checkAmountUpdated(for: coupon),
"description_updated": checkDescriptionUpdated(for: coupon),
"allowed_products_or_categories_updated": checkAllowedProductsAndCategoriesUpdated(for: coupon),
"expiry_date_updated": checkExpiryDateUpdated(for: coupon),
"usage_restrictions_updated": checkUsageRestrictionsUpdated(for: coupon)
])
}
}
// MARK: - Constants
//
private extension AddEditCouponViewModel {
/// Coupon notices
///
enum NoticeFactory {
/// Returns a default coupon editing/creation error notice.
///
static func createCouponErrorNotice(_ couponError: AddEditCouponViewModel.CouponError,
editingOption: AddEditCouponViewModel.EditingOption) -> Notice {
switch couponError {
case .couponCodeEmpty:
return Notice(title: Localization.errorCouponCodeEmpty, feedbackType: .error)
case .couponPercentAmountInvalid:
return Notice(title: Localization.errorCouponAmountInvalid, feedbackType: .error)
default:
switch editingOption {
case .editing:
return Notice(title: Localization.genericUpdateCouponError, feedbackType: .error)
case .creation:
return Notice(title: Localization.genericCreateCouponError, feedbackType: .error)
}
}
}
}
enum Localization {
static let amountPercent = NSLocalizedString("Amount (%)",
comment: "Title of the Amount field in the Coupon Edit" +
" or Creation screen for a percentage discount coupon.")
static let amountFixedDiscount = NSLocalizedString("Amount (%@)",
comment: "Title of the Amount field on the Coupon Edit" +
" or Creation screen for a fixed amount discount coupon." +
"Reads like: Amount ($)")
static let amountPercentSubtitle = NSLocalizedString("Set the percentage of the discount you want to offer.",
comment: "Subtitle of the Amount field in the Coupon Edit" +
" or Creation screen for a percentage discount coupon.")
static let amountPercentWarningSubtitle = NSLocalizedString("Percentages cannot be greater than 100%",
comment: "Subtitle of the Amount field when a percentage " +
"higher than 100 is set in the Coupon Edit or Creation " +
"screen for a percentage discount coupon.")
static let amountFixedDiscountSubtitle = NSLocalizedString("Set the fixed amount of the discount you want to offer.",
comment: "Subtitle of the Amount field on the Coupon Edit" +
" or Creation screen for a fixed amount discount coupon.")
static let addDescriptionButton = NSLocalizedString("Add Description (Optional)",
comment: "Button for adding a description to a coupon in the view for adding or editing a coupon.")
static let editDescriptionButton = NSLocalizedString("Edit Description",
comment: "Button for editing the description of a coupon in the" +
" view for adding or editing a coupon.")
static let couponExpiryDatePlaceholder = NSLocalizedString(
"None",
comment: "Coupon expiry date placeholder in the view for adding or editing a coupon")
static let errorCouponCodeEmpty = NSLocalizedString("The coupon code couldn't be empty",
comment: "Error message in the Add Edit Coupon screen when the coupon code is empty.")
static let errorCouponAmountInvalid = NSLocalizedString("The coupon amount cannot be greater than" +
" 100 for percentage discounts",
comment: "Error message in the Add Edit Coupon screen when the coupon amount is " +
"higher than 100% for a percentage discount")
static let genericUpdateCouponError = NSLocalizedString("Something went wrong while updating the coupon.",
comment: "Error message in the Add Edit Coupon screen " +
"when the update of the coupon goes in error.")
static let genericCreateCouponError = NSLocalizedString("Something went wrong while creating the coupon.",
comment: "Error message in the Add Edit Coupon screen " +
"when the creation of the coupon goes in error.")
static let editProductsButton = NSLocalizedString(
"Edit Products (%1$d)",
comment: "Button specifying the number of products applicable to a coupon in the view for adding or editing a coupon. " +
"Reads like: Edit Products (2)")
static let editProductCategoriesButton = NSLocalizedString(
"Edit Product Categories (%1$d)",
comment: "Button for specify the product categories where a coupon can be applied in the view for adding or editing a coupon. " +
"Reads like: Edit Categories")
static let createCouponTitle = NSLocalizedString("Create coupon", comment: "Title of the Create coupon screen")
static let editCouponTitle = NSLocalizedString("Edit coupon", comment: "Title of the Edit coupon screen")
static let saveButton = NSLocalizedString("Save", comment: "Action for saving a Coupon remotely")
static let createButton = NSLocalizedString("Create", comment: "Action for creating a Coupon remotely")
}
}