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