RT# 74693 - Added Bulk edit of rates only
[freeside.git] / httemplate / browse / cust_main_county.cgi
index 1e969aa..722c699 100755 (executable)
@@ -10,7 +10,9 @@
                            'table'    => 'cust_main_county',
                            'hashref'  => $hashref,
                            'order_by' =>
-                             'ORDER BY country, state, county, taxclass',
+                              'ORDER BY country, state, county, city, '.
+                              'district, taxclass, '.
+                              "COALESCE(taxname, '')",
                          },
      'count_query'    => $count_query,
      'header'         => \@header,
      'link_onclicks'  => \@link_onclicks,
   )
 %>
-%
-% #         <FONT SIZE=-1><A HREF="<% $p %>edit/process/cust_main_county-collapse.cgi?<% $hashref->{taxnum} %>">collapse state</A></FONT>
-% # % } 
-%
 <%once>
 
 my $conf = new FS::Conf;
 my $money_char = $conf->config('money_char') || '$';
 
-my @manual_countries = ( 'US', 'CA', 'AU', 'NZ', 'GB' ); #some manual ordering
-my @all_countries = ( @manual_countries, 
-                      grep { my $c = $_; ! grep { $c eq $_ } @manual_countries }
-                      map { $_->country } 
-                          qsearch({
-                                    'select'    => 'country',
-                                    'table'     => 'cust_main_county',
-                                    'hashref'   => {},
-                                    'extra_sql' => 'GROUP BY country',
-                                 })
-                    );
-
 my $exempt_sub = sub {
   my $cust_main_county = shift;
 
@@ -61,22 +47,23 @@ my $exempt_sub = sub {
   [ map [ {'data'=>$_} ], @exempt ];
 };
 
-my $oldrow;
-my $cell_style;
+my $cs_oldrow;
+my $cell_style = '';
 my $cell_style_sub = sub {
   my $row = shift;
-  if ( $oldrow ne $row ) {
-    if ( $oldrow ) {
-      if ( $oldrow->country ne $row->country ) {
-        $cell_style = 'border-top:1px solid #000000';
-      } elsif ( $oldrow->state ne $row->state ) {
-        $cell_style = 'border-top:1px solid #cccccc'; #default?
-      } elsif ( $oldrow->state eq $row->state ) {
-        #$cell_style = 'border-top:dashed 1px dark gray';
-        $cell_style = 'border-top:1px dashed #cccccc';
+  if ( $cs_oldrow ne $row ) {
+    if ( $cs_oldrow ) {
+      if ( $cs_oldrow->country ne $row->country ) {
+        $cell_style = 'border-top:2px solid #000000';
+      } elsif ( $cs_oldrow->state ne $row->state ) {
+        $cell_style = 'border-top:1px solid #888888';
+      } elsif ( $cs_oldrow->county ne $row->county ) {
+        $cell_style = 'border-top:1px solid #cccccc';
+      } else { 
+        $cell_style = '';
       }
     }
-    $oldrow = $row;
+    $cs_oldrow = $row;
   }
   return $cell_style;
 };
@@ -96,9 +83,16 @@ my $edit_onclick = sub {
          );
 };
 
+my $ex_oldrow;
 sub expand_link {
   my %param = @_;
 
+  if ( $ex_oldrow eq $param{'row'} ) {
+    return '';
+  } else {
+    $ex_oldrow = $param{'row'};
+  }
+
   my $taxnum = $param{'row'}->taxnum;
   my $url = "${p}edit/cust_main_county-expand.cgi?$taxnum";
 
@@ -114,6 +108,86 @@ sub expand_link {
   '</FONT>';
 }
 
+sub add_link {
+  my %param = @_;
+
+  #if ( $ex_oldrow eq $param{'row'} ) {
+  #  return '';
+  #} else {
+  #  $ex_oldrow = $param{'row'};
+  #}
+
+  my %below = ( 'county' => 'city',
+                'state'  => 'county',
+              );
+  my $what = $below{ $param{'col' } };
+
+  my $taxnum = $param{'row'}->taxnum;
+  my $url = "${p}edit/cust_main_county-add.cgi?taxnum=$taxnum;what=$what";
+
+  '<FONT SIZE="-1">'.
+    include( '/elements/popup_link.html',
+               'label'       => $param{'label'},
+               'action'      => $url,
+               'actionlabel' => $param{'desc'},
+               'height'      => 420,
+               #default# 'width'  => 540,
+               #default# 'color' => '#333399',
+           ).
+  '</FONT>';
+}
+
+sub collapse_link {
+  my %param = @_;
+
+  my $row = $param{'row'};
+  my $col = $param{'col'};
+#  return ''
+#    if $col eq 'state' and $row->city
+#                            || qsearch({
+#                                 'table'   => 'cust_main_county',
+#                                 'hashref' => {
+#                                   'country' => $row->country,
+#                                   'state'   => $row->state,
+#                                   'city'    => { op=>'!=', value=>'' },
+#                                 },
+#                                 'order_by' => 'LIMIT 1',
+#                               });
+
+  my %below = ( 'county' => 'city',
+                'state'  => 'county',
+              );
+
+  #XXX can still show the link when you have some counties broken down into
+  #cities and others not :/
+
+  my $taxnum = $param{'row'}->taxnum;
+  my $url = "${p}edit/process/cust_main_county-collapse.cgi?taxnum=$taxnum;".
+              'country='. uri_escape($cgi->param('country')). ';'.
+              'state='.   uri_escape($cgi->param('state')).   ';'.
+              'county='.  uri_escape($cgi->param('county'));
+  $url = "javascript:collapse_areyousure('$url', '$below{$col}', '$col')";
+
+  qq(<FONT SIZE="-1"><A HREF="$url">$param{'label'}</A></FONT>);
+}
+
+sub remove_link {
+  my %param = @_;
+
+  my $row = $param{'row'};
+  my $col = $param{'col'};
+  my $taxnum = $param{'row'}->taxnum;
+  my $url = "${p}edit/process/cust_main_county-remove.cgi?taxnum=$taxnum;".
+              'country='. uri_escape($cgi->param('country')). ';'.
+              'state='.   uri_escape($cgi->param('state')).   ';'.
+              'county='.  uri_escape($cgi->param('county'));
+  $url = "javascript:remove_areyousure('$url', '$col')";
+
+  qq(<FONT SIZE="-1"><A HREF="$url">$param{'label'}</A></FONT>);
+
+}
+
 sub separate_taxclasses_link {
   my( $row ) = @_;
   my $taxnum = $row->taxnum;
@@ -122,6 +196,8 @@ sub separate_taxclasses_link {
   qq!<FONT SIZE="-1"><A HREF="$url">!;
 }
 
+#un-separate taxclasses too
+
 </%once>
 <%init>
 
@@ -134,9 +210,19 @@ my $enable_taxclasses = $conf->exists('enable_taxclasses');
 
 my @menubar;
 
-my $html_init =
-  "Click on <u>add states</u> to specify a country's tax rates by state or province.
-   <BR>Click on <u>add counties</u> to specify a state's tax rates by county.";
+my $html_init = <<END;
+  <SCRIPT>
+    function collapse_areyousure(href,col,above) {
+     if (confirm('Are you sure you want to remove all ' + col + ' tax rates for this ' + above + '?') == true)
+       window.location.href = href;
+    }
+    function remove_areyousure(href,col) {
+     if (confirm('Are you sure you want to remove this ' + col + '?') == true)
+       window.location.href = href;
+    }
+  </SCRIPT>
+END
+
 $html_init .= "<BR>Click on <u>separate taxclasses</u> to specify taxes per taxclass."
   if $enable_taxclasses;
 $html_init .= '<BR><BR>';
@@ -153,19 +239,42 @@ if ( $cgi->param('country') =~ /^(\w\w)$/ ) {
 $cgi->delete('country');
 
 my $state = '';
-if ( $cgi->param('state') =~ /^([\w \-\'\[\]]+)$/ ) {
+if ( $country && $cgi->param('state') =~ /^([\w \-\'\[\]]+)$/ ) {
   $state = $1;
   $title = "$state, $title";
 }
 $cgi->delete('state');
 
 my $county = '';
-if ( $cgi->param('county') =~ /^([\w \-\'\[\]]+)$/ ) {
+if ( $country && $state &&
+     $cgi->param('county') =~
+       /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
+   )
+{
   $county = $1;
-  $title = "$county county, $title";
+  if ( $county eq '__NONE__' ) {
+    $title = "No county, $title";
+  } else {
+    $title = "$county county, $title";
+  }
 }
 $cgi->delete('county');
 
+my $city = '';
+if ( $country && $state && $county &&
+     $cgi->param('city') =~
+       /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
+   )
+{
+  $city = $1;
+  if ( $city eq '__NONE__' ) {
+    $title = "No city, $title";
+  } else {
+    $title = "$city city, $title";
+  }
+}
+$cgi->delete('city');
+
 $title = " for $title" if $title;
 
 my $taxclass = '';
@@ -181,30 +290,105 @@ if ( $country || $taxclass ) {
 
 $cgi->param('dummy', 1);
 
-my $country_filter_change =
-  "window.location = '".
-  $cgi->self_url. ";country=' + this.options[this.selectedIndex].value;";
+my $filter_change =
+  "window.location = '". $cgi->self_url.
+  ";country=' + encodeURIComponent( document.getElementById('country').options[document.getElementById('country').selectedIndex].value ) + ".
+  "';state='   + encodeURIComponent( document.getElementById('state').options[document.getElementById('state').selectedIndex].value ) +".
+  "';county='  + encodeURIComponent( document.getElementById('county').options[document.getElementById('county').selectedIndex].value )";
+
+$filter_change .= " +';city='  + encodeURIComponent( document.getElementById('city').options[document.getElementById('city').selectedIndex].value )"
+  if $conf->exists('enable_taxclasses');
+
+$filter_change .= ";";
 
 #restore this so pagination works
 $cgi->param('country',  $country) if $country;
 $cgi->param('state',    $state  ) if $state;
 $cgi->param('county',   $county ) if $county;
+$cgi->param('city',     $city )   if $city;
 $cgi->param('taxclass', $county ) if $taxclass;
 
 my $html_posttotal =
-  '(show country: '.
-  qq(<SELECT NAME="country" onChange="$country_filter_change">).
-  qq(<OPTION VALUE="">(all)\n).
-  join("\n", map qq[<OPTION VALUE="$_"].
-                   ( $_ eq $country ? 'SELECTED' : '' ).
-                   '>'. code2country($_). " ($_)",
-                 @all_countries
-      ).
-  '</SELECT>)';
+  '<BR>( show country: '.
+  include('/elements/select-country.html',
+            'country'             => $country,
+            'onchange'            => $filter_change,
+            'empty_label'         => '(all)',
+            'disable_empty'       => 0,
+            'disable_stateupdate' => 1,
+         );
+
+my %states_hash = $country ? states_hash($country) : ();
+if ( scalar(keys(%states_hash)) > 1 ) {
+  $html_posttotal .=
+    ' show state: '.
+    include('/elements/select-state.html',
+              'country'              => $country,
+              'state'                => $state,
+              'onchange'             => $filter_change,
+              'empty_label'          => '(all)',
+              'disable_empty'        => 0,
+              'disable_countyupdate' => 1,
+           );
+} else {
+  $html_posttotal .=
+    '<SELECT NAME="state" ID="state" STYLE="display:none">'.
+    '  <OPTION VALUE="" SELECTED>'.
+    '</SELECT>';
+}
+
+my @counties = ( $country && $state ) ? counties($state, $country) : ();
+if ( scalar(@counties) > 1 ) {
+  $html_posttotal .=
+    ' show county: '.
+    include('/elements/select-county.html',
+              'country'              => $country,
+              'state'                => $state,
+              'county'               => $county,
+              'onchange'             => $filter_change,
+              'empty_label'          => '(all)',
+              'empty_data_label'     => '(none)',
+              'empty_data_value'     => '__NONE__',
+              'disable_empty'        => 0,
+              'disable_cityupdate'   => 1,
+           );
+} else {
+  $html_posttotal .=
+    '<SELECT NAME="county" ID="county" STYLE="display:none">'.
+    '  <OPTION VALUE="" SELECTED>'.
+    '</SELECT>';
+}
+
+if ( $conf->exists('enable_taxclasses') ) {
+  my @cities = ( $country && $state && $county ) ? cities($county, $state, $country) : ();
+  if ( scalar(@cities) > 1 ) {
+    $html_posttotal .=
+      ' show city: '.
+      include('/elements/select-city.html',
+              'country'              => $country,
+              'state'                => $state,
+              'county'               => $county,
+              'city'                 => $city,
+              'onchange'             => $filter_change,
+              'empty_label'          => '(all)',
+              'empty_data_label'     => '(none)',
+              'empty_data_value'     => '__NONE__',
+              'disable_empty'        => 0,
+              'disable_cityupdate'   => 1,
+      );
+  } else {
+    $html_posttotal .=
+      '<SELECT NAME="city" ID="city" STYLE="display:none">'.
+      '  <OPTION VALUE="" SELECTED>'.
+      '</SELECT>';
+  }
+}
+
+$html_posttotal .= ' )';
 
 my $bulk_popup_link = 
   include( '/elements/popup_link_onclick.html',
-             'action'      => "${p}edit/bulk-cust_main_county.html?MAGIC_taxnum_MAGIC",
+             'action'      => "${p}edit/bulk-cust_main_county.html?taxnum=MAGIC_taxnum_MAGIC",
              'actionlabel' => 'Bulk add new tax',
              'nofalse'     => 1,
              'height'      => 420,
@@ -237,7 +421,7 @@ my $html_foot = <<END;
     }
   }
 
-  function bulkPopup() {
+  function bulkPopup(action) {
     var bulk_popup_link = "$bulk_popup_link";
     var bulkstring = '';
     theForm = document.taxesForm;
@@ -254,6 +438,7 @@ my $html_foot = <<END;
        
       }
     }
+    bulkstring = bulkstring + ';action=' + action;
     if ( bulk_popup_link.length > 1920 ) { // IE 2083 URL limit
       alert('Too many selections'); // should do some session thing...
       return false;
@@ -269,8 +454,13 @@ my $html_foot = <<END;
 <A HREF="javascript:setAll(false)">unselect all</A> |
 <A HREF="javascript:toggleAll()">toggle all</A>
 <BR><BR>
-<A HREF="javascript:void(0);" onClick="bulkPopup();">Add new tax to selected</A>
-
+<A HREF="javascript:void(0);" onClick="bulkPopup('add');">Add new tax to selected</A>
+|
+<A HREF="javascript:void(0);" onClick="bulkPopup('edit');">Bulk edit selected</A>
+|
+<A HREF="javascript:void(0);" onClick="bulkPopup('edit_rate_only');">Bulk edit rate only selected</A>
+|
+<A HREF="${p}misc/tax_edit_excel.html",">bulk edit with excel file</A>
 END
 
 my $hashref = {};
@@ -281,11 +471,25 @@ if ( $country ) {
 }
 if ( $state ) {
   $hashref->{'state'} = $state;
-  $count_query .= '   AND state   = '. dbh->quote($state);
+  $count_query .= ' AND state   = '. dbh->quote($state);
 }
 if ( $county ) {
-  $hashref->{'country'} = $country;
-  $count_query .= '   AND county  = '. dbh->quote($county);
+  if ( $county eq '__NONE__' ) {
+    $hashref->{'county'} = '';
+    $count_query .= " AND ( county = '' OR county IS NULL ) ";
+  } else {
+    $hashref->{'county'} = $county;
+    $count_query .= ' AND county  = '. dbh->quote($county);
+  }
+}
+if ( $city ) {
+  if ( $city eq '__NONE__' ) {
+    $hashref->{'city'} = '';
+    $count_query .= " AND ( city = '' OR city IS NULL ) ";
+  } else {
+    $hashref->{'city'} = $city;
+    $count_query .= ' AND city  = '. dbh->quote($city);
+  }
 }
 if ( $taxclass ) {
   $hashref->{'taxclass'} = $taxclass;
@@ -296,46 +500,164 @@ if ( $taxclass ) {
 
 $cell_style = '';
 
-my @header        = ( 'Country', 'State/Province', 'County',);
-my @header2       = ( '', '', '', );
-my @links         = ( '', '', '', );
-my @link_onclicks = ( '', '', '', );
-my $align = 'lll';
+my @header        = ( 'Country', 'State/Province', 'County', 'City', '' );
+# last column is 'district', but usually unused
+my @header2       = ( '', '', '', '', '' );
+my @links         = ( '', '', '', '', '' );
+my @link_onclicks = ( '', '', '', '', '' );
+my $align = 'lllll';
+
+my %seen_country = ();
+my %seen_state = ();
+my %seen_county = ();
 
 my @fields = (
   sub { my $country = shift->country;
-        code2country($country). " ($country)";
+        return '' if $seen_country{$country}++;
+        FS::geocode_Mixin->code2country($country). "&nbsp;($country)";
       },
-  sub { state_label($_[0]->state, $_[0]->country).
-        ( $_[0]->state
-            ? ''
-            : '&nbsp'. expand_link( desc  => 'Add States',
-                                    row   => $_[0],
-                                    label => 'add&nbsp;states',
-                                  )
-        )
+
+  #state
+  sub { my $label = $seen_state{$_[0]->country}->{$_[0]->state}++
+                      ? '' : state_label($_[0]->state, $_[0]->country);
+
+        my $countylinks = ( $_[0]->county && $label )
+                             ? '&nbsp;'. add_link(
+                                 desc => 'Add more counties',
+                                 col  => 'state',
+                                 label=> 'add more counties',
+                                 row  => $_[0],
+                                 cgi  => $cgi,
+                               ).
+                               ' '. collapse_link(
+                                 col  => 'state',
+                                 label=> 'remove all counties',
+                                 row  => $_[0],
+                                 cgi  => $cgi,
+                               )
+                             : '';
+
+        my $addlink = 
+          ( $_[0]->state
+              ? ''
+              : '&nbsp;'. expand_link( desc  => 'Add States',
+                                       row   => $_[0],
+                                       label => 'add states',
+                                       cgi  => $cgi,
+                                     )
+          );
+
+        $label.$countylinks.$addlink;
       },
-  sub { $_[0]->county || '(all)&nbsp'.
-                         expand_link( desc  => 'Add Counties',
-                                      row   => $_[0],
-                                      label => 'add&nbsp;counties',
-                                    )
+
+  #county
+  sub { my $label =
+          $seen_county{$_[0]->country}->{$_[0]->state}->{$_[0]->county}++ 
+            ? '' : $_[0]->county;
+
+        my $citylinks = '';
+        if ( $label ) {
+          $citylinks = $_[0]->city
+                       ? '&nbsp;'. add_link(
+                           desc => 'Add more cities',
+                           col  => 'county',
+                           label=> 'add more cities',
+                           row  => $_[0],
+                           cgi  => $cgi,
+                         ).
+                         ' '. collapse_link(
+                           col  => 'county',
+                           label=> 'remove all cities',
+                           row  => $_[0],
+                           cgi  => $cgi,
+                         )
+                       : '&nbsp;'. remove_link( col  => 'county',
+                                                label=> 'remove county',
+                                                row  => $_[0],
+                                                cgi  => $cgi,
+                                              );
+        }
+
+        $_[0]->county
+          ? $label.$citylinks
+          : '(all)&nbsp;'.
+              expand_link(   desc  => 'Add Counties',
+                             row   => $_[0],
+                             label => 'add counties',
+                             cgi  => $cgi,
+                         );
       },
+
+  #city
+  sub {
+        my $r = shift;
+        if ( $r->city ) {
+
+          if ( $r->taxclass #but if it has a taxclass, can't remove
+              or $r->district ) { # or a district
+            $r->city;
+          } else {
+            $r->city. '&nbsp;'.
+              remove_link( col  => 'city',
+                           label=> 'remove city',
+                           row  => $r,
+                           cgi  => $cgi,
+                         );
+          }
+        } else {
+          '(all)&nbsp;'.
+            expand_link(   desc  => 'Add Cities',
+                           row   => $r,
+                           label => 'add cities',
+                           cgi  => $cgi,
+                       );
+        }
+      },
+
+  #district
+  sub {
+        my $r = shift;
+        if ( $r->district ) {
+          $r->district . '&nbsp;'.
+            remove_link( col  => 'district',
+                         label=> 'remove district',
+                         row  => $r,
+                         cgi  => $cgi,
+                       );
+        }
+        # manually editing districts is not exactly intended
+      },
+
 );
 
 my @color = (
   '000000',
   sub { shift->state  ? '000000' : '999999' },
   sub { shift->county ? '000000' : '999999' },
+  sub { shift->city   ? '000000' : '999999' },
 );
 
 if ( $conf->exists('enable_taxclasses') ) {
   push @header, qq!Tax class (<A HREF="${p}edit/part_pkg_taxclass.html">add new</A>)!;
   push @header2, '(per-package classification)';
-  push @fields, sub { $_[0]->taxclass || '(all)&nbsp'.
-                       separate_taxclasses_link($_[0], 'Separate Taxclasses').
-                       'separate&nbsp;taxclasses</A></FONT>'
-                    };
+  push @fields, sub {
+    my $r = shift;
+    if ( $r->taxclass ) {
+      $r->taxclass;
+    } else {
+      my $sql = 'SELECT COUNT(*) FROM cust_main_county
+                   WHERE country = ? AND state = ? AND county = ?
+                     AND city = ? AND taxclass IS NOT NULL';
+      if ( FS::Record->scalar_sql($sql, map $r->$_,
+                                            qw( country state county city) ) ) {
+        '(none)';
+      } else {
+        '(all)&nbsp;'.
+          separate_taxclasses_link($r, 'Separate Taxclasses').
+          'separate&nbsp;taxclasses</A></FONT>';
+      }
+    }
+  };
   push @color, sub { shift->taxclass ? '000000' : '999999' };
   push @links, '';
   push @link_onclicks, '';
@@ -362,9 +684,11 @@ my $cb_sub = sub {
   my $cust_main_county = shift;
 
   if ( $cb_oldrow ) {
-    if (    $cb_oldrow->country  ne $cust_main_county->country 
-         || $cb_oldrow->state    ne $cust_main_county->state  
+    if (    $cb_oldrow->district ne $cust_main_county->district
+         || $cb_oldrow->city     ne $cust_main_county->city 
          || $cb_oldrow->county   ne $cust_main_county->county  
+         || $cb_oldrow->state    ne $cust_main_county->state  
+         || $cb_oldrow->country  ne $cust_main_county->country 
          || $cb_oldrow->taxclass ne $cust_main_county->taxclass )
     {
       $newregion = 1;