forked from woocommerce/woocommerce-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrderDetailsViewController.swift
967 lines (793 loc) · 36.7 KB
/
OrderDetailsViewController.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
import UIKit
import Gridicons
import Contacts
import Yosemite
import SafariServices
import MessageUI
import Combine
import SwiftUI
// MARK: - OrderDetailsViewController: Displays the details for a given Order.
//
final class OrderDetailsViewController: UIViewController {
/// Main Stack View, that contains all the other views of the screen
///
@IBOutlet private weak var stackView: UIStackView!
/// Main TableView.
///
@IBOutlet private weak var tableView: UITableView!
/// The top loader view, that will be embedded inside the stackview, on top of the tableview, while the screen is loading its
/// content for the first time.
///
private var topLoaderView: TopLoaderView = {
let loaderView: TopLoaderView = TopLoaderView.instantiateFromNib()
loaderView.setBody(Localization.Generic.topLoaderBannerDescription)
return loaderView
}()
/// Pull To Refresh Support.
///
private lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
return refreshControl
}()
/// Top banner that announces shipping labels features.
///
private var topBannerView: TopBannerView?
/// EntityListener: Update / Deletion Notifications.
///
private lazy var entityListener: EntityListener<Order> = {
return EntityListener(storageManager: ServiceLocator.storageManager, readOnlyEntity: viewModel.order)
}()
/// Order to be rendered!
///
var viewModel: OrderDetailsViewModel! {
didSet {
reloadTableViewSectionsAndData()
}
}
private let notices = OrderDetailsNotices()
// MARK: - View Lifecycle
/// Create an instance of `Self` from its corresponding storyboard.
///
static func instantiatedViewControllerFromStoryboard() -> Self? {
let storyboard = UIStoryboard.orders
let identifier = "OrderDetailsViewController"
return storyboard.instantiateViewController(withIdentifier: identifier) as? Self
}
override func viewDidLoad() {
super.viewDidLoad()
configureNavigation()
configureTopLoaderView()
configureTableView()
registerTableViewCells()
registerTableViewHeaderFooters()
configureEntityListener()
configureViewModel()
updateTopBannerView()
// FIXME: this is a hack. https://github.com/woocommerce/woocommerce-ios/issues/1779
reloadTableViewSectionsAndData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
syncEverything { [weak self] in
self?.topLoaderView.isHidden = true
/// We add the refresh control to the tableview just after the `topLoaderView` disappear for the first time.
if self?.tableView.refreshControl == nil {
self?.tableView.refreshControl = self?.refreshControl
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.updateHeaderHeight()
}
override var shouldShowOfflineBanner: Bool {
return true
}
}
// MARK: - TableView Configuration
//
private extension OrderDetailsViewController {
/// Setup: TopLoaderView
func configureTopLoaderView() {
stackView.insertArrangedSubview(topLoaderView, at: 0)
}
/// Setup: TableView
///
func configureTableView() {
view.backgroundColor = .listBackground
tableView.backgroundColor = .listBackground
tableView.estimatedSectionHeaderHeight = Constants.sectionHeight
tableView.estimatedRowHeight = Constants.rowHeight
tableView.rowHeight = UITableView.automaticDimension
tableView.dataSource = viewModel.dataSource
}
/// Setup: Navigation
///
func configureNavigation() {
let titleFormat = NSLocalizedString("Order #%1$@", comment: "Order number title. Parameters: %1$@ - order number")
title = String.localizedStringWithFormat(titleFormat, viewModel.order.number)
}
/// Setup: EntityListener
///
func configureEntityListener() {
entityListener.onUpsert = { [weak self] order in
guard let self = self else {
return
}
self.viewModel.update(order: order)
self.reloadTableViewSectionsAndData()
}
}
private func configureViewModel() {
viewModel.onUIReloadRequired = { [weak self] in
self?.reloadTableViewDataIfPossible()
}
viewModel.configureResultsControllers { [weak self] in
self?.reloadTableViewSectionsAndData()
}
viewModel.onCellAction = { [weak self] (actionType, indexPath) in
self?.handleCellAction(actionType, at: indexPath)
}
viewModel.onShippingLabelMoreMenuTapped = { [weak self] shippingLabel, sourceView in
self?.shippingLabelMoreMenuTapped(shippingLabel: shippingLabel, sourceView: sourceView)
}
viewModel.onProductsMoreMenuTapped = { [weak self] sourceView in
self?.productsMoreMenuTapped(sourceView: sourceView)
}
}
/// Reloads the tableView's data, assuming the view has been loaded.
///
func reloadTableViewDataIfPossible() {
guard isViewLoaded else {
return
}
tableView.reloadData()
updateTopBannerView()
}
/// Reloads the tableView's sections and data.
///
func reloadTableViewSectionsAndData() {
reloadSections()
reloadTableViewDataIfPossible()
}
/// Registers all of the available TableViewCells
///
func registerTableViewCells() {
viewModel.registerTableViewCells(tableView)
}
/// Registers all of the available TableViewHeaderFooters
///
func registerTableViewHeaderFooters() {
viewModel.registerTableViewHeaderFooters(tableView)
}
}
// MARK: - Sections
//
private extension OrderDetailsViewController {
func reloadSections() {
viewModel.reloadSections()
}
}
// MARK: - Notices
//
private extension OrderDetailsViewController {
/// Displays the `Unable to delete tracking` Notice.
///
func displayDeleteErrorNotice(order: Order, tracking: ShipmentTracking) {
notices.displayDeleteErrorNotice(order: order, tracking: tracking) { [weak self] in
self?.deleteTracking(tracking)
}
}
}
// MARK: - Top Banner
//
private extension OrderDetailsViewController {
func updateTopBannerView() {
let factory = ShippingLabelsTopBannerFactory(shouldShowShippingLabelCreation: viewModel.dataSource.shouldShowShippingLabelCreation,
shippingLabels: viewModel.dataSource.shippingLabels)
let isExpanded = topBannerView?.isExpanded ?? false
factory.createTopBannerIfNeeded(isExpanded: isExpanded,
expandedStateChangeHandler: { [weak self] in
self?.tableView.updateHeaderHeight()
}, onGiveFeedbackButtonPressed: { [weak self] in
self?.presentShippingLabelsFeedbackSurvey()
}, onDismissButtonPressed: { [weak self] in
self?.dismissTopBanner()
}, onCompletion: { [weak self] topBannerView in
if let topBannerView = topBannerView {
self?.showTopBannerView(topBannerView)
} else {
self?.hideTopBannerView()
}
})
}
func showTopBannerView(_ topBannerView: TopBannerView) {
guard tableView.tableHeaderView == nil else {
return
}
self.topBannerView = topBannerView
// A frame-based container view is needed for table view's `tableHeaderView` and its height is recalculated in `viewDidLayoutSubviews`, so that the
// top banner view can be Auto Layout based with dynamic height.
let headerContainer = UIView(frame: CGRect(x: 0, y: 0, width: Int(tableView.frame.width), height: Int(Constants.headerDefaultHeight)))
headerContainer.addSubview(topBannerView)
headerContainer.pinSubviewToAllEdges(topBannerView, insets: Constants.headerContainerInsets)
tableView.tableHeaderView = headerContainer
tableView.updateHeaderHeight()
}
func hideTopBannerView() {
guard tableView.tableHeaderView != nil else {
return
}
topBannerView?.removeFromSuperview()
topBannerView = nil
tableView.tableHeaderView = nil
tableView.updateHeaderHeight()
}
func presentShippingLabelsFeedbackSurvey() {
let navigationController = SurveyCoordinatingController(survey: .shippingLabelsRelease3Feedback)
present(navigationController, animated: true, completion: nil)
}
func dismissTopBanner() {
hideTopBannerView()
}
}
// MARK: - Action Handlers
//
private extension OrderDetailsViewController {
@objc func pullToRefresh() {
ServiceLocator.analytics.track(.orderDetailPulledToRefresh)
refreshControl.beginRefreshing()
syncEverything { [weak self] in
NotificationCenter.default.post(name: .ordersBadgeReloadRequired, object: nil)
self?.refreshControl.endRefreshing()
}
}
}
// MARK: - Sync'ing Helpers
//
private extension OrderDetailsViewController {
func syncEverything(onCompletion: (() -> ())? = nil) {
let group = DispatchGroup()
group.enter()
syncOrder { _ in
group.leave()
}
group.enter()
syncProducts { _ in
group.leave()
}
group.enter()
syncProductVariations { _ in
group.leave()
}
group.enter()
syncRefunds() { _ in
group.leave()
}
group.enter()
syncShippingLabels() { _ in
group.leave()
}
group.enter()
syncNotes { _ in
group.leave()
}
group.enter()
syncTrackingsEnablingAddButtonIfReachable {
group.leave()
}
group.enter()
checkShippingLabelCreationEligibility {
group.leave()
}
group.enter()
refreshCardPresentPaymentEligibility()
group.leave()
group.enter()
syncSavedReceipts {_ in
group.leave()
}
group.enter()
checkOrderAddOnFeatureSwitchState {
group.leave()
}
group.notify(queue: .main) {
onCompletion?()
}
}
func syncOrder(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncOrder { [weak self] (order, error) in
guard let self = self, let order = order else {
onCompletion?(error)
return
}
self.viewModel.update(order: order)
onCompletion?(nil)
}
}
func syncTracking(onCompletion: ((Error?) -> Void)? = nil) {
viewModel.syncTracking(onCompletion: onCompletion)
}
func syncNotes(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncNotes(onCompletion: onCompletion)
}
func syncProducts(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncProducts(onCompletion: onCompletion)
}
func syncProductVariations(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncProductVariations(onCompletion: onCompletion)
}
func syncRefunds(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncRefunds(onCompletion: onCompletion)
}
func syncShippingLabels(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncShippingLabels(onCompletion: onCompletion)
}
func syncSavedReceipts(onCompletion: ((Error?) -> ())? = nil) {
viewModel.syncSavedReceipts(onCompletion: onCompletion)
}
func syncTrackingsEnablingAddButtonIfReachable(onCompletion: (() -> Void)? = nil) {
syncTracking { [weak self] error in
if error == nil {
self?.viewModel.trackingIsReachable = true
}
self?.reloadTableViewSectionsAndData()
onCompletion?()
}
}
func checkShippingLabelCreationEligibility(onCompletion: (() -> Void)? = nil) {
viewModel.checkShippingLabelCreationEligibility { [weak self] in
self?.reloadTableViewSectionsAndData()
onCompletion?()
}
}
func refreshCardPresentPaymentEligibility() {
viewModel.refreshCardPresentPaymentEligibility()
}
func checkOrderAddOnFeatureSwitchState(onCompletion: (() -> Void)? = nil) {
viewModel.checkOrderAddOnFeatureSwitchState { [weak self] in
self?.reloadTableViewSectionsAndData()
onCompletion?()
}
}
func deleteTracking(_ tracking: ShipmentTracking) {
let order = viewModel.order
viewModel.deleteTracking(tracking) { [weak self] error in
if let _ = error {
self?.displayDeleteErrorNotice(order: order, tracking: tracking)
return
}
self?.reloadSections()
}
}
func syncOrderAfterPaymentCollection(onCompletion: @escaping ()-> Void) {
let group = DispatchGroup()
group.enter()
syncOrder { _ in
group.leave()
}
group.enter()
syncNotes { _ in
group.leave()
}
group.enter()
syncSavedReceipts { _ in
group.leave()
}
group.notify(queue: .main) {
NotificationCenter.default.post(name: .ordersBadgeReloadRequired, object: nil)
onCompletion()
}
}
}
// MARK: - Actions
//
private extension OrderDetailsViewController {
func handleCellAction(_ type: OrderDetailsDataSource.CellActionType, at indexPath: IndexPath?) {
switch type {
case .markComplete:
markOrderCompleteWasPressed()
case .summary:
displayOrderStatusList()
case .tracking:
guard let indexPath = indexPath else {
break
}
trackingWasPressed(at: indexPath)
case .issueRefund:
issueRefundWasPressed()
case .collectPayment:
guard indexPath != nil else {
break
}
collectPayment()
case .reprintShippingLabel(let shippingLabel):
guard let navigationController = navigationController else {
assertionFailure("Cannot reprint a shipping label because `navigationController` is nil")
return
}
let coordinator = PrintShippingLabelCoordinator(shippingLabels: [shippingLabel],
printType: .reprint,
sourceNavigationController: navigationController)
coordinator.showPrintUI()
case .createShippingLabel:
navigateToCreateShippingLabelForm()
case .shippingLabelTrackingMenu(let shippingLabel, let sourceView):
shippingLabelTrackingMoreMenuTapped(shippingLabel: shippingLabel, sourceView: sourceView)
case let .viewAddOns(addOns):
itemAddOnsButtonTapped(addOns: addOns)
case .editCustomerNote:
editCustomerNoteTapped()
case .editShippingAddress:
editShippingAddressTapped()
}
}
func navigateToCreateShippingLabelForm() {
let shippingLabelFormVC = ShippingLabelFormViewController(order: viewModel.order)
shippingLabelFormVC.onLabelPurchase = { [weak self] isOrderComplete in
if isOrderComplete {
self?.markOrderCompleteFromShippingLabels()
}
}
shippingLabelFormVC.onLabelSave = { [weak self] in
guard let self = self, let navigationController = self.navigationController, navigationController.viewControllers.contains(self) else {
// Navigate back to order details when presented from push notification
if let orderLoaderVC = self?.parent as? OrderLoaderViewController {
self?.navigationController?.popToViewController(orderLoaderVC, animated: true)
}
return
}
navigationController.popToViewController(self, animated: true)
}
shippingLabelFormVC.hidesBottomBarWhenPushed = true
navigationController?.show(shippingLabelFormVC, sender: self)
}
func markOrderCompleteWasPressed() {
ServiceLocator.analytics.track(.orderFulfillmentCompleteButtonTapped)
let reviewOrderViewModel = ReviewOrderViewModel(order: viewModel.order, products: viewModel.products, showAddOns: viewModel.dataSource.showAddOns)
let controller = ReviewOrderViewController(viewModel: reviewOrderViewModel) { [weak self] in
guard let self = self else { return }
let fulfillmentProcess = self.viewModel.markCompleted()
let presenter = OrderFulfillmentNoticePresenter()
presenter.present(process: fulfillmentProcess)
}
navigationController?.pushViewController(controller, animated: true)
}
func markOrderCompleteFromShippingLabels() {
let fulfillmentProcess = self.viewModel.markCompleted()
var cancellables = Set<AnyCancellable>()
var cancellable: AnyCancellable = AnyCancellable { }
cancellable = fulfillmentProcess.result.sink { completion in
if case .failure(_) = completion {
ServiceLocator.analytics.track(.shippingLabelOrderFulfillFailed)
}
else {
ServiceLocator.analytics.track(.shippingLabelOrderFulfillSucceeded)
}
cancellables.remove(cancellable)
} receiveValue: {
// Noop. There is no value to receive or act on.
}
// Insert in `cancellables` to keep the `sink` handler active.
cancellables.insert(cancellable)
}
func trackingWasPressed(at indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? OrderTrackingTableViewCell else {
return
}
displayShipmentTrackingAlert(from: cell, indexPath: indexPath)
}
func openTrackingDetails(_ tracking: ShipmentTracking) {
guard let trackingURL = tracking.trackingURL?.addHTTPSSchemeIfNecessary(),
let url = URL(string: trackingURL) else {
return
}
ServiceLocator.analytics.track(.orderDetailTrackPackageButtonTapped)
displayWebView(url: url)
}
func issueRefundWasPressed() {
let issueRefundCoordinatingController = IssueRefundCoordinatingController(order: viewModel.order, refunds: viewModel.refunds)
present(issueRefundCoordinatingController, animated: true)
}
func displayWebView(url: URL) {
let safariViewController = SFSafariViewController(url: url)
present(safariViewController, animated: true, completion: nil)
}
func productsMoreMenuTapped(sourceView: UIView) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.view.tintColor = .text
actionSheet.addCancelActionWithTitle(Localization.ProductsMoreMenu.cancelAction)
actionSheet.addDefaultActionWithTitle(Localization.ProductsMoreMenu.createShippingLabelAction) { [weak self] _ in
self?.navigateToCreateShippingLabelForm()
}
let popoverController = actionSheet.popoverPresentationController
popoverController?.sourceView = sourceView
present(actionSheet, animated: true)
}
func shippingLabelMoreMenuTapped(shippingLabel: ShippingLabel, sourceView: UIView) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.view.tintColor = .text
actionSheet.addCancelActionWithTitle(Localization.ShippingLabelMoreMenu.cancelAction)
actionSheet.addDefaultActionWithTitle(Localization.ShippingLabelMoreMenu.requestRefundAction) { [weak self] _ in
let refundViewController = RefundShippingLabelViewController(shippingLabel: shippingLabel) { [weak self] in
self?.navigationController?.popViewController(animated: true)
}
// Disables the bottom bar (tab bar) when requesting a refund.
refundViewController.hidesBottomBarWhenPushed = true
self?.show(refundViewController, sender: self)
}
if let url = shippingLabel.commercialInvoiceURL, url.isNotEmpty {
actionSheet.addDefaultActionWithTitle(Localization.ShippingLabelMoreMenu.printCustomsFormAction) { [weak self] _ in
let printCustomsFormsView = PrintCustomsFormsView(invoiceURLs: [url])
let hostingController = UIHostingController(rootView: printCustomsFormsView)
hostingController.hidesBottomBarWhenPushed = true
self?.show(hostingController, sender: self)
}
}
let popoverController = actionSheet.popoverPresentationController
popoverController?.sourceView = sourceView
present(actionSheet, animated: true)
}
func shippingLabelTrackingMoreMenuTapped(shippingLabel: ShippingLabel, sourceView: UIView) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.view.tintColor = .text
actionSheet.addCancelActionWithTitle(Localization.ShippingLabelTrackingMoreMenu.cancelAction)
actionSheet.addDefaultActionWithTitle(Localization.ShippingLabelTrackingMoreMenu.copyTrackingNumberAction) { [weak self] _ in
ServiceLocator.analytics.track(event: .shipmentTrackingMenu(action: .copy))
self?.viewModel.dataSource.sendToPasteboard(shippingLabel.trackingNumber, includeTrailingNewline: false)
}
// Only shows the tracking action when there is a tracking URL.
if let url = ShippingLabelTrackingURLGenerator.url(for: shippingLabel) {
actionSheet.addDefaultActionWithTitle(Localization.ShippingLabelTrackingMoreMenu.trackShipmentAction) { [weak self] _ in
guard let self = self else { return }
ServiceLocator.analytics.track(event: .shipmentTrackingMenu(action: .track))
let safariViewController = SFSafariViewController(url: url)
safariViewController.modalPresentationStyle = .pageSheet
self.present(safariViewController, animated: true, completion: nil)
}
}
let popoverController = actionSheet.popoverPresentationController
popoverController?.sourceView = sourceView
present(actionSheet, animated: true)
}
func editCustomerNoteTapped() {
let viewModel = EditCustomerNoteViewModel(order: viewModel.order)
let editNoteViewController = EditCustomerNoteHostingController(viewModel: viewModel)
present(editNoteViewController, animated: true, completion: nil)
ServiceLocator.analytics.track(event: WooAnalyticsEvent.OrderDetailsEdit.orderDetailEditFlowStarted(subject: .customerNote))
}
func editShippingAddressTapped() {
let viewModel = EditOrderAddressFormViewModel(order: viewModel.order, type: .shipping)
let editAddressViewController = EditOrderAddressHostingController(viewModel: viewModel)
let navigationController = WooNavigationController(rootViewController: editAddressViewController)
present(navigationController, animated: true, completion: nil)
}
@objc private func collectPayment() {
viewModel.collectPayment(rootViewController: self, backButtonTitle: Localization.Payments.backToOrder) { [weak self] result in
guard let self = self else { return }
// Refresh date & view once payment has been collected.
if result.isSuccess {
self.syncOrderAfterPaymentCollection {
self.refreshCardPresentPaymentEligibility()
}
}
}
}
private func itemAddOnsButtonTapped(addOns: [OrderItemAttribute]) {
let addOnsViewModel = OrderAddOnListI1ViewModel(attributes: addOns)
let addOnsController = OrderAddOnsListViewController(viewModel: addOnsViewModel)
let navigationController = WooNavigationController(rootViewController: addOnsController)
present(navigationController, animated: true, completion: nil)
}
}
// MARK: - UITableViewDelegate Conformance
//
extension OrderDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
viewModel.tableView(tableView, in: self, didSelectRowAt: indexPath)
}
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
guard viewModel.dataSource.checkIfCopyingIsAllowed(for: indexPath) else {
// Only allow the leading swipe action on the address rows
return UISwipeActionsConfiguration(actions: [])
}
let copyActionTitle = NSLocalizedString("Copy", comment: "Copy address text button title — should be one word and as short as possible.")
let copyAction = UIContextualAction(style: .normal, title: copyActionTitle) { [weak self] (action, view, success) in
self?.viewModel.dataSource.copyText(at: indexPath)
success(true)
}
copyAction.backgroundColor = .primary
return UISwipeActionsConfiguration(actions: [copyAction])
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// No trailing action on any cell
return UISwipeActionsConfiguration(actions: [])
}
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return viewModel.dataSource.checkIfCopyingIsAllowed(for: indexPath)
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(copy(_:))
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
guard action == #selector(copy(_:)) else {
return
}
viewModel.dataSource.copyText(at: indexPath)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Remove the first header
if section == 0 {
return CGFloat.leastNormalMagnitude
}
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return viewModel.dataSource.viewForHeaderInSection(section, tableView: tableView)
}
}
// MARK: - Trackings alert
// Track / delete tracking alert
private extension OrderDetailsViewController {
/// Displays an alert that offers deleting a shipment tracking or opening
/// it in a webview
///
func displayShipmentTrackingAlert(from sourceView: UIView, indexPath: IndexPath) {
guard let tracking = viewModel.dataSource.orderTracking(at: indexPath) else {
return
}
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.view.tintColor = .text
actionSheet.addCancelActionWithTitle(TrackingAction.dismiss)
actionSheet.addDefaultActionWithTitle(TrackingAction.copyTrackingNumber) { [weak self] _ in
self?.viewModel.dataSource.copyText(at: indexPath)
}
if tracking.trackingURL?.isEmpty == false {
actionSheet.addDefaultActionWithTitle(TrackingAction.trackShipment) { [weak self] _ in
self?.openTrackingDetails(tracking)
}
}
actionSheet.addDestructiveActionWithTitle(TrackingAction.deleteTracking) { [weak self] _ in
ServiceLocator.analytics.track(.orderDetailTrackingDeleteButtonTapped)
self?.deleteTracking(tracking)
}
let popoverController = actionSheet.popoverPresentationController
popoverController?.sourceView = sourceView
popoverController?.sourceRect = sourceView.bounds
present(actionSheet, animated: true)
}
}
// MARK: - Order Status List Child View
//
private extension OrderDetailsViewController {
private func displayOrderStatusList() {
ServiceLocator.analytics.track(.orderDetailOrderStatusEditButtonTapped,
withProperties: ["status": viewModel.order.status.rawValue])
let statusList = OrderStatusListViewController(siteID: viewModel.order.siteID,
status: viewModel.order.status)
statusList.didSelectCancel = { [weak statusList] in
statusList?.dismiss(animated: true, completion: nil)
}
statusList.didSelectApply = { [weak statusList] (selectedStatus) in
statusList?.dismiss(animated: true) {
self.setOrderStatus(to: selectedStatus)
}
}
let navigationController = WooNavigationController(rootViewController: statusList)
present(navigationController, animated: true)
}
func setOrderStatus(to newStatus: OrderStatusEnum) {
let orderID = viewModel.order.orderID
let undoStatus = viewModel.order.status
let done = updateOrderStatusAction(siteID: viewModel.order.siteID, orderID: viewModel.order.orderID, status: newStatus)
let undo = updateOrderStatusAction(siteID: viewModel.order.siteID, orderID: viewModel.order.orderID, status: undoStatus)
ServiceLocator.stores.dispatch(done)
ServiceLocator.analytics.track(event: WooAnalyticsEvent.Orders.orderStatusChange(flow: .editing, orderID: orderID, from: undoStatus, to: newStatus))
notices.orderUpdateNotice = displayOrderStatusUpdatedNotice { [weak self] in
guard let self = self else { return }
ServiceLocator.stores.dispatch(undo)
ServiceLocator.analytics.track(event: WooAnalyticsEvent.Orders.orderStatusChange(flow: .editing, orderID: orderID, from: newStatus, to: undoStatus))
self.notices.orderUpdateNotice = nil
}
}
/// Returns an Order Update Action that will result in the specified Order Status updated accordingly.
///
private func updateOrderStatusAction(siteID: Int64, orderID: Int64, status: OrderStatusEnum) -> Action {
return OrderAction.updateOrderStatus(siteID: siteID, orderID: orderID, status: status, onCompletion: { [weak self] error in
guard let error = error else {
NotificationCenter.default.post(name: .ordersBadgeReloadRequired, object: nil)
self?.syncNotes()
ServiceLocator.analytics.track(.orderStatusChangeSuccess)
return
}
ServiceLocator.analytics.track(.orderStatusChangeFailed, withError: error)
DDLogError("⛔️ Order Update Failure: [\(orderID).status = \(status)]. Error: \(error)")
self?.displayOrderStatusErrorNotice(orderID: orderID, status: status)
})
}
/// Enqueues the `Order Updated` Notice. Whenever the `Undo` button gets pressed, we'll execute the `onUndoAction` closure.
///
private func displayOrderStatusUpdatedNotice(onUndoAction: @escaping () -> Void) -> Notice {
let message = NSLocalizedString("Order status updated", comment: "Order status update success notice")
let actionTitle = NSLocalizedString("Undo", comment: "Undo Action")
let notice = Notice(title: message, feedbackType: .success, actionTitle: actionTitle, actionHandler: onUndoAction)
ServiceLocator.noticePresenter.enqueue(notice: notice)
return notice
}
/// Enqueues the `Unable to Change Status of Order` Notice.
///
private func displayOrderStatusErrorNotice(orderID: Int64, status: OrderStatusEnum) {
let titleFormat = NSLocalizedString(
"Unable to change status of order #%1$d",
comment: "Content of error presented when updating the status of an Order fails. "
+ "It reads: Unable to change status of order #{order number}. "
+ "Parameters: %1$d - order number"
)
let title = String.localizedStringWithFormat(titleFormat, orderID)
let actionTitle = NSLocalizedString("Retry", comment: "Retry Action")
let notice = Notice(title: title, message: nil, feedbackType: .error, actionTitle: actionTitle) { [weak self] in
self?.setOrderStatus(to: status)
}
if let orderUpdateNotice = notices.orderUpdateNotice {
ServiceLocator.noticePresenter.cancel(notice: orderUpdateNotice)
}
ServiceLocator.noticePresenter.enqueue(notice: notice)
}
}
// MARK: - Constants
//
private extension OrderDetailsViewController {
enum TrackingAction {
static let dismiss = NSLocalizedString("Dismiss", comment: "Dismiss the shipment tracking action sheet")
static let copyTrackingNumber = NSLocalizedString("Copy Tracking Number", comment: "Copy tracking number button title")
static let trackShipment = NSLocalizedString("Track Shipment", comment: "Track shipment button title")
static let deleteTracking = NSLocalizedString("Delete Tracking", comment: "Delete tracking button title")
}
enum Localization {
enum Generic {
static let topLoaderBannerDescription = NSLocalizedString("Loading content",
comment: "Text of the loading banner in Order Detail when loaded for the first time")
}
enum ProductsMoreMenu {
static let cancelAction = NSLocalizedString("Cancel", comment: "Cancel the more menu action sheet on Products section")
static let createShippingLabelAction = NSLocalizedString("Create Shipping Label",
comment: "Option to create new shipping label from the action " +
"sheet on Products section of Order Details screen")
}
enum ShippingLabelMoreMenu {
static let cancelAction = NSLocalizedString("Cancel", comment: "Cancel the shipping label more menu action sheet")
static let requestRefundAction = NSLocalizedString("Request a Refund",
comment: "Request a refund on a shipping label from the shipping label more menu action sheet")
static let printCustomsFormAction = NSLocalizedString("Print Customs Form",
comment: "Print the customs form for the shipping label" +
" from the shipping label more menu action sheet")
}
enum ShippingLabelTrackingMoreMenu {
static let cancelAction = NSLocalizedString("Cancel", comment: "Cancel the shipping label tracking more menu action sheet")
static let copyTrackingNumberAction =
NSLocalizedString("Copy tracking number",
comment: "Copy tracking number of a shipping label from the shipping label tracking more menu action sheet")
static let trackShipmentAction =
NSLocalizedString("Track shipment",
comment: "Track shipment of a shipping label from the shipping label tracking more menu action sheet")
}
enum Payments {
static let backToOrder = NSLocalizedString("Back to Order",
comment: "Button to dismiss modal overlay and go back to the order after a sucessful payment")
}
}
enum Constants {
static let headerDefaultHeight = CGFloat(130)
static let headerContainerInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
static let rowHeight = CGFloat(38)
static let sectionHeight = CGFloat(44)
}
/// Mailing a receipt failed but the SDK didn't return a more specific error
///
struct UnknownEmailError: Error {}
}