track customer invoice destination emails using contact_email, #25536
[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{'contact_params'} = scalar($cgi->Vars);
160 $options{'cust_payby_params'} = scalar($cgi->Vars);
161
162 my $email;
163
164 if ( $cgi->param('residential_commercial') eq 'Residential' ) {
165
166   $email = $cgi->param('invoice_email') || '';
167   if ( length($email) == 0 and $conf->exists('cust_main-require_invoicing_list_email', $agentnum) ) {
168     $error = 'Email address required';
169   }
170
171   # XXX really should include the phone numbers in here also
172
173 } else {
174
175   # contact UI is enabled; everything will be passed through via
176   # contact_params
177   if ($conf->exists('cust_main-require_invoicing_list_email', $agentnum)) {
178     my $has_email = 0;
179     foreach my $prefix (grep /^contactnum\d+$/, $cgi->param) {
180       if ( length($cgi->param($prefix . '_emailaddress'))
181            and $cgi->param($prefix . '_invoice_dest') ) {
182         $has_email = 1;
183         last;
184       }
185     }
186     $error = "At least one contact must receive email invoices"
187       unless $has_email;
188   }
189
190 }
191
192 #perhaps this stuff should go to cust_main.pm
193 if ( $new->custnum eq '' or $duplicate_of ) {
194
195   my $cust_pkg = '';
196   my $svc;
197
198   if ( $cgi->param('pkgpart_svcpart') ) {
199
200     my $x = $cgi->param('pkgpart_svcpart');
201     $x =~ /^(\d+)_(\d+)$/ or die "illegal pkgpart_svcpart $x\n";
202     my($pkgpart, $svcpart) = ($1, $2);
203     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
204     #false laziness: copied from FS::cust_pkg::order (which should become a
205     #FS::cust_main method)
206     my(%part_pkg);
207     # generate %part_pkg
208     # $part_pkg{$pkgpart} is true iff $custnum may purchase $pkgpart
209     my $agent = qsearchs('agent',{'agentnum'=> $new->agentnum });
210
211     if ( $agent ) {
212       # $pkgpart_href->{PKGPART} is true iff $custnum may purchase $pkgpart
213       my $pkgpart_href = $agent->pkgpart_hashref
214         if $agent;
215       #eslaf
216
217       # this should wind up in FS::cust_pkg!
218       $error ||= "Agent ". $new->agentnum. " (type ". $agent->typenum.
219                  ") can't purchase pkgpart ". $pkgpart
220         #unless $part_pkg{ $pkgpart };
221         unless $pkgpart_href->{ $pkgpart }
222             || $agent->agentnum == $part_pkg->agentnum;
223     } else {
224       $error = 'Select agent';
225     }
226
227     $cust_pkg = new FS::cust_pkg ( {
228       #later         'custnum' => $custnum,
229       'pkgpart'     => $pkgpart,
230       'locationnum' => scalar($cgi->param('locationnum')),
231       'salesnum'    => scalar($cgi->param('salesnum')),
232     } );
233
234
235     my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
236     my $svcdb = $part_svc->svcdb;
237
238     if ( $svcdb eq 'svc_acct' ) {
239
240       my %svc_acct = (
241                        'svcpart'   => $svcpart,
242                        'username'  => scalar($cgi->param('username')),
243                        '_password' => scalar($cgi->param('_password')),
244                        'popnum'    => scalar($cgi->param('popnum')),
245                      );
246       $svc_acct{'domsvc'} = $cgi->param('domsvc')
247         if $cgi->param('domsvc');
248
249       $svc = new FS::svc_acct \%svc_acct;
250
251       #and just in case you were silly
252       $svc->svcpart($svcpart);
253       $svc->username($cgi->param('username'));
254       $svc->_password($cgi->param('_password'));
255       $svc->popnum($cgi->param('popnum'));
256
257     } elsif ( $svcdb eq 'svc_phone' ) {
258
259       my %svc_phone = (
260         'svcpart' => $svcpart,
261         map { $_ => scalar($cgi->param($_)) }
262             qw( countrycode phonenum sip_password pin phone_name )
263       );
264
265       $svc = new FS::svc_phone \%svc_phone;
266
267     } elsif ( $svcdb eq 'svc_dsl' ) {
268
269       my %svc_dsl = (
270         'svcpart' => $svcpart,
271         ( map { $_ => scalar($cgi->param("ship_$_")) || scalar($cgi->param($_))}
272               qw( first last company )
273         ),
274         ( map { $_ => scalar($cgi->param($_)) }
275               qw( loop_type phonenum password isp_chg isp_prev vendor_qual_id )
276         ),
277         'desired_due_date'  => time, #XXX enter?
278         'vendor_order_type' => 'NEW',
279       );
280       $svc = new FS::svc_dsl \%svc_dsl;
281
282     } else {
283       die "$svcdb not handled on new customer yet";
284     }
285
286   }
287
288
289   use Tie::RefHash;
290   tie my %hash, 'Tie::RefHash';
291   %hash = ( $cust_pkg => [ $svc ] ) if $cust_pkg;
292   if ( $duplicate_of ) {
293     # order the package and service normally
294     $error ||= $new->order_pkgs( \%hash ) if $cust_pkg;
295   }
296   else {
297     # create the customer
298     $error ||= $new->insert( \%hash,
299                              [ $email ],
300                              %options,
301                              prospectnum => scalar($cgi->param('prospectnum')),
302                            );
303
304     my $conf = new FS::Conf;
305     if ( $conf->exists('backend-realtime') && ! $error ) {
306
307       my $berror =    $new->bill
308                    || $new->apply_payments_and_credits
309                    || $new->collect( 'realtime' => 1 );
310       warn "Warning, error billing during backend-realtime: $berror" if $berror;
311
312     }
313   } #if $duplicate_of
314   
315 } else { #create old record object
316
317   my $old = qsearchs( 'cust_main', { 'custnum' => $new->custnum } ); 
318   $error ||= "Old record not found!" unless $old;
319
320   if ($new->ss =~ /xx/) {
321     $new->ss($old->ss);
322   }
323   if ($new->stateid =~ /^xxx/) {
324     $new->stateid($old->stateid);
325   }
326
327   if ( ! $conf->exists('cust_main-edit_signupdate') or
328        ! $new->signupdate ) {
329     $new->signupdate($old->signupdate);
330   }
331
332   warn "$me calling $new -> replace( $old )" if $DEBUG;
333   local($FS::cust_main::DEBUG) = $DEBUG if $DEBUG;
334   local($FS::Record::DEBUG)    = $DEBUG if $DEBUG;
335
336   local($Data::Dumper::Sortkeys) = 1;
337   warn Dumper({ new => $new, old => $old }) if $DEBUG;
338
339   $error ||= $new->replace( $old, [ $email ], %options );
340
341   warn "$me returned from replace" if $DEBUG;
342   
343 }
344
345 </%init>