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