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