summaryrefslogtreecommitdiff
path: root/chromium/components/autofill/core/browser/credit_card_save_manager.cc
blob: 910d5e02fd67c692457c7ff50b74c409f07037c2 (plain)
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/browser/credit_card_save_manager.h"

#include <stddef.h>
#include <stdint.h>

#include <algorithm>
#include <limits>
#include <map>
#include <set>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autofill_client.h"
#include "components/autofill/core/browser/autofill_experiments.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/legacy_strike_database.h"
#include "components/autofill/core/browser/payments/payments_client.h"
#include "components/autofill/core/browser/payments/payments_util.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/strike_database.h"
#include "components/autofill/core/browser/validation.h"
#include "components/autofill/core/common/autofill_clock.h"
#include "components/autofill/core/common/autofill_constants.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/autofill_util.h"
#include "services/identity/public/cpp/identity_manager.h"
#include "url/gurl.h"

namespace autofill {

namespace {

// If |name| consists of three whitespace-separated parts and the second of the
// three parts is a single character or a single character followed by a period,
// returns the result of joining the first and third parts with a space.
// Otherwise, returns |name|.
//
// Note that a better way to do this would be to use SplitName from
// src/components/autofill/core/browser/contact_info.cc. However, for now we
// want the logic of which variations of names are considered to be the same to
// exactly match the logic applied on the Payments server.
base::string16 RemoveMiddleInitial(const base::string16& name) {
  std::vector<base::StringPiece16> parts =
      base::SplitStringPiece(name, base::kWhitespaceUTF16,
                             base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  if (parts.size() == 3 && (parts[1].length() == 1 ||
                            (parts[1].length() == 2 &&
                             base::EndsWith(parts[1], base::ASCIIToUTF16("."),
                                            base::CompareCase::SENSITIVE)))) {
    parts.erase(parts.begin() + 1);
    return base::JoinString(parts, base::ASCIIToUTF16(" "));
  }
  return name;
}

}  // namespace

CreditCardSaveManager::CreditCardSaveManager(
    AutofillClient* client,
    payments::PaymentsClient* payments_client,
    const std::string& app_locale,
    PersonalDataManager* personal_data_manager)
    : client_(client),
      payments_client_(payments_client),
      app_locale_(app_locale),
      personal_data_manager_(personal_data_manager),
      weak_ptr_factory_(this) {
  // This is to initialize StrikeDatabase is if it hasn't been already, so that
  // its cache would be loaded and ready to use when the first CCSM is created.
  if (base::FeatureList::IsEnabled(
          features::kAutofillSaveCreditCardUsesStrikeSystemV2) ||
      base::FeatureList::IsEnabled(
          features::kAutofillLocalCardMigrationUsesStrikeSystemV2)) {
    // Only init when |kAutofillSaveCreditCardUsesStrikeSystemV2| is enabled. If
    // flag is off and LegacyStrikeDatabase instead of StrikeDatabase is used,
    // this init will cause failure on GetStrikes().
    client_->GetStrikeDatabase();
  }
}

CreditCardSaveManager::~CreditCardSaveManager() {}

void CreditCardSaveManager::AttemptToOfferCardLocalSave(
    bool has_non_focusable_field,
    const CreditCard& card) {
  local_card_save_candidate_ = card;
  show_save_prompt_ = base::nullopt;
  has_non_focusable_field_ = has_non_focusable_field;

  // Query the Autofill StrikeDatabase on if we should pop up the
  // offer-to-save prompt for this card.
  if (base::FeatureList::IsEnabled(
          features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
    OnDidGetStrikesForLocalSave(GetCreditCardSaveStrikeDatabase()->GetStrikes(
        base::UTF16ToUTF8(local_card_save_candidate_.LastFourDigits())));
  } else if (base::FeatureList::IsEnabled(
                 features::kAutofillSaveCreditCardUsesStrikeSystem)) {
    LegacyStrikeDatabase* strike_database = client_->GetLegacyStrikeDatabase();
    strike_database->GetStrikes(
        strike_database->GetKeyForCreditCardSave(
            base::UTF16ToUTF8(local_card_save_candidate_.LastFourDigits())),
        base::BindRepeating(&CreditCardSaveManager::OnDidGetStrikesForLocalSave,
                            weak_ptr_factory_.GetWeakPtr()));
  } else {
    // Skip retrieving data from the Autofill LegacyStrikeDatabase; assume 0
    // strikes.
    OnDidGetStrikesForLocalSave(0);
  }
}

void CreditCardSaveManager::AttemptToOfferCardUploadSave(
    const FormStructure& submitted_form,
    bool has_non_focusable_field,
    const CreditCard& card,
    const bool uploading_local_card) {
  // Abort the uploading if |payments_client_| is nullptr.
  if (!payments_client_)
    return;
  upload_request_ = payments::PaymentsClient::UploadRequestDetails();
  upload_request_.card = card;
  uploading_local_card_ = uploading_local_card;
  show_save_prompt_ = base::nullopt;

  // In an ideal scenario, when uploading a card, we would have:
  //  1) Card number and expiration
  //  2) CVC
  //  3) 1+ recently-used or modified addresses that meet validation rules (or
  //     only the address countries if the relevant feature is enabled).
  //  4) Cardholder name or names on the address profiles
  // At a minimum, only #1 (card number and expiration) is absolutely required
  // in order to save a card to Google Payments. We perform all checks before
  // returning or logging in order to know where we stand with regards to card
  // upload information. Then, we ping Google Payments and ask if upload save
  // should be offered with the given amount of information, letting Payments
  // make the final offer-to-save decision.
  found_cvc_field_ = false;
  found_value_in_cvc_field_ = false;
  found_cvc_value_in_non_cvc_field_ = false;

  has_non_focusable_field_ = has_non_focusable_field;

  for (const auto& field : submitted_form) {
    const bool is_valid_cvc = IsValidCreditCardSecurityCode(
        field->value, upload_request_.card.network());
    if (field->Type().GetStorableType() == CREDIT_CARD_VERIFICATION_CODE) {
      found_cvc_field_ = true;
      if (!field->value.empty())
        found_value_in_cvc_field_ = true;
      if (is_valid_cvc) {
        upload_request_.cvc = field->value;
        break;
      }
    } else if (is_valid_cvc &&
               field->Type().GetStorableType() == UNKNOWN_TYPE) {
      found_cvc_value_in_non_cvc_field_ = true;
    }
  }

  // Upload requires that recently used or modified addresses meet the
  // client-side validation rules. This call also begins setting the value of
  // |upload_decision_metrics_|.
  SetProfilesForCreditCardUpload(card, &upload_request_);

  pending_upload_request_origin_ = submitted_form.main_frame_origin();

  if (has_non_focusable_field_) {
    upload_decision_metrics_ |=
        AutofillMetrics::UPLOAD_OFFERED_FROM_NON_FOCUSABLE_FIELD;
  }

  if (upload_request_.cvc.empty()) {
    // Apply the CVC decision to |upload_decision_metrics_| to denote a problem
    // was found.
    upload_decision_metrics_ |= GetCVCCardUploadDecisionMetric();
  }

  // Add active Chrome experiments to the request payload here (currently none).

  // We store the detected values in the upload request, because the addresses
  // are being possibly modified in the next code block, and we want the
  // detected values to reflect addresses *before* they are modified.
  upload_request_.detected_values = GetDetectedValues();
  // If the user must provide cardholder name, log it and set
  // |should_request_name_from_user_| so the offer-to-save dialog know to ask
  // for it.
  should_request_name_from_user_ = false;
  if (upload_request_.detected_values & DetectedValue::USER_PROVIDED_NAME) {
    upload_decision_metrics_ |=
        AutofillMetrics::USER_REQUESTED_TO_PROVIDE_CARDHOLDER_NAME;
    should_request_name_from_user_ = true;
  }

  // If the user must provide expiration month or expration year, log it and set
  // |should_request_expiration_date_from_user_| so the offer-to-save dialog
  // knows to ask for it.
  should_request_expiration_date_from_user_ = false;
  if (upload_request_.detected_values &
      DetectedValue::USER_PROVIDED_EXPIRATION_DATE) {
    upload_decision_metrics_ |=
        AutofillMetrics::USER_REQUESTED_TO_PROVIDE_EXPIRATION_DATE;
    LogSaveCardRequestExpirationDateReasonMetric();
    should_request_expiration_date_from_user_ = true;
  }

  // The cardholder name and expiration date fix flows cannot both be
  // active at the same time.  If they are, abort offering upload.
  if (should_request_name_from_user_ &&
      should_request_expiration_date_from_user_) {
    DCHECK(base::FeatureList::IsEnabled(
        features::kAutofillUpstreamEditableExpirationDate));
    LogCardUploadDecisions(upload_decision_metrics_);
    pending_upload_request_origin_ = url::Origin();
    return;
  }
  // If the relevant feature is enabled, only send the country of the
  // recently-used addresses. We make a copy here to avoid modifying
  // |upload_request_.profiles|, which should always have full addresses even
  // after this function goes out of scope.
  bool send_only_country_in_addresses = base::FeatureList::IsEnabled(
      features::kAutofillSendOnlyCountryInGetUploadDetails);
  std::vector<AutofillProfile> country_only_profiles;
  if (send_only_country_in_addresses) {
    for (const AutofillProfile& address : upload_request_.profiles) {
      AutofillProfile country_only;
      country_only.SetInfo(ADDRESS_HOME_COUNTRY,
                           address.GetInfo(ADDRESS_HOME_COUNTRY, app_locale_),
                           app_locale_);
      country_only_profiles.emplace_back(std::move(country_only));
    }
  }

  // All required data is available, start the upload process.
  if (observer_for_testing_)
    observer_for_testing_->OnDecideToRequestUploadSave();
  payments_client_->GetUploadDetails(
      send_only_country_in_addresses ? country_only_profiles
                                     : upload_request_.profiles,
      upload_request_.detected_values, upload_request_.active_experiments,
      app_locale_,
      base::BindOnce(&CreditCardSaveManager::OnDidGetUploadDetails,
                     weak_ptr_factory_.GetWeakPtr()),
      payments::kUploadCardBillableServiceNumber,
      payments::PaymentsClient::UploadCardSource::UPSTREAM_CHECKOUT_FLOW);
  // Query the Autofill StrikeDatabase on if we should pop up the
  // offer-to-save prompt for this card.
  if (base::FeatureList::IsEnabled(
          features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
    OnDidGetStrikesForUploadSave(GetCreditCardSaveStrikeDatabase()->GetStrikes(
        base::UTF16ToUTF8(upload_request_.card.LastFourDigits())));
  } else if (base::FeatureList::IsEnabled(
                 features::kAutofillSaveCreditCardUsesStrikeSystem)) {
    LegacyStrikeDatabase* strike_database = client_->GetLegacyStrikeDatabase();
    strike_database->GetStrikes(
        strike_database->GetKeyForCreditCardSave(
            base::UTF16ToUTF8(upload_request_.card.LastFourDigits())),
        base::BindRepeating(
            &CreditCardSaveManager::OnDidGetStrikesForUploadSave,
            weak_ptr_factory_.GetWeakPtr()));
  } else {
    // Skip retrieving data from the Autofill LegacyStrikeDatabase; assume 0
    // strikes.
    OnDidGetStrikesForUploadSave(0);
  }
}

bool CreditCardSaveManager::IsCreditCardUploadEnabled() {
#if defined(OS_IOS)
  // If observer_for_testing_ is set, assume we are in a browsertest and
  // credit card upload should be enabled by default.
  // TODO(crbug.com/859761): Remove dependency from iOS tests on this behavior.
  if (observer_for_testing_)
    return true;
#endif  // defined(OS_IOS)
  return ::autofill::IsCreditCardUploadEnabled(
      client_->GetPrefs(), client_->GetSyncService(),
      personal_data_manager_->GetAccountInfoForPaymentsServer().email);
}

bool CreditCardSaveManager::IsUploadEnabledForNetwork(
    const std::string& network) {
  if (network == kEloCard &&
      base::FeatureList::IsEnabled(features::kAutofillUpstreamDisallowElo)) {
    return false;
  } else if (network == kJCBCard &&
             base::FeatureList::IsEnabled(
                 features::kAutofillUpstreamDisallowJcb)) {
    return false;
  }
  return true;
}

void CreditCardSaveManager::OnDidUploadCard(
    AutofillClient::PaymentsRpcResult result,
    const std::string& server_id) {
  if (observer_for_testing_)
    observer_for_testing_->OnReceivedUploadCardResponse();

  if (result == AutofillClient::SUCCESS &&
      upload_request_.card.HasFirstAndLastName()) {
    AutofillMetrics::LogSaveCardWithFirstAndLastNameComplete(
        /*is_local=*/false);
  }

  if (result == AutofillClient::SUCCESS) {
    // If the upload succeeds and we can store unmasked cards on this OS, we
    // will keep a copy of the card as a full server card on the device.
    if (!server_id.empty() &&
        OfferStoreUnmaskedCards(payments_client_->is_off_the_record()) &&
        !IsAutofillNoLocalSaveOnUploadSuccessExperimentEnabled()) {
      upload_request_.card.set_record_type(CreditCard::FULL_SERVER_CARD);
      upload_request_.card.SetServerStatus(CreditCard::OK);
      upload_request_.card.set_server_id(server_id);
      DCHECK(personal_data_manager_);
      if (personal_data_manager_)
        personal_data_manager_->AddFullServerCreditCard(upload_request_.card);
    }
    if (base::FeatureList::IsEnabled(
            features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
      // Log how many strikes the card had when it was saved.
      LogStrikesPresentWhenCardSaved(
          /*is_local=*/false,
          GetCreditCardSaveStrikeDatabase()->GetStrikes(
              base::UTF16ToUTF8(upload_request_.card.LastFourDigits())));

      // Clear all CreditCardSave strikes for this card, in case it is later
      // removed.
      GetCreditCardSaveStrikeDatabase()->ClearStrikes(
          base::UTF16ToUTF8(upload_request_.card.LastFourDigits()));
    } else if (base::FeatureList::IsEnabled(
                   features::kAutofillSaveCreditCardUsesStrikeSystem)) {
      LegacyStrikeDatabase* strike_database =
          client_->GetLegacyStrikeDatabase();
      // Log how many strikes the card had when it was saved.
      strike_database->GetStrikes(
          strike_database->GetKeyForCreditCardSave(
              base::UTF16ToUTF8(upload_request_.card.LastFourDigits())),
          base::BindRepeating(
              &CreditCardSaveManager::LogStrikesPresentWhenCardSaved,
              weak_ptr_factory_.GetWeakPtr(),
              /*is_local=*/false));
      // Clear all strikes for this card, in case it is later removed.
      strike_database->ClearAllStrikesForKey(
          strike_database->GetKeyForCreditCardSave(
              base::UTF16ToUTF8(upload_request_.card.LastFourDigits())),
          base::DoNothing());
    }
  } else {
    if (show_save_prompt_.value()) {
      if (base::FeatureList::IsEnabled(
              features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
        // If the upload failed and the bubble was actually shown (NOT just the
        // icon), count that as a strike against offering upload in the future.
        int nth_strike_added = GetCreditCardSaveStrikeDatabase()->AddStrike(
            base::UTF16ToUTF8(upload_request_.card.LastFourDigits()));
        // Notify the browsertests that a strike was added.
        OnStrikeChangeComplete(nth_strike_added);
      } else if (base::FeatureList::IsEnabled(
                     features::kAutofillSaveCreditCardUsesStrikeSystem)) {
        // If the upload failed and the bubble was actually shown (NOT just the
        // icon), count that as a strike against offering upload in the future.
        LegacyStrikeDatabase* strike_database =
            client_->GetLegacyStrikeDatabase();
        strike_database->AddStrike(
            strike_database->GetKeyForCreditCardSave(
                base::UTF16ToUTF8(upload_request_.card.LastFourDigits())),
            base::BindRepeating(&CreditCardSaveManager::OnStrikeChangeComplete,
                                weak_ptr_factory_.GetWeakPtr()));
      }
    }
  }
}

CreditCardSaveStrikeDatabase*
CreditCardSaveManager::GetCreditCardSaveStrikeDatabase() {
  if (credit_card_save_strike_database_.get() == nullptr) {
    credit_card_save_strike_database_ =
        std::make_unique<CreditCardSaveStrikeDatabase>(
            CreditCardSaveStrikeDatabase(client_->GetStrikeDatabase()));
  }
  return credit_card_save_strike_database_.get();
}

LocalCardMigrationStrikeDatabase*
CreditCardSaveManager::GetLocalCardMigrationStrikeDatabase() {
  if (local_card_migration_strike_database_.get() == nullptr) {
    local_card_migration_strike_database_ =
        std::make_unique<LocalCardMigrationStrikeDatabase>(
            LocalCardMigrationStrikeDatabase(client_->GetStrikeDatabase()));
  }
  return local_card_migration_strike_database_.get();
}

void CreditCardSaveManager::OnDidGetStrikesForLocalSave(const int num_strikes) {
  show_save_prompt_ =
      num_strikes < kMaxStrikesToPreventPoppingUpOfferToSavePrompt;

  OfferCardLocalSave();
}

void CreditCardSaveManager::OnDidGetStrikesForUploadSave(
    const int num_strikes) {
  show_save_prompt_ =
      num_strikes < kMaxStrikesToPreventPoppingUpOfferToSavePrompt;

  // Only offer upload once both Payments and the Autofill
  // LegacyStrikeDatabase have returned their decisions. Use population of
  // |upload_request_.context_token| as an indicator of the Payments call
  // returning successfully.
  if (!upload_request_.context_token.empty())
    OfferCardUploadSave();
}

void CreditCardSaveManager::OnDidGetUploadDetails(
    AutofillClient::PaymentsRpcResult result,
    const base::string16& context_token,
    std::unique_ptr<base::Value> legal_message,
    std::vector<std::pair<int, int>> supported_card_bin_ranges) {
  if (observer_for_testing_)
    observer_for_testing_->OnReceivedGetUploadDetailsResponse();
  if (result == AutofillClient::SUCCESS) {
    // Do *not* call payments_client_->Prepare() here. We shouldn't send
    // credentials until the user has explicitly accepted a prompt to upload.
    if (base::FeatureList::IsEnabled(
            features::kAutofillDoNotUploadSaveUnsupportedCards) &&
        !supported_card_bin_ranges.empty() &&
        !IsCreditCardSupported(supported_card_bin_ranges)) {
      AttemptToOfferCardLocalSave(has_non_focusable_field_,
                                  upload_request_.card);
      upload_decision_metrics_ |=
          AutofillMetrics::UPLOAD_NOT_OFFERED_UNSUPPORTED_BIN_RANGE;
      LogCardUploadDecisions(upload_decision_metrics_);
      return;
    }
    upload_request_.context_token = context_token;
    legal_message_ = base::DictionaryValue::From(std::move(legal_message));

    // Only offer upload once both Payments and the Autofill
    // LegacyStrikeDatabase have returned their decisions. Use presence of
    // |show_save_prompt_| as an indicator of LegacyStrikeDatabase retrieving
    // its data.
    if (show_save_prompt_ != base::nullopt)
      OfferCardUploadSave();
  } else {
    // If the upload details request failed and we *know* we have all possible
    // information (card number, expiration, cvc, name, and address), fall back
    // to a local save (for new cards only). It indicates that "Payments doesn't
    // want this card" or "Payments doesn't currently support this country", in
    // which case the upload details request will consistently fail and if we
    // don't fall back to a local save, the user will never be offered *any*
    // kind of credit card save. (Note that this could intermittently backfire
    // if there's a network breakdown or Payments outage, resulting in sometimes
    // showing upload and sometimes offering local save, but such cases should
    // be rare.)
    //
    // Note that calling AttemptToOfferCardLocalSave(~) pings the Autofill
    // LegacyStrikeDatabase again, but A) the result should be cached so this
    // shouldn't hit the disk, and B) the alternative would require hooking into
    // the LegacyStrikeDatabase's GetStrikes() call already in progress, which
    // would be hacky at worst and require additional class state variables at
    // best.
    bool found_name_and_postal_code_and_cvc =
        (upload_request_.detected_values & DetectedValue::CARDHOLDER_NAME ||
         upload_request_.detected_values & DetectedValue::ADDRESS_NAME) &&
        upload_request_.detected_values & DetectedValue::POSTAL_CODE &&
        upload_request_.detected_values & DetectedValue::CVC;
    if (found_name_and_postal_code_and_cvc && !uploading_local_card_) {
      AttemptToOfferCardLocalSave(has_non_focusable_field_,
                                  upload_request_.card);
    }
    upload_decision_metrics_ |=
        AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED;
    LogCardUploadDecisions(upload_decision_metrics_);
  }
}

void CreditCardSaveManager::OfferCardLocalSave() {
#if defined(OS_ANDROID) || defined(OS_IOS)
  bool is_mobile_build = true;
#else
  bool is_mobile_build = false;
#endif  // #if defined(OS_ANDROID) || defined(OS_IOS)

  // If |show_save_prompt_.value()| is false, desktop builds will still offer
  // save in the omnibox without popping-up the bubble. Mobile builds, however,
  // should not display the offer-to-save infobar at all.
  if (!is_mobile_build || show_save_prompt_.value()) {
    if (observer_for_testing_)
      observer_for_testing_->OnOfferLocalSave();
    client_->ConfirmSaveCreditCardLocally(
        local_card_save_candidate_,
        AutofillClient::SaveCreditCardOptions().with_show_prompt(
            show_save_prompt_.value()),
        base::BindOnce(&CreditCardSaveManager::OnUserDidDecideOnLocalSave,
                       weak_ptr_factory_.GetWeakPtr()));

    // Log metrics.
    if (local_card_save_candidate_.HasFirstAndLastName())
      AutofillMetrics::LogSaveCardWithFirstAndLastNameOffered(
          /*is_local=*/true);
  }
  if (!show_save_prompt_.value()) {
    AutofillMetrics::LogCreditCardSaveNotOfferedDueToMaxStrikesMetric(
        AutofillMetrics::SaveTypeMetric::LOCAL);
  }
}

void CreditCardSaveManager::OfferCardUploadSave() {
#if defined(OS_ANDROID) || defined(OS_IOS)
  bool is_mobile_build = true;
#else
  bool is_mobile_build = false;
#endif  // #if defined(OS_ANDROID) || defined(OS_IOS)
  // If |show_save_prompt_.value()| is false, desktop builds will still offer
  // save in the omnibox without popping-up the bubble. Mobile builds, however,
  // should not display the offer-to-save infobar at all.
  if (!is_mobile_build || show_save_prompt_.value()) {
    user_did_accept_upload_prompt_ = false;
    client_->ConfirmSaveCreditCardToCloud(
        upload_request_.card, std::move(legal_message_),
        AutofillClient::SaveCreditCardOptions()
            .with_has_non_focusable_field(has_non_focusable_field_)
            .with_should_request_name_from_user(should_request_name_from_user_)
            .with_should_request_expiration_date_from_user(
                should_request_expiration_date_from_user_)
            .with_show_prompt(show_save_prompt_.value()),
        base::BindOnce(&CreditCardSaveManager::OnUserDidDecideOnUploadSave,
                       weak_ptr_factory_.GetWeakPtr()));
    client_->LoadRiskData(
        base::BindOnce(&CreditCardSaveManager::OnDidGetUploadRiskData,
                       weak_ptr_factory_.GetWeakPtr()));

    // Log metrics.
    AutofillMetrics::LogUploadOfferedCardOriginMetric(
        uploading_local_card_ ? AutofillMetrics::OFFERING_UPLOAD_OF_LOCAL_CARD
                              : AutofillMetrics::OFFERING_UPLOAD_OF_NEW_CARD);
    if (upload_request_.card.HasFirstAndLastName()) {
      AutofillMetrics::LogSaveCardWithFirstAndLastNameOffered(
          /*is_local=*/false);
    }
    // Set that upload was offered.
    upload_decision_metrics_ |= AutofillMetrics::UPLOAD_OFFERED;
  } else {
    // Set that upload was abandoned due to the Autofill LegacyStrikeDatabase
    // returning too many strikes for a mobile infobar to be displayed.
    upload_decision_metrics_ |=
        AutofillMetrics::UPLOAD_NOT_OFFERED_MAX_STRIKES_ON_MOBILE;
  }
  LogCardUploadDecisions(upload_decision_metrics_);
  if (!show_save_prompt_.value()) {
    AutofillMetrics::LogCreditCardSaveNotOfferedDueToMaxStrikesMetric(
        AutofillMetrics::SaveTypeMetric::SERVER);
  }
}

void CreditCardSaveManager::OnUserDidDecideOnLocalSave(
    AutofillClient::SaveCardOfferUserDecision user_decision) {
  switch (user_decision) {
    case AutofillClient::ACCEPTED:
      if (local_card_save_candidate_.HasFirstAndLastName())
        AutofillMetrics::LogSaveCardWithFirstAndLastNameComplete(
            /*is_local=*/true);
      if (base::FeatureList::IsEnabled(
              features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
        // Log how many CreditCardSave strikes the card had when it was saved.
        LogStrikesPresentWhenCardSaved(
            /*is_local=*/true,
            GetCreditCardSaveStrikeDatabase()->GetStrikes(base::UTF16ToUTF8(
                local_card_save_candidate_.LastFourDigits())));
        // Clear all CreditCardSave strikes for this card, in case it is later
        // removed.
        GetCreditCardSaveStrikeDatabase()->ClearStrikes(
            base::UTF16ToUTF8(local_card_save_candidate_.LastFourDigits()));
      } else if (base::FeatureList::IsEnabled(
                     features::kAutofillSaveCreditCardUsesStrikeSystem)) {
        LegacyStrikeDatabase* strike_database =
            client_->GetLegacyStrikeDatabase();
        // Log how many strikes the card had when it was saved.
        strike_database->GetStrikes(
            strike_database->GetKeyForCreditCardSave(
                base::UTF16ToUTF8(local_card_save_candidate_.LastFourDigits())),
            base::BindRepeating(
                &CreditCardSaveManager::LogStrikesPresentWhenCardSaved,
                weak_ptr_factory_.GetWeakPtr(),
                /*is_local=*/true));
        // Clear all strikes for this card, in case it is later removed.
        strike_database->ClearAllStrikesForKey(
            strike_database->GetKeyForCreditCardSave(
                base::UTF16ToUTF8(local_card_save_candidate_.LastFourDigits())),
            base::DoNothing());
      }
      if (base::FeatureList::IsEnabled(
              features::kAutofillLocalCardMigrationUsesStrikeSystemV2)) {
        GetLocalCardMigrationStrikeDatabase()->RemoveStrikes(
            LocalCardMigrationStrikeDatabase::
                kStrikesToRemoveWhenLocalCardAdded);
      }

      personal_data_manager_->OnAcceptedLocalCreditCardSave(
          local_card_save_candidate_);
      break;

    case AutofillClient::DECLINED:
    case AutofillClient::IGNORED:
      OnUserDidIgnoreOrDeclineSave(local_card_save_candidate_.LastFourDigits());
      break;
  }
}

void CreditCardSaveManager::LogStrikesPresentWhenCardSaved(
    bool is_local,
    const int num_strikes) {
  std::string suffix = is_local ? "StrikesPresentWhenLocalCardSaved"
                                : "StrikesPresentWhenServerCardSaved";
  base::UmaHistogramCounts1000("Autofill.StrikeDatabase." + suffix,
                               num_strikes);
}

void CreditCardSaveManager::SetProfilesForCreditCardUpload(
    const CreditCard& card,
    payments::PaymentsClient::UploadRequestDetails* upload_request) {
  std::vector<AutofillProfile> candidate_profiles;
  const base::Time now = AutofillClock::Now();
  const base::TimeDelta fifteen_minutes = base::TimeDelta::FromMinutes(15);
  // Reset |upload_decision_metrics_| to begin logging detected problems.
  upload_decision_metrics_ = 0;
  bool has_profile = false;
  bool has_modified_profile = false;

  // First, collect all of the addresses used or modified recently.
  for (AutofillProfile* profile : personal_data_manager_->GetProfiles()) {
    has_profile = true;
    if ((now - profile->modification_date()) < fifteen_minutes) {
      has_modified_profile = true;
      candidate_profiles.push_back(*profile);
    } else if ((now - profile->use_date()) < fifteen_minutes) {
      candidate_profiles.push_back(*profile);
    }
  }

  AutofillMetrics::LogHasModifiedProfileOnCreditCardFormSubmission(
      has_modified_profile);

  if (candidate_profiles.empty()) {
    upload_decision_metrics_ |=
        has_profile
            ? AutofillMetrics::UPLOAD_NOT_OFFERED_NO_RECENTLY_USED_ADDRESS
            : AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE;
  }

  // If any of the names on the card or the addresses don't match the
  // candidate set is invalid. This matches the rules for name matching applied
  // server-side by Google Payments and ensures that we don't send upload
  // requests that are guaranteed to fail.
  const base::string16 card_name =
      card.GetInfo(AutofillType(CREDIT_CARD_NAME_FULL), app_locale_);
  base::string16 verified_name;
  if (candidate_profiles.empty()) {
    verified_name = card_name;
  } else {
    bool found_conflicting_names = false;
    verified_name = RemoveMiddleInitial(card_name);
    for (const AutofillProfile& profile : candidate_profiles) {
      const base::string16 address_name =
          RemoveMiddleInitial(profile.GetInfo(NAME_FULL, app_locale_));
      if (address_name.empty())
        continue;
      if (verified_name.empty()) {
        verified_name = address_name;
      } else if (!base::EqualsCaseInsensitiveASCII(verified_name,
                                                   address_name)) {
        found_conflicting_names = true;
        break;
      }
    }
    if (found_conflicting_names) {
      upload_decision_metrics_ |=
          AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES;
    }
  }

  // If neither the card nor any of the addresses have a name associated with
  // them, the candidate set is invalid.
  if (verified_name.empty()) {
    upload_decision_metrics_ |= AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME;
  }

  // If any of the candidate addresses have a non-empty zip that doesn't match
  // any other non-empty zip, then the candidate set is invalid.
  base::string16 verified_zip;
  const AutofillType kZipCode(ADDRESS_HOME_ZIP);
  for (const AutofillProfile& profile : candidate_profiles) {
    const base::string16 zip = profile.GetRawInfo(ADDRESS_HOME_ZIP);
    if (!zip.empty()) {
      if (verified_zip.empty()) {
        verified_zip = zip;
      } else {
        // To compare two zips, we check to see if either is a prefix of the
        // other. This allows us to consider a 5-digit zip and a zip+4 to be a
        // match if the first 5 digits are the same without hardcoding any
        // specifics of how postal codes are represented. (They can be numeric
        // or alphanumeric and vary from 3 to 10 digits long by country. See
        // https://en.wikipedia.org/wiki/Postal_code#Presentation.) The Payments
        // backend will apply a more sophisticated address-matching procedure.
        // This check is simply meant to avoid offering upload in cases that are
        // likely to fail.
        if (!(StartsWith(verified_zip, zip, base::CompareCase::SENSITIVE) ||
              StartsWith(zip, verified_zip, base::CompareCase::SENSITIVE))) {
          upload_decision_metrics_ |=
              AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS;
          break;
        }
      }
    }
  }

  // If none of the candidate addresses have a zip, the candidate set is
  // invalid.
  if (verified_zip.empty() && !candidate_profiles.empty())
    upload_decision_metrics_ |= AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE;

  // Set up |upload_request->profiles|.
  upload_request->profiles.assign(candidate_profiles.begin(),
                                  candidate_profiles.end());
  if (!has_modified_profile) {
    for (const AutofillProfile& profile : candidate_profiles) {
      UMA_HISTOGRAM_COUNTS_1000(
          "Autofill.DaysSincePreviousUseAtSubmission.Profile",
          (profile.use_date() - profile.previous_use_date()).InDays());
    }
  }
}

int CreditCardSaveManager::GetDetectedValues() const {
  int detected_values = 0;

  // Report detecting CVC if it was found.
  if (!upload_request_.cvc.empty()) {
    detected_values |= DetectedValue::CVC;
  }

  // If cardholder name exists, set it as detected as long as
  // UPLOAD_NOT_OFFERED_CONFLICTING_NAMES was not set.
  if (!upload_request_.card
           .GetInfo(AutofillType(CREDIT_CARD_NAME_FULL), app_locale_)
           .empty() &&
      !(upload_decision_metrics_ &
        AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES)) {
    detected_values |= DetectedValue::CARDHOLDER_NAME;
  }

  // Go through the upload request's profiles and set the following as detected:
  //  - ADDRESS_NAME, as long as UPLOAD_NOT_OFFERED_CONFLICTING_NAMES was not
  //    set
  //  - POSTAL_CODE, as long as UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS was not set
  //  - Any other address fields found on any addresses, regardless of conflicts
  for (const AutofillProfile& profile : upload_request_.profiles) {
    if (!profile.GetInfo(NAME_FULL, app_locale_).empty() &&
        !(upload_decision_metrics_ &
          AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES)) {
      detected_values |= DetectedValue::ADDRESS_NAME;
    }
    if (!profile.GetInfo(ADDRESS_HOME_ZIP, app_locale_).empty() &&
        !(upload_decision_metrics_ &
          AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS)) {
      detected_values |= DetectedValue::POSTAL_CODE;
    }
    if (!profile.GetInfo(ADDRESS_HOME_LINE1, app_locale_).empty()) {
      detected_values |= DetectedValue::ADDRESS_LINE;
    }
    if (!profile.GetInfo(ADDRESS_HOME_CITY, app_locale_).empty()) {
      detected_values |= DetectedValue::LOCALITY;
    }
    if (!profile.GetInfo(ADDRESS_HOME_STATE, app_locale_).empty()) {
      detected_values |= DetectedValue::ADMINISTRATIVE_AREA;
    }
    if (!profile.GetRawInfo(ADDRESS_HOME_COUNTRY).empty()) {
      detected_values |= DetectedValue::COUNTRY_CODE;
    }
  }

  // If the billing_customer_number is non-zero, it means the user has a Google
  // Payments account. Include a bit for existence of this account (NOT the id
  // itself), as it will help determine if a new Payments customer might need to
  // be created when save is accepted.
  if (payments::GetBillingCustomerId(personal_data_manager_,
                                     payments_client_->GetPrefService()) != 0) {
    detected_values |= DetectedValue::HAS_GOOGLE_PAYMENTS_ACCOUNT;
  }

  if (base::FeatureList::IsEnabled(
          features::kAutofillUpstreamEditableExpirationDate)) {
    // If expiration date month or expiration year are missing, signal that
    // expiration date will be explicitly requested in the offer-to-save bubble.
    if (!upload_request_.card
             .GetInfo(AutofillType(CREDIT_CARD_EXP_MONTH), app_locale_)
             .empty()) {
      detected_values |= DetectedValue::CARD_EXPIRATION_MONTH;
    }
    if (!(upload_request_.card
              .GetInfo(AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale_)
              .empty())) {
      detected_values |= DetectedValue::CARD_EXPIRATION_YEAR;
    }

    // Set |USER_PROVIDED_EXPIRATION_DATE| if expiration date is detected as
    // expired or missing.
    if (detected_values & DetectedValue::CARD_EXPIRATION_MONTH &&
        detected_values & DetectedValue::CARD_EXPIRATION_YEAR) {
      int month_value = 0, year_value = 0;
      bool parsable =
          base::StringToInt(
              upload_request_.card.GetInfo(AutofillType(CREDIT_CARD_EXP_MONTH),
                                           app_locale_),
              &month_value) &&
          base::StringToInt(
              upload_request_.card.GetInfo(
                  AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale_),
              &year_value);
      DCHECK(parsable);
      if (!IsValidCreditCardExpirationDate(year_value, month_value,
                                           AutofillClock::Now())) {
        detected_values |= DetectedValue::USER_PROVIDED_EXPIRATION_DATE;
      }
    } else {
      detected_values |= DetectedValue::USER_PROVIDED_EXPIRATION_DATE;
    }
  }

  // If one of the following is true, signal that cardholder name will be
  // explicitly requested in the offer-to-save bubble:
  //  1) Name is conflicting/missing, and the user does NOT have a Google
  //     Payments account
  //  2) The AutofillUpstreamAlwaysRequestCardholderName experiment is enabled
  //     (should only ever be used by testers, never launched)
  if ((!(detected_values & DetectedValue::CARDHOLDER_NAME) &&
       !(detected_values & DetectedValue::ADDRESS_NAME) &&
       !(detected_values & DetectedValue::HAS_GOOGLE_PAYMENTS_ACCOUNT) &&
       features::IsAutofillUpstreamEditableCardholderNameExperimentEnabled()) ||
      features::
          IsAutofillUpstreamAlwaysRequestCardholderNameExperimentEnabled()) {
    detected_values |= DetectedValue::USER_PROVIDED_NAME;
  }

  return detected_values;
}

void CreditCardSaveManager::OnUserDidDecideOnUploadSave(
    AutofillClient::SaveCardOfferUserDecision user_decision,
    const AutofillClient::UserProvidedCardDetails& user_provided_card_details) {
  switch (user_decision) {
    case AutofillClient::ACCEPTED:
// On Android, requesting cardholder name or expiration date is a two step
// flow.
#if defined(OS_ANDROID)
      if (should_request_name_from_user_) {
        client_->ConfirmAccountNameFixFlow(base::BindOnce(
            &CreditCardSaveManager::OnUserDidAcceptAccountNameFixFlow,
            weak_ptr_factory_.GetWeakPtr()));
      } else if (should_request_expiration_date_from_user_) {
        client_->ConfirmExpirationDateFixFlow(
            upload_request_.card,
            base::BindOnce(
                &CreditCardSaveManager::OnUserDidAcceptExpirationDateFixFlow,
                weak_ptr_factory_.GetWeakPtr()));
      } else {
        OnUserDidAcceptUploadHelper(user_provided_card_details);
      }
#else
      OnUserDidAcceptUploadHelper(user_provided_card_details);
#endif
      break;

    case AutofillClient::DECLINED:
    case AutofillClient::IGNORED:
      OnUserDidIgnoreOrDeclineSave(upload_request_.card.LastFourDigits());
      break;
  }

  personal_data_manager_->OnUserAcceptedUpstreamOffer();
}

#if defined(OS_ANDROID)
void CreditCardSaveManager::OnUserDidAcceptAccountNameFixFlow(
    const base::string16& cardholder_name) {
  DCHECK(should_request_name_from_user_);

  OnUserDidAcceptUploadHelper({cardholder_name,
                               /*expiration_date_month=*/base::string16(),
                               /*expiration_date_year=*/base::string16()});
}

void CreditCardSaveManager::OnUserDidAcceptExpirationDateFixFlow(
    const base::string16& month,
    const base::string16& year) {
  OnUserDidAcceptUploadHelper(
      {/*cardholder_name=*/base::string16(), month, year});
}
#endif

void CreditCardSaveManager::OnUserDidAcceptUploadHelper(
    const AutofillClient::UserProvidedCardDetails& user_provided_card_details) {
  // If cardholder name was explicitly requested for the user to enter/confirm,
  // replace the name on |upload_request_.card| with the entered name.  (Note
  // that it is possible a name already existed on the card if conflicting names
  // were found, which this intentionally overwrites.)
  if (!user_provided_card_details.cardholder_name.empty()) {
    DCHECK(should_request_name_from_user_);
    upload_request_.card.SetInfo(CREDIT_CARD_NAME_FULL,
                                 user_provided_card_details.cardholder_name,
                                 app_locale_);
  }

  user_did_accept_upload_prompt_ = true;
  // If expiration date was explicitly requested for the user to select, replace
  // the expiration date on |upload_request_.card| with the selected date.
  if (!user_provided_card_details.expiration_date_month.empty() &&
      !user_provided_card_details.expiration_date_year.empty()) {
    DCHECK(should_request_expiration_date_from_user_);
    upload_request_.card.SetInfo(
        CREDIT_CARD_EXP_MONTH, user_provided_card_details.expiration_date_month,
        app_locale_);
    upload_request_.card.SetInfo(
        CREDIT_CARD_EXP_4_DIGIT_YEAR,
        user_provided_card_details.expiration_date_year, app_locale_);
  }
  // Populating risk data and offering upload occur asynchronously.
  // If |risk_data| has already been loaded, send the upload card request.
  // Otherwise, continue to wait and let OnDidGetUploadRiskData handle it.
  if (!upload_request_.risk_data.empty())
    SendUploadCardRequest();
}

void CreditCardSaveManager::OnDidGetUploadRiskData(
    const std::string& risk_data) {
  upload_request_.risk_data = risk_data;
  // Populating risk data and offering upload occur asynchronously.
  // If the dialog has already been accepted, send the upload card request.
  // Otherwise, continue to wait for the user to accept the save dialog.
  if (user_did_accept_upload_prompt_)
    SendUploadCardRequest();
}

void CreditCardSaveManager::SendUploadCardRequest() {
  if (observer_for_testing_)
    observer_for_testing_->OnSentUploadCardRequest();
  upload_request_.app_locale = app_locale_;
  upload_request_.billing_customer_number = payments::GetBillingCustomerId(
      personal_data_manager_, payments_client_->GetPrefService());

  AutofillMetrics::LogUploadAcceptedCardOriginMetric(
      uploading_local_card_
          ? AutofillMetrics::USER_ACCEPTED_UPLOAD_OF_LOCAL_CARD
          : AutofillMetrics::USER_ACCEPTED_UPLOAD_OF_NEW_CARD);
  payments_client_->UploadCard(
      upload_request_, base::BindOnce(&CreditCardSaveManager::OnDidUploadCard,
                                      weak_ptr_factory_.GetWeakPtr()));
}

void CreditCardSaveManager::OnUserDidIgnoreOrDeclineSave(
    const base::string16& card_last_four_digits) {
  if (show_save_prompt_ != base::nullopt && show_save_prompt_.value()) {
    if (base::FeatureList::IsEnabled(
            features::kAutofillSaveCreditCardUsesStrikeSystemV2)) {
      // If the user rejected or ignored save and the offer-to-save bubble or
      // infobar was actually shown (NOT just the icon if on desktop), count
      // that as a strike against offering upload in the future.
      int nth_strike_added = GetCreditCardSaveStrikeDatabase()->AddStrike(
          base::UTF16ToUTF8(card_last_four_digits));
      OnStrikeChangeComplete(nth_strike_added);
    } else if (base::FeatureList::IsEnabled(
                   features::kAutofillSaveCreditCardUsesStrikeSystem)) {
      // If the user rejected or ignored save and the offer-to-save bubble or
      // infobar was actually shown (NOT just the icon if on desktop), count
      // that as a strike against offering upload in the future.
      LegacyStrikeDatabase* strike_database =
          client_->GetLegacyStrikeDatabase();
      strike_database->AddStrike(
          strike_database->GetKeyForCreditCardSave(
              base::UTF16ToUTF8(card_last_four_digits)),
          base::BindRepeating(&CreditCardSaveManager::OnStrikeChangeComplete,
                              weak_ptr_factory_.GetWeakPtr()));
    }
  }
}

void CreditCardSaveManager::OnStrikeChangeComplete(const int num_strikes) {
  if (observer_for_testing_)
    observer_for_testing_->OnStrikeChangeComplete();
}

AutofillMetrics::CardUploadDecisionMetric
CreditCardSaveManager::GetCVCCardUploadDecisionMetric() const {
  // This function assumes a valid CVC was not found.
  if (found_cvc_field_) {
    return found_value_in_cvc_field_ ? AutofillMetrics::INVALID_CVC_VALUE
                                     : AutofillMetrics::CVC_VALUE_NOT_FOUND;
  }
  return found_cvc_value_in_non_cvc_field_
             ? AutofillMetrics::FOUND_POSSIBLE_CVC_VALUE_IN_NON_CVC_FIELD
             : AutofillMetrics::CVC_FIELD_NOT_FOUND;
}

void CreditCardSaveManager::LogCardUploadDecisions(
    int upload_decision_metrics) {
  AutofillMetrics::LogCardUploadDecisionMetrics(upload_decision_metrics);
  AutofillMetrics::LogCardUploadDecisionsUkm(
      client_->GetUkmRecorder(), client_->GetUkmSourceId(),
      pending_upload_request_origin_.GetURL(), upload_decision_metrics);
  pending_upload_request_origin_ = url::Origin();
}

void CreditCardSaveManager::LogSaveCardRequestExpirationDateReasonMetric() {
  bool is_month_empty =
      upload_request_.card
          .GetInfo(AutofillType(CREDIT_CARD_EXP_MONTH), app_locale_)
          .empty();
  bool is_year_empty =
      upload_request_.card
          .GetInfo(AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale_)
          .empty();

  if (is_month_empty && is_year_empty) {
    AutofillMetrics::LogSaveCardRequestExpirationDateReasonMetric(
        AutofillMetrics::SaveCardRequestExpirationDateReasonMetric::
            kMonthAndYearMissing);
  } else if (is_month_empty) {
    AutofillMetrics::LogSaveCardRequestExpirationDateReasonMetric(
        AutofillMetrics::SaveCardRequestExpirationDateReasonMetric::
            kMonthMissingOnly);
  } else if (is_year_empty) {
    AutofillMetrics::LogSaveCardRequestExpirationDateReasonMetric(
        AutofillMetrics::SaveCardRequestExpirationDateReasonMetric::
            kYearMissingOnly);
  } else {
    int month = 0, year = 0;
    bool parsable =
        base::StringToInt(
            upload_request_.card.GetInfo(
                AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale_),
            &year) &&
        base::StringToInt(upload_request_.card.GetInfo(
                              AutofillType(CREDIT_CARD_EXP_MONTH), app_locale_),
                          &month);
    DCHECK(parsable);
    // Month and year are not empty, so they must be expired.
    DCHECK(!IsValidCreditCardExpirationDate(year, month, AutofillClock::Now()));
    AutofillMetrics::LogSaveCardRequestExpirationDateReasonMetric(
        AutofillMetrics::SaveCardRequestExpirationDateReasonMetric::
            kExpirationDatePresentButExpired);
  }
}

bool CreditCardSaveManager::IsCreditCardSupported(
    std::vector<std::pair<int, int>> supported_card_bin_ranges) {
  base::string16 stripped_number =
      CreditCard::StripSeparators(upload_request_.card.number());
  for (auto& bin_range : supported_card_bin_ranges) {
    unsigned long range_num_of_digits =
        base::NumberToString(bin_range.first).size();
    DCHECK_EQ(range_num_of_digits,
              base::NumberToString(bin_range.second).size());
    // The first n digits of credit card number, where n is the number of
    // digits in range's starting/ending number.
    int first_digits_start, first_digits_end;
    base::StringToInt(stripped_number.substr(0, range_num_of_digits),
                      &first_digits_start);
    base::StringToInt(stripped_number.substr(0, range_num_of_digits),
                      &first_digits_end);
    if (first_digits_start >= bin_range.first &&
        first_digits_end <= bin_range.second) {
      return true;
    }
  }
  return false;
}

}  // namespace autofill