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