add an explicit compile-time dependancy on OLE::Storage_Lite, for large spreadsheets...
[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');
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');
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   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2008     %callback_opt
2009   );
2010
2011   #kinda false laziness with FS::cust_main::bill, but perhaps
2012   #we should really change this bit to DateTime and DateTime::Duration
2013   #
2014   #change this bit to use Date::Manip? CAREFUL with timezones (see
2015   # mailing list archive)
2016   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2017     (localtime($p->{ending}) )[0,1,2,3,4,5];
2018   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2019     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2020
2021   if ( $freq =~ /^\d+$/ ) {
2022     $nmon += $freq;
2023     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2024     $pmon -= $freq;
2025     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2026   } elsif ( $freq =~ /^(\d+)w$/ ) {
2027     my $weeks = $1;
2028     $nmday += $weeks * 7;
2029     $pmday -= $weeks * 7;
2030   } elsif ( $freq =~ /^(\d+)d$/ ) {
2031     my $days = $1;
2032     $nmday += $days;
2033     $pmday -= $days;
2034   } elsif ( $freq =~ /^(\d+)h$/ ) {
2035     my $hours = $1;
2036     $nhour += $hours;
2037     $phour -= $hours;
2038   } else {
2039     return { 'error' => "unparsable frequency: ". $freq };
2040   }
2041   
2042   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2043   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2044
2045   { 
2046     'error'     => '',
2047     'svcnum'    => $p->{svcnum},
2048     'beginning' => $p->{beginning},
2049     'ending'    => $p->{ending},
2050     'previous'  => ($previous > $start) ? $previous : $start,
2051     'next'      => ($next < $end) ? $next : $end,
2052     'header'    => $header,
2053     'usage'     => \@usage,
2054   };
2055 }
2056
2057 sub order_pkg {
2058   my $p = shift;
2059
2060   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2061   return { 'error' => $session } if $context eq 'error';
2062
2063   my $search = { 'custnum' => $custnum };
2064   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2065   my $cust_main = qsearchs('cust_main', $search )
2066     or return { 'error' => "unknown custnum $custnum" };
2067
2068   my $status = $cust_main->status;
2069   #false laziness w/ClientAPI/Signup.pm
2070
2071   my $cust_pkg = new FS::cust_pkg ( {
2072     'custnum' => $custnum,
2073     'pkgpart' => $p->{'pkgpart'},
2074   } );
2075   my $error = $cust_pkg->check;
2076   return { 'error' => $error } if $error;
2077
2078   my @svc = ();
2079   unless ( $p->{'svcpart'} eq 'none' ) {
2080
2081     my $svcdb;
2082     my $svcpart = '';
2083     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2084       $svcpart = $1;
2085       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2086       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2087       $svcdb = $part_svc->svcdb;
2088     } else {
2089       $svcdb = 'svc_acct';
2090     }
2091     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2092
2093     my %fields = (
2094       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2095       'svc_domain'   => [ qw( domain ) ],
2096       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2097       'svc_external' => [ qw( id title ) ],
2098       'svc_pbx'      => [ qw( id title ) ],
2099     );
2100   
2101     my $svc_x = "FS::$svcdb"->new( {
2102       'svcpart'   => $svcpart,
2103       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2104     } );
2105     
2106     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2107       my @acct_snarf;
2108       my $snarfnum = 1;
2109       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2110         my $acct_snarf = new FS::acct_snarf ( {
2111           'machine'   => $p->{"snarf_machine$snarfnum"},
2112           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2113           'username'  => $p->{"snarf_username$snarfnum"},
2114           '_password' => $p->{"snarf_password$snarfnum"},
2115         } );
2116         $snarfnum++;
2117         push @acct_snarf, $acct_snarf;
2118       }
2119       $svc_x->child_objects( \@acct_snarf );
2120     }
2121     
2122     my $y = $svc_x->setdefault; # arguably should be in new method
2123     return { 'error' => $y } if $y && !ref($y);
2124   
2125     $error = $svc_x->check;
2126     return { 'error' => $error } if $error;
2127
2128     push @svc, $svc_x;
2129
2130   }
2131
2132   use Tie::RefHash;
2133   tie my %hash, 'Tie::RefHash';
2134   %hash = ( $cust_pkg => \@svc );
2135   #msgcat
2136   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2137   return { 'error' => $error } if $error;
2138
2139   my $conf = new FS::Conf;
2140   if ( $conf->exists('signup_server-realtime') ) {
2141
2142     my $bill_error = _do_bop_realtime( $cust_main, $status );
2143
2144     if ($bill_error) {
2145       $cust_pkg->cancel('quiet'=>1);
2146       return $bill_error;
2147     } else {
2148       $cust_pkg->reexport;
2149     }
2150
2151   } else {
2152     $cust_pkg->reexport;
2153   }
2154
2155   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2156
2157   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2158
2159 }
2160
2161 sub change_pkg {
2162   my $p = shift;
2163
2164   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2165   return { 'error' => $session } if $context eq 'error';
2166
2167   my $search = { 'custnum' => $custnum };
2168   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2169   my $cust_main = qsearchs('cust_main', $search )
2170     or return { 'error' => "unknown custnum $custnum" };
2171
2172   my $status = $cust_main->status;
2173   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2174     or return { 'error' => "unknown package $p->{pkgnum}" };
2175
2176   my @newpkg;
2177   my $error = FS::cust_pkg::order( $custnum,
2178                                    [$p->{pkgpart}],
2179                                    [$p->{pkgnum}],
2180                                    \@newpkg,
2181                                  );
2182
2183   my $conf = new FS::Conf;
2184   if ( $conf->exists('signup_server-realtime') ) {
2185
2186     my $bill_error = _do_bop_realtime( $cust_main, $status );
2187
2188     if ($bill_error) {
2189       $newpkg[0]->suspend;
2190       return $bill_error;
2191     } else {
2192       $newpkg[0]->reexport;
2193     }
2194
2195   } else {  
2196     $newpkg[0]->reexport;
2197   }
2198
2199   return { error => '', pkgnum => $cust_pkg->pkgnum };
2200
2201 }
2202
2203 sub order_recharge {
2204   my $p = shift;
2205
2206   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2207   return { 'error' => $session } if $context eq 'error';
2208
2209   my $search = { 'custnum' => $custnum };
2210   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2211   my $cust_main = qsearchs('cust_main', $search )
2212     or return { 'error' => "unknown custnum $custnum" };
2213
2214   my $status = $cust_main->status;
2215   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2216     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2217
2218   my $svc_x = $cust_svc->svc_x;
2219   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2220
2221   my %vhash =
2222     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2223     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2224          recharge_totalbytes );
2225   my $amount = $part_pkg->option('recharge_amount', 1); 
2226   
2227   my ($l, $v, $d) = $cust_svc->label;  # blah
2228   my $pkg = "Recharge $v"; 
2229
2230   my $bill_error = $cust_main->charge($amount, $pkg,
2231      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2232      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2233      $part_pkg->taxclass); #meh
2234
2235   my $conf = new FS::Conf;
2236   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2237
2238     $bill_error = _do_bop_realtime( $cust_main, $status );
2239
2240     if ($bill_error) {
2241       return $bill_error;
2242     } else {
2243       my $error = $svc_x->recharge (\%vhash);
2244       return { 'error' => $error } if $error;
2245     }
2246
2247   } else {  
2248     my $error = $bill_error;
2249     $error ||= $svc_x->recharge (\%vhash);
2250     return { 'error' => $error } if $error;
2251   }
2252
2253   return { error => '', svc => $cust_svc->part_svc->svc };
2254
2255 }
2256
2257 sub _do_bop_realtime {
2258   my ($cust_main, $status) = (shift, shift);
2259
2260     my $old_balance = $cust_main->balance;
2261
2262     my $bill_error =    $cust_main->bill
2263                      || $cust_main->apply_payments_and_credits
2264                      || $cust_main->realtime_collect('selfservice' => 1);
2265
2266     if (    $cust_main->balance > $old_balance
2267          && $cust_main->balance > 0
2268          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2269               1 : $status eq 'suspended' ) ) {
2270       #this makes sense.  credit is "un-doing" the invoice
2271       my $conf = new FS::Conf;
2272       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2273                           'self-service decline',
2274                           'reason_type' => $conf->config('signup_credit_type'),
2275                         );
2276       $cust_main->apply_credits( 'order' => 'newest' );
2277
2278       return { 'error' => '_decline', 'bill_error' => $bill_error };
2279     }
2280
2281     '';
2282 }
2283
2284 sub renew_info {
2285   my $p = shift;
2286
2287   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2288   return { 'error' => $session } if $context eq 'error';
2289
2290   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2291     or return { 'error' => "unknown custnum $custnum" };
2292
2293   my @cust_pkg = sort { $a->bill <=> $b->bill }
2294                  grep { $_->part_pkg->freq ne '0' }
2295                  $cust_main->ncancelled_pkgs;
2296
2297   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2298
2299   my $total = $cust_main->balance;
2300
2301   my @array = map {
2302                     my $bill = $_->bill;
2303                     $total += $_->part_pkg->base_recur($_, \$bill);
2304                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2305                     {
2306                       'pkgnum'             => $_->pkgnum,
2307                       'amount'             => sprintf('%.2f', $total),
2308                       'bill_date'          => $_->bill,
2309                       'bill_date_pretty'   => time2str('%x', $_->bill),
2310                       'renew_date'         => $renew_date,
2311                       'renew_date_pretty'  => time2str('%x', $renew_date),
2312                       'expire_date'        => $_->expire,
2313                       'expire_date_pretty' => time2str('%x', $_->expire),
2314                     };
2315                   }
2316                   @cust_pkg;
2317
2318   return { 'dates' => \@array };
2319
2320 }
2321
2322 sub payment_info_renew_info {
2323   my $p = shift;
2324   my $renew_info   = renew_info($p);
2325   my $payment_info = payment_info($p);
2326   return { %$renew_info,
2327            %$payment_info,
2328          };
2329 }
2330
2331 sub order_renew {
2332   my $p = shift;
2333
2334   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2335   return { 'error' => $session } if $context eq 'error';
2336
2337   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2338     or return { 'error' => "unknown custnum $custnum" };
2339
2340   my $date = $p->{'date'};
2341
2342   my $now = time;
2343
2344   #freeside-daily -n -d $date fs_daily $custnum
2345   $cust_main->bill_and_collect( 'time'         => $date,
2346                                 'invoice_time' => $now,
2347                                 'actual_time'  => $now,
2348                                 'check_freq'   => '1d',
2349                               );
2350
2351   return { 'error' => '' };
2352
2353 }
2354
2355 sub suspend_pkg {
2356   my $p = shift;
2357   my $session = _cache->get($p->{'session_id'})
2358     or return { 'error' => "Can't resume session" }; #better error message
2359
2360   my $custnum = $session->{'custnum'};
2361
2362   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2363     or return { 'error' => "unknown custnum $custnum" };
2364
2365   my $conf = new FS::Conf;
2366   my $reasonnum = 
2367     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2368       or return { 'error' => 'Permission denied' };
2369
2370   my $pkgnum = $p->{'pkgnum'};
2371
2372   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2373                                         'pkgnum'  => $pkgnum,   } )
2374     or return { 'error' => "unknown pkgnum $pkgnum" };
2375
2376   my $error = $cust_pkg->suspend(reason => $reasonnum);
2377   return { 'error' => $error };
2378
2379 }
2380
2381 sub cancel_pkg {
2382   my $p = shift;
2383   my $session = _cache->get($p->{'session_id'})
2384     or return { 'error' => "Can't resume session" }; #better error message
2385
2386   my $custnum = $session->{'custnum'};
2387
2388   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2389     or return { 'error' => "unknown custnum $custnum" };
2390
2391   my $pkgnum = $p->{'pkgnum'};
2392
2393   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2394                                         'pkgnum'  => $pkgnum,   } )
2395     or return { 'error' => "unknown pkgnum $pkgnum" };
2396
2397   my $error = $cust_pkg->cancel('quiet' => 1);
2398   return { 'error' => $error };
2399
2400 }
2401
2402 sub provision_phone {
2403  my $p = shift;
2404  my @bulkdid;
2405  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2406
2407  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2408       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2409       return { 'error' => $session } if $context eq 'error';
2410     
2411       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2412       return { 'error' => 'service not found' } unless $svc_phone;
2413       return { 'error' => 'invalid svcnum' } 
2414         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2415
2416       $svc_phone->email($p->{'email'}) 
2417         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2418       $svc_phone->forwarddst($p->{'forwarddst'}) 
2419         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2420             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2421       return { 'error' => $svc_phone->replace };
2422  }
2423
2424 # single DID LNP
2425  unless($p->{'lnp'}) {
2426     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2427     $p->{'lnp_status'} = "portingin";
2428     return _provision( 'FS::svc_phone',
2429                   [qw(lnp_desired_due_date lnp_other_provider 
2430                     lnp_other_provider_account phonenum countrycode lnp_status)],
2431                   [qw(phonenum countrycode)],
2432                   $p,
2433                   @_
2434                 );
2435  }
2436
2437 # single DID order
2438  unless (scalar(@bulkdid)) {
2439     return _provision( 'FS::svc_phone',
2440                   [qw(phonenum countrycode)],
2441                   [qw(phonenum countrycode)],
2442                   $p,
2443                   @_
2444                 );
2445  }
2446
2447 # bulk DID order case
2448   my $error;
2449   foreach my $did ( @bulkdid ) {
2450     $did =~ s/[^0-9]//g;
2451     $error = _provision( 'FS::svc_phone',
2452               [qw(phonenum countrycode)],
2453               [qw(phonenum countrycode)],
2454               {
2455                 'pkgnum' => $p->{'pkgnum'},
2456                 'svcpart' => $p->{'svcpart'},
2457                 'phonenum' => $did,
2458                 'countrycode' => $p->{'countrycode'},
2459                 'session_id' => $p->{'session_id'},
2460               }
2461             );
2462     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2463   }
2464   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2465 }
2466
2467 sub provision_acct {
2468   my $p = shift;
2469   warn "provision_acct called\n"
2470     if $DEBUG;
2471
2472   return { 'error' => gettext('passwords_dont_match') }
2473     if $p->{'_password'} ne $p->{'_password2'};
2474   return { 'error' => gettext('empty_password') }
2475     unless length($p->{'_password'});
2476  
2477   if ($p->{'domsvc'}) {
2478     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2479                                                   qw ( svcpart pkgnum ) );
2480     return { 'error' => gettext('invalid_domain') }
2481       unless ($domains{$p->{'domsvc'}});
2482   }
2483
2484   warn "provision_acct calling _provision\n"
2485     if $DEBUG;
2486   _provision( 'FS::svc_acct',
2487               [qw(username _password domsvc)],
2488               [qw(username _password domsvc)],
2489               $p,
2490               @_
2491             );
2492 }
2493
2494 sub provision_external {
2495   my $p = shift;
2496   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2497   _provision( 'FS::svc_external',
2498               [],
2499               [qw(id title)],
2500               $p,
2501               @_
2502             );
2503 }
2504
2505 sub _provision {
2506   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2507   warn "_provision called for $class\n"
2508     if $DEBUG;
2509
2510   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2511   return { 'error' => $session } if $context eq 'error';
2512
2513   my $search = { 'custnum' => $custnum };
2514   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2515   my $cust_main = qsearchs('cust_main', $search )
2516     or return { 'error' => "unknown custnum $custnum" };
2517
2518   my $pkgnum = $p->{'pkgnum'};
2519
2520   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2521     if $DEBUG;
2522   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2523                                         'pkgnum'  => $pkgnum,
2524                                                                } )
2525     or return { 'error' => "unknown pkgnum $pkgnum" };
2526
2527   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2528     if $DEBUG;
2529   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2530     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2531
2532   warn "creating $class record\n"
2533     if $DEBUG;
2534   my $svc_x = $class->new( {
2535     'pkgnum'  => $p->{'pkgnum'},
2536     'svcpart' => $p->{'svcpart'},
2537     map { $_ => $p->{$_} } @$fields
2538   } );
2539   warn "inserting $class record\n"
2540     if $DEBUG;
2541   my $error = $svc_x->insert;
2542
2543   unless ( $error ) {
2544     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2545       if $DEBUG;
2546     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2547   }
2548
2549   my $return = { 'svc'   => $part_svc->svc,
2550                  'error' => $error,
2551                  map { $_ => $svc_x->get($_) } @$return_fields
2552                };
2553   warn "_provision returning ". Dumper($return). "\n"
2554     if $DEBUG;
2555   return $return;
2556
2557 }
2558
2559 sub part_svc_info {
2560   my $p = shift;
2561
2562   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2563   return { 'error' => $session } if $context eq 'error';
2564
2565   my $search = { 'custnum' => $custnum };
2566   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2567   my $cust_main = qsearchs('cust_main', $search )
2568     or return { 'error' => "unknown custnum $custnum" };
2569
2570   my $pkgnum = $p->{'pkgnum'};
2571
2572   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2573                                         'pkgnum'  => $pkgnum,
2574                                                                } )
2575     or return { 'error' => "unknown pkgnum $pkgnum" };
2576
2577   my $svcpart = $p->{'svcpart'};
2578
2579   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2580                                       'svcpart' => $svcpart,           } )
2581     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2582   my $part_svc = $pkg_svc->part_svc;
2583
2584   my $conf = new FS::Conf;
2585
2586   my $ret = {
2587     'svc'     => $part_svc->svc,
2588     'svcdb'   => $part_svc->svcdb,
2589     'pkgnum'  => $pkgnum,
2590     'svcpart' => $svcpart,
2591     'custnum' => $custnum,
2592
2593     'security_phrase' => 0, #XXX !
2594     'svc_acct_pop'    => [], #XXX !
2595     'popnum'          => '',
2596     'init_popstate'   => '',
2597     'popac'           => '',
2598     'acstate'         => '',
2599
2600     'small_custview' =>
2601       small_custview( $cust_main, $conf->config('countrydefault') ),
2602
2603   };
2604
2605   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2606                      && $ret->{'svcdb'} eq 'svc_phone') {
2607         $ret->{'svcnum'} = $p->{'svcnum'};
2608         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2609         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2610             $ret->{'email'} = $svc_phone->email;
2611             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2612         }
2613   }
2614
2615   $ret;
2616 }
2617
2618 sub unprovision_svc {
2619   my $p = shift;
2620
2621   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2622   return { 'error' => $session } if $context eq 'error';
2623
2624   my $search = { 'custnum' => $custnum };
2625   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2626   my $cust_main = qsearchs('cust_main', $search )
2627     or return { 'error' => "unknown custnum $custnum" };
2628
2629   my $svcnum = $p->{'svcnum'};
2630
2631   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2632     or return { 'error' => "unknown svcnum $svcnum" };
2633
2634   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2635     unless $cust_svc->cust_pkg->custnum == $custnum;
2636
2637   my $conf = new FS::Conf;
2638
2639   return { 'svc'   => $cust_svc->part_svc->svc,
2640            'error' => $cust_svc->cancel,
2641            'small_custview' =>
2642              small_custview( $cust_main, $conf->config('countrydefault') ),
2643          };
2644
2645 }
2646
2647 sub myaccount_passwd {
2648   my $p = shift;
2649   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2650   return { 'error' => $session } if $context eq 'error';
2651
2652   return { 'error' => "New passwords don't match." }
2653     if $p->{'new_password'} ne $p->{'new_password2'};
2654
2655   return { 'error' => 'Enter new password' }
2656     unless length($p->{'new_password'});
2657
2658   #my $search = { 'custnum' => $custnum };
2659   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2660   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2661   my $search = " AND custnum = $1";
2662   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2663
2664   my $svc_acct = qsearchs( {
2665     'table'     => 'svc_acct',
2666     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2667                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2668                    'LEFT JOIN cust_main USING ( custnum ) ',
2669     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2670     'extra_sql' => $search, #important
2671   } )
2672     or return { 'error' => "Service not found" };
2673
2674   if ( exists($p->{'old_password'}) ) {
2675     return { 'error' => "Incorrect password." }
2676       unless $svc_acct->check_password($p->{'old_password'});
2677   }
2678
2679   $svc_acct->set_password($p->{'new_password'});
2680   my $error = $svc_acct->replace();
2681
2682   my($label, $value) = $svc_acct->cust_svc->label;
2683
2684   return { 'error' => $error,
2685            'label' => $label,
2686            'value' => $value,
2687          };
2688
2689 }
2690
2691 sub reset_passwd {
2692   my $p = shift;
2693
2694   my $conf = new FS::Conf;
2695   my $verification = $conf->config('selfservice-password_reset_verification')
2696     or return { 'error' => 'Password resets disabled' };
2697
2698   my $username = $p->{'username'};
2699
2700   my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2701     or return { 'error' => 'Account not found' };
2702
2703   my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2704                                         'domsvc'   => $svc_domain->svcnum  }
2705                          )
2706     or return { 'error' => 'Account not found' };
2707
2708   my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2709     or return { 'error' => 'Account not found' };
2710
2711   my $cust_main = $cust_pkg->cust_main;
2712
2713   my %verify = (
2714     'paymask' => sub { 
2715       my( $p, $cust_main ) = @_;
2716       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2717         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2718     },
2719     'amount'  => sub {
2720       my( $p, $cust_main ) = @_;
2721       my $cust_pay = qsearchs({
2722         'table' => 'cust_pay',
2723         'hashref' => { 'custnum' => $cust_main->custnum },
2724         'order_by' => 'ORDER BY _date DESC LIMIT 1',
2725       })
2726         or return 0;
2727
2728       $p->{'amount'} == $cust_pay->paid;
2729     },
2730     'zip'     => sub {
2731       my( $p, $cust_main ) = @_;
2732       $p->{'zip'} eq $cust_main->zip
2733         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2734     },
2735   );
2736
2737   foreach my $verify ( split(',', $verification) ) {
2738
2739     &{ $verify{$verify} }( $p, $cust_main )
2740       or return { 'error' => 'Account not found' };
2741
2742   }
2743
2744   #okay, we're verified, now create a unique session
2745
2746   my $reset_session = {
2747     'svcnum' => $svc_acct->svcnum,
2748   };
2749
2750   my $timeout = '1 hour'; #?
2751
2752   my $reset_session_id;
2753   do {
2754     $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2755   } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2756
2757   _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2758
2759   #email it
2760
2761   my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2762   #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2763   return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2764   my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2765   my $error = $msg_template->send( 'cust_main'     => $cust_main,
2766                                    'object'        => $svc_acct,
2767                                    'substitutions' => {
2768                                      'session_id' => $reset_session_id,
2769                                    }
2770                                  );
2771   if ( $error ) {
2772     return { 'error' => $error }; #????
2773   }
2774
2775   return { 'error' => '' };
2776 }
2777
2778 sub check_reset_passwd {
2779   my $p = shift;
2780
2781   my $conf = new FS::Conf;
2782   my $verification = $conf->config('selfservice-password_reset_verification')
2783     or return { 'error' => 'Password resets disabled' };
2784
2785   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2786     or return { 'error' => "Can't resume session" }; #better error message
2787
2788   my $svcnum = $reset_session->{'svcnum'};
2789
2790   my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2791     or return { 'error' => "Service not found" };
2792
2793   return { 'error'    => '',
2794            'username' => $svc_acct->username,
2795          };
2796
2797 }
2798
2799 sub process_reset_passwd {
2800   my $p = shift;
2801
2802   my $conf = new FS::Conf;
2803   my $verification = $conf->config('selfservice-password_reset_verification')
2804     or return { 'error' => 'Password resets disabled' };
2805
2806   return { 'error' => "New passwords don't match." }
2807     if $p->{'new_password'} ne $p->{'new_password2'};
2808
2809   return { 'error' => 'Enter new password' }
2810     unless length($p->{'new_password'});
2811
2812   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2813     or return { 'error' => "Can't resume session" }; #better error message
2814
2815   my $svcnum = $reset_session->{'svcnum'};
2816
2817   my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2818     or return { 'error' => "Service not found" };
2819
2820   $svc_acct->set_password($p->{'new_password'});
2821   my $error = $svc_acct->replace();
2822
2823   my($label, $value) = $svc_acct->cust_svc->label;
2824
2825   return { 'error' => $error,
2826            #'label' => $label,
2827            #'value' => $value,
2828          };
2829
2830 }
2831
2832 sub create_ticket {
2833   my $p = shift;
2834   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2835   return { 'error' => $session } if $context eq 'error';
2836
2837   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2838   FS::TicketSystem->init();
2839
2840   my $conf = new FS::Conf;
2841   my $queue = $p->{'queue'}
2842               || $conf->config('ticket_system-selfservice_queueid')
2843               || $conf->config('ticket_system-default_queueid');
2844
2845   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2846   my $err_or_ticket = FS::TicketSystem->create_ticket(
2847     '', #create RT session based on FS CurrentUser (fs_selfservice)
2848     'queue'   => $queue,
2849     'custnum' => $custnum,
2850     'svcnum'  => $session->{'svcnum'},
2851     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2852   );
2853
2854   if ( ref($err_or_ticket) ) {
2855     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2856       if $DEBUG;
2857     return { 'error'     => '',
2858              'ticket_id' => $err_or_ticket->id,
2859            };
2860   } else {
2861     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2862       if $DEBUG;
2863     return { 'error' => $err_or_ticket };
2864   }
2865
2866
2867 }
2868
2869 sub did_report {
2870   my $p = shift;
2871   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872   return { 'error' => $session } if $context eq 'error';
2873  
2874   return { error => 'requested format not implemented' } 
2875     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2876
2877   my $conf = new FS::Conf;
2878   my $age_threshold = 0;
2879   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2880     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2881
2882   my $search = { 'custnum' => $custnum };
2883   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2884   my $cust_main = qsearchs('cust_main', $search )
2885     or return { 'error' => "unknown custnum $custnum" };
2886
2887 # does it make more sense to just run one sql query for this instead of all the
2888 # insanity below? would increase performance greately for large data sets?
2889   my @svc_phone = ();
2890   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2891         my @part_svc = $cust_pkg->part_svc;
2892         foreach my $part_svc ( @part_svc ) {
2893             if($part_svc->svcdb eq 'svc_phone'){
2894                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2895                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2896                     push @svc_phone, $cust_pkg_svc->svc_x
2897                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2898                 }
2899             }
2900         }
2901   }
2902
2903   my $csv;
2904   my $xls;
2905   my($xls_r,$xls_c) = (0,0);
2906   my $xls_workbook;
2907   my $content = '';
2908   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2909   if($p->{'format'} eq 'csv') {
2910     $csv = new Text::CSV_XS { 'always_quote' => 1,
2911                                  'eol'          => "\n",
2912                                 };
2913     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2914     $content .= $csv->string;
2915   }
2916   elsif($p->{'format'} eq 'xls') {
2917     my $XLS1 = new IO::Scalar \$content;
2918     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2919         or return { 'error' => "Error opening .xls file: $!" };
2920     $xls = $xls_workbook->add_worksheet('DIDs');
2921     foreach ( @fields ) {
2922         $xls->write(0,$xls_c++,$_);
2923     }
2924     $xls_r++;
2925   }
2926
2927   foreach my $svc_phone ( @svc_phone ) {
2928     my @cols = map { $svc_phone->$_ } @fields;
2929     if($p->{'format'} eq 'csv') {
2930         return { 'error' => 'Unable to create CSV' } 
2931             unless $csv->combine(@cols);
2932         $content .= $csv->string;
2933     }
2934     elsif($p->{'format'} eq 'xls') {
2935         $xls_c = 0;
2936         foreach ( @cols ) {
2937             $xls->write($xls_r,$xls_c++,$_);
2938         }
2939         $xls_r++;
2940     }
2941   }
2942
2943   $xls_workbook->close() if $p->{'format'} eq 'xls';
2944   
2945   { content => $content, format => $p->{'format'}, };
2946 }
2947
2948 sub get_ticket {
2949   my $p = shift;
2950   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2951   return { 'error' => $session } if $context eq 'error';
2952
2953   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2954   FS::TicketSystem->init();
2955   return { 'error' => 'get_ticket configuration error' }
2956     if $FS::TicketSystem::system ne 'RT_Internal';
2957
2958   # check existence and ownership as part of this
2959   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2960   my $rt_session = FS::TicketSystem->session('');
2961   my $Ticket = FS::TicketSystem->get_ticket_object(
2962     $rt_session, 
2963     ticket_id => $p->{'ticket_id'},
2964     custnum => $custnum
2965   );
2966   return { 'error' => 'ticket not found' } if !$Ticket;
2967
2968   if ( length( $p->{'subject'} || '' ) ) {
2969     # subject change
2970     if ( $p->{'subject'} ne $Ticket->Subject ) {
2971       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2972       return { 'error' => "unable to set subject: $msg" } if !$val;
2973     }
2974   }
2975
2976   if(length($p->{'reply'})) {
2977     my @err_or_res = FS::TicketSystem->correspond_ticket(
2978       $rt_session,
2979       'ticket_id' => $p->{'ticket_id'},
2980       'content' => $p->{'reply'},
2981     );
2982
2983     return { 'error' => 'unable to reply to ticket' } 
2984     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2985   }
2986
2987   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2988   my $err_or_ticket = FS::TicketSystem->get_ticket(
2989     $rt_session,
2990     'ticket_id' => $p->{'ticket_id'},
2991   );
2992
2993   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2994     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2995       if $DEBUG;
2996     return { 'error' => $err_or_ticket };
2997   }
2998
2999   my @custs = @{$err_or_ticket->{'custs'}};
3000   my @txns = @{$err_or_ticket->{'txns'}};
3001   my @filtered_txns;
3002
3003   # superseded by check in get_ticket_object
3004   #return { 'error' => 'invalid ticket requested' } 
3005   #unless grep($_ eq $custnum, @custs);
3006
3007   foreach my $txn ( @txns ) {
3008     push @filtered_txns, $txn 
3009     if ($txn->{'type'} eq 'EmailRecord' 
3010       || $txn->{'type'} eq 'Correspond'
3011       || $txn->{'type'} eq 'Create');
3012   }
3013
3014   warn "$me get_ticket: successful: \n"
3015   if $DEBUG;
3016   return { 'error'     => '',
3017     'transactions' => \@filtered_txns,
3018     'ticket_fields' => $err_or_ticket->{'fields'},
3019     'ticket_id' => $p->{'ticket_id'},
3020   };
3021 }
3022
3023 sub adjust_ticket_priority {
3024   my $p = shift;
3025   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3026   return { 'error' => $session } if $context eq 'error';
3027
3028   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3029   FS::TicketSystem->init;
3030   my $ss_priority = FS::TicketSystem->selfservice_priority;
3031
3032   return { 'error' => 'adjust_ticket_priority configuration error' }
3033     if $FS::TicketSystem::system ne 'RT_Internal'
3034       or !$ss_priority;
3035
3036   my $values = $p->{'values'}; #hashref, id => priority value
3037   my %ticket_error;
3038
3039   foreach my $id (keys %$values) {
3040     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3041     my $Ticket = FS::TicketSystem->get_ticket_object('',
3042       'ticket_id' => $id,
3043       'custnum'   => $custnum,
3044     );
3045     if ( !$Ticket ) {
3046       $ticket_error{$id} = 'ticket not found';
3047       next;
3048     }
3049     
3050   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3051   # We're not going to implement it for RT_External.
3052     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3053     my $new_value = $values->{$id};
3054     next if $old_value eq $new_value;
3055
3056     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3057
3058     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3059     # a single-valued custom field, which it should be.  If it's not, you're 
3060     # doing something wrong.
3061     my ($val, $msg);
3062     if ( length($new_value) ) {
3063       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3064         Field => $ss_priority,
3065         Value => $new_value,
3066       );
3067     }
3068     else {
3069       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3070         Field => $ss_priority,
3071         Value => $old_value,
3072       );
3073     }
3074
3075     $ticket_error{$id} = $msg if !$val;
3076     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3077   }
3078   return { 'error' => '',
3079            'ticket_error' => \%ticket_error,
3080            %{ customer_info($p) } # send updated customer info back
3081          }
3082 }
3083
3084 #--
3085
3086 sub _custoragent_session_custnum {
3087   my $p = shift;
3088
3089   my($context, $session, $custnum);
3090   if ( $p->{'session_id'} ) {
3091
3092     $context = 'customer';
3093     $session = _cache->get($p->{'session_id'})
3094       or return ( 'error' => "Can't resume session" ); #better error message
3095     $custnum = $session->{'custnum'};
3096
3097   } elsif ( $p->{'agent_session_id'} ) {
3098
3099     $context = 'agent';
3100     my $agent_cache = new FS::ClientAPI_SessionCache( {
3101       'namespace' => 'FS::ClientAPI::Agent',
3102     } );
3103     $session = $agent_cache->get($p->{'agent_session_id'})
3104       or return ( 'error' => "Can't resume session" ); #better error message
3105     $custnum = $p->{'custnum'};
3106
3107   } else {
3108     $context = 'error';
3109     return ( 'error' => "Can't resume session" ); #better error message
3110   }
3111
3112   ($context, $session, $custnum);
3113
3114 }
3115
3116 1;
3117