RT# 82949 - changes section name from fees to pricing, better opiton
[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 # add any virtual fields to the new cust_main record
101 foreach ($new->virtual_fields) {
102   $new->setfield($_, scalar($cgi->param($_)));
103 }
104
105 warn Dumper( $new ) if $DEBUG > 1;
106
107 if ( $duplicate_of ) {
108   # then negate all changes to the customer; the only change we should
109   # make is to order a package, if requested
110   $new = qsearchs('cust_main', { 'custnum' => $duplicate_of })
111   # this should never happen
112     or die "nonexistent existing customer (custnum $duplicate_of)";
113 }
114
115 for my $pre (qw(bill ship)) {
116   $new->set($pre.'_location', $locations{$pre});
117   $new->set($pre.'_locationnum', $locations{$pre}->locationnum);
118 }
119
120 if ( $cgi->param('no_credit_limit') ) {
121   $new->setfield('credit_limit', '');
122 }
123
124 #$new->tagnum( [ $cgi->param('tagnum') ] );
125 my $params = $cgi->Vars;
126 $new->tagnum( [
127   map { /^tagnum(\d+)/ && $1 }
128     grep { /^tagnum(\d+)/ && $cgi->param($_) } keys %$params
129 ] );
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 $options{'cust_payby_params'} = scalar($cgi->Vars);
187
188 if ( $cgi->param('residential_commercial') eq 'Residential' ) {
189
190   my $email = $cgi->param('invoice_email') || '';
191   if ( length($email) == 0 and $conf->exists('cust_main-require_invoicing_list_email', $agentnum) ) {
192     $error = 'Email address required';
193   }
194
195   $options{'invoicing_list'} = [ split(/[,\s]+/, $email) ];
196   # XXX really should include the phone numbers in here also
197
198 } else {
199
200   # contact UI is enabled
201   $options{'contact_params'} = scalar($cgi->Vars);
202
203   if ($conf->exists('cust_main-require_invoicing_list_email', $agentnum)) {
204     my $has_email = 0;
205     foreach my $prefix (grep /^contactnum\d+$/, $cgi->param) {
206       if ( length($cgi->param($prefix . '_emailaddress'))
207            and $cgi->param($prefix . '_invoice_dest') ) {
208         $has_email = 1;
209         last;
210       }
211     }
212     $error = "At least one contact must receive email invoices"
213       unless $has_email;
214   }
215
216 }
217
218 # kind of a hack, but some tax data vendors require a status and others
219 # don't.
220 my $vendor = $conf->config('tax_data_vendor');
221 if ( $vendor eq 'avalara' or $vendor eq 'suretax' ) {
222   if ( ! $cgi->param('taxstatusnum') ) {
223     $error ||= 'Tax status required';
224   }
225 }
226
227 #perhaps this stuff should go to cust_main.pm
228 my $freeside_status = '';
229 if ( $new->custnum eq '' or $duplicate_of ) {
230
231   $freeside_status = 'Customer added';
232
233   my $cust_pkg = '';
234   my $svc;
235
236   if ( $cgi->param('pkgpart_svcpart') ) {
237
238     my $x = $cgi->param('pkgpart_svcpart');
239     $x =~ /^(\d+)_(\d+)$/ or die "illegal pkgpart_svcpart $x\n";
240     my($pkgpart, $svcpart) = ($1, $2);
241     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
242     #false laziness: copied from FS::cust_pkg::order (which should become a
243     #FS::cust_main method)
244     my(%part_pkg);
245     # generate %part_pkg
246     # $part_pkg{$pkgpart} is true iff $custnum may purchase $pkgpart
247     my $agent = qsearchs('agent',{'agentnum'=> $new->agentnum });
248
249     if ( $agent ) {
250       # $pkgpart_href->{PKGPART} is true iff $custnum may purchase $pkgpart
251       my $pkgpart_href = $agent->pkgpart_hashref
252         if $agent;
253       #eslaf
254
255       # this should wind up in FS::cust_pkg!
256       $error ||= "Agent ". $new->agentnum. " (type ". $agent->typenum.
257                  ") can't purchase pkgpart ". $pkgpart
258         #unless $part_pkg{ $pkgpart };
259         unless $pkgpart_href->{ $pkgpart }
260             || $agent->agentnum == $part_pkg->agentnum;
261     } else {
262       $error = 'Select agent';
263     }
264
265     $cust_pkg = new FS::cust_pkg ( {
266       #later         'custnum' => $custnum,
267       'pkgpart'     => $pkgpart,
268       'locationnum' => scalar($cgi->param('locationnum')),
269       'salesnum'    => scalar($cgi->param('salesnum')),
270     } );
271
272
273     my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
274     my $svcdb = $part_svc->svcdb;
275
276     if ( $svcdb eq 'svc_acct' ) {
277
278       my %svc_acct = (
279                        'svcpart'   => $svcpart,
280                        'username'  => scalar($cgi->param('username')),
281                        '_password' => scalar($cgi->param('_password')),
282                        'popnum'    => scalar($cgi->param('popnum')),
283                      );
284       $svc_acct{'domsvc'} = $cgi->param('domsvc')
285         if $cgi->param('domsvc');
286
287       $svc = new FS::svc_acct \%svc_acct;
288
289       #and just in case you were silly
290       $svc->svcpart($svcpart);
291       $svc->username($cgi->param('username'));
292       $svc->_password($cgi->param('_password'));
293       $svc->popnum($cgi->param('popnum'));
294
295     } elsif ( $svcdb eq 'svc_phone' ) {
296
297       my %svc_phone = (
298         'svcpart' => $svcpart,
299         map { $_ => scalar($cgi->param($_)) }
300             qw( countrycode phonenum sip_password pin phone_name )
301       );
302
303       $svc = new FS::svc_phone \%svc_phone;
304
305     } elsif ( $svcdb eq 'svc_dsl' ) {
306
307       my %svc_dsl = (
308         'svcpart' => $svcpart,
309         ( map { $_ => scalar($cgi->param("ship_$_")) || scalar($cgi->param($_))}
310               qw( first last company )
311         ),
312         ( map { $_ => scalar($cgi->param($_)) }
313               qw( loop_type phonenum password isp_chg isp_prev vendor_qual_id )
314         ),
315         'desired_due_date'  => time, #XXX enter?
316         'vendor_order_type' => 'NEW',
317       );
318       $svc = new FS::svc_dsl \%svc_dsl;
319
320     } else {
321       die "$svcdb not handled on new customer yet";
322     }
323
324   }
325
326
327   use Tie::RefHash;
328   tie my %hash, 'Tie::RefHash';
329   %hash = ( $cust_pkg => [ $svc ] ) if $cust_pkg;
330   if ( $duplicate_of ) {
331     # order the package and service normally
332     $error ||= $new->order_pkgs( \%hash ) if $cust_pkg;
333   }
334   else {
335     # create the customer
336     $error ||= $new->insert( \%hash,
337                              %options,
338                              prospectnum => scalar($cgi->param('prospectnum')),
339                            );
340
341     my $conf = new FS::Conf;
342     if ( $conf->exists('backend-realtime') && ! $error ) {
343
344       my $berror =    $new->bill
345                    || $new->apply_payments_and_credits
346                    || $new->collect( 'realtime' => 1 );
347       warn "Warning, error billing during backend-realtime: $berror" if $berror;
348
349     }
350   } #if $duplicate_of
351   
352 } else { #create old record object
353
354   $freeside_status = 'Customer edited';
355
356   my $old = qsearchs( 'cust_main', { 'custnum' => $new->custnum } ); 
357   $error ||= "Old record not found!" unless $old;
358
359   if ($new->ss =~ /xx/) {
360     $new->ss($old->ss);
361   }
362   if ($new->stateid =~ /^xxx/) {
363     $new->stateid($old->stateid);
364   }
365
366   if ( ! $conf->exists('cust_main-edit_signupdate') or
367        ! $new->signupdate ) {
368     $new->signupdate($old->signupdate);
369   }
370
371   warn "$me calling $new -> replace( $old )" if $DEBUG;
372   local($FS::cust_main::DEBUG) = $DEBUG if $DEBUG;
373   local($FS::Record::DEBUG)    = $DEBUG if $DEBUG;
374
375   local($Data::Dumper::Sortkeys) = 1;
376   warn Dumper({ new => $new, old => $old, options => \%options}) if $DEBUG;
377
378   $error ||= $new->replace( $old, %options );
379
380   warn "$me returned from replace" if $DEBUG;
381   
382 }
383
384 </%init>