strip degree signs from coord fields before saving CGI param state, workaround for...
[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 @invoicing_list = split( /\s*\,\s*/, $cgi->param('invoicing_list') );
33 #push @invoicing_list, 'POST' if $cgi->param('invoicing_list_POST');
34 #push @invoicing_list, 'FAX' if $cgi->param('invoicing_list_FAX');
35 #$cgi->param('invoicing_list', join(',', @invoicing_list) );
36
37 my $agentnum = $cgi->param('agentnum');
38
39 # is this actually used?  if so, we need to clone locations...
40 # but I can't find anything that sets this parameter to a non-empty value
41 # yes, fec48523d3cf056da08813f9b2b7d633b27aaf8d for #16582 is where it came in,
42 # for "duplicate address checking for new customers".  afaict still in
43 # edit/cust_main/bottomfixup.html (and working?)
44 $cgi->param('duplicate_of_custnum') =~ /^(\d+)$/;
45 my $duplicate_of = $1;
46
47 # if this is enabled, enforce it
48 if ( $conf->exists('agent-ship_address', $cgi->param('agentnum')) ) {
49   my $agent = FS::agent->by_key($cgi->param('agentnum'));
50   my $agent_cust_main = $agent->agent_cust_main;
51   if ( $agent_cust_main ) {
52     my $agent_location = $agent_cust_main->ship_location;
53     foreach (qw(address1 city state zip country latitude longitude district)) {
54       $cgi->param("ship_$_", $agent_location->get($_));
55     }
56   }
57 }
58
59 my %locations;
60 for my $pre (qw(bill ship)) {
61
62   foreach (qw( latitude longitude)) {
63     my $coord = $cgi->param($pre.'_'.$_);
64     $coord =~ s/\N{DEGREE SIGN}\s*$//;
65     $cgi->param($pre.'_'.$_, $coord);
66   }
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   $locations{$pre} = FS::cust_location->new(\%hash);
75 }
76
77 if ( ($cgi->param('same') || '') eq 'Y' ) {
78   $locations{ship} = $locations{bill};
79 }
80
81 #create new record object
82 # but explicitly avoid setting ship_ fields
83
84 my $new = new FS::cust_main ( {
85   (map { ( $_, scalar($cgi->param($_)) ) } (fields('cust_main'))),
86   (map { ( "ship_$_", '' ) } (FS::cust_main->location_fields))
87 } );
88
89 warn Dumper( $new ) if $DEBUG > 1;
90
91 if ( $duplicate_of ) {
92   # then negate all changes to the customer; the only change we should
93   # make is to order a package, if requested
94   $new = qsearchs('cust_main', { 'custnum' => $duplicate_of })
95   # this should never happen
96     or die "nonexistent existing customer (custnum $duplicate_of)";
97 }
98
99 for my $pre (qw(bill ship)) {
100   $new->set($pre.'_location', $locations{$pre});
101   $new->set($pre.'_locationnum', $locations{$pre}->locationnum);
102 }
103
104 if ( $cgi->param('no_credit_limit') ) {
105   $new->setfield('credit_limit', '');
106 }
107
108 $new->tagnum( [ $cgi->param('tagnum') ] );
109
110 $error ||= $new->set_national_id_from_cgi( $cgi );
111
112 my %usedatetime = ( 'birthdate'        => 1,
113                     'spouse_birthdate' => 1,
114                     'anniversary_date' => 1,
115                   );
116
117 foreach my $dfield (qw(
118   signupdate birthdate spouse_birthdate anniversary_date
119 )) {
120
121   if ( $cgi->param($dfield) && $cgi->param($dfield) =~ /^([ 0-9\-\/]{0,10})$/) {
122
123     my $value = $1;
124     my $parsed = '';
125
126     if ( exists $usedatetime{$dfield} && $usedatetime{$dfield} ) {
127
128       my $format = $conf->config('date_format') || "%m/%d/%Y";
129       my $parser = DateTime::Format::Strptime->new( pattern   => $format,
130                                                     time_zone => 'floating',
131                                                   );
132       my $dt = $parser->parse_datetime($value);
133       if ( $dt ) {
134         $parsed = $dt->epoch;
135       } else {
136         $error ||= "Invalid $dfield: $value";
137       }
138
139     } else {
140
141       $parsed = parse_datetime($value)
142         or $error ||= "Invalid $dfield: $value";
143
144     }
145
146     $new->setfield( $dfield, $parsed );
147     $cgi->param(    $dfield, $parsed );
148
149   }
150
151 }
152
153 $new->setfield('paid', $cgi->param('paid') )
154   if $cgi->param('paid');
155
156 my %options = ();
157 if ( $curuser->access_right('Edit customer tax exemptions') ) { 
158   my @exempt_groups = grep /\S/, $conf->config('tax-cust_exempt-groups');
159   my @tax_exempt = grep { $cgi->param("tax_$_") eq 'Y' } @exempt_groups;
160   $options{'tax_exemption'} = {
161     map { $_ => scalar($cgi->param("tax_$_".'_num')) } @tax_exempt
162   };
163 }
164
165 $options{'cust_payby_params'} = scalar($cgi->Vars);
166
167 if ( $cgi->param('residential_commercial') eq 'Residential' ) {
168
169   my $email = $cgi->param('invoice_email') || '';
170   if ( length($email) == 0 and $conf->exists('cust_main-require_invoicing_list_email', $agentnum) ) {
171     $error = 'Email address required';
172   }
173
174   $options{'invoicing_list'} = [ split(/\s*,\s*/, $email) ];
175   # XXX really should include the phone numbers in here also
176
177 } else {
178
179   # contact UI is enabled
180   $options{'contact_params'} = scalar($cgi->Vars);
181
182   if ($conf->exists('cust_main-require_invoicing_list_email', $agentnum)) {
183     my $has_email = 0;
184     foreach my $prefix (grep /^contactnum\d+$/, $cgi->param) {
185       if ( length($cgi->param($prefix . '_emailaddress'))
186            and $cgi->param($prefix . '_invoice_dest') ) {
187         $has_email = 1;
188         last;
189       }
190     }
191     $error = "At least one contact must receive email invoices"
192       unless $has_email;
193   }
194
195 }
196
197 # kind of a hack, but some tax data vendors require a status and others
198 # don't.
199 my $vendor = $conf->config('tax_data_vendor');
200 if ( $vendor eq 'avalara' or $vendor eq 'suretax' ) {
201   if ( ! $cgi->param('taxstatusnum') ) {
202     $error ||= 'Tax status required';
203   }
204 }
205
206 #perhaps this stuff should go to cust_main.pm
207 if ( $new->custnum eq '' or $duplicate_of ) {
208
209   my $cust_pkg = '';
210   my $svc;
211
212   if ( $cgi->param('pkgpart_svcpart') ) {
213
214     my $x = $cgi->param('pkgpart_svcpart');
215     $x =~ /^(\d+)_(\d+)$/ or die "illegal pkgpart_svcpart $x\n";
216     my($pkgpart, $svcpart) = ($1, $2);
217     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
218     #false laziness: copied from FS::cust_pkg::order (which should become a
219     #FS::cust_main method)
220     my(%part_pkg);
221     # generate %part_pkg
222     # $part_pkg{$pkgpart} is true iff $custnum may purchase $pkgpart
223     my $agent = qsearchs('agent',{'agentnum'=> $new->agentnum });
224
225     if ( $agent ) {
226       # $pkgpart_href->{PKGPART} is true iff $custnum may purchase $pkgpart
227       my $pkgpart_href = $agent->pkgpart_hashref
228         if $agent;
229       #eslaf
230
231       # this should wind up in FS::cust_pkg!
232       $error ||= "Agent ". $new->agentnum. " (type ". $agent->typenum.
233                  ") can't purchase pkgpart ". $pkgpart
234         #unless $part_pkg{ $pkgpart };
235         unless $pkgpart_href->{ $pkgpart }
236             || $agent->agentnum == $part_pkg->agentnum;
237     } else {
238       $error = 'Select agent';
239     }
240
241     $cust_pkg = new FS::cust_pkg ( {
242       #later         'custnum' => $custnum,
243       'pkgpart'     => $pkgpart,
244       'locationnum' => scalar($cgi->param('locationnum')),
245       'salesnum'    => scalar($cgi->param('salesnum')),
246     } );
247
248
249     my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
250     my $svcdb = $part_svc->svcdb;
251
252     if ( $svcdb eq 'svc_acct' ) {
253
254       my %svc_acct = (
255                        'svcpart'   => $svcpart,
256                        'username'  => scalar($cgi->param('username')),
257                        '_password' => scalar($cgi->param('_password')),
258                        'popnum'    => scalar($cgi->param('popnum')),
259                      );
260       $svc_acct{'domsvc'} = $cgi->param('domsvc')
261         if $cgi->param('domsvc');
262
263       $svc = new FS::svc_acct \%svc_acct;
264
265       #and just in case you were silly
266       $svc->svcpart($svcpart);
267       $svc->username($cgi->param('username'));
268       $svc->_password($cgi->param('_password'));
269       $svc->popnum($cgi->param('popnum'));
270
271     } elsif ( $svcdb eq 'svc_phone' ) {
272
273       my %svc_phone = (
274         'svcpart' => $svcpart,
275         map { $_ => scalar($cgi->param($_)) }
276             qw( countrycode phonenum sip_password pin phone_name )
277       );
278
279       $svc = new FS::svc_phone \%svc_phone;
280
281     } elsif ( $svcdb eq 'svc_dsl' ) {
282
283       my %svc_dsl = (
284         'svcpart' => $svcpart,
285         ( map { $_ => scalar($cgi->param("ship_$_")) || scalar($cgi->param($_))}
286               qw( first last company )
287         ),
288         ( map { $_ => scalar($cgi->param($_)) }
289               qw( loop_type phonenum password isp_chg isp_prev vendor_qual_id )
290         ),
291         'desired_due_date'  => time, #XXX enter?
292         'vendor_order_type' => 'NEW',
293       );
294       $svc = new FS::svc_dsl \%svc_dsl;
295
296     } else {
297       die "$svcdb not handled on new customer yet";
298     }
299
300   }
301
302
303   use Tie::RefHash;
304   tie my %hash, 'Tie::RefHash';
305   %hash = ( $cust_pkg => [ $svc ] ) if $cust_pkg;
306   if ( $duplicate_of ) {
307     # order the package and service normally
308     $error ||= $new->order_pkgs( \%hash ) if $cust_pkg;
309   }
310   else {
311     # create the customer
312     $error ||= $new->insert( \%hash,
313                              %options,
314                              prospectnum => scalar($cgi->param('prospectnum')),
315                            );
316
317     my $conf = new FS::Conf;
318     if ( $conf->exists('backend-realtime') && ! $error ) {
319
320       my $berror =    $new->bill
321                    || $new->apply_payments_and_credits
322                    || $new->collect( 'realtime' => 1 );
323       warn "Warning, error billing during backend-realtime: $berror" if $berror;
324
325     }
326   } #if $duplicate_of
327   
328 } else { #create old record object
329
330   my $old = qsearchs( 'cust_main', { 'custnum' => $new->custnum } ); 
331   $error ||= "Old record not found!" unless $old;
332
333   if ($new->ss =~ /xx/) {
334     $new->ss($old->ss);
335   }
336   if ($new->stateid =~ /^xxx/) {
337     $new->stateid($old->stateid);
338   }
339
340   if ( ! $conf->exists('cust_main-edit_signupdate') or
341        ! $new->signupdate ) {
342     $new->signupdate($old->signupdate);
343   }
344
345   warn "$me calling $new -> replace( $old )" if $DEBUG;
346   local($FS::cust_main::DEBUG) = $DEBUG if $DEBUG;
347   local($FS::Record::DEBUG)    = $DEBUG if $DEBUG;
348
349   local($Data::Dumper::Sortkeys) = 1;
350   warn Dumper({ new => $new, old => $old, options => \%options}) if $DEBUG;
351
352   $error ||= $new->replace( $old, %options );
353
354   warn "$me returned from replace" if $DEBUG;
355   
356 }
357
358 </%init>