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