552327836189009592a17f1b62059269acefad5d
[freeside.git] / httemplate / browse / cust_main_county.cgi
1 <% include( 'elements/browse.html',
2      'title'          => "Tax Rates $title",
3      'name_singular'  => 'tax rate',
4      'menubar'        => \@menubar,
5      'html_init'      => $html_init,
6      'html_posttotal' => $html_posttotal,
7      'html_form'      => '<FORM NAME="taxesForm">',
8      'html_foot'      => $html_foot,
9      'query'          => {
10                            'table'    => 'cust_main_county',
11                            'hashref'  => $hashref,
12                            'order_by' =>
13                               'ORDER BY country, state, county, city, '.
14                               'district, taxclass, '.
15                               "COALESCE(taxname, '')",
16                          },
17      'count_query'    => $count_query,
18      'header'         => \@header,
19      'header2'        => \@header2,
20      'fields'         => \@fields,
21      'align'          => $align,
22      'color'          => \@color,
23      'cell_style'     => \@cell_style,
24      'links'          => \@links,
25      'link_onclicks'  => \@link_onclicks,
26   )
27 %>
28 <%once>
29
30 my $conf = new FS::Conf;
31 my $money_char = $conf->config('money_char') || '$';
32
33 my $exempt_sub = sub {
34   my $cust_main_county = shift;
35
36   my @exempt = ();
37   push @exempt,
38        sprintf("$money_char%.2f&nbsp;per&nbsp;month", $cust_main_county->exempt_amount )
39     if $cust_main_county->exempt_amount > 0;
40
41   push @exempt, 'Setup&nbsp;fee'
42     if $cust_main_county->setuptax =~ /^Y$/i;
43
44   push @exempt, 'Recurring&nbsp;fee'
45     if $cust_main_county->recurtax =~ /^Y$/i;
46
47   [ map [ {'data'=>$_} ], @exempt ];
48 };
49
50 my $cs_oldrow;
51 my $cell_style = '';
52 my $cell_style_sub = sub {
53   my $row = shift;
54   if ( $cs_oldrow ne $row ) {
55     if ( $cs_oldrow ) {
56       if ( $cs_oldrow->country ne $row->country ) {
57         $cell_style = 'border-top:2px solid #000000';
58       } elsif ( $cs_oldrow->state ne $row->state ) {
59         $cell_style = 'border-top:1px solid #888888';
60       } elsif ( $cs_oldrow->county ne $row->county ) {
61         $cell_style = 'border-top:1px solid #cccccc';
62       } else { 
63         $cell_style = '';
64       }
65     }
66     $cs_oldrow = $row;
67   }
68   return $cell_style;
69 };
70
71 #my $edit_link = [ "${p}edit/cust_main_county.html", 'taxnum' ];
72 my $edit_link = [ 'javascript:void(0);', sub { ''; } ];
73
74 my $edit_onclick = sub {
75   my $row = shift;
76   my $taxnum = $row->taxnum;
77   include( '/elements/popup_link_onclick.html',
78              'action'      => "${p}edit/cust_main_county.html?$taxnum",
79              'actionlabel' => 'Edit tax rate',
80              'height'      => 420,
81              #default# 'width'  => 540,
82              #default# 'color' => '#333399',
83          );
84 };
85
86 my $ex_oldrow;
87 sub expand_link {
88   my %param = @_;
89
90   if ( $ex_oldrow eq $param{'row'} ) {
91     return '';
92   } else {
93     $ex_oldrow = $param{'row'};
94   }
95
96   my $taxnum = $param{'row'}->taxnum;
97   my $url = "${p}edit/cust_main_county-expand.cgi?$taxnum";
98
99   '<FONT SIZE="-1">'.
100     include( '/elements/popup_link.html',
101                'label'       => $param{'label'},
102                'action'      => $url,
103                'actionlabel' => $param{'desc'},
104                'height'      => 420,
105                #default# 'width'  => 540,
106                #default# 'color' => '#333399',
107            ).
108   '</FONT>';
109 }
110
111 sub add_link {
112   my %param = @_;
113
114   #if ( $ex_oldrow eq $param{'row'} ) {
115   #  return '';
116   #} else {
117   #  $ex_oldrow = $param{'row'};
118   #}
119
120   my %below = ( 'county' => 'city',
121                 'state'  => 'county',
122               );
123   my $what = $below{ $param{'col' } };
124
125   my $taxnum = $param{'row'}->taxnum;
126   my $url = "${p}edit/cust_main_county-add.cgi?taxnum=$taxnum;what=$what";
127
128   '<FONT SIZE="-1">'.
129     include( '/elements/popup_link.html',
130                'label'       => $param{'label'},
131                'action'      => $url,
132                'actionlabel' => $param{'desc'},
133                'height'      => 420,
134                #default# 'width'  => 540,
135                #default# 'color' => '#333399',
136            ).
137   '</FONT>';
138 }
139
140 sub collapse_link {
141   my %param = @_;
142
143   my $row = $param{'row'};
144   my $col = $param{'col'};
145 #  return ''
146 #    if $col eq 'state' and $row->city
147 #                            || qsearch({
148 #                                 'table'   => 'cust_main_county',
149 #                                 'hashref' => {
150 #                                   'country' => $row->country,
151 #                                   'state'   => $row->state,
152 #                                   'city'    => { op=>'!=', value=>'' },
153 #                                 },
154 #                                 'order_by' => 'LIMIT 1',
155 #                               });
156
157   my %below = ( 'county' => 'city',
158                 'state'  => 'county',
159               );
160
161   #XXX can still show the link when you have some counties broken down into
162   #cities and others not :/
163
164   my $taxnum = $param{'row'}->taxnum;
165   my $url = "${p}edit/process/cust_main_county-collapse.cgi?taxnum=$taxnum;".
166               'country='. uri_escape($cgi->param('country')). ';'.
167               'state='.   uri_escape($cgi->param('state')).   ';'.
168               'county='.  uri_escape($cgi->param('county'));
169   $url = "javascript:collapse_areyousure('$url', '$below{$col}', '$col')";
170
171   qq(<FONT SIZE="-1"><A HREF="$url">$param{'label'}</A></FONT>);
172 }
173
174 sub remove_link {
175   my %param = @_;
176
177   my $row = $param{'row'};
178   my $col = $param{'col'};
179  
180   my $taxnum = $param{'row'}->taxnum;
181   my $url = "${p}edit/process/cust_main_county-remove.cgi?taxnum=$taxnum;".
182               'country='. uri_escape($cgi->param('country')). ';'.
183               'state='.   uri_escape($cgi->param('state')).   ';'.
184               'county='.  uri_escape($cgi->param('county'));
185   $url = "javascript:remove_areyousure('$url', '$col')";
186
187   qq(<FONT SIZE="-1"><A HREF="$url">$param{'label'}</A></FONT>);
188
189 }
190
191 sub separate_taxclasses_link {
192   my( $row ) = @_;
193   my $taxnum = $row->taxnum;
194   my $url = "${p}edit/process/cust_main_county-expand.cgi?taxclass=1;taxnum=$taxnum";
195
196   qq!<FONT SIZE="-1"><A HREF="$url">!;
197 }
198
199 #un-separate taxclasses too
200
201 </%once>
202 <%init>
203
204 die "access denied"
205   unless $FS::CurrentUser::CurrentUser->access_right('Configuration');
206
207 #my $conf = new FS::Conf;
208 #my $money_char = $conf->config('money_char') || '$';
209 my $enable_taxclasses = $conf->exists('enable_taxclasses');
210
211 my @menubar;
212
213 my $html_init = <<END;
214   <SCRIPT>
215     function collapse_areyousure(href,col,above) {
216      if (confirm('Are you sure you want to remove all ' + col + ' tax rates for this ' + above + '?') == true)
217        window.location.href = href;
218     }
219     function remove_areyousure(href,col) {
220      if (confirm('Are you sure you want to remove this ' + col + '?') == true)
221        window.location.href = href;
222     }
223   </SCRIPT>
224 END
225
226 $html_init .= "<BR>Click on <u>separate taxclasses</u> to specify taxes per taxclass."
227   if $enable_taxclasses;
228 $html_init .= '<BR><BR>';
229
230 $html_init .= include('/elements/init_overlib.html');
231
232 my $title = '';
233
234 my $country = '';
235 if ( $cgi->param('country') =~ /^(\w\w)$/ ) {
236   $country = $1;
237   $title = $country;
238 }
239 $cgi->delete('country');
240
241 my $state = '';
242 if ( $country && $cgi->param('state') =~ /^([\w \-\'\[\]]+)$/ ) {
243   $state = $1;
244   $title = "$state, $title";
245 }
246 $cgi->delete('state');
247
248 my $county = '';
249 if ( $country && $state &&
250      $cgi->param('county') =~
251        /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
252    )
253 {
254   $county = $1;
255   if ( $county eq '__NONE__' ) {
256     $title = "No county, $title";
257   } else {
258     $title = "$county county, $title";
259   }
260 }
261 $cgi->delete('county');
262
263 $title = " for $title" if $title;
264
265 my $taxclass = '';
266 if ( $cgi->param('taxclass') =~ /^([\w \-]+)$/ ) {
267   $taxclass = $1;
268   $title .= " for $taxclass tax class";
269 }
270 $cgi->delete('taxclass');
271
272 if ( $country || $taxclass ) {
273   push @menubar, 'View all tax rates' => $p.'browse/cust_main_county.cgi';
274 }
275
276 $cgi->param('dummy', 1);
277
278 my $filter_change =
279   "window.location = '". $cgi->self_url.
280   ";country=' + encodeURIComponent( document.getElementById('country').options[document.getElementById('country').selectedIndex].value ) + ".
281   "';state='   + encodeURIComponent( document.getElementById('state').options[document.getElementById('state').selectedIndex].value ) +".
282   "';county='  + encodeURIComponent( document.getElementById('county').options[document.getElementById('county').selectedIndex].value );";
283
284 #restore this so pagination works
285 $cgi->param('country',  $country) if $country;
286 $cgi->param('state',    $state  ) if $state;
287 $cgi->param('county',   $county ) if $county;
288 $cgi->param('taxclass', $county ) if $taxclass;
289
290 my $html_posttotal =
291   '<BR>( show country: '.
292   include('/elements/select-country.html',
293             'country'             => $country,
294             'onchange'            => $filter_change,
295             'empty_label'         => '(all)',
296             'disable_empty'       => 0,
297             'disable_stateupdate' => 1,
298          );
299
300 my %states_hash = $country ? states_hash($country) : ();
301 if ( scalar(keys(%states_hash)) > 1 ) {
302   $html_posttotal .=
303     ' show state: '.
304     include('/elements/select-state.html',
305               'country'              => $country,
306               'state'                => $state,
307               'onchange'             => $filter_change,
308               'empty_label'          => '(all)',
309               'disable_empty'        => 0,
310               'disable_countyupdate' => 1,
311            );
312 } else {
313   $html_posttotal .=
314     '<SELECT NAME="state" ID="state" STYLE="display:none">'.
315     '  <OPTION VALUE="" SELECTED>'.
316     '</SELECT>';
317 }
318
319 my @counties = ( $country && $state ) ? counties($state, $country) : ();
320 if ( scalar(@counties) > 1 ) {
321   $html_posttotal .=
322     ' show county: '.
323     include('/elements/select-county.html',
324               'country'              => $country,
325               'state'                => $state,
326               'county'               => $county,
327               'onchange'             => $filter_change,
328               'empty_label'          => '(all)',
329               'empty_data_label'     => '(none)',
330               'empty_data_value'     => '__NONE__',
331               'disable_empty'        => 0,
332               'disable_cityupdate'   => 1,
333            );
334 } else {
335   $html_posttotal .=
336     '<SELECT NAME="county" ID="county" STYLE="display:none">'.
337     '  <OPTION VALUE="" SELECTED>'.
338     '</SELECT>';
339 }
340
341 $html_posttotal .= ' )';
342
343 my $bulk_popup_link = 
344   include( '/elements/popup_link_onclick.html',
345              'action'      => "${p}edit/bulk-cust_main_county.html?taxnum=MAGIC_taxnum_MAGIC",
346              'actionlabel' => 'Bulk add new tax',
347              'nofalse'     => 1,
348              'height'      => 420,
349              #default# 'width'  => 540,
350              #default# 'color' => '#333399',
351          );
352
353 my $html_foot = <<END;
354 <SCRIPT TYPE="text/javascript">
355
356   function setAll(setTo) {
357     theForm = document.taxesForm;
358     for (i=0,n=theForm.elements.length;i<n;i++) {
359       if (theForm.elements[i].name.indexOf("cust_main_county") != -1) {
360         theForm.elements[i].checked = setTo;
361       }
362     }
363   }
364
365   function toggleAll() {
366     theForm = document.taxesForm;
367     for (i=0,n=theForm.elements.length;i<n;i++) {
368       if (theForm.elements[i].name.indexOf("cust_main_county") != -1) {
369         if ( theForm.elements[i].checked == true ) {
370           theForm.elements[i].checked = false;
371         } else {
372           theForm.elements[i].checked = true;
373         }
374       }
375     }
376   }
377
378   function bulkPopup(action) {
379     var bulk_popup_link = "$bulk_popup_link";
380     var bulkstring = '';
381     theForm = document.taxesForm;
382     for (i=0,n=theForm.elements.length;i<n;i++) {
383       if (    theForm.elements[i].name.indexOf("cust_main_county") != -1
384            && theForm.elements[i].checked == true
385          ) {
386         var name = theForm.elements[i].name;
387         var taxnum = name.replace(/cust_main_county/, '');
388         if ( bulkstring != '' ) {
389           bulkstring = bulkstring + ',';
390         }
391         bulkstring = bulkstring + taxnum;
392        
393       }
394     }
395     bulkstring = bulkstring + ';action=' + action;
396     if ( bulk_popup_link.length > 1920 ) { // IE 2083 URL limit
397       alert('Too many selections'); // should do some session thing...
398       return false;
399     }
400     bulk_popup_link = bulk_popup_link.replace(/MAGIC_taxnum_MAGIC/, bulkstring);
401     eval(bulk_popup_link);
402   }
403
404 </SCRIPT>
405
406 <BR>
407 <A HREF="javascript:setAll(true)">select all</A> |
408 <A HREF="javascript:setAll(false)">unselect all</A> |
409 <A HREF="javascript:toggleAll()">toggle all</A>
410 <BR><BR>
411 <A HREF="javascript:void(0);" onClick="bulkPopup('add');">Add new tax to selected</A>
412 |
413 <A HREF="javascript:void(0);" onClick="bulkPopup('edit');">Bulk edit selected</A>
414 |
415 <A HREF="${p}misc/tax_edit_excel.html",">bulk edit with excel file</A>
416 END
417
418 my $hashref = {};
419 my $count_query = 'SELECT COUNT(*) FROM cust_main_county';
420 if ( $country ) {
421   $hashref->{'country'} = $country;
422   $count_query .= ' WHERE country = '. dbh->quote($country);
423 }
424 if ( $state ) {
425   $hashref->{'state'} = $state;
426   $count_query .= ' AND state   = '. dbh->quote($state);
427 }
428 if ( $county ) {
429   if ( $county eq '__NONE__' ) {
430     $hashref->{'county'} = '';
431     $count_query .= " AND ( county = '' OR county IS NULL ) ";
432   } else {
433     $hashref->{'county'} = $county;
434     $count_query .= ' AND county  = '. dbh->quote($county);
435   }
436 }
437 if ( $taxclass ) {
438   $hashref->{'taxclass'} = $taxclass;
439   $count_query .= ( $count_query =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
440                   ' taxclass  = '. dbh->quote($taxclass);
441 }
442
443
444 $cell_style = '';
445
446 my @header        = ( 'Country', 'State/Province', 'County', 'City', '' );
447 # last column is 'district', but usually unused
448 my @header2       = ( '', '', '', '', '' );
449 my @links         = ( '', '', '', '', '' );
450 my @link_onclicks = ( '', '', '', '', '' );
451 my $align = 'lllll';
452
453 my %seen_country = ();
454 my %seen_state = ();
455 my %seen_county = ();
456
457 my @fields = (
458   sub { my $country = shift->country;
459         return '' if $seen_country{$country}++;
460         FS::geocode_Mixin->code2country($country). "&nbsp;($country)";
461       },
462
463   #state
464   sub { my $label = $seen_state{$_[0]->country}->{$_[0]->state}++
465                       ? '' : state_label($_[0]->state, $_[0]->country);
466
467         my $countylinks = ( $_[0]->county && $label )
468                              ? '&nbsp;'. add_link(
469                                  desc => 'Add more counties',
470                                  col  => 'state',
471                                  label=> 'add more counties',
472                                  row  => $_[0],
473                                  cgi  => $cgi,
474                                ).
475                                ' '. collapse_link(
476                                  col  => 'state',
477                                  label=> 'remove all counties',
478                                  row  => $_[0],
479                                  cgi  => $cgi,
480                                )
481                              : '';
482
483         my $addlink = 
484           ( $_[0]->state
485               ? ''
486               : '&nbsp;'. expand_link( desc  => 'Add States',
487                                        row   => $_[0],
488                                        label => 'add states',
489                                        cgi  => $cgi,
490                                      )
491           );
492
493         $label.$countylinks.$addlink;
494       },
495
496   #county
497   sub { my $label =
498           $seen_county{$_[0]->country}->{$_[0]->state}->{$_[0]->county}++ 
499             ? '' : $_[0]->county;
500
501         my $citylinks = '';
502         if ( $label ) {
503           $citylinks = $_[0]->city
504                        ? '&nbsp;'. add_link(
505                            desc => 'Add more cities',
506                            col  => 'county',
507                            label=> 'add more cities',
508                            row  => $_[0],
509                            cgi  => $cgi,
510                          ).
511                          ' '. collapse_link(
512                            col  => 'county',
513                            label=> 'remove all cities',
514                            row  => $_[0],
515                            cgi  => $cgi,
516                          )
517                        : '&nbsp;'. remove_link( col  => 'county',
518                                                 label=> 'remove county',
519                                                 row  => $_[0],
520                                                 cgi  => $cgi,
521                                               );
522         }
523
524         $_[0]->county
525           ? $label.$citylinks
526           : '(all)&nbsp;'.
527               expand_link(   desc  => 'Add Counties',
528                              row   => $_[0],
529                              label => 'add counties',
530                              cgi  => $cgi,
531                          );
532       },
533
534   #city
535   sub {
536         my $r = shift;
537         if ( $r->city ) {
538
539           if ( $r->taxclass #but if it has a taxclass, can't remove
540               or $r->district ) { # or a district
541             $r->city;
542           } else {
543             $r->city. '&nbsp;'.
544               remove_link( col  => 'city',
545                            label=> 'remove city',
546                            row  => $r,
547                            cgi  => $cgi,
548                          );
549           }
550         } else {
551           '(all)&nbsp;'.
552             expand_link(   desc  => 'Add Cities',
553                            row   => $r,
554                            label => 'add cities',
555                            cgi  => $cgi,
556                        );
557         }
558       },
559
560   #district
561   sub {
562         my $r = shift;
563         if ( $r->district ) {
564           $r->district . '&nbsp;'.
565             remove_link( col  => 'district',
566                          label=> 'remove district',
567                          row  => $r,
568                          cgi  => $cgi,
569                        );
570         }
571         # manually editing districts is not exactly intended
572       },
573
574 );
575
576 my @color = (
577   '000000',
578   sub { shift->state  ? '000000' : '999999' },
579   sub { shift->county ? '000000' : '999999' },
580   sub { shift->city   ? '000000' : '999999' },
581 );
582
583 if ( $conf->exists('enable_taxclasses') ) {
584   push @header, qq!Tax class (<A HREF="${p}edit/part_pkg_taxclass.html">add new</A>)!;
585   push @header2, '(per-package classification)';
586   push @fields, sub {
587     my $r = shift;
588     if ( $r->taxclass ) {
589       $r->taxclass;
590     } else {
591       my $sql = 'SELECT COUNT(*) FROM cust_main_county
592                    WHERE country = ? AND state = ? AND county = ?
593                      AND city = ? AND taxclass IS NOT NULL';
594       if ( FS::Record->scalar_sql($sql, map $r->$_,
595                                             qw( country state county city) ) ) {
596         '(none)';
597       } else {
598         '(all)&nbsp;'.
599           separate_taxclasses_link($r, 'Separate Taxclasses').
600           'separate&nbsp;taxclasses</A></FONT>';
601       }
602     }
603   };
604   push @color, sub { shift->taxclass ? '000000' : '999999' };
605   push @links, '';
606   push @link_onclicks, '';
607   $align .= 'l';
608 }
609
610 push @header,
611               '', #checkbox column
612               'Tax name',
613               'Rate', #'Tax',
614               'Exemptions',
615               ;
616
617 push @header2,
618                '',
619                '(printed on invoices)',
620                '',
621                '',
622                ;
623
624 my $newregion = 1;
625 my $cb_oldrow = '';
626 my $cb_sub = sub {
627   my $cust_main_county = shift;
628
629   if ( $cb_oldrow ) {
630     if (    $cb_oldrow->district ne $cust_main_county->district
631          || $cb_oldrow->city     ne $cust_main_county->city 
632          || $cb_oldrow->county   ne $cust_main_county->county  
633          || $cb_oldrow->state    ne $cust_main_county->state  
634          || $cb_oldrow->country  ne $cust_main_county->country 
635          || $cb_oldrow->taxclass ne $cust_main_county->taxclass )
636     {
637       $newregion = 1;
638     } else {
639       $newregion = 0;
640     }  
641     
642   } else {
643     $newregion = 1;
644   }
645   $cb_oldrow = $cust_main_county;
646
647   if ( $newregion ) {
648     my $taxnum = $cust_main_county->taxnum;
649     qq!<INPUT NAME="cust_main_county$taxnum" TYPE="checkbox" VALUE="1">!;
650   } else {
651     '';
652   }
653 };
654
655 push @fields, 
656   $cb_sub,
657   sub { shift->taxname || 'Tax' },
658   sub { shift->tax. '%&nbsp;<FONT SIZE="-1">(edit)</FONT>' },
659   $exempt_sub,
660 ;
661
662 push @color,
663   '000000',
664   sub { shift->taxname ? '000000' : '666666' },
665   sub { shift->tax     ? '000000' : '666666' },
666   '000000',
667 ;
668
669 $align .= 'clrl';
670
671 my @cell_style = map $cell_style_sub, (1..scalar(@header));
672
673 push @links,         '', '', $edit_link,    '';
674 push @link_onclicks, '', '', $edit_onclick, '';
675
676 </%init>