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