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