+sub merge_all {
+ my @dupes = FS::cust_main_county->find_wa_tax_dupes;
+
+ unless ( @dupes ) {
+ say 'No duplicate tax rows detected for WA sales tax districts';
+ return;
+ }
+
+ confirm_to_continue(sprintf "
+
+ %s blocking duplicate rows detected
+
+ Duplicate rows will be merged using FS::cust_main_county::_merge_into()
+
+ Rows are considered duplicates when they:
+ - Share the same tax class
+ - Share the same district
+ - Contain 'wa_sales' in the source column
+
+ ", scalar @dupes);
+
+ # Sort dupes into buckets to be merged, by taxclass and district
+ # $to_merge{taxclass}->{district} = [ @rows_to_merge ]
+ my %to_merge;
+ for my $row ( @dupes ) {
+ my $taxclass = $row->taxclass || 'none';
+ $to_merge{$taxclass} ||= {};
+ $to_merge{$taxclass}->{$row->district} ||= [];
+ push @{ $to_merge{$taxclass}->{$row->district} }, $row;
+ }
+
+ # Merge the duplicates
+ for my $taxclass ( keys %to_merge ) {
+ for my $district ( keys %{ $to_merge{$taxclass} }) {
+
+ # Keep the first row in the list as the target.
+ # Merge the remaining rows into the target
+ my $rows = $to_merge{$taxclass}->{$district};
+ my $target = shift @$rows;
+
+ while ( @$rows ) {
+ merge_into( shift(@$rows), $target );
+ }
+ }
+ }
+
+ say "
+
+ Merge operations completed
+
+ Please run freeside-wa-tax-table-update. This will update
+ the merged district rows with correct county and city names
+
+ ";
+
+}
+
+sub fix_usf {
+ confirm_to_continue("
+
+ Search for duplicate districts within the tax tables with
+ - duplicate district column values
+ - source = NULL
+ - district = NOT NULL
+ - taxclass = USF
+ - tax > 17
+
+ Merge these rows into a single USF row for each tax district
+
+ ");
+
+ my @rows = qsearch( cust_main_county => {
+ taxclass => 'USF',
+ source => undef,
+ state => 'WA',
+ country => 'US',
+ tax => { op => '>', value => 17 },
+ district => { op => '!=', value => undef },
+ });
+
+ my %to_merge;
+ for my $row (@rows) {
+ $to_merge{$row->district} ||= [];
+ push @{ $to_merge{$row->district} }, $row;
+ }
+
+ for my $dist_rows ( values %to_merge ) {
+ my $target = shift @$dist_rows;
+ while ( @$dist_rows ) {
+ merge_into( shift(@$dist_rows), $target );
+ }
+ }
+
+ say "
+
+ USF clean up completed
+
+ Please run freeside-wa-tax-table-update. This will update
+ the merged district rows with correct county and city names
+
+ ";
+}
+