a9439fa89f8810ab65a1aec2438af4c3341a9107
[freeside.git] / httemplate / edit / process / cust_main.cgi
1 % if ( $error ) {
2 %   $cgi->param('error', $error);
3 %   my $query = $m->scomp('/elements/create_uri_query', 'secure'=>1);
4 <% $cgi->redirect(popurl(2). "cust_main.cgi?$query" ) %>
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 # yes, fec48523d3cf056da08813f9b2b7d633b27aaf8d for #16582 is where it came in,
63 # for "duplicate address checking for new customers".  afaict still in
64 # edit/cust_main/bottomfixup.html (and working?)
65 $cgi->param('duplicate_of_custnum') =~ /^(\d+)$/;
66 my $duplicate_of = $1;
67
68 # if this is enabled, enforce it
69 if ( $conf->exists('agent-ship_address', $cgi->param('agentnum')) ) {
70   my $agent = FS::agent->by_key($cgi->param('agentnum'));
71   my $agent_cust_main = $agent->agent_cust_main;
72   if ( $agent_cust_main ) {
73     my $agent_location = $agent_cust_main->ship_location;
74     foreach (qw(address1 city state zip country latitude longitude district)) {
75       $cgi->param("ship_$_", $agent_location->get($_));
76     }
77   }
78 }
79
80 my %locations;
81 for my $pre (qw(bill ship)) {
82
83   foreach (qw( latitude longitude)) {
84     my $coord = $cgi->param($pre.'_'.$_);
85     $coord =~ s/\N{DEGREE SIGN}\s*$//;
86     $cgi->param($pre.'_'.$_, $coord);
87   }
88
89   my %hash;
90   foreach ( FS::cust_main->location_fields ) {
91     $hash{$_} = scalar($cgi->param($pre.'_'.$_));
92   }
93   $hash{'custnum'} = $cgi->param('custnum');
94   warn Dumper \%hash if $DEBUG;
95   $locations{$pre} = FS::cust_location->new(\%hash);
96 }
97
98 if ( ($cgi->param('same') || '') eq 'Y' ) {
99   $locations{ship} = $locations{bill};
100 }
101
102 #create new record object
103 # but explicitly avoid setting ship_ fields
104
105 my $new = new FS::cust_main ( {
106   (map { ( $_, scalar($cgi->param($_)) ) } (fields('cust_main'))),
107   (map { ( "ship_$_", '' ) } (FS::cust_main->location_fields))
108 } );
109
110 $new->invoice_noemail( ($cgi->param('invoice_email') eq 'Y') ? '' : 'Y' );
111
112 if ( $duplicate_of ) {
113   # then negate all changes to the customer; the only change we should
114   # make is to order a package, if requested
115   $new = qsearchs('cust_main', { 'custnum' => $duplicate_of })
116   # this should never happen
117     or die "nonexistent existing customer (custnum $duplicate_of)";
118 }
119
120 for my $pre (qw(bill ship)) {
121   $new->set($pre.'_location', $locations{$pre});
122   $new->set($pre.'_locationnum', $locations{$pre}->locationnum);
123 }
124
125 if ( $cgi->param('no_credit_limit') ) {
126   $new->setfield('credit_limit', '');
127 }
128
129 $new->tagnum( [ $cgi->param('tagnum') ] );
130
131 $error ||= $new->set_national_id_from_cgi( $cgi );
132
133 my %usedatetime = ( 'birthdate'        => 1,
134                     'spouse_birthdate' => 1,
135                     'anniversary_date' => 1,
136                   );
137
138 foreach my $dfield (qw(
139   signupdate birthdate spouse_birthdate anniversary_date
140 )) {
141
142   if ( $cgi->param($dfield) && $cgi->param($dfield) =~ /^([ 0-9\-\/]{0,10})$/) {
143
144     my $value = $1;
145     my $parsed = '';
146
147     if ( exists $usedatetime{$dfield} && $usedatetime{$dfield} ) {
148
149       my $format = $conf->config('date_format') || "%m/%d/%Y";
150       my $parser = DateTime::Format::Strptime->new( pattern   => $format,
151                                                     time_zone => 'floating',
152                                                   );
153       my $dt = $parser->parse_datetime($value);
154       if ( $dt ) {
155         $parsed = $dt->epoch;
156       } else {
157         $error ||= "Invalid $dfield: $value";
158       }
159
160     } else {
161
162       $parsed = parse_datetime($value)
163         or $error ||= "Invalid $dfield: $value";
164
165     }
166
167     $new->setfield( $dfield, $parsed );
168     $cgi->param(    $dfield, $parsed );
169
170   }
171
172 }
173
174 $new->setfield('paid', $cgi->param('paid') )
175   if $cgi->param('paid');
176
177 my %options = ();
178 if ( $curuser->access_right('Edit customer tax exemptions') ) { 
179   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
180   my @tax_exempt = grep { $cgi->param("tax_$_") eq 'Y' } @exempt_groups;
181   $options{'tax_exemption'} = {
182     map { $_ => scalar($cgi->param("tax_$_".'_num')) } @tax_exempt
183   };
184 }
185
186 #perhaps this stuff should go to cust_main.pm
187 if ( $new->custnum eq '' or $duplicate_of ) {
188
189   my $cust_pkg = '';
190   my $svc;
191
192   if ( $cgi->param('pkgpart_svcpart') ) {
193
194     my $x = $cgi->param('pkgpart_svcpart');
195     $x =~ /^(\d+)_(\d+)$/ or die "illegal pkgpart_svcpart $x\n";
196     my($pkgpart, $svcpart) = ($1, $2);
197     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
198     #false laziness: copied from FS::cust_pkg::order (which should become a
199     #FS::cust_main method)
200     my(%part_pkg);
201     # generate %part_pkg
202     # $part_pkg{$pkgpart} is true iff $custnum may purchase $pkgpart
203     my $agent = qsearchs('agent',{'agentnum'=> $new->agentnum });
204
205     if ( $agent ) {
206       # $pkgpart_href->{PKGPART} is true iff $custnum may purchase $pkgpart
207       my $pkgpart_href = $agent->pkgpart_hashref
208         if $agent;
209       #eslaf
210
211       # this should wind up in FS::cust_pkg!
212       $error ||= "Agent ". $new->agentnum. " (type ". $agent->typenum.
213                  ") can't purchase pkgpart ". $pkgpart
214         #unless $part_pkg{ $pkgpart };
215         unless $pkgpart_href->{ $pkgpart }
216             || $agent->agentnum == $part_pkg->agentnum;
217     } else {
218       $error = 'Select agent';
219     }
220
221     $cust_pkg = new FS::cust_pkg ( {
222       #later         'custnum' => $custnum,
223       'pkgpart'     => $pkgpart,
224       'locationnum' => scalar($cgi->param('locationnum')),
225       'salesnum'    => scalar($cgi->param('salesnum')),
226     } );
227
228
229     my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
230     my $svcdb = $part_svc->svcdb;
231
232     if ( $svcdb eq 'svc_acct' ) {
233
234       my %svc_acct = (
235                        'svcpart'   => $svcpart,
236                        'username'  => scalar($cgi->param('username')),
237                        '_password' => scalar($cgi->param('_password')),
238                        'popnum'    => scalar($cgi->param('popnum')),
239                      );
240       $svc_acct{'domsvc'} = $cgi->param('domsvc')
241         if $cgi->param('domsvc');
242
243       $svc = new FS::svc_acct \%svc_acct;
244
245       #and just in case you were silly
246       $svc->svcpart($svcpart);
247       $svc->username($cgi->param('username'));
248       $svc->_password($cgi->param('_password'));
249       $svc->popnum($cgi->param('popnum'));
250
251     } elsif ( $svcdb eq 'svc_phone' ) {
252
253       my %svc_phone = (
254         'svcpart' => $svcpart,
255         map { $_ => scalar($cgi->param($_)) }
256             qw( countrycode phonenum sip_password pin phone_name )
257       );
258
259       $svc = new FS::svc_phone \%svc_phone;
260
261     } elsif ( $svcdb eq 'svc_dsl' ) {
262
263       my %svc_dsl = (
264         'svcpart' => $svcpart,
265         ( map { $_ => scalar($cgi->param("ship_$_")) || scalar($cgi->param($_))}
266               qw( first last company )
267         ),
268         ( map { $_ => scalar($cgi->param($_)) }
269               qw( loop_type phonenum password isp_chg isp_prev vendor_qual_id )
270         ),
271         'desired_due_date'  => time, #XXX enter?
272         'vendor_order_type' => 'NEW',
273       );
274       $svc = new FS::svc_dsl \%svc_dsl;
275
276     } else {
277       die "$svcdb not handled on new customer yet";
278     }
279
280   }
281
282
283   use Tie::RefHash;
284   tie my %hash, 'Tie::RefHash';
285   %hash = ( $cust_pkg => [ $svc ] ) if $cust_pkg;
286   if ( $duplicate_of ) {
287     # order the package and service normally
288     $error ||= $new->order_pkgs( \%hash ) if $cust_pkg;
289   }
290   else {
291     # create the customer
292     $error ||= $new->insert( \%hash, \@invoicing_list,
293                              %options,
294                              prospectnum => scalar($cgi->param('prospectnum')),
295                            );
296
297     my $conf = new FS::Conf;
298     if ( $conf->exists('backend-realtime') && ! $error ) {
299
300       my $berror =    $new->bill
301                    || $new->apply_payments_and_credits
302                    || $new->collect( 'realtime' => 1 );
303       warn "Warning, error billing during backend-realtime: $berror" if $berror;
304
305     }
306   } #if $duplicate_of
307   
308 } else { #create old record object
309
310   my $old = qsearchs( 'cust_main', { 'custnum' => $new->custnum } ); 
311   $error ||= "Old record not found!" unless $old;
312
313   if ( length($old->paycvv) && $new->paycvv =~ /^\s*\*+\s*$/ ) {
314     $new->paycvv($old->paycvv);
315   }
316   if ($new->ss =~ /xx/) {
317     $new->ss($old->ss);
318   }
319   if ($new->stateid =~ /^xxx/) {
320     $new->stateid($old->stateid);
321   }
322   if ( $new->payby =~ /^(CARD|DCRD)$/
323        && (    $new->payinfo =~ /xx/
324             || $new->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
325           )
326      )
327   {
328     $new->payinfo($old->payinfo);
329
330   } elsif ( $new->payby =~ /^(CHEK|DCHK)$/ && $new->payinfo =~ /xx/ ) {
331     #fix for #3085 "edit of customer's routing code only surprisingly causes
332     #nothing to happen...
333     # this probably won't do the right thing when we don't have the
334     # public key (can't actually get the real $old->payinfo)
335     my($new_account, $new_aba) = split('@', $new->payinfo);
336     my($old_account, $old_aba) = split('@', $old->payinfo);
337     $new_account = $old_account if $new_account =~ /xx/;
338     $new_aba     = $old_aba     if $new_aba     =~ /xx/;
339     $new->payinfo($new_account.'@'.$new_aba);
340   }
341
342   if ( ! $conf->exists('cust_main-edit_signupdate') or
343        ! $new->signupdate ) {
344     $new->signupdate($old->signupdate);
345   }
346
347   warn "$me calling $new -> replace( $old, \ @invoicing_list )" if $DEBUG;
348   local($FS::cust_main::DEBUG) = $DEBUG if $DEBUG;
349   local($FS::Record::DEBUG)    = $DEBUG if $DEBUG;
350
351   local($Data::Dumper::Sortkeys) = 1;
352   warn Dumper({ new => $new, old => $old }) if $DEBUG;
353
354   $error ||= $new->replace( $old, \@invoicing_list,
355                             %options,
356                           );
357
358   warn "$me returned from replace" if $DEBUG;
359   
360 }
361
362 unless ( $error ) { #XXX i should be transactional... all in the insert
363                     # or replace call
364
365   $error = $new->process_o2m( 'table'  => 'contact',
366                               'fields' => FS::contact->cgi_contact_fields,
367                               'params' => scalar($cgi->Vars),
368                             );
369 }
370
371 </%init>