738f7e1971c71365a1c50e350283c1887277ba7f
[freeside.git] / FS / FS / ClientAPI / MyAccount.pm
1 package FS::ClientAPI::MyAccount;
2
3 use 5.008; #require 5.8+ for Time::Local 1.05+
4 use strict;
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
7 use IO::Scalar;
8 use Data::Dumper;
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
11 use Date::Format;
12 use Time::Duration;
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard;
15 use HTML::Entities;
16 use Text::CSV_XS;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
20 use FS::UI::Web;
21 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Conf;
23 #use FS::UID qw(dbh);
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
28 use FS::TicketSystem;
29 use FS::ClientAPI_SessionCache;
30 use FS::cust_svc;
31 use FS::svc_acct;
32 use FS::svc_forward;
33 use FS::svc_domain;
34 use FS::svc_phone;
35 use FS::svc_external;
36 use FS::svc_dsl;
37 use FS::dsl_device;
38 use FS::part_svc;
39 use FS::cust_main;
40 use FS::cust_bill;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
43 use FS::part_pkg;
44 use FS::cust_pkg;
45 use FS::payby;
46 use FS::acct_rt_transaction;
47 use FS::msg_template;
48 use FS::contact;
49 use FS::cust_location;
50
51 use FS::ClientAPI::MyAccount::quotation; # just for code organization
52
53 $DEBUG = 0;
54 $me = '[FS::ClientAPI::MyAccount]';
55
56 use vars qw( @cust_main_editable_fields @location_editable_fields );
57 @cust_main_editable_fields = qw(
58   first last company daytime night fax mobile
59   locale
60   payby payinfo payname paystart_month paystart_year payissue payip
61   ss paytype paystate stateid stateid_state
62 );
63 @location_editable_fields = qw(
64   address1 address2 city county state zip country
65 );
66
67
68 BEGIN { #preload to reduce time customer_info takes
69   if ( $FS::TicketSystem::system ) {
70     warn "$me: initializing ticket system\n" if $DEBUG;
71     FS::TicketSystem->init();
72   }
73 }
74
75 sub _cache {
76   $cache ||= new FS::ClientAPI_SessionCache( {
77                'namespace' => 'FS::ClientAPI::MyAccount',
78              } );
79 }
80
81 sub skin_info {
82   my $p = shift;
83
84   my($context, $session, $custnum) = _custoragent_session_custnum($p);
85   #return { 'error' => $session } if $context eq 'error';
86
87   my $agentnum = '';
88   if ( $context eq 'customer' ) {
89
90     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
91       or die dbh->errstr;
92
93     $sth->execute($custnum) or die $sth->errstr;
94
95     $agentnum = $sth->fetchrow_arrayref->[0]
96       or die "no agentnum for custnum $custnum";
97
98   #} elsif ( $context eq 'agent' ) {
99   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
100     $agentnum = $1;
101   }
102   $p->{'agentnum'} = $agentnum;
103
104   my $conf = new FS::Conf;
105
106   #false laziness w/Signup.pm
107
108   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
109
110   if ( $skin_info_cache_agent ) {
111
112     warn "$me loading cached skin info for agentnum $agentnum\n"
113       if $DEBUG > 1;
114
115   } else {
116
117     warn "$me populating skin info cache for agentnum $agentnum\n"
118       if $DEBUG > 1;
119
120     $skin_info_cache_agent = {
121       'agentnum' => $agentnum,
122       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
123         qw( company_name date_format ) ),
124       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
125         qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
126             text_color link_color vlink_color hlink_color alink_color
127             font title_color title_align title_size menu_bgcolor menu_fontsize
128           )
129       ),
130       'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
131       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
132         qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
133       ),
134       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
135         qw( title_left_image title_right_image
136             menu_top_image menu_body_image menu_bottom_image
137           )
138       ),
139       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
140       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
141         qw( head body_header body_footer company_address ) ),
142       'money_char' => $conf->config("money_char") || '$',
143       'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
144                 'main.php Home
145
146                  services.php Services
147                  services.php My Services
148                  services_new.php Order a new service
149
150                  personal.php Profile
151                  personal.php Personal Information
152                  password.php Change Password
153
154                  payment.php Payments
155                  payment_cc.php Credit Card Payment
156                  payment_ach.php Electronic Check Payment
157                  payment_paypal.php PayPal Payment
158                  payment_webpay.php Webpay Payments
159
160                  usage.php Usage
161                  usage_data.php Data usage
162                  usage_cdr.php Call usage
163
164                  tickets.php Help Desk
165                  tickets.php Open Tickets
166                  tickets_resolved.php Resolved Tickets
167                  ticket_create.php Create a new ticket
168
169                  docs.php FAQs
170
171                  logout.php Logout
172                 ',
173     };
174
175     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
176
177   }
178
179   #{ %$skin_info_cache_agent };
180   $skin_info_cache_agent;
181
182 }
183
184 sub login_info {
185   my $p = shift;
186
187   my $conf = new FS::Conf;
188
189   my %info = (
190     %{ skin_info($p) },
191     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
192     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
193     'banner_url'       => scalar($conf->config('selfservice-login_banner_url')),
194     'banner_image_md5' => 
195       md5_hex($conf->config_binary('selfservice-login_banner_image')),
196   );
197
198   return \%info;
199
200 }
201
202 sub login_banner_image {
203   my $p = shift;
204   my $conf = new FS::Conf;
205   my $image = $conf->config_binary('selfservice-login_banner_image');
206   return { 
207     'md5'   => md5_hex($image),
208     'image' => $image,
209   };
210 }
211
212 #false laziness w/FS::ClientAPI::passwd::passwd
213 sub login {
214   my $p = shift;
215
216   my $conf = new FS::Conf;
217
218   my $svc_x = '';
219   my $session = {};
220   if ( $p->{'domain'} eq 'svc_phone'
221        && $conf->exists('selfservice_server-phone_login') ) { 
222
223     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
224     return { error => 'Number not found.' } unless $svc_phone;
225
226     #XXX?
227     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
228     #return { error => 'Only primary user may log in.' } 
229     #  if $conf->exists('selfservice_server-primary_only')
230     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
231
232     return { error => 'Incorrect PIN.' }
233       unless $svc_phone->check_pin($p->{'password'});
234
235     $svc_x = $svc_phone;
236
237   } elsif ( $p->{email}
238               && (my $contact = FS::contact->by_selfservice_email($p->{email}))
239           )
240   {
241     return { error => 'Incorrect contact password.' }
242       unless $contact->authenticate_password($p->{'password'});
243
244     $session->{'custnum'} = $contact->custnum;
245
246   } else {
247
248     ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
249
250     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
251       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
252
253     my @svc_acct = qsearch( 'svc_acct', { 'username'  => $p->{'username'},
254                                           'domsvc'    => $svc_domain->svcnum, }
255                           );
256
257     if ( $conf->exists('selfservice_server-login_svcpart') ) {
258       my @svcpart = $conf->config('selfservice_server-login_svcpart');
259       @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
260                          scalar( grep( $_ eq $svcpart, @svcpart ) );
261                        }
262                     @svc_acct;
263     }
264
265     if ( $conf->exists('selfservice_server-primary_only') ) {
266         @svc_acct =
267           grep {
268             my $cust_svc = $_->cust_svc;
269             $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
270               == $cust_svc->svcpart
271           }
272           @svc_acct;
273     }
274
275     return { error => 'User not found.' } unless @svc_acct;
276
277     #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
278
279     my $svc_acct = $svc_acct[0];
280
281     if ( $conf->exists('selfservice_server-login_svcpart') ) {
282       my @svcpart = $conf->config('selfservice_server-login_svcpart');
283       my $svcpart = $svc_acct->cust_svc->svcpart;
284       return { error => 'Invalid user.' } 
285         unless grep($_ eq $svcpart, @svcpart);
286     }
287
288     return { error => 'Incorrect password.' }
289       unless $svc_acct->check_password($p->{'password'});
290
291     $svc_x = $svc_acct;
292
293   }
294
295   if ( $svc_x ) {
296
297     $session->{'svcnum'} = $svc_x->svcnum;
298
299     my $cust_svc = $svc_x->cust_svc;
300     my $cust_pkg = $cust_svc->cust_pkg;
301     if ( $cust_pkg ) {
302       my $cust_main = $cust_pkg->cust_main;
303       $session->{'custnum'} = $cust_main->custnum;
304       if ( $conf->exists('pkg-balances') ) {
305         my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
306                             $cust_main->ncancelled_pkgs;
307         $session->{'pkgnum'} = $cust_pkg->pkgnum
308           if scalar(@cust_pkg) > 1;
309       }
310     }
311
312     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
313     #return { error => 'Only primary user may log in.' } 
314     #  if $conf->exists('selfservice_server-primary_only')
315     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
316     my $part_pkg = $cust_pkg->part_pkg;
317     return { error => 'Only primary user may log in.' }
318       if $conf->exists('selfservice_server-primary_only')
319          && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
320
321   }
322
323   my $session_id;
324   do {
325     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
326   } until ( ! defined _cache->get($session_id) ); #just in case
327
328   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
329   _cache->set( $session_id, $session, $timeout );
330
331   return { 'error'      => '',
332            'session_id' => $session_id,
333          };
334 }
335
336 sub logout {
337   my $p = shift;
338   my $skin_info = skin_info($p);
339   if ( $p->{'session_id'} ) {
340     _cache->remove($p->{'session_id'});
341     return { %$skin_info, 'error' => '' };
342   } else {
343     return { %$skin_info, 'error' => "Can't resume session" }; #better error message
344   }
345 }
346
347 sub switch_acct {
348   my $p = shift;
349
350   my($context, $session, $custnum) = _custoragent_session_custnum($p);
351   return { 'error' => $session } if $context eq 'error';
352
353   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
354     or return { 'error' => "Service not found" };
355
356   $session->{'svcnum'} = $svc_acct->svcnum;
357
358   my $conf = new FS::Conf;
359   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
360   _cache->set( $p->{'session_id'}, $session, $timeout );
361
362   return { 'error' => '' };
363
364 }
365
366 sub payment_gateway {
367   # internal use only
368   # takes a cust_main and a cust_payby entry, returns the payment_gateway
369   my $conf = new FS::Conf;
370   my $cust_main = shift;
371   my $cust_payby = shift;
372   my $gatewaynum = $conf->config('selfservice-payment_gateway');
373   if ( $gatewaynum ) {
374     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
375     die "configured gatewaynum $gatewaynum not found!" if !$pg;
376     return $pg;
377   }
378   else {
379     return '' if ! FS::payby->realtime($cust_payby);
380     my $pg = $cust_main->agent->payment_gateway(
381       'method'  => FS::payby->payby2bop($cust_payby),
382       'nofatal' => 1
383     );
384     return $pg;
385   }
386 }
387
388 sub access_info {
389   my $p = shift;
390
391   my $conf = new FS::Conf;
392
393   my $info = skin_info($p);
394
395   use vars qw( $cust_paybys ); #cache for performance
396   unless ( $cust_paybys ) {
397
398     my %cust_paybys = map { $_ => 1 }
399                       map { FS::payby->payby2payment($_) }
400                           $conf->config('signup_server-payby');
401
402     $cust_paybys = [ keys %cust_paybys ];
403
404   }
405   $info->{'cust_paybys'} = $cust_paybys;
406
407   my($context, $session, $custnum) = _custoragent_session_custnum($p);
408   return { 'error' => $session } if $context eq 'error';
409
410   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
411     or return { 'error' => "unknown custnum $custnum" };
412
413   $info->{'hide_payment_fields'} = [ 
414     map { 
415       my $pg = payment_gateway($cust_main, $_);
416       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
417     } @{ $info->{cust_paybys} }
418   ];
419
420   $info->{'self_suspend_reason'} = 
421       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
422
423   $info->{'edit_ticket_subject'} =
424       $conf->exists('ticket_system-selfservice_edit_subject') && 
425       $cust_main->edit_subject;
426
427   $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
428
429   $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
430
431   return { %$info,
432            'custnum'       => $custnum,
433            'access_pkgnum' => $session->{'pkgnum'},
434            'access_svcnum' => $session->{'svcnum'},
435          };
436 }
437
438 sub customer_info {
439   my $p = shift;
440
441   my($context, $session, $custnum) = _custoragent_session_custnum($p);
442   return { 'error' => $session } if $context eq 'error';
443
444   my %return;
445
446   my $conf = new FS::Conf;
447   $return{'require_address2'} = $conf->exists('cust_main-require_address2');
448
449 #  if ( $FS::TicketSystem::system ) {
450 #    warn "$me customer_info: initializing ticket system\n" if $DEBUG;
451 #    FS::TicketSystem->init();
452 #  }
453  
454   if ( $custnum ) { #customer record
455
456     %return = ( %return, %{ customer_info_short($p) } );
457
458     #redundant with customer_info_short, but we need it for several things below
459     my $search = { 'custnum' => $custnum };
460     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
461     my $cust_main = qsearchs('cust_main', $search )
462       or return { 'error' => "unknown custnum $custnum" };
463
464     my $list_tickets = list_tickets($p);
465     $return{'tickets'} = $list_tickets->{'tickets'};
466
467     if ( $session->{'pkgnum'} ) {
468       #XXX open invoices in the pkg-balances case
469     } else {
470       $return{'money_char'} = $conf->config("money_char") || '$';
471       my @open = map {
472                        {
473                          invnum     => $_->invnum,
474                          date       => time2str("%b %o, %Y", $_->_date),
475                          owed       => $_->owed,
476                          charged    => $_->charged,
477                        };
478                      } $cust_main->open_cust_bill;
479       $return{open_invoices} = \@open;
480
481       my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
482       my $sth = dbh->prepare($sql) or die  dbh->errstr;
483       $sth->execute($custnum)      or die $sth->errstr;
484       $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
485       $return{'last_invoice_date_pretty'} =
486         time2str('%m/%d/%Y', $return{'last_invoice_date'} );
487     }
488
489     #customer_info_short always has nobalance on..
490     $return{small_custview} =
491       small_custview( $cust_main,
492                       $return{countrydefault},
493                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
494                     );
495
496     $return{has_ship_address} = $cust_main->has_ship_address;
497     $return{status} = $cust_main->status;
498     $return{statuscolor} = $cust_main->statuscolor;
499
500     # compatibility: some places in selfservice use this to determine
501     # if there's a ship address
502     if ( $return{has_ship_address} ) {
503       $return{ship_last}  = $cust_main->last;
504       $return{ship_first} = $cust_main->first;
505     }
506
507     if (scalar($conf->config('support_packages'))) {
508       my @support_services = ();
509       foreach ($cust_main->support_services) {
510         my $seconds = $_->svc_x->seconds || 0;
511         my $time_remaining = (($seconds < 0) ? '-' : '' ).
512                              int(abs($seconds)/3600)."h".
513                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
514         my $cust_pkg = $_->cust_pkg;
515         my $pkgnum = '';
516         my $pkg = '';
517         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
518         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
519         push @support_services, { svcnum => $_->svcnum,
520                                   time => $time_remaining,
521                                   pkgnum => $pkgnum,
522                                   pkg => $pkg,
523                                 };
524       }
525       $return{support_services} = \@support_services;
526     }
527
528     if ( $conf->config('prepayment_discounts-credit_type') ) {
529       #need to eval?
530       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
531     }
532
533   } elsif ( $session->{'svcnum'} ) { #no customer record
534
535     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
536       or die "unknown svcnum";
537     $return{name} = $svc_acct->email;
538
539   } else {
540
541     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
542
543   }
544
545   return { 'error'   => '',
546            'custnum' => $custnum,
547            %return,
548          };
549
550 }
551
552 sub customer_info_short {
553   my $p = shift;
554
555   my($context, $session, $custnum) = _custoragent_session_custnum($p);
556   return { 'error' => $session } if $context eq 'error';
557
558   my %return;
559
560   my $conf = new FS::Conf;
561
562   if ( $custnum ) { #customer record
563
564     my $search = { 'custnum' => $custnum };
565     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
566     my $cust_main = qsearchs('cust_main', $search )
567       or return { 'error' => "unknown custnum $custnum" };
568
569     $return{display_custnum} = $cust_main->display_custnum;
570
571     if ( $session->{'pkgnum'} ) { 
572       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
573       #next_bill_date from cust_pkg?
574     } else {
575       $return{balance} = $cust_main->balance;
576       $return{next_bill_date} = $cust_main->next_bill_date;
577       $return{next_bill_date_pretty} =
578         $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
579                                 : '(none)';
580     }
581     $return{balance_pretty} = money_pretty($return{balance});
582
583     $return{countrydefault} = scalar($conf->config('countrydefault'));
584
585     $return{small_custview} =
586       small_custview( $cust_main,
587                       $return{countrydefault},
588                       1, ##nobalance
589                     );
590
591     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
592
593     $return{payby} = $cust_main->payby;
594
595     #none of these are terribly expensive if we want 'em...
596     for (@cust_main_editable_fields) {
597       $return{$_} = $cust_main->get($_);
598     }
599     #maybe a little more expensive, but it should be cached by now
600     for (@location_editable_fields) {
601       $return{$_} = $cust_main->bill_location->get($_);
602       $return{'ship_'.$_} = $cust_main->ship_location->get($_);
603     }
604  
605     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
606       $return{payinfo} = $cust_main->paymask;
607       @return{'month', 'year'} = $cust_main->paydate_monthyear;
608     }
609     
610     my @invoicing_list = $cust_main->invoicing_list;
611     $return{'invoicing_list'} =
612       join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
613     $return{'postal_invoicing'} =
614       0 < ( grep { $_ eq 'POST' } @invoicing_list );
615
616     if ( $session->{'svcnum'} ) {
617       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
618       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
619       $return{'svcnum'} = $session->{'svcnum'};
620     }
621
622   } elsif ( $session->{'svcnum'} ) { #no customer record
623
624     #uuh, not supproted yet... die?
625     return { 'error' => 'customer_info_short not yet supported as agent' };
626
627   } else {
628
629     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
630
631   }
632
633   return { 'error'          => '',
634            'custnum'        => $custnum,
635            %return,
636          };
637 }
638
639 sub billing_history {
640   my $p = shift;
641
642   my($context, $session, $custnum) = _custoragent_session_custnum($p);
643   return { 'error' => $session } if $context eq 'error';
644
645   return { 'error' => 'No customer' } unless $custnum;
646
647   my $search = { 'custnum' => $custnum };
648   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
649   my $cust_main = qsearchs('cust_main', $search )
650     or return { 'error' => "unknown custnum $custnum" };
651
652   my %return = ();
653
654   if ( $session->{'pkgnum'} ) { 
655     #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
656     #next_bill_date from cust_pkg?
657     return { 'error' => 'No history for package' };
658   }
659
660   $return{balance} = $cust_main->balance;
661   $return{balance_pretty} = money_pretty($return{balance});
662   $return{next_bill_date} = $cust_main->next_bill_date;
663   $return{next_bill_date_pretty} =
664     $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
665                             : '(none)';
666
667   my $conf = new FS::Conf;
668
669   $return{'history'} = [
670     $cust_main->payment_history(
671       'line_items' => $conf->exists('selfservice-billing_history-line_items'),
672       'reverse_sort' => 1,
673     )
674   ];
675
676   $return{'money_char'} = $conf->config("money_char") || '$',
677
678   return \%return;
679
680 }
681
682 sub edit_info {
683   my $p = shift;
684   my $session = _cache->get($p->{'session_id'})
685     or return { 'error' => "Can't resume session" }; #better error message
686
687   my $custnum = $session->{'custnum'}
688     or return { 'error' => "no customer record" };
689
690   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
691     or return { 'error' => "unknown custnum $custnum" };
692
693   my $new = new FS::cust_main { $cust_main->hash };
694
695   $new->set( $_ => $p->{$_} )
696     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
697
698   if ( exists($p->{address1}) ) {
699     my $bill_location = FS::cust_location->new({
700         map { $_ => $p->{$_} } @location_editable_fields
701     });
702     # if this is unchanged from before, cust_main::replace will ignore it
703     $new->set('bill_location' => $bill_location);
704   }
705
706   if ( exists($p->{ship_address1}) ) {
707     my $ship_location = FS::cust_location->new({
708         map { $_ => $p->{"ship_$_"} } @location_editable_fields
709     });
710     if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
711       # Selfservice unfortunately tries to indicate "same as billing 
712       # address" by sending all fields empty.  Did this ever work?
713       $ship_location = $cust_main->bill_location;
714     }
715     $new->set('ship_location' => $ship_location);
716   }
717   # but if it hasn't been passed in at all, leave ship_location alone--
718   # DON'T change it to match bill_location.
719
720   my $payby = '';
721   if (exists($p->{'payby'})) {
722     $p->{'payby'} =~ /^([A-Z]{4})$/
723       or return { 'error' => "illegal_payby " . $p->{'payby'} };
724     $payby = $1;
725   }
726
727   my $conf = new FS::Conf;
728
729   if ( $payby =~ /^(CARD|DCRD)$/ ) {
730
731     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
732
733     if ( $new->payinfo eq $cust_main->paymask ) {
734       $new->payinfo($cust_main->payinfo);
735       $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
736     } else {
737       $new->payinfo($p->{'payinfo'});
738       return { 'error' => 'CVV2 is required' }
739         if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
740       $new->paycvv( $p->{'paycvv'} )
741     }
742
743     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
744
745   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
746
747     my $payinfo;
748     $p->{'payinfo1'} =~ /^([\dx]+)$/
749       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
750     my $payinfo1 = $1;
751      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
752       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
753     my $payinfo2 = $1;
754     $payinfo = $payinfo1. '@'. $payinfo2;
755
756     $new->payinfo( ($payinfo eq $cust_main->paymask)
757                      ? $cust_main->payinfo
758                      : $payinfo
759                  );
760
761     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
762
763   } elsif ( $payby =~ /^(BILL)$/ ) {
764     #no-op
765   } elsif ( $payby ) {  #notyet ready
766     return { 'error' => "unknown payby $payby" };
767   }
768
769   my @invoicing_list;
770   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
771     #false laziness with httemplate/edit/process/cust_main.cgi
772     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
773     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
774   } else {
775     @invoicing_list = $cust_main->invoicing_list;
776   }
777
778   my $error = $new->replace($cust_main, \@invoicing_list);
779   return { 'error' => $error } if $error;
780   #$cust_main = $new;
781   
782   return { 'error' => '' };
783 }
784
785 sub payment_info {
786   my $p = shift;
787   my $session = _cache->get($p->{'session_id'})
788     or return { 'error' => "Can't resume session" }; #better error message
789
790   ##
791   #generic
792   ##
793
794   my $conf = new FS::Conf;
795   use vars qw($payment_info); #cache for performance
796   unless ( $payment_info ) {
797
798     my %states = map { $_->state => 1 }
799                    qsearch('cust_main_county', {
800                      'country' => $conf->config('countrydefault') || 'US'
801                    } );
802
803     my %cust_paybys = map { $_ => 1 }
804                       map { FS::payby->payby2payment($_) }
805                           $conf->config('signup_server-payby');
806
807     my @cust_paybys = keys %cust_paybys;
808
809     $payment_info = {
810
811       #list all counties/states/countries
812       'cust_main_county' => 
813         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
814
815       #shortcut for one-country folks
816       'states' =>
817         [ sort { $a cmp $b } keys %states ],
818
819       'card_types' => card_types(),
820
821       'withcvv'            => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
822       'require_cvv'        => $conf->exists('selfservice-require_cvv'),
823       'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
824
825       'paytypes' => [ @FS::cust_main::paytypes ],
826
827       'paybys' => [ $conf->config('signup_server-payby') ],
828       'cust_paybys' => \@cust_paybys,
829
830       'stateid_label' => FS::Msgcat::_gettext('stateid'),
831       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
832
833       'show_ss'  => $conf->exists('show_ss'),
834       'show_stateid' => $conf->exists('show_stateid'),
835       'show_paystate' => $conf->exists('show_bankstate'),
836
837       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
838
839       'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
840     };
841
842   }
843
844   ##
845   #customer-specific
846   ##
847
848   my %return = %$payment_info;
849
850   my $custnum = $session->{'custnum'};
851
852   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
853     or return { 'error' => "unknown custnum $custnum" };
854
855   $return{'hide_payment_fields'} = [
856     map { 
857       my $pg = payment_gateway($cust_main, $_);
858       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
859     } @{ $return{cust_paybys} }
860   ];
861
862   $return{balance} = $cust_main->balance; #XXX pkg-balances?
863
864   $return{payname} = $cust_main->payname
865                      || ( $cust_main->first. ' '. $cust_main->get('last') );
866
867   $return{$_} = $cust_main->bill_location->get($_) 
868     for qw(address1 address2 city state zip);
869
870   $return{payby} = $cust_main->payby;
871   $return{stateid_state} = $cust_main->stateid_state;
872
873   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
874     $return{card_type} = cardtype($cust_main->payinfo);
875     $return{payinfo} = $cust_main->paymask;
876
877     @return{'month', 'year'} = $cust_main->paydate_monthyear;
878
879   }
880
881   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
882     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
883     $return{payinfo1} = $payinfo1;
884     $return{payinfo2} = $payinfo2;
885     $return{paytype}  = $cust_main->paytype;
886     $return{paystate} = $cust_main->paystate;
887     $return{payname}  = $cust_main->payname;    # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
888   }
889
890   if ( $conf->config('prepayment_discounts-credit_type') ) {
891     #need to eval?
892     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
893   }
894
895   #doubleclick protection
896   my $_date = time;
897   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
898   $return{paybatch} = $return{payunique};  #back compat
899
900   return { 'error' => '',
901            %return,
902          };
903
904 }
905
906 #some false laziness with httemplate/process/payment.cgi - look there for
907 #ACH and CVV support stuff
908
909 sub validate_payment {
910   my $p = shift;
911
912   my $session = _cache->get($p->{'session_id'})
913     or return { 'error' => "Can't resume session" }; #better error message
914
915   my $custnum = $session->{'custnum'};
916
917   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
918     or return { 'error' => "unknown custnum $custnum" };
919
920   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
921     or return { 'error' => gettext('illegal_amount') };
922   my $amount = $1;
923   return { error => 'Amount must be greater than 0' } unless $amount > 0;
924
925   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
926   #changing the hidden form values
927   my $conf = new FS::Conf;
928   my $fee_display = $conf->config('selfservice_process-display') || 'add';
929   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
930   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
931   if ( $fee_display eq 'add'
932          and $fee_pkgpart
933          and ! $fee_skip_first || scalar($cust_main->cust_pay)
934      )
935   {
936     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
937     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
938   }
939
940   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
941     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
942   my $discount_term = $1;
943
944   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
945     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
946   my $payname = $1;
947
948   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
949     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
950   my $payunique = $1;
951
952   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
953     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
954   my $paybatch = $1;
955
956   $payunique = $paybatch if ! length($payunique) && length($paybatch);
957
958   $p->{'payby'} ||= 'CARD';
959   $p->{'payby'} =~ /^([A-Z]{4})$/
960     or return { 'error' => "illegal_payby " . $p->{'payby'} };
961   my $payby = $1;
962
963   #false laziness w/process/payment.cgi
964   my $payinfo;
965   my $paycvv = '';
966   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
967   
968     $p->{'payinfo1'} =~ /^([\dx]+)$/
969       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
970     my $payinfo1 = $1;
971      $p->{'payinfo2'} =~ /^([\dx]+)$/
972       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
973     my $payinfo2 = $1;
974     $payinfo = $payinfo1. '@'. $payinfo2;
975
976     $payinfo = $cust_main->payinfo
977       if $cust_main->paymask eq $payinfo;
978    
979   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
980    
981     $payinfo = $p->{'payinfo'};
982
983     my $onfile = 0;
984
985     #more intelligent matching will be needed here if you change
986     #card_masking_method and don't remove existing paymasks
987     if ( $cust_main->paymask eq $payinfo ) {
988       $payinfo = $cust_main->payinfo;
989       $onfile = 1;
990     }
991
992     $payinfo =~ s/\D//g;
993     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
994       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
995     $payinfo = $1;
996
997     validate($payinfo)
998       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
999     return { 'error' => gettext('unknown_card_type') }
1000       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1001
1002     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1003       if ( cardtype($payinfo) eq 'American Express card' ) {
1004         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1005           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1006         $paycvv = $1;
1007       } else {
1008         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1009           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1010         $paycvv = $1;
1011       }
1012     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1013       return { 'error' => 'CVV2 is required' };
1014     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1015       return { 'error' => 'CVV2 is required' };
1016     }
1017   
1018   } else {
1019     die "unknown payby $payby";
1020   }
1021
1022   my %payby2fields = (
1023     'CARD' => [ qw( paystart_month paystart_year payissue payip
1024                     address1 address2 city state zip country    ) ],
1025     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1026   );
1027
1028   my $card_type = '';
1029   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1030
1031   { 
1032     'cust_main'      => $cust_main, #XXX or just custnum??
1033     'amount'         => sprintf('%.2f', $amount),
1034     'payby'          => $payby,
1035     'payinfo'        => $payinfo,
1036     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
1037     'card_type'      => $card_type,
1038     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1039     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1040     'month'          => $p->{'month'},
1041     'year'           => $p->{'year'},
1042     'payname'        => $payname,
1043     'payunique'      => $payunique,
1044     'paybatch'       => $paybatch,
1045     'paycvv'         => $paycvv,
1046     'payname'        => $payname,
1047     'discount_term'  => $discount_term,
1048     'pkgnum'         => $session->{'pkgnum'},
1049     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1050                              qw( save auto ),
1051                            )
1052   };
1053
1054 }
1055
1056 sub store_payment {
1057   my $p = shift;
1058
1059   my $validate = validate_payment($p);
1060   return $validate if $validate->{'error'};
1061
1062   my $conf = new FS::Conf;
1063   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1064   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1065
1066   +{ map { $_=>$validate->{$_} }
1067       qw( card_type paymask payname paydate_pretty month year amount
1068           address1 address2 city state zip country
1069         )
1070   };
1071
1072 }
1073
1074 sub process_stored_payment {
1075   my $p = shift;
1076
1077   my $session_id = $p->{'session_id'};
1078
1079   my $payment_info = _cache->get( "payment_$session_id" )
1080     or return { 'error' => "Can't resume session" }; #better error message
1081
1082   do_process_payment($payment_info);
1083
1084 }
1085
1086 sub process_payment {
1087   my $p = shift;
1088
1089   my $payment_info = validate_payment($p);
1090   return $payment_info if $payment_info->{'error'};
1091
1092   do_process_payment($payment_info);
1093
1094 }
1095
1096 sub do_process_payment {
1097   my $validate = shift;
1098
1099   my $cust_main = $validate->{'cust_main'};
1100
1101   my $amount = delete $validate->{'amount'};
1102   my $paynum = '';
1103
1104   my $payby = delete $validate->{'payby'};
1105
1106   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1107     'quiet'       => 1,
1108     'manual'      => 1,
1109     'selfservice' => 1,
1110     'paynum_ref'  => \$paynum,
1111     %$validate,
1112   );
1113   return { 'error' => $error } if $error;
1114
1115   #no error, so order the fee package if applicable...
1116   my $conf = new FS::Conf;
1117   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1118   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1119   
1120   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1121
1122     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1123
1124     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1125     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1126       if $error;
1127
1128     #and generate an invoice for it now too
1129     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1130     return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1131       if $error;
1132
1133   }
1134
1135   $cust_main->apply_payments;
1136
1137   if ( $validate->{'save'} ) {
1138     my $new = new FS::cust_main { $cust_main->hash };
1139     if ($payby eq 'CARD' || $payby eq 'DCRD') {
1140       $new->set( $_ => $validate->{$_} )
1141         foreach qw( payname paystart_month paystart_year payissue payip );
1142       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1143
1144       my $bill_location = FS::cust_location->new({
1145           map { $_ => $validate->{$_} } 
1146           qw(address1 address2 city state country zip)
1147       }); # county?
1148       $new->set('bill_location' => $bill_location);
1149       # but don't allow the service address to change this way.
1150
1151     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1152       $new->set( $_ => $validate->{$_} )
1153         foreach qw( payname payip paytype paystate
1154                     stateid stateid_state );
1155       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1156     }
1157     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1158     $new->set( 'paydate' => $validate->{'paydate'} );
1159     my $error = $new->replace($cust_main);
1160     if ( $error ) {
1161       #no, this causes customers to process their payments again
1162       #return { 'error' => $error };
1163       #XXX just warn verosely for now so i can figure out how these happen in
1164       # the first place, eventually should redirect them to the "change
1165       #address" page but indicate the payment did process??
1166       delete($validate->{'payinfo'}); #don't want to log this!
1167       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1168            "NEW: ". Dumper($new)."\n".
1169            "OLD: ". Dumper($cust_main)."\n".
1170            "PACKET: ". Dumper($validate)."\n";
1171     #} else {
1172       #not needed...
1173       #$cust_main = $new;
1174     }
1175   }
1176
1177   my $cust_pay = '';
1178   my $receipt_html = '';
1179   if ($paynum) {
1180       # currently supported for realtime CC only; send receipt data to SS
1181       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1182       if($cust_pay) {
1183         $receipt_html = qq!
1184 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1185
1186 <TR>
1187   <TD ALIGN="right">Payment#</TD>
1188   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1189 </TR>
1190
1191 <TR>
1192   <TD ALIGN="right">Date</TD>
1193
1194   <TD BGCOLOR="#FFFFFF"><B>! . 
1195         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1196                                                             . qq!</B></TD>
1197 </TR>
1198
1199
1200 <TR>
1201   <TD ALIGN="right">Amount</TD>
1202   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1203
1204 </TR>
1205
1206 <TR>
1207   <TD ALIGN="right">Payment method</TD>
1208   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1209                                                                 . qq!</B></TD>
1210 </TR>
1211
1212 </TABLE>
1213 !;
1214       }
1215   }
1216
1217   if ( $cust_pay ) {
1218
1219     return {
1220       'error'        => '',
1221       'amount'       => sprintf('%.2f', $cust_pay->paid),
1222       'date'         => $cust_pay->_date,
1223       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1224       'time_pretty'  => time2str('%T', $cust_pay->_date),
1225       'auth_num'     => $cust_pay->auth,
1226       'order_num'    => $cust_pay->order_number,
1227       'receipt_html' => $receipt_html,
1228     };
1229
1230   } else {
1231
1232     return {
1233       'error'        => '',
1234       'receipt_html' => '',
1235     };
1236
1237   }
1238
1239 }
1240
1241 sub realtime_collect {
1242   my $p = shift;
1243
1244   my $session = _cache->get($p->{'session_id'})
1245     or return { 'error' => "Can't resume session" }; #better error message
1246
1247   my $custnum = $session->{'custnum'};
1248
1249   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1250     or return { 'error' => "unknown custnum $custnum" };
1251
1252   my $amount;
1253   if ( $p->{'amount'} ) {
1254     $amount = $p->{'amount'};
1255   }
1256   elsif ( $session->{'pkgnum'} ) {
1257     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1258   }
1259   else {
1260     $amount = $cust_main->balance;
1261   }
1262
1263   my $error = $cust_main->realtime_collect(
1264     'method'     => $p->{'method'},
1265     'amount'     => $amount,
1266     'pkgnum'     => $session->{'pkgnum'},
1267     'session_id' => $p->{'session_id'},
1268     'apply'      => 1,
1269     'selfservice'=> 1,
1270   );
1271   return { 'error' => $error } unless ref( $error );
1272
1273   return { 'error' => '', amount => $amount, %$error };
1274 }
1275
1276 sub start_thirdparty {
1277   my $p = shift;
1278   my $session = _cache->get($p->{'session_id'})
1279     or return { 'error' => "Can't resume session" }; #better error message
1280   my $custnum = $session->{'custnum'};
1281   my $cust_main = FS::cust_main->by_key($custnum);
1282   
1283   my $amount = $p->{'amount'}
1284     or return { error => 'no amount' };
1285
1286   my $result = $cust_main->create_payment(
1287     'method'      => $p->{'method'},
1288     'amount'      => $p->{'amount'},
1289     'pkgnum'      => $session->{'pkgnum'},
1290     'session_id'  => $p->{'session_id'},
1291   );
1292   
1293   if ( ref($result) ) { # hashref or error
1294     return $result;
1295   } else {
1296     return { error => $result };
1297   }
1298 }
1299
1300 sub finish_thirdparty {
1301   my $p = shift;
1302   my $session_id = delete $p->{'session_id'};
1303   my $session = _cache->get($session_id)
1304     or return { 'error' => "Can't resume session" };
1305   my $custnum = $session->{'custnum'};
1306   my $cust_main = FS::cust_main->by_key($custnum);
1307
1308   if ( $p->{_cancel} ) {
1309     # customer backed out of making a payment
1310     return $cust_main->cancel_payment( $session_id );
1311   }
1312   my $result = $cust_main->execute_payment( $session_id, %$p );
1313   if ( ref($result) ) {
1314     return $result;
1315   } else {
1316     return { error => $result };
1317   }
1318 }
1319
1320 sub process_payment_order_pkg {
1321   my $p = shift;
1322
1323   my $hr = process_payment($p);
1324   return $hr if $hr->{'error'};
1325
1326   order_pkg($p);
1327 }
1328
1329 sub process_payment_order_renew {
1330   my $p = shift;
1331
1332   my $hr = process_payment($p);
1333   return $hr if $hr->{'error'};
1334
1335   order_renew($p);
1336 }
1337
1338 sub process_prepay {
1339
1340   my $p = shift;
1341
1342   my $session = _cache->get($p->{'session_id'})
1343     or return { 'error' => "Can't resume session" }; #better error message
1344
1345   my %return;
1346
1347   my $custnum = $session->{'custnum'};
1348
1349   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1350     or return { 'error' => "unknown custnum $custnum" };
1351
1352   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1353   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1354                                            \$amount,
1355                                            \$seconds,
1356                                            \$upbytes,
1357                                            \$downbytes,
1358                                            \$totalbytes,
1359                                          );
1360
1361   return { 'error' => $error } if $error;
1362
1363   return { 'error'     => '',
1364            'amount'    => $amount,
1365            'seconds'   => $seconds,
1366            'duration'  => duration_exact($seconds),
1367            'upbytes'   => $upbytes,
1368            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1369            'downbytes' => $downbytes,
1370            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1371            'totalbytes'=> $totalbytes,
1372            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1373          };
1374
1375 }
1376
1377 sub invoice {
1378   my $p = shift;
1379   my $session = _cache->get($p->{'session_id'})
1380     or return { 'error' => "Can't resume session" }; #better error message
1381
1382   my $custnum = $session->{'custnum'};
1383
1384   my $invnum = $p->{'invnum'};
1385
1386   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1387                                           'custnum' => $custnum } )
1388     or return { 'error' => "Can't find invnum" };
1389
1390   #my %return;
1391
1392   return { 'error'        => '',
1393            'invnum'       => $invnum,
1394            'invoice_text' => join('', $cust_bill->print_text ),
1395            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1396          };
1397
1398 }
1399
1400 sub invoice_pdf {
1401   my $p = shift;
1402   my $session = _cache->get($p->{'session_id'})
1403     or return { 'error' => "Can't resume session" }; #better error message
1404
1405   my $custnum = $session->{'custnum'};
1406
1407   my $invnum = $p->{'invnum'};
1408
1409   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1410                                           'custnum' => $custnum } )
1411     or return { 'error' => "Can't find invnum" };
1412
1413   #my %return;
1414
1415   return { 'error'       => '',
1416            'invnum'      => $invnum,
1417            'invoice_pdf' => $cust_bill->print_pdf({
1418                               'unsquelch_cdr' => 1,
1419                               'locale'        => $p->{'locale'},
1420                             }),
1421          };
1422
1423 }
1424
1425 sub legacy_invoice {
1426   my $p = shift;
1427   my $session = _cache->get($p->{'session_id'})
1428     or return { 'error' => "Can't resume session" }; #better error message
1429
1430   my $custnum = $session->{'custnum'};
1431
1432   my $legacyinvnum = $p->{'legacyinvnum'};
1433
1434   my %hash = (
1435     'legacyinvnum' => $legacyinvnum,
1436     'custnum'      => $custnum,
1437   );
1438
1439   my $legacy_cust_bill =
1440          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1441       || qsearchs('legacy_cust_bill', \%hash )
1442     or return { 'error' => "Can't find legacyinvnum" };
1443
1444   #my %return;
1445
1446   return { 'error'        => '',
1447            'legacyinvnum' => $legacyinvnum,
1448            'legacyid'     => $legacy_cust_bill->legacyid,
1449            'invoice_html' => $legacy_cust_bill->content_html,
1450          };
1451
1452 }
1453
1454 sub legacy_invoice_pdf {
1455   my $p = shift;
1456   my $session = _cache->get($p->{'session_id'})
1457     or return { 'error' => "Can't resume session" }; #better error message
1458
1459   my $custnum = $session->{'custnum'};
1460
1461   my $legacyinvnum = $p->{'legacyinvnum'};
1462
1463   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1464     'legacyinvnum' => $legacyinvnum,
1465     'custnum'      => $custnum,
1466   }) or return { 'error' => "Can't find legacyinvnum" };
1467
1468   #my %return;
1469
1470   return { 'error'        => '',
1471            'legacyinvnum' => $legacyinvnum,
1472            'legacyid'     => $legacy_cust_bill->legacyid,
1473            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1474          };
1475
1476 }
1477
1478 sub invoice_logo {
1479   my $p = shift;
1480
1481   #sessioning for this?  how do we get the session id to the backend invoice
1482   # template so it can add it to the link, blah
1483
1484   my $agentnum = '';
1485   if ( $p->{'invnum'} ) {
1486     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1487       or return { 'error' => 'unknown invnum' };
1488     $agentnum = $cust_bill->cust_main->agentnum;
1489   }
1490
1491   my $templatename = $p->{'template'} || $p->{'templatename'};
1492
1493   #false laziness-ish w/view/cust_bill-logo.cgi
1494
1495   my $conf = new FS::Conf;
1496   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1497     $templatename = "_$1";
1498   } else {
1499     $templatename = '';
1500   }
1501
1502   my $filename = "logo$templatename.png";
1503
1504   return { 'error'        => '',
1505            'logo'         => $conf->config_binary($filename, $agentnum),
1506            'content_type' => 'image/png', #should allow gif, jpg too
1507          };
1508 }
1509
1510
1511 sub list_invoices {
1512   my $p = shift;
1513   my $session = _cache->get($p->{'session_id'})
1514     or return { 'error' => "Can't resume session" }; #better error message
1515
1516   my $custnum = $session->{'custnum'};
1517
1518   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1519     or return { 'error' => "unknown custnum $custnum" };
1520
1521   my $conf = new FS::Conf;
1522
1523   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1524
1525   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1526
1527   my $balance = 0;
1528   my $invoices = [
1529     map {
1530       #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1531       my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1532       my $owed = $_->owed;
1533       $balance += $owed;
1534       +{ 'invnum'       => $_->invnum,
1535          '_date'        => $_->_date,
1536          'date'         => time2str("%b %o, %Y", $_->_date),
1537          'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1538          'previous'     => sprintf('%.2f', ($_->previous)[0]),
1539          'charged'      => sprintf('%.2f', $_->charged),
1540          'owed'         => sprintf('%.2f', $owed),
1541          'balance'      => sprintf('%.2f', $balance),
1542          'lastpay'      => @payments_and_credits 
1543                            ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1544                            : '',
1545       }
1546     } @cust_bill
1547   ];
1548
1549   return  { 'error'       => '',
1550             'balance'     => $cust_main->balance,
1551             'money_char'  => $conf->config("money_char") || '$',
1552             'invoices'    => $invoices,
1553             'legacy_invoices' => [
1554               map {
1555                     +{ 'legacyinvnum' => $_->legacyinvnum,
1556                        'legacyid'     => $_->legacyid,
1557                        '_date'        => $_->_date,
1558                        'date'         => time2str("%b %o, %Y", $_->_date),
1559                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1560                        'charged'      => sprintf('%.2f', $_->charged),
1561                        'has_content'  => (    length($_->content_pdf)
1562                                            || length($_->content_html) ),
1563                      }
1564                   }
1565                   @legacy_cust_bill
1566             ],
1567           };
1568 }
1569
1570 sub cancel {
1571   my $p = shift;
1572   my $session = _cache->get($p->{'session_id'})
1573     or return { 'error' => "Can't resume session" }; #better error message
1574
1575   my $custnum = $session->{'custnum'};
1576
1577   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1578     or return { 'error' => "unknown custnum $custnum" };
1579
1580   my @errors = $cust_main->cancel( 'quiet'=>1 );
1581
1582   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1583
1584   return { 'error' => $error };
1585
1586 }
1587
1588 sub list_pkgs {
1589   my $p = shift;
1590
1591   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1592   return { 'error' => $session } if $context eq 'error';
1593
1594   my $search = { 'custnum' => $custnum };
1595   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1596   my $cust_main = qsearchs('cust_main', $search )
1597     or return { 'error' => "unknown custnum $custnum" };
1598
1599   my $conf = new FS::Conf;
1600   my $immutable = $conf->exists('selfservice_immutable-package');
1601   
1602 # the duplication below is necessary:
1603 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1604 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1605 # non-backwards-compatible change breaking the software of anyone using the API
1606 # instead of the stock selfservice
1607 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1608   if( $conf->exists('selfservice_server-view-wholesale') ) {
1609     return { 'svcnum'   => $session->{'svcnum'},
1610             'custnum'  => $custnum,
1611             'cust_pkg' => [ map {
1612                           { $_->hash,
1613                             immutable => $immutable,
1614                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1615                             part_svc =>
1616                               [ map $_->hashref, $_->available_part_svc ],
1617                             cust_svc => 
1618                               [ map { my $ref = { $_->hash,
1619                                                   label => [ $_->label ],
1620                                                 };
1621                                       $ref->{_password} = $_->svc_x->_password
1622                                         if $context eq 'agent'
1623                                         && $conf->exists('agent-showpasswords')
1624                                         && $_->part_svc->svcdb eq 'svc_acct';
1625                                       $ref;
1626                                     } $_->cust_svc
1627                               ],
1628                           };
1629                         } $cust_main->cust_pkg
1630                   ],
1631     'small_custview' =>
1632       small_custview( $cust_main, $conf->config('countrydefault') ),
1633     'wholesale_view' => 1,
1634     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1635     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1636     'lnp' => $conf->exists('svc_phone-lnp'),
1637       };
1638   }
1639
1640   { 'svcnum'   => $session->{'svcnum'},
1641     'custnum'  => $custnum,
1642     'cust_pkg' => [ map {
1643                           my $primary_cust_svc = $_->primary_cust_svc;
1644                           +{ $_->hash,
1645                             $_->part_pkg->hash,
1646                             immutable   => $immutable,
1647                             pkg_label   => $_->pkg_locale,
1648                             status      => $_->status,
1649                             statuscolor => $_->statuscolor,
1650                             part_svc =>
1651                               [ map { $_->hashref }
1652                                   grep { $_->selfservice_access ne 'hidden' }
1653                                     $_->available_part_svc
1654                               ],
1655                             cust_svc => 
1656                               [ map { my $ref = { $_->hash,
1657                                                   label => [ $_->label ],
1658                                                 };
1659                                       $ref->{_password} = $_->svc_x->_password
1660                                         if $context eq 'agent'
1661                                         && $conf->exists('agent-showpasswords')
1662                                         && $_->part_svc->svcdb eq 'svc_acct';
1663                                       $ref->{svchash} = { $_->svc_x->hash } if 
1664                                         $_->part_svc->svcdb eq 'svc_phone';
1665                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1666                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1667                                       $ref;
1668                                     }
1669                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
1670                                     $_->cust_svc
1671                               ],
1672                             primary_cust_svc =>
1673                               $primary_cust_svc
1674                                 ? { $primary_cust_svc->hash,
1675                                     label => [ $primary_cust_svc->label ],
1676                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1677                                     $primary_cust_svc->part_svc->hash,
1678                                   }
1679                                 : {}, #'' ?
1680                           };
1681                         } $cust_main->ncancelled_pkgs
1682                   ],
1683     'small_custview' =>
1684       small_custview( $cust_main, $conf->config('countrydefault') ),
1685     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1686   };
1687
1688 }
1689
1690 sub list_svcs {
1691   my $p = shift;
1692
1693   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1694   return { 'error' => $session } if $context eq 'error';
1695
1696   my $conf = new FS::Conf;
1697
1698   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1699   my $search = { 'custnum' => $custnum };
1700   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1701   my $cust_main = qsearchs('cust_main', $search )
1702     or return { 'error' => "unknown custnum $custnum" };
1703
1704   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1705   if ( ! $pkgnum && $p->{'svcnum'} ) {
1706     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1707     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1708   }
1709
1710   my @cust_svc = ();
1711   my @cust_pkg_usage = ();
1712   foreach my $cust_pkg ( $p->{'ncancelled'} 
1713                          ? $cust_main->ncancelled_pkgs
1714                          : $cust_main->unsuspended_pkgs ) {
1715     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1716     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1717     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1718   }
1719
1720   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1721   my %usage_pools;
1722   if (!$hide_usage) {
1723     foreach (@cust_pkg_usage) {
1724       my $part = $_->part_pkg_usage;
1725       my $tag = $part->description . ($part->shared ? 1 : 0);
1726       my $row = $usage_pools{$tag} 
1727             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1728       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1729       $row->[2] += $part->minutes; # minutes total
1730     }
1731   } # otherwise just leave them empty
1732
1733   if ( $p->{'svcdb'} ) {
1734     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1735                   ? $p->{'svcdb'}
1736                   : ref($p->{'svcdb'}) eq 'ARRAY'
1737                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1738                     : { $p->{'svcdb'} => 1 };
1739     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1740   }
1741
1742   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1743   #              @svc_x;
1744
1745   my @svcs; # stuff to return to the client
1746   foreach my $cust_svc (@cust_svc) {
1747     my $svc_x = $cust_svc->svc_x;
1748     my($label, $value) = $cust_svc->label;
1749     my $part_svc = $cust_svc->part_svc;
1750     my $svcdb = $part_svc->svcdb;
1751     my $cust_pkg = $cust_svc->cust_pkg;
1752     my $part_pkg = $cust_pkg->part_pkg;
1753
1754     my %hash = (
1755       'svcnum'         => $cust_svc->svcnum,
1756       'display_svcnum' => $cust_svc->display_svcnum,
1757       'svcdb'          => $svcdb,
1758       'label'          => $label,
1759       'value'          => $value,
1760       'pkg_label'      => $cust_pkg->pkg_locale,
1761       'pkg_status'     => $cust_pkg->status,
1762       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
1763     );
1764
1765     # would it make sense to put this in a svc_* method?
1766
1767     if ( $svcdb eq 'svc_acct' ) {
1768       foreach (qw(username email finger seconds)) {
1769         $hash{$_} = $svc_x->$_;
1770       }
1771
1772       if (!$hide_usage) {
1773         %hash = (
1774           %hash,
1775           'upbytes'    => display_bytecount($svc_x->upbytes),
1776           'downbytes'  => display_bytecount($svc_x->downbytes),
1777           'totalbytes' => display_bytecount($svc_x->totalbytes),
1778
1779           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1780           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1781           'recharge_upbytes'    =>
1782             display_bytecount($part_pkg->option('recharge_upbytes',1)),
1783           'recharge_downbytes'  =>
1784             display_bytecount($part_pkg->option('recharge_downbytes',1)),
1785           'recharge_totalbytes' =>
1786             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1787           # more...
1788         );
1789       }
1790
1791     } elsif ( $svcdb eq 'svc_dsl' ) {
1792
1793       $hash{'phonenum'} = $svc_x->phonenum;
1794       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1795         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1796         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1797           if $svc_x->company;
1798       } else {
1799         $hash{'name'} = $cust_main->name;
1800       }
1801       # no usage to hide here
1802
1803     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1804       if (!$hide_usage) {
1805         # could potentially show lots of things...
1806         $hash{'outbound'} = 1;
1807         $hash{'inbound'}  = 0;
1808         if ( $svcdb eq 'svc_phone' ) {
1809           if ( $part_pkg->plan eq 'voip_inbound' ) {
1810             $hash{'outbound'} = 0;
1811             $hash{'inbound'}  = 1;
1812           } elsif ( $part_pkg->option('selfservice_inbound_format')
1813                 or  $conf->config('selfservice-default_inbound_cdr_format')
1814           ) {
1815             $hash{'inbound'}  = 1;
1816           }
1817         }
1818         foreach (qw(inbound outbound)) {
1819           # hmm...we can't filter by status here, because there might
1820           # not be cdr_terminations at all.  have to go by date.
1821           # find all since the last bill date.
1822           # XXX cdr types?  we are going to need them.
1823           if ( $hash{$_} ) {
1824             my $sum_cdr = $svc_x->sum_cdrs(
1825               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1826               'begin'   => ($cust_pkg->last_bill || 0),
1827               'nonzero' => 1,
1828               'disable_charged_party' => 1,
1829             );
1830             $hash{$_} = $sum_cdr->hashref;
1831           }
1832         }
1833       } # not hiding usage
1834     } # svcdb
1835
1836     push @svcs, \%hash;
1837   } # foreach $cust_svc
1838
1839   return { 
1840     'svcnum'   => $session->{'svcnum'},
1841     'custnum'  => $custnum,
1842     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1843     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1844     'svcs'     => \@svcs,
1845     'usage_pools' => [
1846       map { $usage_pools{$_} }
1847       sort { $a cmp $b }
1848       keys %usage_pools
1849     ],
1850     'hide_usage' => $hide_usage,
1851   };
1852
1853 }
1854
1855 sub _customer_svc_x {
1856   my($custnum, $svcnum, $table) = (shift, shift, shift);
1857   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1858
1859   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1860   my $search = " AND custnum = $1";
1861   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1862
1863   qsearchs( {
1864     'table'     => ($table || 'svc_acct'),
1865     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1866                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1867                    #'LEFT JOIN cust_main USING ( custnum ) ',
1868     'hashref'   => $hashref,
1869     'extra_sql' => $search, #important
1870   } );
1871
1872 }
1873
1874 sub svc_status_html {
1875   my $p = shift;
1876
1877   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1878   return { 'error' => $session } if $context eq 'error';
1879
1880   #XXX only svc_dsl for now
1881   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1882     or return { 'error' => "Service not found" };
1883
1884   my $html = $svc_x->getstatus_html;
1885
1886   return { 'html' => $html };
1887
1888 }
1889
1890 sub svc_status_hash {
1891   my $p = shift;
1892
1893   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1894   return { 'error' => $session } if $context eq 'error';
1895
1896   #XXX only svc_acct for now
1897   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1898     or return { 'error' => "Service not found" };
1899
1900   my ( $html, $hashref ) = $svc_x->export_getstatus;
1901   return $hashref;
1902
1903 }
1904
1905 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
1906 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1907 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1908 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1909 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1910
1911 sub _svc_method_X {
1912   my( $p, $method ) = @_;
1913
1914   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1915   return { 'error' => $session } if $context eq 'error';
1916
1917   #XXX only svc_acct for now
1918   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1919     or return { 'error' => "Service not found" };
1920
1921   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1922     if $DEBUG;
1923   my $error = $svc_x->$method($p); #$p? returns error?
1924   return { 'error' => $error } if $error;
1925
1926   return {}; #? { 'error' => '' }
1927
1928 }
1929
1930 sub acct_forward_info {
1931   my $p = shift;
1932
1933   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1934   return { 'error' => $session } if $context eq 'error';
1935
1936   my $svc_forward = _customer_svc_x( $custnum,
1937                                      { 'srcsvc' => $p->{'svcnum'} },
1938                                      'svc_forward',
1939                                    )
1940     or return { 'error' => '',
1941                 'dst'   => '',
1942               };
1943
1944   return { 'error' => '',
1945            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1946          };
1947
1948 }
1949
1950 sub process_acct_forward {
1951   my $p = shift;
1952   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1953   return { 'error' => $session } if $context eq 'error';
1954
1955   my $old = _customer_svc_x( $custnum,
1956                              { 'srcsvc' => $p->{'svcnum'} },
1957                              'svc_forward',
1958                            );
1959
1960   if ( $p->{'dst'} eq '' ) {
1961     if ( $old ) {
1962       my $error = $old->delete;
1963       return { 'error' => $error };
1964     }
1965     return { 'error' => '' };
1966   }
1967
1968   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1969                                   'dst'    => $p->{'dst'},
1970                                 };
1971
1972   my $error;
1973   if ( $old ) {
1974     $new->svcnum($old->svcnum);
1975     my $cust_svc = $old->cust_svc;
1976     $new->svcpart($old->svcpart);
1977     $new->pkgnuym($old->pkgnum);
1978     $error = $new->replace($old);
1979   } else {
1980     my $conf = new FS::Conf;
1981     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1982
1983     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1984       or return { 'error' => 'No service' }; #how would we even get here?
1985
1986     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1987
1988     $error = $new->insert;
1989   }
1990
1991   return { 'error' => $error };
1992
1993 }
1994
1995 sub list_dsl_devices {
1996   my $p = shift;
1997
1998   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1999   return { 'error' => $session } if $context eq 'error';
2000
2001   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2002     or return { 'error' => "Service not found" };
2003
2004   return {
2005     'devices' => [ map {
2006                          +{ 'mac_addr' => $_->mac_addr };
2007                        } $svc_dsl->dsl_device
2008                  ],
2009   };
2010
2011 }
2012
2013 sub add_dsl_device {
2014   my $p = shift;
2015
2016   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2017   return { 'error' => $session } if $context eq 'error';
2018
2019   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2020     or return { 'error' => "Service not found" };
2021
2022   return { 'error' => 'No MAC address supplied' }
2023     unless length($p->{'mac_addr'});
2024
2025   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2026                                         'mac_addr' => scalar($p->{'mac_addr'}),
2027                                       };
2028   my $error = $dsl_device->insert;
2029   return { 'error' => $error };
2030
2031 }
2032
2033 sub delete_dsl_device {
2034   my $p = shift;
2035
2036   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2037   return { 'error' => $session } if $context eq 'error';
2038
2039   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2040     or return { 'error' => "Service not found" };
2041
2042   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2043                                             'mac_addr' => scalar($p->{'mac_addr'}),
2044                                           }
2045                            )
2046     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2047
2048   my $error = $dsl_device->delete;
2049   return { 'error' => $error };
2050
2051 }
2052
2053 sub port_graph {
2054   my $p = shift;
2055   _usage_details( \&_port_graph, $p,
2056                   'svcdb' => 'svc_port',
2057                 );
2058 }
2059
2060 sub _port_graph {
2061   my($svc_port, $begin, $end) = @_;
2062   my @usage = ();
2063   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2064   push @usage, { 'png' => $pngOrError };
2065   (@usage);
2066 }
2067
2068 sub _list_svc_usage {
2069   my($svc_acct, $begin, $end) = @_;
2070   my @usage = ();
2071   foreach my $part_export ( 
2072     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2073     qw( sqlradius sqlradius_withdomain )
2074   ) {
2075     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2076   }
2077   (@usage);
2078 }
2079
2080 sub list_svc_usage {
2081   _usage_details(\&_list_svc_usage, @_);
2082 }
2083
2084 sub _list_support_usage {
2085   my($svc_acct, $begin, $end) = @_;
2086   my @usage = ();
2087   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2088             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2089           ) {
2090     push @usage, { 'seconds'  => $_->seconds,
2091                    'support'  => $_->support,
2092                    '_date'    => $_->_date,
2093                    'id'       => $_->transaction_id,
2094                    'creator'  => $_->creator,
2095                    'subject'  => $_->subject,
2096                    'status'   => $_->status,
2097                    'ticketid' => $_->ticketid,
2098                  };
2099   }
2100   (@usage);
2101 }
2102
2103 sub list_support_usage {
2104   _usage_details(\&_list_support_usage, @_);
2105 }
2106
2107 sub _list_cdr_usage {
2108   # XXX CDR type support...
2109   # XXX any way to do a paged search on this?
2110   # we have to return the results all at once...
2111   my($svc_x, $begin, $end, %opt) = @_;
2112   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2113     $svc_x->get_cdrs(
2114       'begin' => $begin,
2115       'end'   => $end,
2116       'disable_charged_party' => 1,
2117       %opt
2118     );
2119 }
2120
2121 sub list_cdr_usage {
2122   my $p = shift;
2123   _usage_details( \&_list_cdr_usage, $p );
2124 }
2125
2126 sub _usage_details {
2127   my($callback, $p, %opt) = @_;
2128   my $conf = FS::Conf->new;
2129
2130   if ( $conf->exists('selfservice_hide-usage') ) {
2131     return { 'error' => 'Viewing usage is not allowed.' };
2132   }
2133
2134   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2135   return { 'error' => $session } if $context eq 'error';
2136
2137   my $search = { 'svcnum' => $p->{'svcnum'} };
2138   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2139
2140   my $cust_svc = qsearchs( 'cust_svc', $search );
2141   return { 'error' => 'No service selected in list_svc_usage' } 
2142     unless $cust_svc;
2143
2144   my $svc_x = $cust_svc->svc_x;
2145   my $svcdb = $svc_x->table;
2146   my $cust_pkg = $cust_svc->cust_pkg;
2147   my $freq     = $cust_pkg->part_pkg->freq;
2148   my %callback_opt;
2149   my $header = [];
2150   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2151     my $format = '';
2152     if ( $p->{inbound} ) {
2153       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2154                 || $conf->config('selfservice-default_inbound_cdr_format')
2155                 || 'source_default';
2156       $callback_opt{inbound} = 1;
2157     } else {
2158       $format = $cust_pkg->part_pkg->option('selfservice_format')
2159                 || $conf->config('selfservice-default_cdr_format')
2160                 || 'default';
2161     }
2162
2163     $callback_opt{format} = $format;
2164     $callback_opt{use_clid} = 1;
2165     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2166   }
2167
2168   my $start    = $cust_pkg->setup;
2169   #my $end      = $cust_pkg->bill; # or time?
2170   my $end      = time;
2171
2172   unless ( $p->{beginning} ) {
2173     $p->{beginning} = $cust_pkg->last_bill;
2174     $p->{ending}    = $end;
2175   }
2176
2177   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2178   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2179
2180   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2181     %callback_opt
2182   );
2183
2184   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2185     # ugly kludge, I know
2186     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2187     if (defined $delete_col) {
2188       delete($_->[$delete_col]) foreach ($header, @usage);
2189     }
2190   }
2191
2192   #kinda false laziness with FS::cust_main::bill, but perhaps
2193   #we should really change this bit to DateTime and DateTime::Duration
2194   #
2195   #change this bit to use Date::Manip? CAREFUL with timezones (see
2196   # mailing list archive)
2197   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2198     (localtime($p->{ending}) )[0,1,2,3,4,5];
2199   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2200     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2201
2202   if ( $freq =~ /^\d+$/ ) {
2203     $nmon += $freq;
2204     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2205     $pmon -= $freq;
2206     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2207   } elsif ( $freq =~ /^(\d+)w$/ ) {
2208     my $weeks = $1;
2209     $nmday += $weeks * 7;
2210     $pmday -= $weeks * 7;
2211   } elsif ( $freq =~ /^(\d+)d$/ ) {
2212     my $days = $1;
2213     $nmday += $days;
2214     $pmday -= $days;
2215   } elsif ( $freq =~ /^(\d+)h$/ ) {
2216     my $hours = $1;
2217     $nhour += $hours;
2218     $phour -= $hours;
2219   } else {
2220     return { 'error' => "unparsable frequency: ". $freq };
2221   }
2222   
2223   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2224   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2225
2226   { 
2227     'error'     => '',
2228     'svcnum'    => $p->{svcnum},
2229     'beginning' => $p->{beginning},
2230     'ending'    => $p->{ending},
2231     'inbound'   => $p->{inbound},
2232     'previous'  => ($previous > $start) ? $previous : $start,
2233     'next'      => ($next < $end) ? $next : $end,
2234     'header'    => $header,
2235     'usage'     => \@usage,
2236   };
2237 }
2238
2239 sub order_pkg {
2240   my $p = shift;
2241
2242   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2243   return { 'error' => $session } if $context eq 'error';
2244
2245   my $search = { 'custnum' => $custnum };
2246   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2247   my $cust_main = qsearchs('cust_main', $search )
2248     or return { 'error' => "unknown custnum $custnum" };
2249
2250   my $status = $cust_main->status;
2251
2252   my %order_pkg_options = ();
2253   if ( $p->{locationnum} > 0 ) {
2254     $order_pkg_options{locationnum} = delete($p->{locationnum});
2255   } elsif ( $p->{address1} ) {
2256     $order_pkg_options{'cust_location'} = new FS::cust_location {
2257       map { $_ => $p->{$_} }
2258         qw( address1 address2 city county state zip country )
2259     };
2260   }
2261
2262   #false laziness w/ClientAPI/Signup.pm
2263
2264   my $cust_pkg = new FS::cust_pkg ( {
2265     'custnum'  => $custnum,
2266     'pkgpart'  => $p->{'pkgpart'},
2267     'quantity' => $p->{'quantity'} || 1,
2268   } );
2269   my $error = $cust_pkg->check;
2270   return { 'error' => $error } if $error;
2271
2272   my @svc = ();
2273   unless ( $p->{'svcpart'} eq 'none' ) {
2274
2275     my $svcdb;
2276     my $svcpart = '';
2277     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2278       $svcpart = $1;
2279       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2280       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2281       $svcdb = $part_svc->svcdb;
2282     } else {
2283       $svcdb = 'svc_acct';
2284     }
2285     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2286
2287     my %fields = (
2288       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2289       'svc_domain'   => [ qw( domain ) ],
2290       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2291       'svc_external' => [ qw( id title ) ],
2292       'svc_pbx'      => [ qw( id title ) ],
2293     );
2294   
2295     my $svc_x = "FS::$svcdb"->new( {
2296       'svcpart'   => $svcpart,
2297       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2298     } );
2299     
2300     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2301       my @acct_snarf;
2302       my $snarfnum = 1;
2303       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2304         my $acct_snarf = new FS::acct_snarf ( {
2305           'machine'   => $p->{"snarf_machine$snarfnum"},
2306           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2307           'username'  => $p->{"snarf_username$snarfnum"},
2308           '_password' => $p->{"snarf_password$snarfnum"},
2309         } );
2310         $snarfnum++;
2311         push @acct_snarf, $acct_snarf;
2312       }
2313       $svc_x->child_objects( \@acct_snarf );
2314     }
2315     
2316     my $y = $svc_x->setdefault; # arguably should be in new method
2317     return { 'error' => $y } if $y && !ref($y);
2318   
2319     $error = $svc_x->check;
2320     return { 'error' => $error } if $error;
2321
2322     push @svc, $svc_x;
2323
2324   }
2325
2326   $error = $cust_main->order_pkg(
2327     'cust_pkg' => $cust_pkg,
2328     'svcs'     => \@svc,
2329     'noexport' => 1,
2330     %order_pkg_options,
2331   );
2332   return { 'error' => $error } if $error;
2333
2334   my $conf = new FS::Conf;
2335   if ( $conf->exists('signup_server-realtime') ) {
2336
2337     my $bill_error = _do_bop_realtime( $cust_main, $status );
2338
2339     if ($bill_error) {
2340       $cust_pkg->cancel('quiet'=>1);
2341       return $bill_error;
2342     } else {
2343       $cust_pkg->reexport;
2344     }
2345
2346   } else {
2347     $cust_pkg->reexport;
2348   }
2349
2350   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2351
2352   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2353
2354 }
2355
2356 sub change_pkg {
2357   my $p = shift;
2358
2359   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2360   return { 'error' => $session } if $context eq 'error';
2361
2362   my $conf = new FS::Conf;
2363   my $immutable = $conf->exists('selfservice_immutable-package');
2364   return { 'error' => "Package modification disabled" } if $immutable;
2365
2366   my $search = { 'custnum' => $custnum };
2367   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2368   my $cust_main = qsearchs('cust_main', $search )
2369     or return { 'error' => "unknown custnum $custnum" };
2370
2371   my $status = $cust_main->status;
2372   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2373     or return { 'error' => "unknown package $p->{pkgnum}" };
2374
2375   #if someone does need self-service package change of suspended packages,
2376   # figure out how to be more discriminating
2377   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2378     if $cust_pkg->status eq 'suspended';
2379
2380   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2381                                            'quantity' => $p->{'quantity'} || 1,
2382                                          );
2383
2384   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2385     unless ref($err_or_cust_pkg);
2386
2387   if ( $conf->exists('signup_server-realtime') ) {
2388
2389     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2390
2391     if ($bill_error) {
2392       $err_or_cust_pkg->suspend;
2393       return $bill_error;
2394     } else {
2395       $err_or_cust_pkg->reexport;
2396     }
2397
2398   } else {  
2399     $err_or_cust_pkg->reexport;
2400   }
2401
2402   return { error => '', pkgnum => $cust_pkg->pkgnum };
2403
2404 }
2405
2406 sub order_recharge {
2407   my $p = shift;
2408
2409   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2410   return { 'error' => $session } if $context eq 'error';
2411
2412   my $search = { 'custnum' => $custnum };
2413   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2414   my $cust_main = qsearchs('cust_main', $search )
2415     or return { 'error' => "unknown custnum $custnum" };
2416
2417   my $status = $cust_main->status;
2418   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2419     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2420
2421   my $svc_x = $cust_svc->svc_x;
2422   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2423
2424   my %vhash =
2425     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2426     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2427          recharge_totalbytes );
2428   my $amount = $part_pkg->option('recharge_amount', 1); 
2429   
2430   my ($l, $v, $d) = $cust_svc->label;  # blah
2431   my $pkg = "Recharge $v"; 
2432
2433   my $bill_error = $cust_main->charge($amount, $pkg,
2434      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2435      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2436      $part_pkg->taxclass); #meh
2437
2438   my $conf = new FS::Conf;
2439   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2440
2441     $bill_error = _do_bop_realtime( $cust_main, $status );
2442
2443     if ($bill_error) {
2444       return $bill_error;
2445     } else {
2446       my $error = $svc_x->recharge (\%vhash);
2447       return { 'error' => $error } if $error;
2448     }
2449
2450   } else {  
2451     my $error = $bill_error;
2452     $error ||= $svc_x->recharge (\%vhash);
2453     return { 'error' => $error } if $error;
2454   }
2455
2456   return { error => '', svc => $cust_svc->part_svc->svc };
2457
2458 }
2459
2460 sub _do_bop_realtime {
2461   my ($cust_main, $status, %opt) = @_;
2462
2463     my $old_balance = $cust_main->balance;
2464
2465     my $bill_error =    $cust_main->bill
2466                      || $cust_main->apply_payments_and_credits;
2467
2468     $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2469       if $cust_main->payby =~ /^(CARD|CHEK)$/;
2470
2471     if (    $cust_main->balance > $old_balance
2472          && $cust_main->balance > 0
2473          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2474                 || $status eq 'suspended'
2475             )
2476        )
2477     {
2478       unless ( $opt{'no_credit'} ) {
2479         #this makes sense.  credit is "un-doing" the invoice
2480         my $conf = new FS::Conf;
2481         $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2482                             'self-service decline',
2483                             reason_type=>$conf->config('signup_credit_type'),
2484                           );
2485         $cust_main->apply_credits( 'order' => 'newest' );
2486       }
2487
2488       return { 'error' => '_decline', 'bill_error' => $bill_error };
2489     }
2490
2491     '';
2492 }
2493
2494 sub renew_info {
2495   my $p = shift;
2496
2497   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2498   return { 'error' => $session } if $context eq 'error';
2499
2500   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2501     or return { 'error' => "unknown custnum $custnum" };
2502
2503   my @cust_pkg = sort { $a->bill <=> $b->bill }
2504                  grep { $_->part_pkg->freq ne '0' }
2505                  $cust_main->ncancelled_pkgs;
2506
2507   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2508
2509   my $total = $cust_main->balance;
2510
2511   my @array = map {
2512                     my $bill = $_->bill;
2513                     $total += $_->part_pkg->base_recur($_, \$bill);
2514                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2515                     {
2516                       'pkgnum'             => $_->pkgnum,
2517                       'amount'             => sprintf('%.2f', $total),
2518                       'bill_date'          => $_->bill,
2519                       'bill_date_pretty'   => time2str('%x', $_->bill),
2520                       'renew_date'         => $renew_date,
2521                       'renew_date_pretty'  => time2str('%x', $renew_date),
2522                       'expire_date'        => $_->expire,
2523                       'expire_date_pretty' => time2str('%x', $_->expire),
2524                     };
2525                   }
2526                   @cust_pkg;
2527
2528   return { 'dates' => \@array };
2529
2530 }
2531
2532 sub payment_info_renew_info {
2533   my $p = shift;
2534   my $renew_info   = renew_info($p);
2535   my $payment_info = payment_info($p);
2536   return { %$renew_info,
2537            %$payment_info,
2538          };
2539 }
2540
2541 sub order_renew {
2542   my $p = shift;
2543
2544   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2545   return { 'error' => $session } if $context eq 'error';
2546
2547   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2548     or return { 'error' => "unknown custnum $custnum" };
2549
2550   my $date = $p->{'date'};
2551
2552   my $now = time;
2553
2554   #freeside-daily -n -d $date fs_daily $custnum
2555   $cust_main->bill_and_collect( 'time'         => $date,
2556                                 'invoice_time' => $now,
2557                                 'actual_time'  => $now,
2558                                 'check_freq'   => '1d',
2559                               );
2560
2561   return { 'error' => '' };
2562
2563 }
2564
2565 sub suspend_pkg {
2566   my $p = shift;
2567   my $session = _cache->get($p->{'session_id'})
2568     or return { 'error' => "Can't resume session" }; #better error message
2569
2570   my $custnum = $session->{'custnum'};
2571
2572   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2573     or return { 'error' => "unknown custnum $custnum" };
2574
2575   my $conf = new FS::Conf;
2576   my $reasonnum = 
2577     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2578       or return { 'error' => 'Permission denied' };
2579
2580   my $pkgnum = $p->{'pkgnum'};
2581
2582   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2583                                         'pkgnum'  => $pkgnum,   } )
2584     or return { 'error' => "unknown pkgnum $pkgnum" };
2585
2586   my $error = $cust_pkg->suspend(reason => $reasonnum);
2587   return { 'error' => $error };
2588
2589 }
2590
2591 sub cancel_pkg {
2592   my $p = shift;
2593   my $session = _cache->get($p->{'session_id'})
2594     or return { 'error' => "Can't resume session" }; #better error message
2595
2596   my $custnum = $session->{'custnum'};
2597
2598   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2599     or return { 'error' => "unknown custnum $custnum" };
2600
2601   my $pkgnum = $p->{'pkgnum'};
2602
2603   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2604                                         'pkgnum'  => $pkgnum,   } )
2605     or return { 'error' => "unknown pkgnum $pkgnum" };
2606
2607   my $error = $cust_pkg->cancel('quiet' => 1);
2608   return { 'error' => $error };
2609
2610 }
2611
2612 sub provision_phone {
2613   my $p = shift;
2614   my @bulkdid;
2615   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2616
2617   #editing an existing phone number
2618   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2619       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2620       return { 'error' => $session } if $context eq 'error';
2621     
2622       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2623       return { 'error' => 'service not found' } unless $svc_phone;
2624       return { 'error' => 'invalid svcnum' } 
2625         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2626
2627       $svc_phone->email($p->{'email'}) 
2628         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2629       $svc_phone->forwarddst($p->{'forwarddst'}) 
2630         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2631             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2632       return { 'error' => $svc_phone->replace };
2633  }
2634
2635   # single DID LNP
2636   unless ( $p->{'lnp'} ) {
2637     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2638     $p->{'lnp_status'} = "portingin";
2639     return _provision( 'FS::svc_phone',
2640                   [qw(lnp_desired_due_date lnp_other_provider 
2641                     lnp_other_provider_account phonenum countrycode lnp_status)],
2642                   [qw(phonenum countrycode)],
2643                   $p,
2644                   @_
2645                 );
2646   }
2647
2648   # single DID order (the usual case)
2649   unless (scalar(@bulkdid)) {
2650     return _provision( 'FS::svc_phone',
2651                   [qw(phonenum countrycode)],
2652                   [qw(phonenum countrycode)],
2653                   $p,
2654                   @_
2655                 );
2656   }
2657
2658   # bulk DID order case
2659   my $error;
2660   foreach my $did ( @bulkdid ) {
2661     $did =~ s/[^0-9]//g;
2662     $error = _provision( 'FS::svc_phone',
2663               [qw(phonenum countrycode)],
2664               [qw(phonenum countrycode)],
2665               {
2666                 'pkgnum' => $p->{'pkgnum'},
2667                 'svcpart' => $p->{'svcpart'},
2668                 'phonenum' => $did,
2669                 'countrycode' => $p->{'countrycode'},
2670                 'session_id' => $p->{'session_id'},
2671               }
2672             );
2673     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2674   }
2675   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2676 }
2677
2678 sub provision_pbx {
2679   my $p = shift;
2680   warn "provision_pbx called\n"
2681     if $DEBUG;
2682
2683   warn "provision_pbx calling _provision\n"
2684     if $DEBUG;
2685   _provision( 'FS::svc_pbx',
2686               [qw(id title max_extensions max_simultaneous ip_addr)],
2687               [qw(id title max_extensions max_simultaneous ip_addr)],
2688               $p,
2689               @_
2690             );
2691 }
2692
2693 sub provision_acct {
2694   my $p = shift;
2695   warn "provision_acct called\n"
2696     if $DEBUG;
2697
2698   return { 'error' => gettext('passwords_dont_match') }
2699     if $p->{'_password'} ne $p->{'_password2'};
2700   return { 'error' => gettext('empty_password') }
2701     unless length($p->{'_password'});
2702  
2703   if ($p->{'domsvc'}) {
2704     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2705                                                   qw ( svcpart pkgnum ) );
2706     return { 'error' => gettext('invalid_domain') }
2707       unless ($domains{$p->{'domsvc'}});
2708   }
2709
2710   warn "provision_acct calling _provision\n"
2711     if $DEBUG;
2712   _provision( 'FS::svc_acct',
2713               [qw(username _password domsvc)],
2714               [qw(username _password domsvc)],
2715               $p,
2716               @_
2717             );
2718 }
2719
2720 sub provision_external {
2721   my $p = shift;
2722   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2723   _provision( 'FS::svc_external',
2724               [],
2725               [qw(id title)],
2726               $p,
2727               @_
2728             );
2729 }
2730
2731 sub provision_forward {
2732   my $p = shift;
2733   _provision( 'FS::svc_forward',
2734               ['srcsvc','src','dstsvc','dst'],
2735               [],
2736               $p,
2737             );
2738 }
2739
2740 sub _provision {
2741   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2742   warn "_provision called for $class\n"
2743     if $DEBUG;
2744
2745   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2746   return { 'error' => $session } if $context eq 'error';
2747
2748   my $search = { 'custnum' => $custnum };
2749   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2750   my $cust_main = qsearchs('cust_main', $search )
2751     or return { 'error' => "unknown custnum $custnum" };
2752
2753   my $pkgnum = $p->{'pkgnum'};
2754
2755   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2756     if $DEBUG;
2757   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2758                                         'pkgnum'  => $pkgnum,
2759                                                                } )
2760     or return { 'error' => "unknown pkgnum $pkgnum" };
2761
2762   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2763     if $DEBUG;
2764   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2765     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2766
2767   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2768     if $class ne 'FS::'. $part_svc->svcdb;
2769
2770   warn "creating $class record\n"
2771     if $DEBUG;
2772   my $svc_x = $class->new( {
2773     'pkgnum'  => $p->{'pkgnum'},
2774     'svcpart' => $p->{'svcpart'},
2775     map { $_ => $p->{$_} } @$fields
2776   } );
2777
2778   my %insert_args = ();
2779   #i shouldn't be a special case here (pass an option or something)
2780   if ( $class eq 'FS::svc_phone'
2781          && grep length($p->{$_}), @location_editable_fields
2782      )
2783   {
2784     $insert_args{'cust_location'} = new FS::cust_location {
2785       map { $_ => $p->{$_} } @location_editable_fields
2786     };
2787   }
2788
2789   warn "inserting $class record\n"
2790     if $DEBUG;
2791   my $error = $svc_x->insert(%insert_args);
2792
2793   unless ( $error ) {
2794     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2795       if $DEBUG;
2796     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2797   }
2798
2799   my $return = { 'svc'   => $part_svc->svc,
2800                  'error' => $error,
2801                  map { $_ => $svc_x->get($_) } @$return_fields
2802                };
2803   warn "_provision returning ". Dumper($return). "\n"
2804     if $DEBUG;
2805   return $return;
2806
2807 }
2808
2809 sub part_svc_info {
2810   my $p = shift;
2811
2812   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2813   return { 'error' => $session } if $context eq 'error';
2814
2815   my $search = { 'custnum' => $custnum };
2816   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2817   my $cust_main = qsearchs('cust_main', $search )
2818     or return { 'error' => "unknown custnum $custnum" };
2819
2820   my $pkgnum = $p->{'pkgnum'};
2821
2822   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2823                                         'pkgnum'  => $pkgnum,
2824                                                                } )
2825     or return { 'error' => "unknown pkgnum $pkgnum" };
2826
2827   my $svcpart = $p->{'svcpart'};
2828
2829   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2830                                       'svcpart' => $svcpart,           } )
2831     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2832   my $part_svc = $pkg_svc->part_svc;
2833
2834   my $conf = new FS::Conf;
2835
2836   my $ret = {
2837     'svc'     => $part_svc->svc,
2838     'svcdb'   => $part_svc->svcdb,
2839     'pkgnum'  => $pkgnum,
2840     'svcpart' => $svcpart,
2841     'custnum' => $custnum,
2842
2843     'security_phrase' => 0, #XXX !
2844     'svc_acct_pop'    => [], #XXX !
2845     'popnum'          => '',
2846     'init_popstate'   => '',
2847     'popac'           => '',
2848     'acstate'         => '',
2849
2850     'small_custview' =>
2851       small_custview( $cust_main, $conf->config('countrydefault') ),
2852
2853   };
2854
2855   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2856                      && $ret->{'svcdb'} eq 'svc_phone') {
2857         $ret->{'svcnum'} = $p->{'svcnum'};
2858         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2859         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2860             $ret->{'email'} = $svc_phone->email;
2861             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2862         }
2863   }
2864
2865   if ($ret->{'svcdb'} eq 'svc_forward') {
2866     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
2867   }
2868
2869   $ret;
2870 }
2871
2872 sub unprovision_svc {
2873   my $p = shift;
2874
2875   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2876   return { 'error' => $session } if $context eq 'error';
2877
2878   my $search = { 'custnum' => $custnum };
2879   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2880   my $cust_main = qsearchs('cust_main', $search )
2881     or return { 'error' => "unknown custnum $custnum" };
2882
2883   my $svcnum = $p->{'svcnum'};
2884
2885   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2886     or return { 'error' => "unknown svcnum $svcnum" };
2887
2888   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2889     unless $cust_svc->cust_pkg->custnum == $custnum;
2890
2891   my $conf = new FS::Conf;
2892
2893   return { 'svc'   => $cust_svc->part_svc->svc,
2894            'error' => $cust_svc->cancel,
2895            'small_custview' =>
2896              small_custview( $cust_main, $conf->config('countrydefault') ),
2897          };
2898
2899 }
2900
2901 sub myaccount_passwd {
2902   my $p = shift;
2903   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2904   return { 'error' => $session } if $context eq 'error';
2905
2906   return { 'error' => "New passwords don't match." }
2907     if $p->{'new_password'} ne $p->{'new_password2'};
2908
2909   return { 'error' => 'Enter new password' }
2910     unless length($p->{'new_password'});
2911
2912   #my $search = { 'custnum' => $custnum };
2913   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2914   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2915   my $search = " AND custnum = $1";
2916   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2917
2918   my $svc_acct = qsearchs( {
2919     'table'     => 'svc_acct',
2920     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2921                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2922                    'LEFT JOIN cust_main USING ( custnum ) ',
2923     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2924     'extra_sql' => $search, #important
2925   } )
2926     or return { 'error' => "Service not found" };
2927
2928   my $error = '';
2929
2930   my $conf = new FS::Conf;
2931
2932   return { 'error' => 'Incorrect current password.' }
2933     if  ( exists($p->{'old_password'})
2934           || $conf->exists('selfservice-password_change_oldpass')
2935         )
2936     && ! $svc_acct->check_password($p->{'old_password'});
2937
2938   $error = 'Password too short.'
2939     if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2940   $error = 'Password too long.'
2941     if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2942
2943   $svc_acct->set_password($p->{'new_password'});
2944   $error ||= $svc_acct->replace();
2945
2946   #regular pw change in self-service should change contact pw too, otherwise its
2947   #way too confusing.  hell its confusing they're separate at all, but alas.
2948   #need to support the "ISP provides email that's used as a contact email" case
2949   #as well as we can.
2950   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2951   if ( $contact && $contact->custnum == $custnum ) {
2952     #svc_acct was successful but this one returns an error?  "shouldn't happen"
2953     $error ||= $contact->change_password($p->{'new_password'});
2954   }
2955
2956   my($label, $value) = $svc_acct->cust_svc->label;
2957
2958   return { 'error' => $error,
2959            'label' => $label,
2960            'value' => $value,
2961          };
2962
2963 }
2964
2965 #  sub contact_passwd {
2966 #    my $p = shift;
2967 #    my($context, $session, $custnum) = _custoragent_session_custnum($p);
2968 #    return { 'error' => $session } if $context eq 'error';
2969 #  
2970 #    return { 'error' => 'Not logged in as a contact.' }
2971 #      unless $session->{'contactnum'};
2972 #  
2973 #    return { 'error' => "New passwords don't match." }
2974 #      if $p->{'new_password'} ne $p->{'new_password2'};
2975 #  
2976 #    return { 'error' => 'Enter new password' }
2977 #      unless length($p->{'new_password'});
2978 #  
2979 #    #my $search = { 'custnum' => $custnum };
2980 #    #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2981 #    $custnum =~ /^(\d+)$/ or die "illegal custnum";
2982 #    my $search = " AND selfservice_access IS NOT NULL ".
2983 #                 " AND selfservice_access = 'Y' ".
2984 #                 " AND ( disabled IS NULL OR disabled = '' )".
2985 #                 " AND custnum IS NOT NULL AND custnum = $1";
2986 #    $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2987 #  
2988 #    my $contact = qsearchs( {
2989 #      'table'     => 'contact',
2990 #      'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2991 #      'hashref'   => { 'contactnum' => $session->{'contactnum'}, },
2992 #      'extra_sql' => $search, #important
2993 #    } )
2994 #      or return { 'error' => "Email not found" }; #?  how did we get logged in?
2995 #                                                  # deleted since then?
2996 #  
2997 #    my $error = '';
2998 #  
2999 #    # use these svc_acct length restrictions??
3000 #    my $conf = new FS::Conf;
3001 #    $error = 'Password too short.'
3002 #      if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3003 #    $error = 'Password too long.'
3004 #      if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3005 #  
3006 #    $error ||= $contact->change_password($p->{'new_password'});
3007 #  
3008 #    return { 'error' => $error, };
3009 #  
3010 #  }
3011
3012 sub reset_passwd {
3013   my $p = shift;
3014
3015   my $info = skin_info($p);
3016
3017   my $conf = new FS::Conf;
3018   my $verification = $conf->config('selfservice-password_reset_verification')
3019     or return { %$info, 'error' => 'Password resets disabled' };
3020
3021   my $contact = '';
3022   my $svc_acct = '';
3023   my $cust_main = '';
3024   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3025   
3026     $contact = FS::contact->by_selfservice_email($p->{'email'});
3027
3028     $cust_main = $contact->cust_main if $contact;
3029
3030     #also look for an svc_acct, otherwise it would be super confusing
3031
3032     my($username, $domain) = split('@', $p->{'email'});
3033     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3034     if ( $svc_domain ) {
3035       $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3036                                          'domsvc'   => $svc_domain->svcnum  }
3037                           );
3038       if ( $svc_acct ) {
3039         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3040         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3041
3042         #precaution: don't change svc_acct password not part of the same
3043         # customer as contact
3044         $svc_acct = '' if ! $cust_pkg
3045                        || $cust_pkg->custnum != $cust_main->custnum;
3046       }
3047       
3048     }
3049
3050     return { %$info, 'error' => 'Email address not found' }
3051       unless $contact || $svc_acct;
3052
3053   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3054
3055     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3056       or return { %$info, 'error' => 'Account not found' };
3057
3058     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3059                                        'domsvc'   => $svc_domain->svcnum  }
3060                         )
3061       or return { %$info, 'error' => 'Account not found' };
3062
3063     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3064       or return { %$info, 'error' => 'Account not found' };
3065
3066     $cust_main = $cust_pkg->cust_main;
3067
3068   }
3069
3070   my %verify = (
3071     'email'   => sub { 1; },
3072     'paymask' => sub { 
3073       my( $p, $cust_main ) = @_;
3074       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3075         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3076     },
3077     'amount'  => sub {
3078       my( $p, $cust_main ) = @_;
3079       my $cust_pay = qsearchs({
3080         'table' => 'cust_pay',
3081         'hashref' => { 'custnum' => $cust_main->custnum },
3082         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3083       })
3084         or return 0;
3085
3086       $p->{'amount'} == $cust_pay->paid;
3087     },
3088     'zip'     => sub {
3089       my( $p, $cust_main ) = @_;
3090       $p->{'zip'} eq $cust_main->zip
3091         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3092     },
3093   );
3094
3095   foreach my $verify ( split(',', $verification) ) {
3096
3097     &{ $verify{$verify} }( $p, $cust_main )
3098       or return { %$info, 'error' => 'Account not found' };
3099
3100   }
3101
3102   #okay, we're verified
3103
3104   if ( $contact ) {
3105
3106     my $error = $contact->send_reset_email(
3107                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3108                           );
3109
3110     if ( $error ) {
3111       return { %$info, 'error' => $error }; #????
3112     }
3113
3114   } elsif ( $svc_acct ) {
3115
3116     #create a unique session
3117
3118     my $reset_session = {
3119       'svcnum'   => $svc_acct->svcnum,
3120       'agentnum' =>
3121     };
3122
3123     my $timeout = '1 hour'; #?
3124
3125     my $reset_session_id;
3126     do {
3127       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3128     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3129       #just in case
3130
3131     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3132
3133     #email it
3134
3135     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3136                                $cust_main->agentnum);
3137     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3138     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3139       unless $msgnum;
3140     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3141     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3142                                      'object'        => $svc_acct,
3143                                      'substitutions' => {
3144                                        'session_id' => $reset_session_id,
3145                                      }
3146                                    );
3147     if ( $error ) {
3148       return { %$info, 'error' => $error }; #????
3149     }
3150
3151   }
3152
3153   return { %$info, 'error' => '' };
3154 }
3155
3156 sub check_reset_passwd {
3157   my $p = shift;
3158
3159   my $conf = new FS::Conf;
3160   my $verification = $conf->config('selfservice-password_reset_verification')
3161     or return { 'error' => 'Password resets disabled' };
3162
3163   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3164     or return { 'error' => "Can't resume session" }; #better error message
3165
3166   if ( $reset_session->{'svcnum'} ) {
3167
3168     my $svcnum = $reset_session->{'svcnum'};
3169
3170     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3171       or return { 'error' => "Service not found" };
3172
3173     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3174     my $info = skin_info($p);
3175
3176     return { %$info,
3177              'error'      => '',
3178              'session_id' => $p->{'session_id'},
3179              'username'   => $svc_acct->username,
3180            };
3181
3182   } elsif ( $reset_session->{'contactnum'} ) {
3183
3184     my $contactnum = $reset_session->{'contactnum'};
3185
3186     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3187       or return { 'error' => "Contact not found" };
3188
3189     my @contact_email = $contact->contact_email;
3190     return { 'error' => 'No contact email' } unless @contact_email;
3191
3192     $p->{'agentnum'} = $contact->cust_main->agentnum;
3193     my $info = skin_info($p);
3194
3195     return { %$info,
3196              'error'      => '',
3197              'session_id' => $p->{'session_id'},
3198              'email'      => $contact_email[0]->email, #the first?
3199            };
3200
3201   } else {
3202
3203     return { 'error' => 'No svcnum or contactnum in session' }; #??
3204
3205   }
3206
3207 }
3208
3209 sub process_reset_passwd {
3210   my $p = shift;
3211
3212   my $conf = new FS::Conf;
3213   my $verification = $conf->config('selfservice-password_reset_verification')
3214     or return { 'error' => 'Password resets disabled' };
3215
3216   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3217     or return { 'error' => "Can't resume session" }; #better error message
3218
3219   my $info = '';
3220
3221   my $svc_acct = '';
3222   if ( $reset_session->{'svcnum'} ) {
3223
3224     my $svcnum = $reset_session->{'svcnum'};
3225
3226     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3227       or return { 'error' => "Service not found" };
3228
3229     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3230     $info ||= skin_info($p);
3231
3232   }
3233
3234   my $contact = '';
3235   if ( $reset_session->{'contactnum'} ) {
3236
3237     my $contactnum = $reset_session->{'contactnum'};
3238
3239     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3240       or return { 'error' => "Contact not found" };
3241
3242     $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3243     $info ||= skin_info($p);
3244
3245   }
3246
3247   return { %$info, 'error' => "New passwords don't match." }
3248     if $p->{'new_password'} ne $p->{'new_password2'};
3249
3250   return { %$info, 'error' => 'Enter new password' }
3251     unless length($p->{'new_password'});
3252
3253   if ( $svc_acct ) {
3254
3255     $svc_acct->set_password($p->{'new_password'});
3256     my $error = $svc_acct->replace();
3257
3258     return { %$info, 'error' => $error } if $error;
3259
3260     #my($label, $value) = $svc_acct->cust_svc->label;
3261     #return { 'error' => $error,
3262     #         #'label' => $label,
3263     #         #'value' => $value,
3264     #       };
3265
3266   }
3267
3268   if ( $contact ) {
3269
3270     my $error = $contact->change_password($p->{'new_password'});
3271
3272     return { %$info, 'error' => $error }; # if $error;
3273
3274   }
3275
3276   #password changed ,so remove session, don't want it reused
3277   _cache->remove($p->{'session_id'});
3278
3279   return { %$info, 'error' => '' };
3280
3281 }
3282
3283 sub list_tickets {
3284   my $p = shift;
3285   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3286   return { 'error' => $session } if $context eq 'error';
3287
3288   my @tickets = ();
3289   if ( $session->{'pkgnum'} ) { 
3290
3291     #tickets for specific service with pkg-balances on
3292     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3293                                           'pkgnum'  => $session->{'pkgnum'} })
3294                      or return { 'error' => 'unknown package' };
3295     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3296       push @tickets, $cust_svc->tickets( $p->{status} );
3297     }
3298
3299   } else {
3300
3301     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3302       or return { 'error' => "unknown custnum $custnum" };
3303
3304     @tickets = $cust_main->tickets( $p->{status} );
3305   }
3306
3307   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3308   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3309     my $conf = new FS::Conf;
3310     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3311     +{ tickets => [ 
3312          sort { 
3313            (
3314              ($a->{'_selfservice_priority'} eq '') <=>
3315              ($b->{'_selfservice_priority'} eq '')
3316            ) ||
3317            ( $dir * 
3318              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3319            )
3320          } @tickets
3321        ]
3322     };
3323   } else {
3324     +{ tickets => \@tickets };
3325   }
3326
3327 }
3328
3329 sub create_ticket {
3330   my $p = shift;
3331   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3332   return { 'error' => $session } if $context eq 'error';
3333
3334   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3335   FS::TicketSystem->init();
3336
3337   my $conf = new FS::Conf;
3338   my $queue = $p->{'queue'}
3339               || $conf->config('ticket_system-selfservice_queueid')
3340               || $conf->config('ticket_system-default_queueid');
3341
3342   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3343   my $err_or_ticket = FS::TicketSystem->create_ticket(
3344     '', #create RT session based on FS CurrentUser (fs_selfservice)
3345     'queue'   => $queue,
3346     'custnum' => $custnum,
3347     'svcnum'  => $session->{'svcnum'},
3348     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3349   );
3350
3351   if ( ref($err_or_ticket) ) {
3352     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3353       if $DEBUG;
3354     return { 'error'     => '',
3355              'ticket_id' => $err_or_ticket->id,
3356            };
3357   } else {
3358     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3359       if $DEBUG;
3360     return { 'error' => $err_or_ticket };
3361   }
3362
3363
3364 }
3365
3366 sub did_report {
3367   my $p = shift;
3368   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3369   return { 'error' => $session } if $context eq 'error';
3370  
3371   return { error => 'requested format not implemented' } 
3372     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3373
3374   my $conf = new FS::Conf;
3375   my $age_threshold = 0;
3376   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3377     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3378
3379   my $search = { 'custnum' => $custnum };
3380   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3381   my $cust_main = qsearchs('cust_main', $search )
3382     or return { 'error' => "unknown custnum $custnum" };
3383
3384 # does it make more sense to just run one sql query for this instead of all the
3385 # insanity below? would increase performance greately for large data sets?
3386   my @svc_phone = ();
3387   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3388         my @part_svc = $cust_pkg->part_svc;
3389         foreach my $part_svc ( @part_svc ) {
3390             if($part_svc->svcdb eq 'svc_phone'){
3391                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3392                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3393                     push @svc_phone, $cust_pkg_svc->svc_x
3394                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3395                 }
3396             }
3397         }
3398   }
3399
3400   my $csv;
3401   my $xls;
3402   my($xls_r,$xls_c) = (0,0);
3403   my $xls_workbook;
3404   my $content = '';
3405   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3406   if($p->{'format'} eq 'csv') {
3407     $csv = new Text::CSV_XS { 'always_quote' => 1,
3408                                  'eol'          => "\n",
3409                                 };
3410     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3411     $content .= $csv->string;
3412   }
3413   elsif($p->{'format'} eq 'xls') {
3414     my $XLS1 = new IO::Scalar \$content;
3415     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3416         or return { 'error' => "Error opening .xls file: $!" };
3417     $xls = $xls_workbook->add_worksheet('DIDs');
3418     foreach ( @fields ) {
3419         $xls->write(0,$xls_c++,$_);
3420     }
3421     $xls_r++;
3422   }
3423
3424   foreach my $svc_phone ( @svc_phone ) {
3425     my @cols = map { $svc_phone->$_ } @fields;
3426     if($p->{'format'} eq 'csv') {
3427         return { 'error' => 'Unable to create CSV' } 
3428             unless $csv->combine(@cols);
3429         $content .= $csv->string;
3430     }
3431     elsif($p->{'format'} eq 'xls') {
3432         $xls_c = 0;
3433         foreach ( @cols ) {
3434             $xls->write($xls_r,$xls_c++,$_);
3435         }
3436         $xls_r++;
3437     }
3438   }
3439
3440   $xls_workbook->close() if $p->{'format'} eq 'xls';
3441   
3442   { content => $content, format => $p->{'format'}, };
3443 }
3444
3445 sub get_ticket {
3446   my $p = shift;
3447   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3448   return { 'error' => $session } if $context eq 'error';
3449
3450 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3451 #  FS::TicketSystem->init();
3452 #  return { 'error' => 'get_ticket configuration error' }
3453 #    if $FS::TicketSystem::system ne 'RT_Internal';
3454
3455   # check existence and ownership as part of this
3456   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3457   my $rt_session = FS::TicketSystem->session('');
3458   my $Ticket = FS::TicketSystem->get_ticket_object(
3459     $rt_session, 
3460     ticket_id => $p->{'ticket_id'},
3461     custnum => $custnum
3462   );
3463   return { 'error' => 'ticket not found' } if !$Ticket;
3464
3465   if ( length( $p->{'subject'} || '' ) ) {
3466     # subject change
3467     if ( $p->{'subject'} ne $Ticket->Subject ) {
3468       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3469       return { 'error' => "unable to set subject: $msg" } if !$val;
3470     }
3471   }
3472
3473   if(length($p->{'reply'})) {
3474     my @err_or_res = FS::TicketSystem->correspond_ticket(
3475       $rt_session,
3476       'ticket_id' => $p->{'ticket_id'},
3477       'content' => $p->{'reply'},
3478     );
3479
3480     return { 'error' => 'unable to reply to ticket' } 
3481     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3482   }
3483
3484   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3485   my $err_or_ticket = FS::TicketSystem->get_ticket(
3486     $rt_session,
3487     'ticket_id' => $p->{'ticket_id'},
3488   );
3489
3490   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3491     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3492       if $DEBUG;
3493     return { 'error' => $err_or_ticket };
3494   }
3495
3496   my @custs = @{$err_or_ticket->{'custs'}};
3497   my @txns = @{$err_or_ticket->{'txns'}};
3498   my @filtered_txns;
3499
3500   # superseded by check in get_ticket_object
3501   #return { 'error' => 'invalid ticket requested' } 
3502   #unless grep($_ eq $custnum, @custs);
3503
3504   foreach my $txn ( @txns ) {
3505     push @filtered_txns, $txn 
3506     if ($txn->{'type'} eq 'EmailRecord' 
3507       || $txn->{'type'} eq 'Correspond'
3508       || $txn->{'type'} eq 'Create');
3509   }
3510
3511   warn "$me get_ticket: successful: \n"
3512   if $DEBUG;
3513   return { 'error'     => '',
3514     'transactions' => \@filtered_txns,
3515     'ticket_fields' => $err_or_ticket->{'fields'},
3516     'ticket_id' => $p->{'ticket_id'},
3517   };
3518 }
3519
3520 sub adjust_ticket_priority {
3521   my $p = shift;
3522   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3523   return { 'error' => $session } if $context eq 'error';
3524
3525 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3526 #  FS::TicketSystem->init;
3527   my $ss_priority = FS::TicketSystem->selfservice_priority;
3528
3529   return { 'error' => 'adjust_ticket_priority configuration error' }
3530     if $FS::TicketSystem::system ne 'RT_Internal'
3531       or !$ss_priority;
3532
3533   my $values = $p->{'values'}; #hashref, id => priority value
3534   my %ticket_error;
3535
3536   foreach my $id (keys %$values) {
3537     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3538     my $Ticket = FS::TicketSystem->get_ticket_object('',
3539       'ticket_id' => $id,
3540       'custnum'   => $custnum,
3541     );
3542     if ( !$Ticket ) {
3543       $ticket_error{$id} = 'ticket not found';
3544       next;
3545     }
3546     
3547   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3548   # We're not going to implement it for RT_External.
3549     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3550     my $new_value = $values->{$id};
3551     next if $old_value eq $new_value;
3552
3553     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3554
3555     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3556     # a single-valued custom field, which it should be.  If it's not, you're 
3557     # doing something wrong.
3558     my ($val, $msg);
3559     if ( length($new_value) ) {
3560       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3561         Field => $ss_priority,
3562         Value => $new_value,
3563       );
3564     }
3565     else {
3566       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3567         Field => $ss_priority,
3568         Value => $old_value,
3569       );
3570     }
3571
3572     $ticket_error{$id} = $msg if !$val;
3573     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3574   }
3575   return { 'error' => '',
3576            'ticket_error' => \%ticket_error,
3577            %{ customer_info($p) } # send updated customer info back
3578          }
3579 }
3580
3581 #--
3582
3583 sub _custoragent_session_custnum {
3584   my $p = shift;
3585
3586   my($context, $session, $custnum);
3587   if ( $p->{'session_id'} ) {
3588
3589     $context = 'customer';
3590     $session = _cache->get($p->{'session_id'})
3591       or return ( 'error' => "Can't resume session" ); #better error message
3592     $custnum = $session->{'custnum'};
3593
3594   } elsif ( $p->{'agent_session_id'} ) {
3595
3596     $context = 'agent';
3597     my $agent_cache = new FS::ClientAPI_SessionCache( {
3598       'namespace' => 'FS::ClientAPI::Agent',
3599     } );
3600     $session = $agent_cache->get($p->{'agent_session_id'})
3601       or return ( 'error' => "Can't resume session" ); #better error message
3602     $custnum = $p->{'custnum'};
3603
3604   } else {
3605     $context = 'error';
3606     return ( 'error' => "Can't resume session" ); #better error message
3607   }
3608
3609   ($context, $session, $custnum);
3610
3611 }
3612
3613 1;
3614