add separate "Edit customer tax exemptions" access right, RT#21416
[freeside.git] / httemplate / edit / process / cust_main.cgi
1 % if ( $error ) {
2 %   $cgi->param('error', $error);
3 %
4 <% $cgi->redirect(popurl(2). "cust_main.cgi?". $cgi->query_string ) %>
5 %
6 % } else { 
7 %
8 <% $cgi->redirect(popurl(3). "view/cust_main.cgi?". $new->custnum) %>
9 %
10 % }
11 <%once>
12
13 my $me = '[edit/process/cust_main.cgi]';
14 my $DEBUG = 0;
15
16 </%once>
17 <%init>
18
19 my $curuser = $FS::CurrentUser::CurrentUser;
20 die "access denied" unless $curuser->access_right('Edit customer');
21
22 my $conf = new FS::Conf;
23
24 my $error = '';
25
26 #unmunge stuff
27
28 $cgi->param('tax','') unless defined $cgi->param('tax');
29
30 $cgi->param('refnum', (split(/:/, ($cgi->param('refnum'))[0] ))[0] );
31
32 my $payby = $cgi->param('payby');
33
34 my %noauto = (
35   'CARD' => 'DCRD',
36   'CHEK' => 'DCHK',
37 );
38 $payby = $noauto{$payby}
39   if ! $cgi->param('payauto') && exists $noauto{$payby};
40
41 $cgi->param('payby', $payby);
42
43 if ( $payby ) {
44   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
45       my $payinfo = $cgi->param('payinfo1'). '@';
46       $payinfo .= $cgi->param('payinfo3').'.' 
47             if $conf->config('echeck-country') eq 'CA';
48       $payinfo .= $cgi->param('payinfo2');
49       $cgi->param('payinfo',$payinfo);
50   }
51   $cgi->param('paydate',
52     $cgi->param( 'exp_month' ). '-'. $cgi->param( 'exp_year' ) );
53 }
54
55 my @invoicing_list = split( /\s*\,\s*/, $cgi->param('invoicing_list') );
56 push @invoicing_list, 'POST' if $cgi->param('invoicing_list_POST');
57 push @invoicing_list, 'FAX' if $cgi->param('invoicing_list_FAX');
58 $cgi->param('invoicing_list', join(',', @invoicing_list) );
59
60 # is this actually used?  if so, we need to clone locations...
61 # but I can't find anything that sets this parameter to a non-empty value
62 $cgi->param('duplicate_of_custnum') =~ /^(\d+)$/;
63 my $duplicate_of = $1;
64
65 my %locations;
66 for my $pre (qw(bill ship)) {
67
68   my %hash;
69   foreach ( FS::cust_main->location_fields ) {
70     $hash{$_} = scalar($cgi->param($pre.'_'.$_));
71   }
72   $hash{'custnum'} = $cgi->param('custnum');
73   warn Dumper \%hash if $DEBUG;
74   # if we can qsearchs it, then it's unchanged, so use that
75   $locations{$pre} = qsearchs('cust_location', \%hash)
76                      || FS::cust_location->new( \%hash );
77
78 }
79
80 if ( ($cgi->param('same') || '') eq 'Y' ) {
81   $locations{ship} = $locations{bill};
82 }
83
84 #create new record object
85 # but explicitly avoid setting ship_ fields
86
87 my $new = new FS::cust_main ( {
88   map { ( $_, scalar($cgi->param($_)) ) } (fields('cust_main')),
89   map { ( "ship_$_", '' ) } (FS::cust_main->location_fields)
90 } );
91
92 $new->invoice_noemail( ($cgi->param('invoice_email') eq 'Y') ? '' : 'Y' );
93
94 if ( $duplicate_of ) {
95   # then negate all changes to the customer; the only change we should
96   # make is to order a package, if requested
97   $new = qsearchs('cust_main', { 'custnum' => $duplicate_of })
98   # this should never happen
99     or die "nonexistent existing customer (custnum $duplicate_of)";
100 }
101
102 for my $pre (qw(bill ship)) {
103   $new->set($pre.'_location', $locations{$pre});
104   $new->set($pre.'_locationnum', $locations{$pre}->locationnum);
105 }
106
107 if ( $cgi->param('no_credit_limit') ) {
108   $new->setfield('credit_limit', '');
109 }
110
111 $new->tagnum( [ $cgi->param('tagnum') ] );
112
113 $error ||= $new->set_national_id_from_cgi( $cgi );
114
115 my %usedatetime = ( 'birthdate'        => 1,
116                     'spouse_birthdate' => 1,
117                     'anniversary_date' => 1,
118                   );
119
120 foreach my $dfield (qw(
121   signupdate birthdate spouse_birthdate anniversary_date
122 )) {
123
124   if ( $cgi->param($dfield) && $cgi->param($dfield) =~ /^([ 0-9\-\/]{0,10})$/) {
125
126     my $value = $1;
127     my $parsed = '';
128
129     if ( exists $usedatetime{$dfield} && $usedatetime{$dfield} ) {
130
131       my $format = $conf->config('date_format') || "%m/%d/%Y";
132       my $parser = DateTime::Format::Strptime->new( pattern   => $format,
133                                                     time_zone => 'floating',
134                                                   );
135       my $dt = $parser->parse_datetime($value);
136       if ( $dt ) {
137         $parsed = $dt->epoch;
138       } else {
139         $error ||= "Invalid $dfield: $value";
140       }
141
142     } else {
143
144       $parsed = parse_datetime($value)
145         or $error ||= "Invalid $dfield: $value";
146
147     }
148
149     $new->setfield( $dfield, $parsed );
150     $cgi->param(    $dfield, $parsed );
151
152   }
153
154 }
155
156 $new->setfield('paid', $cgi->param('paid') )
157   if $cgi->param('paid');
158
159 my %options = ();
160 if ( $curuser->access_right('Edit customer tax exemptions') ) { 
161   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
162   my @tax_exempt = grep { $cgi->param("tax_$_") eq 'Y' } @exempt_groups;
163   $options{'tax_exemption'} = {
164     map { $_ => scalar($cgi->param("tax_$_".'_num')) } @tax_exempt
165   };
166 }
167
168 #perhaps this stuff should go to cust_main.pm
169 if ( $new->custnum eq '' or $duplicate_of ) {
170
171   my $cust_pkg = '';
172   my $svc;
173
174   if ( $cgi->param('pkgpart_svcpart') ) {
175
176     my $x = $cgi->param('pkgpart_svcpart');
177     $x =~ /^(\d+)_(\d+)$/ or die "illegal pkgpart_svcpart $x\n";
178     my($pkgpart, $svcpart) = ($1, $2);
179     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
180     #false laziness: copied from FS::cust_pkg::order (which should become a
181     #FS::cust_main method)
182     my(%part_pkg);
183     # generate %part_pkg
184     # $part_pkg{$pkgpart} is true iff $custnum may purchase $pkgpart
185     my $agent = qsearchs('agent',{'agentnum'=> $new->agentnum });
186
187     if ( $agent ) {
188       # $pkgpart_href->{PKGPART} is true iff $custnum may purchase $pkgpart
189       my $pkgpart_href = $agent->pkgpart_hashref
190         if $agent;
191       #eslaf
192
193       # this should wind up in FS::cust_pkg!
194       $error ||= "Agent ". $new->agentnum. " (type ". $agent->typenum.
195                  ") can't purchase pkgpart ". $pkgpart
196         #unless $part_pkg{ $pkgpart };
197         unless $pkgpart_href->{ $pkgpart }
198             || $agent->agentnum == $part_pkg->agentnum;
199     } else {
200       $error = 'Select agent';
201     }
202
203     $cust_pkg = new FS::cust_pkg ( {
204       #later         'custnum' => $custnum,
205       'pkgpart'     => $pkgpart,
206       'locationnum' => scalar($cgi->param('locationnum')),
207     } );
208
209
210     my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
211     my $svcdb = $part_svc->svcdb;
212
213     if ( $svcdb eq 'svc_acct' ) {
214
215       my %svc_acct = (
216                        'svcpart'   => $svcpart,
217                        'username'  => scalar($cgi->param('username')),
218                        '_password' => scalar($cgi->param('_password')),
219                        'popnum'    => scalar($cgi->param('popnum')),
220                      );
221       $svc_acct{'domsvc'} = $cgi->param('domsvc')
222         if $cgi->param('domsvc');
223
224       $svc = new FS::svc_acct \%svc_acct;
225
226       #and just in case you were silly
227       $svc->svcpart($svcpart);
228       $svc->username($cgi->param('username'));
229       $svc->_password($cgi->param('_password'));
230       $svc->popnum($cgi->param('popnum'));
231
232     } elsif ( $svcdb eq 'svc_phone' ) {
233
234       my %svc_phone = (
235         'svcpart' => $svcpart,
236         map { $_ => scalar($cgi->param($_)) }
237             qw( countrycode phonenum sip_password pin phone_name )
238       );
239
240       $svc = new FS::svc_phone \%svc_phone;
241
242     } elsif ( $svcdb eq 'svc_dsl' ) {
243
244       my %svc_dsl = (
245         'svcpart' => $svcpart,
246         ( map { $_ => scalar($cgi->param("ship_$_")) || scalar($cgi->param($_))}
247               qw( first last company )
248         ),
249         ( map { $_ => scalar($cgi->param($_)) }
250               qw( loop_type phonenum password isp_chg isp_prev vendor_qual_id )
251         ),
252         'desired_due_date'  => time, #XXX enter?
253         'vendor_order_type' => 'NEW',
254       );
255       $svc = new FS::svc_dsl \%svc_dsl;
256
257     } else {
258       die "$svcdb not handled on new customer yet";
259     }
260
261   }
262
263
264   use Tie::RefHash;
265   tie my %hash, 'Tie::RefHash';
266   %hash = ( $cust_pkg => [ $svc ] ) if $cust_pkg;
267   if ( $duplicate_of ) {
268     # order the package and service normally
269     $error ||= $new->order_pkgs( \%hash ) if $cust_pkg;
270   }
271   else {
272     # create the customer
273     $error ||= $new->insert( \%hash, \@invoicing_list,
274                              %options,
275                              prospectnum => scalar($cgi->param('prospectnum')),
276                            );
277
278     my $conf = new FS::Conf;
279     if ( $conf->exists('backend-realtime') && ! $error ) {
280
281       my $berror =    $new->bill
282                    || $new->apply_payments_and_credits
283                    || $new->collect( 'realtime' => 1 );
284       warn "Warning, error billing during backend-realtime: $berror" if $berror;
285
286     }
287   } #if $duplicate_of
288   
289 } else { #create old record object
290
291   my $old = qsearchs( 'cust_main', { 'custnum' => $new->custnum } ); 
292   $error ||= "Old record not found!" unless $old;
293
294   if ( length($old->paycvv) && $new->paycvv =~ /^\s*\*+\s*$/ ) {
295     $new->paycvv($old->paycvv);
296   }
297   if ($new->ss =~ /xx/) {
298     $new->ss($old->ss);
299   }
300   if ($new->stateid =~ /^xxx/) {
301     $new->stateid($old->stateid);
302   }
303   if ( $new->payby =~ /^(CARD|DCRD)$/
304        && (    $new->payinfo =~ /xx/
305             || $new->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
306           )
307      )
308   {
309     $new->payinfo($old->payinfo);
310
311   } elsif ( $new->payby =~ /^(CHEK|DCHK)$/ && $new->payinfo =~ /xx/ ) {
312     #fix for #3085 "edit of customer's routing code only surprisingly causes
313     #nothing to happen...
314     # this probably won't do the right thing when we don't have the
315     # public key (can't actually get the real $old->payinfo)
316     my($new_account, $new_aba) = split('@', $new->payinfo);
317     my($old_account, $old_aba) = split('@', $old->payinfo);
318     $new_account = $old_account if $new_account =~ /xx/;
319     $new_aba     = $old_aba     if $new_aba     =~ /xx/;
320     $new->payinfo($new_account.'@'.$new_aba);
321   }
322
323   if ( ! $conf->exists('cust_main-edit_signupdate') or
324        ! $new->signupdate ) {
325     $new->signupdate($old->signupdate);
326   }
327
328   warn "$me calling $new -> replace( $old, \ @invoicing_list )" if $DEBUG;
329   local($FS::cust_main::DEBUG) = $DEBUG if $DEBUG;
330   local($FS::Record::DEBUG)    = $DEBUG if $DEBUG;
331
332   local($Data::Dumper::Sortkeys) = 1;
333   warn Dumper({ new => $new, old => $old }) if $DEBUG;
334
335   $error ||= $new->replace( $old, \@invoicing_list,
336                             %options,
337                           );
338
339   warn "$me returned from replace" if $DEBUG;
340   
341 }
342
343 unless ( $error ) { #XXX i guess i should be transactional... all in the insert
344                     # or replace call
345   my @contact_fields = qw( classnum first last title comment emailaddress );
346   foreach my $phone_type ( qsearch({table=>'phone_type', order_by=>'weight'}) ) {
347     push @contact_fields, 'phonetypenum'.$phone_type->phonetypenum;
348   }
349
350   $error = $new->process_o2m( 'table'  => 'contact',
351                               'fields' => \@contact_fields,
352                               'params' => scalar($cgi->Vars),
353                             );
354 }
355
356 </%init>