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