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