RT# 82949 - changes section name from fees to pricing, better opiton
[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 my $city = '';
264 if ( $country && $state && $county &&
265      $cgi->param('city') =~
266        /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
267    )
268 {
269   $city = $1;
270   if ( $city eq '__NONE__' ) {
271     $title = "No city, $title";
272   } else {
273     $title = "$city city, $title";
274   }
275 }
276 $cgi->delete('city');
277
278 $title = " for $title" if $title;
279
280 my $taxclass = '';
281 if ( $cgi->param('taxclass') =~ /^([\w \-]+)$/ ) {
282   $taxclass = $1;
283   $title .= " for $taxclass tax class";
284 }
285 $cgi->delete('taxclass');
286
287 if ( $country || $taxclass ) {
288   push @menubar, 'View all tax rates' => $p.'browse/cust_main_county.cgi';
289 }
290
291 $cgi->param('dummy', 1);
292
293 my $filter_change =
294   "window.location = '". $cgi->self_url.
295   ";country=' + encodeURIComponent( document.getElementById('country').options[document.getElementById('country').selectedIndex].value ) + ".
296   "';state='   + encodeURIComponent( document.getElementById('state').options[document.getElementById('state').selectedIndex].value ) +".
297   "';county='  + encodeURIComponent( document.getElementById('county').options[document.getElementById('county').selectedIndex].value )";
298
299 $filter_change .= " +';city='  + encodeURIComponent( document.getElementById('city').options[document.getElementById('city').selectedIndex].value )"
300   if $conf->exists('enable_taxclasses');
301
302 $filter_change .= ";";
303
304 #restore this so pagination works
305 $cgi->param('country',  $country) if $country;
306 $cgi->param('state',    $state  ) if $state;
307 $cgi->param('county',   $county ) if $county;
308 $cgi->param('city',     $city )   if $city;
309 $cgi->param('taxclass', $county ) if $taxclass;
310
311 my $html_posttotal =
312   '<BR>( show country: '.
313   include('/elements/select-country.html',
314             'country'             => $country,
315             'onchange'            => $filter_change,
316             'empty_label'         => '(all)',
317             'disable_empty'       => 0,
318             'disable_stateupdate' => 1,
319          );
320
321 my %states_hash = $country ? states_hash($country) : ();
322 if ( scalar(keys(%states_hash)) > 1 ) {
323   $html_posttotal .=
324     ' show state: '.
325     include('/elements/select-state.html',
326               'country'              => $country,
327               'state'                => $state,
328               'onchange'             => $filter_change,
329               'empty_label'          => '(all)',
330               'disable_empty'        => 0,
331               'disable_countyupdate' => 1,
332            );
333 } else {
334   $html_posttotal .=
335     '<SELECT NAME="state" ID="state" STYLE="display:none">'.
336     '  <OPTION VALUE="" SELECTED>'.
337     '</SELECT>';
338 }
339
340 my @counties = ( $country && $state ) ? counties($state, $country) : ();
341 if ( scalar(@counties) > 1 ) {
342   $html_posttotal .=
343     ' show county: '.
344     include('/elements/select-county.html',
345               'country'              => $country,
346               'state'                => $state,
347               'county'               => $county,
348               'onchange'             => $filter_change,
349               'empty_label'          => '(all)',
350               'empty_data_label'     => '(none)',
351               'empty_data_value'     => '__NONE__',
352               'disable_empty'        => 0,
353               'disable_cityupdate'   => 1,
354            );
355 } else {
356   $html_posttotal .=
357     '<SELECT NAME="county" ID="county" STYLE="display:none">'.
358     '  <OPTION VALUE="" SELECTED>'.
359     '</SELECT>';
360 }
361
362 if ( $conf->exists('enable_taxclasses') ) {
363   my @cities = ( $country && $state && $county ) ? cities($county, $state, $country) : ();
364   if ( scalar(@cities) > 1 ) {
365     $html_posttotal .=
366       ' show city: '.
367       include('/elements/select-city.html',
368               'country'              => $country,
369               'state'                => $state,
370               'county'               => $county,
371               'city'                 => $city,
372               'onchange'             => $filter_change,
373               'empty_label'          => '(all)',
374               'empty_data_label'     => '(none)',
375               'empty_data_value'     => '__NONE__',
376               'disable_empty'        => 0,
377               'disable_cityupdate'   => 1,
378       );
379   } else {
380     $html_posttotal .=
381       '<SELECT NAME="city" ID="city" STYLE="display:none">'.
382       '  <OPTION VALUE="" SELECTED>'.
383       '</SELECT>';
384   }
385 }
386
387 $html_posttotal .= ' )';
388
389 my $bulk_popup_link = 
390   include( '/elements/popup_link_onclick.html',
391              'action'      => "${p}edit/bulk-cust_main_county.html?taxnum=MAGIC_taxnum_MAGIC",
392              'actionlabel' => 'Bulk add new tax',
393              'nofalse'     => 1,
394              'height'      => 420,
395              #default# 'width'  => 540,
396              #default# 'color' => '#333399',
397          );
398
399 my $html_foot = <<END;
400 <SCRIPT TYPE="text/javascript">
401
402   function setAll(setTo) {
403     theForm = document.taxesForm;
404     for (i=0,n=theForm.elements.length;i<n;i++) {
405       if (theForm.elements[i].name.indexOf("cust_main_county") != -1) {
406         theForm.elements[i].checked = setTo;
407       }
408     }
409   }
410
411   function toggleAll() {
412     theForm = document.taxesForm;
413     for (i=0,n=theForm.elements.length;i<n;i++) {
414       if (theForm.elements[i].name.indexOf("cust_main_county") != -1) {
415         if ( theForm.elements[i].checked == true ) {
416           theForm.elements[i].checked = false;
417         } else {
418           theForm.elements[i].checked = true;
419         }
420       }
421     }
422   }
423
424   function bulkPopup(action) {
425     var bulk_popup_link = "$bulk_popup_link";
426     var bulkstring = '';
427     theForm = document.taxesForm;
428     for (i=0,n=theForm.elements.length;i<n;i++) {
429       if (    theForm.elements[i].name.indexOf("cust_main_county") != -1
430            && theForm.elements[i].checked == true
431          ) {
432         var name = theForm.elements[i].name;
433         var taxnum = name.replace(/cust_main_county/, '');
434         if ( bulkstring != '' ) {
435           bulkstring = bulkstring + ',';
436         }
437         bulkstring = bulkstring + taxnum;
438        
439       }
440     }
441     bulkstring = bulkstring + ';action=' + action;
442     if ( bulk_popup_link.length > 1920 ) { // IE 2083 URL limit
443       alert('Too many selections'); // should do some session thing...
444       return false;
445     }
446     bulk_popup_link = bulk_popup_link.replace(/MAGIC_taxnum_MAGIC/, bulkstring);
447     eval(bulk_popup_link);
448   }
449
450 </SCRIPT>
451
452 <BR>
453 <A HREF="javascript:setAll(true)">select all</A> |
454 <A HREF="javascript:setAll(false)">unselect all</A> |
455 <A HREF="javascript:toggleAll()">toggle all</A>
456 <BR><BR>
457 <A HREF="javascript:void(0);" onClick="bulkPopup('add');">Add new tax to selected</A>
458 |
459 <A HREF="javascript:void(0);" onClick="bulkPopup('edit');">Bulk edit selected</A>
460 |
461 <A HREF="javascript:void(0);" onClick="bulkPopup('edit_rate_only');">Bulk edit rate only selected</A>
462 END
463
464 my $hashref = {};
465 my $count_query = 'SELECT COUNT(*) FROM cust_main_county';
466 if ( $country ) {
467   $hashref->{'country'} = $country;
468   $count_query .= ' WHERE country = '. dbh->quote($country);
469 }
470 if ( $state ) {
471   $hashref->{'state'} = $state;
472   $count_query .= ' AND state   = '. dbh->quote($state);
473 }
474 if ( $county ) {
475   if ( $county eq '__NONE__' ) {
476     $hashref->{'county'} = '';
477     $count_query .= " AND ( county = '' OR county IS NULL ) ";
478   } else {
479     $hashref->{'county'} = $county;
480     $count_query .= ' AND county  = '. dbh->quote($county);
481   }
482 }
483 if ( $city ) {
484   if ( $city eq '__NONE__' ) {
485     $hashref->{'city'} = '';
486     $count_query .= " AND ( city = '' OR city IS NULL ) ";
487   } else {
488     $hashref->{'city'} = $city;
489     $count_query .= ' AND city  = '. dbh->quote($city);
490   }
491 }
492 if ( $taxclass ) {
493   $hashref->{'taxclass'} = $taxclass;
494   $count_query .= ( $count_query =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
495                   ' taxclass  = '. dbh->quote($taxclass);
496 }
497
498
499 $cell_style = '';
500
501 my @header        = ( 'Country', 'State/Province', 'County', 'City', '' );
502 # last column is 'district', but usually unused
503 my @header2       = ( '', '', '', '', '' );
504 my @links         = ( '', '', '', '', '' );
505 my @link_onclicks = ( '', '', '', '', '' );
506 my $align = 'lllll';
507
508 my %seen_country = ();
509 my %seen_state = ();
510 my %seen_county = ();
511
512 my @fields = (
513   sub { my $country = shift->country;
514         return '' if $seen_country{$country}++;
515         FS::geocode_Mixin->code2country($country). "&nbsp;($country)";
516       },
517
518   #state
519   sub { my $label = $seen_state{$_[0]->country}->{$_[0]->state}++
520                       ? '' : state_label($_[0]->state, $_[0]->country);
521
522         my $countylinks = ( $_[0]->county && $label )
523                              ? '&nbsp;'. add_link(
524                                  desc => 'Add more counties',
525                                  col  => 'state',
526                                  label=> 'add more counties',
527                                  row  => $_[0],
528                                  cgi  => $cgi,
529                                ).
530                                ' '. collapse_link(
531                                  col  => 'state',
532                                  label=> 'remove all counties',
533                                  row  => $_[0],
534                                  cgi  => $cgi,
535                                )
536                              : '';
537
538         my $addlink = 
539           ( $_[0]->state
540               ? ''
541               : '&nbsp;'. expand_link( desc  => 'Add States',
542                                        row   => $_[0],
543                                        label => 'add states',
544                                        cgi  => $cgi,
545                                      )
546           );
547
548         $label.$countylinks.$addlink;
549       },
550
551   #county
552   sub { my $label =
553           $seen_county{$_[0]->country}->{$_[0]->state}->{$_[0]->county}++ 
554             ? '' : $_[0]->county;
555
556         my $citylinks = '';
557         if ( $label ) {
558           $citylinks = $_[0]->city
559                        ? '&nbsp;'. add_link(
560                            desc => 'Add more cities',
561                            col  => 'county',
562                            label=> 'add more cities',
563                            row  => $_[0],
564                            cgi  => $cgi,
565                          ).
566                          ' '. collapse_link(
567                            col  => 'county',
568                            label=> 'remove all cities',
569                            row  => $_[0],
570                            cgi  => $cgi,
571                          )
572                        : '&nbsp;'. remove_link( col  => 'county',
573                                                 label=> 'remove county',
574                                                 row  => $_[0],
575                                                 cgi  => $cgi,
576                                               );
577         }
578
579         $_[0]->county
580           ? $label.$citylinks
581           : '(all)&nbsp;'.
582               expand_link(   desc  => 'Add Counties',
583                              row   => $_[0],
584                              label => 'add counties',
585                              cgi  => $cgi,
586                          );
587       },
588
589   #city
590   sub {
591         my $r = shift;
592         if ( $r->city ) {
593
594           if ( $r->taxclass #but if it has a taxclass, can't remove
595               or $r->district ) { # or a district
596             $r->city;
597           } else {
598             $r->city. '&nbsp;'.
599               remove_link( col  => 'city',
600                            label=> 'remove city',
601                            row  => $r,
602                            cgi  => $cgi,
603                          );
604           }
605         } else {
606           '(all)&nbsp;'.
607             expand_link(   desc  => 'Add Cities',
608                            row   => $r,
609                            label => 'add cities',
610                            cgi  => $cgi,
611                        );
612         }
613       },
614
615   #district
616   sub {
617         my $r = shift;
618         if ( $r->district ) {
619           $r->district . '&nbsp;'.
620             remove_link( col  => 'district',
621                          label=> 'remove district',
622                          row  => $r,
623                          cgi  => $cgi,
624                        );
625         }
626         # manually editing districts is not exactly intended
627       },
628
629 );
630
631 my @color = (
632   '000000',
633   sub { shift->state  ? '000000' : '999999' },
634   sub { shift->county ? '000000' : '999999' },
635   sub { shift->city   ? '000000' : '999999' },
636 );
637
638 if ( $conf->exists('enable_taxclasses') ) {
639   push @header, qq!Tax class (<A HREF="${p}edit/part_pkg_taxclass.html">add new</A>)!;
640   push @header2, '(per-package classification)';
641   push @fields, sub {
642     my $r = shift;
643     if ( $r->taxclass ) {
644       $r->taxclass;
645     } else {
646       my $sql = 'SELECT COUNT(*) FROM cust_main_county
647                    WHERE country = ? AND state = ? AND county = ?
648                      AND city = ? AND taxclass IS NOT NULL';
649       if ( FS::Record->scalar_sql($sql, map $r->$_,
650                                             qw( country state county city) ) ) {
651         '(none)';
652       } else {
653         '(all)&nbsp;'.
654           separate_taxclasses_link($r, 'Separate Taxclasses').
655           'separate&nbsp;taxclasses</A></FONT>';
656       }
657     }
658   };
659   push @color, sub { shift->taxclass ? '000000' : '999999' };
660   push @links, '';
661   push @link_onclicks, '';
662   $align .= 'l';
663 }
664
665 push @header,
666               '', #checkbox column
667               'Tax name',
668               'Rate', #'Tax',
669               'Exemptions',
670               ;
671
672 push @header2,
673                '',
674                '(printed on invoices)',
675                '',
676                '',
677                ;
678
679 my $newregion = 1;
680 my $cb_oldrow = '';
681 my $cb_sub = sub {
682   my $cust_main_county = shift;
683
684   if ( $cb_oldrow ) {
685     if (    $cb_oldrow->district ne $cust_main_county->district
686          || $cb_oldrow->city     ne $cust_main_county->city 
687          || $cb_oldrow->county   ne $cust_main_county->county  
688          || $cb_oldrow->state    ne $cust_main_county->state  
689          || $cb_oldrow->country  ne $cust_main_county->country 
690          || $cb_oldrow->taxclass ne $cust_main_county->taxclass )
691     {
692       $newregion = 1;
693     } else {
694       $newregion = 0;
695     }  
696     
697   } else {
698     $newregion = 1;
699   }
700   $cb_oldrow = $cust_main_county;
701
702   if ( $newregion ) {
703     my $taxnum = $cust_main_county->taxnum;
704     qq!<INPUT NAME="cust_main_county$taxnum" TYPE="checkbox" VALUE="1">!;
705   } else {
706     '';
707   }
708 };
709
710 push @fields, 
711   $cb_sub,
712   sub { shift->taxname || 'Tax' },
713   sub { shift->tax. '%&nbsp;<FONT SIZE="-1">(edit)</FONT>' },
714   $exempt_sub,
715 ;
716
717 push @color,
718   '000000',
719   sub { shift->taxname ? '000000' : '666666' },
720   sub { shift->tax     ? '000000' : '666666' },
721   '000000',
722 ;
723
724 $align .= 'clrl';
725
726 my @cell_style = map $cell_style_sub, (1..scalar(@header));
727
728 push @links,         '', '', $edit_link,    '';
729 push @link_onclicks, '', '', $edit_onclick, '';
730
731 </%init>