big update for reseller interface
[freeside.git] / fs_selfservice / FS-SelfService / SelfService.pm
1 package FS::SelfService;
2
3 use strict;
4 use vars qw($VERSION @ISA @EXPORT_OK $socket %autoload $tag);
5 use Exporter;
6 use Socket;
7 use FileHandle;
8 #use IO::Handle;
9 use IO::Select;
10 use Storable 2.09 qw(nstore_fd fd_retrieve);
11
12 $VERSION = '0.03';
13
14 @ISA = qw( Exporter );
15
16 $socket =  "/usr/local/freeside/selfservice_socket";
17 $socket .= '.'.$tag if defined $tag && length($tag);
18
19 #maybe should ask ClientAPI for this list
20 %autoload = (
21   'passwd'               => 'passwd/passwd',
22   'chfn'                 => 'passwd/passwd',
23   'chsh'                 => 'passwd/passwd',
24   'login'                => 'MyAccount/login',
25   'logout'               => 'MyAccount/logout',
26   'customer_info'        => 'MyAccount/customer_info',
27   'edit_info'            => 'MyAccount/edit_info',     #add to ss cgi!
28   'invoice'              => 'MyAccount/invoice',
29   'list_invoices'        => 'MyAccount/list_invoices', #?
30   'cancel'               => 'MyAccount/cancel',        #add to ss cgi!
31   'payment_info'         => 'MyAccount/payment_info',
32   'process_payment'      => 'MyAccount/process_payment',
33   'list_pkgs'            => 'MyAccount/list_pkgs',     #add to ss cgi!
34   'order_pkg'            => 'MyAccount/order_pkg',     #add to ss cgi!
35   'cancel_pkg'           => 'MyAccount/cancel_pkg',    #add to ss cgi!
36   'charge'               => 'MyAccount/charge',        #?
37   'part_svc_info'        => 'MyAccount/part_svc_info',
38   'provision_acct'       => 'MyAccount/provision_acct',
39   'unprovision_svc'      => 'MyAccount/unprovision_svc',
40   'signup_info'          => 'Signup/signup_info',
41   'new_customer'         => 'Signup/new_customer',
42   'agent_login'          => 'Agent/agent_login',
43   'agent_logout'         => 'Agent/agent_logout',
44   'agent_info'           => 'Agent/agent_info',
45   'agent_list_customers' => 'Agent/agent_list_customers',
46 );
47 @EXPORT_OK = ( keys(%autoload), qw( regionselector expselect popselector ) );
48
49 $ENV{'PATH'} ='/usr/bin:/usr/ucb:/bin';
50 $ENV{'SHELL'} = '/bin/sh';
51 $ENV{'IFS'} = " \t\n";
52 $ENV{'CDPATH'} = '';
53 $ENV{'ENV'} = '';
54 $ENV{'BASH_ENV'} = '';
55
56 my $freeside_uid = scalar(getpwnam('freeside'));
57 die "not running as the freeside user\n" if $> != $freeside_uid;
58
59 foreach my $autoload ( keys %autoload ) {
60
61   my $eval =
62   "sub $autoload { ". '
63                    my $param;
64                    if ( ref($_[0]) ) {
65                      $param = shift;
66                    } else {
67                      $param = { @_ };
68                    }
69
70                    $param->{_packet} = \''. $autoload{$autoload}. '\';
71
72                    simple_packet($param);
73                  }';
74
75   eval $eval;
76   die $@ if $@;
77
78 }
79
80 sub simple_packet {
81   my $packet = shift;
82   socket(SOCK, PF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
83   connect(SOCK, sockaddr_un($socket)) or die "connect: $!";
84   nstore_fd($packet, \*SOCK) or die "can't send packet: $!";
85   SOCK->flush;
86
87   #shoudl trap: Magic number checking on storable file failed at blib/lib/Storable.pm (autosplit into blib/lib/auto/Storable/fd_retrieve.al) line 337, at /usr/local/share/perl/5.6.1/FS/SelfService.pm line 71
88
89   #block until there is a message on socket
90 #  my $w = new IO::Select;
91 #  $w->add(\*SOCK);
92 #  my @wait = $w->can_read;
93   my $return = fd_retrieve(\*SOCK) or die "error reading result: $!";
94   die $return->{'_error'} if defined $return->{_error} && $return->{_error};
95
96   $return;
97 }
98
99 =head1 NAME
100
101 FS::SelfService - Freeside self-service API
102
103 =head1 SYNOPSIS
104
105   # password and shell account changes
106   use FS::SelfService qw(passwd chfn chsh);
107
108   # "my account" functionality
109   use FS::SelfService qw( login customer_info invoice cancel payment_info process_payment );
110
111   my $rv = login( { 'username' => $username,
112                     'domain'   => $domain,
113                     'password' => $password,
114                   }
115                 );
116
117   if ( $rv->{'error'} ) {
118     #handle login error...
119   } else {
120     #successful login
121     my $session_id = $rv->{'session_id'};
122   }
123
124   my $customer_info = customer_info( { 'session_id' => $session_id } );
125
126   #payment_info and process_payment are available in 1.5+ only
127   my $payment_info = payment_info( { 'session_id' => $session_id } );
128
129   #!!! process_payment example
130
131   #!!! list_pkgs example
132
133   #!!! order_pkg example
134
135   #!!! cancel_pkg example
136
137   # signup functionality
138   use FS::SelfService qw( signup_info new_customer );
139
140   my $signup_info = signup_info;
141
142   $rv = new_customer( {
143                         'first'            => $first,
144                         'last'             => $last,
145                         'company'          => $company,
146                         'address1'         => $address1,
147                         'address2'         => $address2,
148                         'city'             => $city,
149                         'state'            => $state,
150                         'zip'              => $zip,
151                         'country'          => $country,
152                         'daytime'          => $daytime,
153                         'night'            => $night,
154                         'fax'              => $fax,
155                         'payby'            => $payby,
156                         'payinfo'          => $payinfo,
157                         'paycvv'           => $paycvv,
158                         'paydate'          => $paydate,
159                         'payname'          => $payname,
160                         'invoicing_list'   => $invoicing_list,
161                         'referral_custnum' => $referral_custnum,
162                         'pkgpart'          => $pkgpart,
163                         'username'         => $username,
164                         '_password'        => $password,
165                         'popnum'           => $popnum,
166                         'agentnum'         => $agentnum,
167                       }
168                     );
169   
170   my $error = $rv->{'error'};
171   if ( $error eq '_decline' ) {
172     print_decline();
173   } elsif ( $error ) {
174     reprint_signup();
175   } else {
176     print_success();
177   }
178
179 =head1 DESCRIPTION
180
181 Use this API to implement your own client "self-service" module.
182
183 If you just want to customize the look of the existing "self-service" module,
184 see XXXX instead.
185
186 =head1 PASSWORD, GECOS, SHELL CHANGING FUNCTIONS
187
188 =over 4
189
190 =item passwd
191
192 =item chfn
193
194 =item chsh
195
196 =back
197
198 =head1 "MY ACCOUNT" FUNCTIONS
199
200 =over 4
201
202 =item login HASHREF
203
204 Creates a user session.  Takes a hash reference as parameter with the
205 following keys:
206
207 =over 4
208
209 =item username
210
211 =item domain
212
213 =item password
214
215 =back
216
217 Returns a hash reference with the following keys:
218
219 =over 4
220
221 =item error
222
223 Empty on success, or an error message on errors.
224
225 =item session_id
226
227 Session identifier for successful logins
228
229 =back
230
231 =item customer_info HASHREF
232
233 Returns general customer information.
234
235 Takes a hash reference as parameter with a single key: B<session_id>
236
237 Returns a hash reference with the following keys:
238
239 =over 4
240
241 =item name
242
243 Customer name
244
245 =item balance
246
247 Balance owed
248
249 =item open
250
251 Array reference of hash references of open inoices.  Each hash reference has
252 the following keys: invnum, date, owed
253
254 =item small_custview
255
256 An HTML fragment containing shipping and billing addresses.
257
258 =item The following fields are also returned: first last company address1 address2 city county state zip country daytime night fax ship_first ship_last ship_company ship_address1 ship_address2 ship_city ship_state ship_zip ship_country ship_daytime ship_night ship_fax payby payinfo payname month year invoicing_list postal_invoicing
259
260 =back
261
262 =item edit_info HASHREF
263
264 Takes a hash reference as parameter with any of the following keys:
265
266 first last company address1 address2 city county state zip country daytime night fax ship_first ship_last ship_company ship_address1 ship_address2 ship_city ship_state ship_zip ship_country ship_daytime ship_night ship_fax payby payinfo paycvv payname month year invoicing_list postal_invoicing
267
268 If a field exists, the customer record is updated with the new value of that
269 field.  If a field does not exist, that field is not changed on the customer
270 record.
271
272 Returns a hash reference with a single key, B<error>, empty on success, or an
273 error message on errors
274
275 =item invoice HASHREF
276
277 Returns an invoice.  Takes a hash reference as parameter with two keys:
278 session_id and invnum
279
280 Returns a hash reference with the following keys:
281
282 =over 4
283
284 =item error
285
286 Empty on success, or an error message on errors
287
288 =item invnum
289
290 Invoice number
291
292 =item invoice_text
293
294 Invoice text
295
296 =back
297
298 =item list_invoices HASHREF
299
300 Returns a list of all customer invoices.  Takes a hash references with a single
301 key, session_id.
302
303 Returns a hash reference with the following keys:
304
305 =over 4
306
307 =item error
308
309 Empty on success, or an error message on errors
310
311 =item invoices
312
313 Reference to array of hash references with the following keys:
314
315 =over 4
316
317 =item invnum
318
319 Invoice ID
320
321 =item _date
322
323 Invoice date, in UNIX epoch time
324
325 =back
326
327 =back
328
329 =item cancel HASHREF
330
331 Cancels this customer.
332
333 Takes a hash reference as parameter with a single key: B<session_id>
334
335 Returns a hash reference with a single key, B<error>, which is empty on
336 success or an error message on errors.
337
338 =item payment_info HASHREF
339
340 Returns information that may be useful in displaying a payment page.
341
342 Takes a hash reference as parameter with a single key: B<session_id>.
343
344 Returns a hash reference with the following keys:
345
346 =over 4
347
348 =item error
349
350 Empty on success, or an error message on errors
351
352 =item balance
353
354 Balance owed
355
356 =item payname
357
358 Exact name on credit card (CARD/DCRD)
359
360 =item address1
361
362 =item address2
363
364 =item city
365
366 =item state
367
368 =item zip
369
370 =item payby
371
372 Customer's current default payment type.
373
374 =item card_type
375
376 For CARD/DCRD payment types, the card type (Visa card, MasterCard, Discover card, American Express card, etc.)
377
378 =item payinfo
379
380 For CARD/DCRD payment types, the card number
381
382 =item month
383
384 For CARD/DCRD payment types, expiration month
385
386 =item year
387
388 For CARD/DCRD payment types, expiration year
389
390 =item cust_main_county
391
392 County/state/country data - array reference of hash references, each of which has the fields of a cust_main_county record (see L<FS::cust_main_county>).  Note these are not FS::cust_main_county objects, but hash references of columns and values.
393
394 =item states
395
396 Array reference of all states in the current default country.
397
398 =item card_types
399
400 Hash reference of card types; keys are card types, values are the exact strings
401 passed to the process_payment function
402
403 =item paybatch
404
405 Unique transaction identifier (prevents multiple charges), passed to the
406 process_payment function
407
408 =back
409
410 =item process_payment HASHREF
411
412 Processes a payment and possible change of address or payment type.  Takes a
413 hash reference as parameter with the following keys:
414
415 =over 4
416
417 =item session_id
418
419 =item save
420
421 If true, address and card information entered will be saved for subsequent
422 transactions.
423
424 =item auto
425
426 If true, future credit card payments will be done automatically (sets payby to
427 CARD).  If false, future credit card payments will be done on-demand (sets
428 payby to DCRD).  This option only has meaning if B<save> is set true.  
429
430 =item payname
431
432 =item address1
433
434 =item address2
435
436 =item city
437
438 =item state
439
440 =item zip
441
442 =item payinfo
443
444 Card number
445
446 =item month
447
448 Card expiration month
449
450 =item year
451
452 Card expiration year
453
454 =item paybatch
455
456 Unique transaction identifier, returned from the payment_info function.
457 Prevents multiple charges.
458
459 =back
460
461 Returns a hash reference with a single key, B<error>, empty on success, or an
462 error message on errors
463
464 =item list_pkgs
465
466 Returns package information for this customer.
467
468 Takes a hash reference as parameter with a single key: B<session_id>
469
470 Returns a hash reference containing customer package information.  The hash reference contains the following keys:
471
472 =over 4
473
474
475 =item cust_pkg HASHREF
476
477 Array reference of hash references, each of which has the fields of a cust_pkg
478 record (see L<FS::cust_pkg>) as well as the fields below.  Note these are not
479 the internal FS:: objects, but hash references of columns and values.
480
481 =item all fields of part_pkg (XXXpare this down to a secure subset)
482
483 =item part_svc - An array of hash references, each of which has the following keys:
484
485 =over 4
486
487 =item all fields of part_svc (XXXpare this down to a secure subset)
488
489 =item avail
490
491 =back
492
493 =item error
494
495 Empty on success, or an error message on errors.
496
497 =back
498
499 =item order_pkg
500
501 Orders a package for this customer.
502
503 Takes a hash reference as parameter with the following keys:
504
505 =over 4
506
507 =item session_id
508
509 =item pkgpart
510
511 =item svcpart
512
513 optional svcpart, required only if the package definition does not contain
514 one svc_acct service definition with quantity 1 (it may contain others with
515 quantity >1)
516
517 =item username
518
519 =item _password
520
521 =item sec_phrase
522
523 =item popnum
524
525 =back
526
527 Returns a hash reference with a single key, B<error>, empty on success, or an
528 error message on errors.  The special error '_decline' is returned for
529 declined transactions.
530
531 =item cancel_pkg
532
533 Cancels a package for this customer.
534
535 Takes a hash reference as parameter with the following keys:
536
537 =over 4
538
539 =item session_id
540
541 =item pkgpart
542
543 =back
544
545 Returns a hash reference with a single key, B<error>, empty on success, or an
546 error message on errors.
547
548 =back
549
550 =head1 SIGNUP FUNCTIONS
551
552 =over 4
553
554 =item signup_info HASHREF
555
556 Takes a hash reference as parameter with the following keys:
557
558 =over 4
559
560 =item session_id - Optional agent/reseller interface session
561
562 =back
563
564 Returns a hash reference containing information that may be useful in
565 displaying a signup page.  The hash reference contains the following keys:
566
567 =over 4
568
569 =item cust_main_county
570
571 County/state/country data - array reference of hash references, each of which has the fields of a cust_main_county record (see L<FS::cust_main_county>).  Note these are not FS::cust_main_county objects, but hash references of columns and values.
572
573 =item part_pkg
574
575 Available packages - array reference of hash references, each of which has the fields of a part_pkg record (see L<FS::part_pkg>).  Each hash reference also has an additional 'payby' field containing an array reference of acceptable payment types specific to this package (see below and L<FS::part_pkg/payby>).  Note these are not FS::part_pkg objects, but hash references of columns and values.  Requires the 'signup_server-default_agentnum' configuration value to be set, or
576 an agentnum specified explicitly via reseller interface session_id in the
577 options.
578
579 =item agent
580
581 Array reference of hash references, each of which has the fields of an agent record (see L<FS::agent>).  Note these are not FS::agent objects, but hash references of columns and values.
582
583 =item agentnum2part_pkg
584
585 Hash reference; keys are agentnums, values are array references of available packages for that agent, in the same format as the part_pkg arrayref above.
586
587 =item svc_acct_pop
588
589 Access numbers - array reference of hash references, each of which has the fields of an svc_acct_pop record (see L<FS::svc_acct_pop>).  Note these are not FS::svc_acct_pop objects, but hash references of columns and values.
590
591 =item security_phrase
592
593 True if the "security_phrase" feature is enabled
594
595 =item payby
596
597 Array reference of acceptable payment types for signup
598
599 =over 4
600
601 =item CARD (credit card - automatic)
602
603 =item DCRD (credit card - on-demand - version 1.5+ only)
604
605 =item CHEK (electronic check - automatic)
606
607 =item DCHK (electronic check - on-demand - version 1.5+ only)
608
609 =item LECB (Phone bill billing)
610
611 =item BILL (billing, not recommended for signups)
612
613 =item COMP (free, definately not recommended for signups)
614
615 =item PREPAY (special billing type: applies a credit (see FS::prepay_credit) and sets billing type to BILL)
616
617 =back
618
619 =item cvv_enabled
620
621 True if CVV features are available (1.5+ or 1.4.2 with CVV schema patch)
622
623 =item msgcat
624
625 Hash reference of message catalog values, to support error message customization.  Currently available keys are: passwords_dont_match, invalid_card, unknown_card_type, and not_a (as in "Not a Discover card").  Values are configured in the web interface under "View/Edit message catalog".
626
627 =item statedefault
628
629 Default state
630
631 =item countrydefault
632
633 Default country
634
635 =back
636
637 =item new_customer HASHREF
638
639 Creates a new customer.  Takes a hash reference as parameter with the
640 following keys:
641
642 =over 4
643
644 =item first - first name (required)
645
646 =item last - last name (required)
647
648 =item ss (not typically collected; mostly used for ACH transactions)
649
650 =item company
651
652 =item address1 (required)
653
654 =item address2
655
656 =item city (required)
657
658 =item county
659
660 =item state (required)
661
662 =item zip (required)
663
664 =item daytime - phone
665
666 =item night - phone
667
668 =item fax - phone
669
670 =item payby - CARD, DCRD, CHEK, DCHK, LECB, BILL, COMP or PREPAY (see L</signup_info> (required)
671
672 =item payinfo - Card number for CARD/DCRD, account_number@aba_number for CHEK/DCHK, prepaid "pin" for PREPAY, purchase order number for BILL
673
674 =item paycvv - Credit card CVV2 number (1.5+ or 1.4.2 with CVV schema patch)
675
676 =item paydate - Expiration date for CARD/DCRD
677
678 =item payname - Exact name on credit card for CARD/DCRD, bank name for CHEK/DCHK
679
680 =item invoicing_list - comma-separated list of email addresses for email invoices.  The special value 'POST' is used to designate postal invoicing (it may be specified alone or in addition to email addresses),
681
682 =item referral_custnum - referring customer number
683
684 =item pkgpart - pkgpart of initial package
685
686 =item username
687
688 =item _password
689
690 =item sec_phrase - security phrase
691
692 =item popnum - access number (index, not the literal number)
693
694 =item agentnum - agent number
695
696 =back
697
698 Returns a hash reference with the following keys:
699
700 =over 4
701
702 =item error Empty on success, or an error message on errors.  The special error '_decline' is returned for declined transactions; other error messages should be suitable for display to the user (and are customizable in under Sysadmin | View/Edit message catalog)
703
704 =back
705
706 =item regionselector HASHREF | LIST
707
708 Takes as input a hashref or list of key/value pairs with the following keys:
709
710 =over 4
711
712 =item selected_county
713
714 =item selected_state
715
716 =item selected_country
717
718 =item prefix - Specify a unique prefix string  if you intend to use the HTML output multiple time son one page.
719
720 =item onchange - Specify a javascript subroutine to call on changes
721
722 =item default_state
723
724 =item default_country
725
726 =item locales - An arrayref of hash references specifying regions.  Normally you can just pass the value of the I<cust_main_county> field returned by B<signup_info>.
727
728 =back
729
730 Returns a list consisting of three HTML fragments for county selection,
731 state selection and country selection, respectively.
732
733 =cut
734
735 #false laziness w/FS::cust_main_county (this is currently the "newest" version)
736 sub regionselector {
737   my $param;
738   if ( ref($_[0]) ) {
739     $param = shift;
740   } else {
741     $param = { @_ };
742   }
743   $param->{'selected_country'} ||= $param->{'default_country'};
744   $param->{'selected_state'} ||= $param->{'default_state'};
745
746   my $prefix = exists($param->{'prefix'}) ? $param->{'prefix'} : '';
747
748   my $countyflag = 0;
749
750   my %cust_main_county;
751
752 #  unless ( @cust_main_county ) { #cache 
753     #@cust_main_county = qsearch('cust_main_county', {} );
754     #foreach my $c ( @cust_main_county ) {
755     foreach my $c ( @{ $param->{'locales'} } ) {
756       #$countyflag=1 if $c->county;
757       $countyflag=1 if $c->{county};
758       #push @{$cust_main_county{$c->country}{$c->state}}, $c->county;
759       #$cust_main_county{$c->country}{$c->state}{$c->county} = 1;
760       $cust_main_county{$c->{country}}{$c->{state}}{$c->{county}} = 1;
761     }
762 #  }
763   $countyflag=1 if $param->{selected_county};
764
765   my $script_html = <<END;
766     <SCRIPT>
767     function opt(what,value,text) {
768       var optionName = new Option(text, value, false, false);
769       var length = what.length;
770       what.options[length] = optionName;
771     }
772     function ${prefix}country_changed(what) {
773       country = what.options[what.selectedIndex].text;
774       for ( var i = what.form.${prefix}state.length; i >= 0; i-- )
775           what.form.${prefix}state.options[i] = null;
776 END
777       #what.form.${prefix}state.options[0] = new Option('', '', false, true);
778
779   foreach my $country ( sort keys %cust_main_county ) {
780     $script_html .= "\nif ( country == \"$country\" ) {\n";
781     foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
782       my $text = $state || '(n/a)';
783       $script_html .= qq!opt(what.form.${prefix}state, "$state", "$text");\n!;
784     }
785     $script_html .= "}\n";
786   }
787
788   $script_html .= <<END;
789     }
790     function ${prefix}state_changed(what) {
791 END
792
793   if ( $countyflag ) {
794     $script_html .= <<END;
795       state = what.options[what.selectedIndex].text;
796       country = what.form.${prefix}country.options[what.form.${prefix}country.selectedIndex].text;
797       for ( var i = what.form.${prefix}county.length; i >= 0; i-- )
798           what.form.${prefix}county.options[i] = null;
799 END
800
801     foreach my $country ( sort keys %cust_main_county ) {
802       $script_html .= "\nif ( country == \"$country\" ) {\n";
803       foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
804         $script_html .= "\nif ( state == \"$state\" ) {\n";
805           #foreach my $county ( sort @{$cust_main_county{$country}{$state}} ) {
806           foreach my $county ( sort keys %{$cust_main_county{$country}{$state}} ) {
807             my $text = $county || '(n/a)';
808             $script_html .=
809               qq!opt(what.form.${prefix}county, "$county", "$text");\n!;
810           }
811         $script_html .= "}\n";
812       }
813       $script_html .= "}\n";
814     }
815   }
816
817   $script_html .= <<END;
818     }
819     </SCRIPT>
820 END
821
822   my $county_html = $script_html;
823   if ( $countyflag ) {
824     $county_html .= qq!<SELECT NAME="${prefix}county" onChange="$param->{'onchange'}">!;
825     $county_html .= '</SELECT>';
826   } else {
827     $county_html .=
828       qq!<INPUT TYPE="hidden" NAME="${prefix}county" VALUE="$param->{'selected_county'}">!;
829   }
830
831   my $state_html = qq!<SELECT NAME="${prefix}state" !.
832                    qq!onChange="${prefix}state_changed(this); $param->{'onchange'}">!;
833   foreach my $state ( sort keys %{ $cust_main_county{$param->{'selected_country'}} } ) {
834     my $text = $state || '(n/a)';
835     my $selected = $state eq $param->{'selected_state'} ? 'SELECTED' : '';
836     $state_html .= "\n<OPTION $selected VALUE=$state>$text</OPTION>"
837   }
838   $state_html .= '</SELECT>';
839
840   $state_html .= '</SELECT>';
841
842   my $country_html = qq!<SELECT NAME="${prefix}country" !.
843                      qq!onChange="${prefix}country_changed(this); $param->{'onchange'}">!;
844   my $countrydefault = $param->{default_country} || 'US';
845   foreach my $country (
846     sort { ($b eq $countrydefault) <=> ($a eq $countrydefault) or $a cmp $b }
847       keys %cust_main_county
848   ) {
849     my $selected = $country eq $param->{'selected_country'} ? ' SELECTED' : '';
850     $country_html .= "\n<OPTION$selected>$country</OPTION>"
851   }
852   $country_html .= '</SELECT>';
853
854   ($county_html, $state_html, $country_html);
855
856 }
857
858 #=item expselect HASHREF | LIST
859 #
860 #Takes as input a hashref or list of key/value pairs with the following keys:
861 #
862 #=over 4
863 #
864 #=item prefix - Specify a unique prefix string  if you intend to use the HTML output multiple time son one page.
865 #
866 #=item date - current date, in yyyy-mm-dd or m-d-yyyy format
867 #
868 #=back
869
870 =item expselect PREFIX [ DATE ]
871
872 Takes as input a unique prefix string and the current expiration date, in
873 yyyy-mm-dd or m-d-yyyy format
874
875 Returns an HTML fragments for expiration date selection.
876
877 =cut
878
879 sub expselect {
880   #my $param;
881   #if ( ref($_[0]) ) {
882   #  $param = shift;
883   #} else {
884   #  $param = { @_ };
885   #my $prefix = $param->{'prefix'};
886   #my $prefix = exists($param->{'prefix'}) ? $param->{'prefix'} : '';
887   #my $date =   exists($param->{'date'})   ? $param->{'date'}   : '';
888   my $prefix = shift;
889   my $date = scalar(@_) ? shift : '';
890
891   my( $m, $y ) = ( 0, 0 );
892   if ( $date  =~ /^(\d{4})-(\d{2})-\d{2}$/ ) { #PostgreSQL date format
893     ( $m, $y ) = ( $2, $1 );
894   } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
895     ( $m, $y ) = ( $1, $3 );
896   }
897   my $return = qq!<SELECT NAME="$prefix!. qq!_month" SIZE="1">!;
898   for ( 1 .. 12 ) {
899     $return .= "<OPTION";
900     $return .= " SELECTED" if $_ == $m;
901     $return .= ">$_";
902   }
903   $return .= qq!</SELECT>/<SELECT NAME="$prefix!. qq!_year" SIZE="1">!;
904   my @t = localtime;
905   my $thisYear = $t[5] + 1900;
906   for ( ($thisYear > $y && $y > 0 ? $y : $thisYear) .. 2037 ) {
907     $return .= "<OPTION";
908     $return .= " SELECTED" if $_ == $y;
909     $return .= ">$_";
910   }
911   $return .= "</SELECT>";
912
913   $return;
914 }
915
916 =item popselector HASHREF | LIST
917
918 Takes as input a hashref or list of key/value pairs with the following keys:
919
920 =over 4
921
922 =item popnum
923
924 =item pops - An arrayref of hash references specifying access numbers.  Normally you can just pass the value of the I<svc_acct_pop> field returned by B<signup_info>.
925
926 =back
927
928 Returns an HTML fragment for access number selection.
929
930 =cut
931
932 #horrible false laziness with FS/FS/svc_acct_pop.pm::popselector
933 sub popselector {
934   my $param;
935   if ( ref($_[0]) ) {
936     $param = shift;
937   } else {
938     $param = { @_ };
939   }
940   my $popnum = $param->{'popnum'};
941   my $pops = $param->{'pops'};
942
943   return '<INPUT TYPE="hidden" NAME="popnum" VALUE="">' unless @$pops;
944   return $pops->[0]{city}. ', '. $pops->[0]{state}.
945          ' ('. $pops->[0]{ac}. ')/'. $pops->[0]{exch}. '-'. $pops->[0]{loc}.
946          '<INPUT TYPE="hidden" NAME="popnum" VALUE="'. $pops->[0]{popnum}. '">'
947     if scalar(@$pops) == 1;
948
949   my %pop = ();
950   my %popnum2pop = ();
951   foreach (@$pops) {
952     push @{ $pop{ $_->{state} }->{ $_->{ac} } }, $_;
953     $popnum2pop{$_->{popnum}} = $_;
954   }
955
956   my $text = <<END;
957     <SCRIPT>
958     function opt(what,href,text) {
959       var optionName = new Option(text, href, false, false)
960       var length = what.length;
961       what.options[length] = optionName;
962     }
963 END
964
965   my $init_popstate = $param->{'init_popstate'};
966   if ( $init_popstate ) {
967     $text .= '<INPUT TYPE="hidden" NAME="init_popstate" VALUE="'.
968              $init_popstate. '">';
969   } else {
970     $text .= <<END;
971       function acstate_changed(what) {
972         state = what.options[what.selectedIndex].text;
973         what.form.popac.options.length = 0
974         what.form.popac.options[0] = new Option("Area code", "-1", false, true);
975 END
976   } 
977
978   my @states = $init_popstate ? ( $init_popstate ) : keys %pop;
979   foreach my $state ( sort { $a cmp $b } @states ) {
980     $text .= "\nif ( state == \"$state\" ) {\n" unless $init_popstate;
981
982     foreach my $ac ( sort { $a cmp $b } keys %{ $pop{$state} }) {
983       $text .= "opt(what.form.popac, \"$ac\", \"$ac\");\n";
984       if ($ac eq $param->{'popac'}) {
985         $text .= "what.form.popac.options[what.form.popac.length-1].selected = true;\n";
986       }
987     }
988     $text .= "}\n" unless $init_popstate;
989   }
990   $text .= "popac_changed(what.form.popac)}\n";
991
992   $text .= <<END;
993   function popac_changed(what) {
994     ac = what.options[what.selectedIndex].text;
995     what.form.popnum.options.length = 0;
996     what.form.popnum.options[0] = new Option("City", "-1", false, true);
997
998 END
999
1000   foreach my $state ( @states ) {
1001     foreach my $popac ( keys %{ $pop{$state} } ) {
1002       $text .= "\nif ( ac == \"$popac\" ) {\n";
1003
1004       foreach my $pop ( @{$pop{$state}->{$popac}}) {
1005         my $o_popnum = $pop->{popnum};
1006         my $poptext =  $pop->{city}. ', '. $pop->{state}.
1007                        ' ('. $pop->{ac}. ')/'. $pop->{exch}. '-'. $pop->{loc};
1008
1009         $text .= "opt(what.form.popnum, \"$o_popnum\", \"$poptext\");\n";
1010         if ($popnum == $o_popnum) {
1011           $text .= "what.form.popnum.options[what.form.popnum.length-1].selected = true;\n";
1012         }
1013       }
1014       $text .= "}\n";
1015     }
1016   }
1017
1018
1019   $text .= "}\n</SCRIPT>\n";
1020
1021   $text .=
1022     qq!<TABLE CELLPADDING="0"><TR><TD><SELECT NAME="acstate"! .
1023     qq!SIZE=1 onChange="acstate_changed(this)"><OPTION VALUE=-1>State!;
1024   $text .= "<OPTION" . ($_ eq $param->{'acstate'} ? " SELECTED" : "") .
1025            ">$_" foreach sort { $a cmp $b } @states;
1026   $text .= '</SELECT>'; #callback? return 3 html pieces?  #'</TD>';
1027
1028   $text .=
1029     qq!<SELECT NAME="popac" SIZE=1 onChange="popac_changed(this)">!.
1030     qq!<OPTION>Area code</SELECT></TR><TR VALIGN="top">!;
1031
1032   $text .= qq!<TR><TD><SELECT NAME="popnum" SIZE=1 STYLE="width: 20em"><OPTION>City!;
1033
1034
1035   #comment this block to disable initial list polulation
1036   my @initial_select = ();
1037   if ( scalar( @$pops ) > 100 ) {
1038     push @initial_select, $popnum2pop{$popnum} if $popnum2pop{$popnum};
1039   } else {
1040     @initial_select = @$pops;
1041   }
1042   foreach my $pop ( sort { $a->{state} cmp $b->{state} } @initial_select ) {
1043     $text .= qq!<OPTION VALUE="!. $pop->{popnum}. '"'.
1044              ( ( $popnum && $pop->{popnum} == $popnum ) ? ' SELECTED' : '' ). ">".
1045              $pop->{city}. ', '. $pop->{state}.
1046                ' ('. $pop->{ac}. ')/'. $pop->{exch}. '-'. $pop->{loc};
1047   }
1048
1049   $text .= qq!</SELECT></TD></TR></TABLE>!;
1050
1051   $text;
1052
1053 }
1054
1055 =back
1056
1057 =head1 RESELLER FUNCTIONS
1058
1059 Note: Resellers can also use the B<signup_info> and B<new_customer> functions
1060 with their active session, and the B<customer_info> and B<order_pkg> functions
1061 with their active session and an additonal I<custnum> parameter.
1062
1063 =over 4
1064
1065 =item agent_login
1066
1067 =item agent_info
1068
1069 =item agent_list_customers
1070
1071 =back
1072
1073 =head1 BUGS
1074
1075 =head1 SEE ALSO
1076
1077 L<freeside-selfservice-clientd>, L<freeside-selfservice-server>
1078
1079 =cut
1080
1081 1;
1082