add month, year, address info to validate_payment selfservice API call, pkg_label...
[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     'month'          => $p->{'month'},
984     'year'           => $p->{'year'},
985     'payname'        => $payname,
986     'paybatch'       => $paybatch, #this doesn't actually do anything
987     'paycvv'         => $paycvv,
988     'payname'        => $payname,
989     'discount_term'  => $discount_term,
990     'pkgnum'         => $session->{'pkgnum'},
991     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
992                              qw( save auto ),
993                            )
994   };
995
996 }
997
998 sub store_payment {
999   my $p = shift;
1000
1001   my $validate = validate_payment($p);
1002   return $validate if $validate->{'error'};
1003
1004   my $conf = new FS::Conf;
1005   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1006   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1007
1008   +{ map { $_=>$validate->{$_} }
1009       qw( card_type paymask payname paydate_pretty month year amount
1010           address1 address2 city state zip country
1011         )
1012   };
1013
1014 }
1015
1016 sub process_stored_payment {
1017   my $p = shift;
1018
1019   my $session_id = $p->{'session_id'};
1020
1021   my $payment_info = _cache->get( "payment_$session_id" )
1022     or return { 'error' => "Can't resume session" }; #better error message
1023
1024   do_process_payment($payment_info);
1025
1026 }
1027
1028 sub process_payment {
1029   my $p = shift;
1030
1031   my $payment_info = validate_payment($p);
1032   return $payment_info if $payment_info->{'error'};
1033
1034   do_process_payment($payment_info);
1035
1036 }
1037
1038 sub do_process_payment {
1039   my $validate = shift;
1040
1041   my $cust_main = $validate->{'cust_main'};
1042
1043   my $amount = delete $validate->{'amount'};
1044   my $paynum = '';
1045
1046   my $payby = delete $validate->{'payby'};
1047
1048   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1049     'quiet'       => 1,
1050     'selfservice' => 1,
1051     'paynum_ref'  => \$paynum,
1052     %$validate,
1053   );
1054   return { 'error' => $error } if $error;
1055
1056   $cust_main->apply_payments;
1057
1058   if ( $validate->{'save'} ) {
1059     my $new = new FS::cust_main { $cust_main->hash };
1060     if ($payby eq 'CARD' || $payby eq 'DCRD') {
1061       $new->set( $_ => $validate->{$_} )
1062         foreach qw( payname paystart_month paystart_year payissue payip );
1063       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1064
1065       # Avoid accidentally changing the service address.
1066       if ( !$new->has_ship_address ) {
1067         $new->set( "ship_$_" => $new->get($_) ) 
1068           foreach $new->addr_fields;
1069       }
1070       $new->set( $_ => $validate->{$_} )
1071         foreach qw(address1 address2 city state country zip);
1072
1073     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1074       $new->set( $_ => $validate->{$_} )
1075         foreach qw( payname payip paytype paystate
1076                     stateid stateid_state );
1077       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1078     }
1079     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1080     $new->set( 'paydate' => $validate->{'paydate'} );
1081     my $error = $new->replace($cust_main);
1082     if ( $error ) {
1083       #no, this causes customers to process their payments again
1084       #return { 'error' => $error };
1085       #XXX just warn verosely for now so i can figure out how these happen in
1086       # the first place, eventually should redirect them to the "change
1087       #address" page but indicate the payment did process??
1088       delete($validate->{'payinfo'}); #don't want to log this!
1089       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1090            "NEW: ". Dumper($new)."\n".
1091            "OLD: ". Dumper($cust_main)."\n".
1092            "PACKET: ". Dumper($validate)."\n";
1093     #} else {
1094       #not needed...
1095       #$cust_main = $new;
1096     }
1097   }
1098
1099   my $cust_pay = '';
1100   my $receipt_html = '';
1101   if ($paynum) {
1102       # currently supported for realtime CC only; send receipt data to SS
1103       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1104       if($cust_pay) {
1105         $receipt_html = qq!
1106 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1107
1108 <TR>
1109   <TD ALIGN="right">Payment#</TD>
1110   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1111 </TR>
1112
1113 <TR>
1114   <TD ALIGN="right">Date</TD>
1115
1116   <TD BGCOLOR="#FFFFFF"><B>! . 
1117         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1118                                                             . qq!</B></TD>
1119 </TR>
1120
1121
1122 <TR>
1123   <TD ALIGN="right">Amount</TD>
1124   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1125
1126 </TR>
1127
1128 <TR>
1129   <TD ALIGN="right">Payment method</TD>
1130   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1131                                                                 . qq!</B></TD>
1132 </TR>
1133
1134 </TABLE>
1135 !;
1136       }
1137   }
1138
1139   if ( $cust_pay ) {
1140
1141     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1142
1143     return {
1144       'error'        => '',
1145       'amount'       => sprintf('%.2f', $cust_pay->paid),
1146       'date'         => $cust_pay->_date,
1147       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1148       'time_pretty'  => time2str('%T', $cust_pay->_date),
1149       'auth_num'     => $auth,
1150       'order_num'    => $order,
1151       'receipt_html' => $receipt_html,
1152     };
1153
1154   } else {
1155
1156     return {
1157       'error'        => '',
1158       'receipt_html' => '',
1159     };
1160
1161   }
1162
1163 }
1164
1165 sub realtime_collect {
1166   my $p = shift;
1167
1168   my $session = _cache->get($p->{'session_id'})
1169     or return { 'error' => "Can't resume session" }; #better error message
1170
1171   my $custnum = $session->{'custnum'};
1172
1173   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1174     or return { 'error' => "unknown custnum $custnum" };
1175
1176   my $amount;
1177   if ( $p->{'amount'} ) {
1178     $amount = $p->{'amount'};
1179   }
1180   elsif ( $session->{'pkgnum'} ) {
1181     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1182   }
1183   else {
1184     $amount = $cust_main->balance;
1185   }
1186
1187   my $error = $cust_main->realtime_collect(
1188     'method'     => $p->{'method'},
1189     'amount'     => $amount,
1190     'pkgnum'     => $session->{'pkgnum'},
1191     'session_id' => $p->{'session_id'},
1192     'apply'      => 1,
1193     'selfservice'=> 1,
1194   );
1195   return { 'error' => $error } unless ref( $error );
1196
1197   return { 'error' => '', amount => $amount, %$error };
1198 }
1199
1200 sub process_payment_order_pkg {
1201   my $p = shift;
1202
1203   my $hr = process_payment($p);
1204   return $hr if $hr->{'error'};
1205
1206   order_pkg($p);
1207 }
1208
1209 sub process_payment_order_renew {
1210   my $p = shift;
1211
1212   my $hr = process_payment($p);
1213   return $hr if $hr->{'error'};
1214
1215   order_renew($p);
1216 }
1217
1218 sub process_prepay {
1219
1220   my $p = shift;
1221
1222   my $session = _cache->get($p->{'session_id'})
1223     or return { 'error' => "Can't resume session" }; #better error message
1224
1225   my %return;
1226
1227   my $custnum = $session->{'custnum'};
1228
1229   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1230     or return { 'error' => "unknown custnum $custnum" };
1231
1232   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1233   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1234                                            \$amount,
1235                                            \$seconds,
1236                                            \$upbytes,
1237                                            \$downbytes,
1238                                            \$totalbytes,
1239                                          );
1240
1241   return { 'error' => $error } if $error;
1242
1243   return { 'error'     => '',
1244            'amount'    => $amount,
1245            'seconds'   => $seconds,
1246            'duration'  => duration_exact($seconds),
1247            'upbytes'   => $upbytes,
1248            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1249            'downbytes' => $downbytes,
1250            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1251            'totalbytes'=> $totalbytes,
1252            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1253          };
1254
1255 }
1256
1257 sub invoice {
1258   my $p = shift;
1259   my $session = _cache->get($p->{'session_id'})
1260     or return { 'error' => "Can't resume session" }; #better error message
1261
1262   my $custnum = $session->{'custnum'};
1263
1264   my $invnum = $p->{'invnum'};
1265
1266   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1267                                           'custnum' => $custnum } )
1268     or return { 'error' => "Can't find invnum" };
1269
1270   #my %return;
1271
1272   return { 'error'        => '',
1273            'invnum'       => $invnum,
1274            'invoice_text' => join('', $cust_bill->print_text ),
1275            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1276          };
1277
1278 }
1279
1280 sub invoice_pdf {
1281   my $p = shift;
1282   my $session = _cache->get($p->{'session_id'})
1283     or return { 'error' => "Can't resume session" }; #better error message
1284
1285   my $custnum = $session->{'custnum'};
1286
1287   my $invnum = $p->{'invnum'};
1288
1289   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1290                                           'custnum' => $custnum } )
1291     or return { 'error' => "Can't find invnum" };
1292
1293   #my %return;
1294
1295   return { 'error'       => '',
1296            'invnum'      => $invnum,
1297            'invoice_pdf' => $cust_bill->print_pdf({
1298                               'unsquelch_cdr' => 1,
1299                               'locale'        => $p->{'locale'},
1300                             }),
1301          };
1302
1303 }
1304
1305 sub legacy_invoice {
1306   my $p = shift;
1307   my $session = _cache->get($p->{'session_id'})
1308     or return { 'error' => "Can't resume session" }; #better error message
1309
1310   my $custnum = $session->{'custnum'};
1311
1312   my $legacyinvnum = $p->{'legacyinvnum'};
1313
1314   my %hash = (
1315     'legacyinvnum' => $legacyinvnum,
1316     'custnum'      => $custnum,
1317   );
1318
1319   my $legacy_cust_bill =
1320          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1321       || qsearchs('legacy_cust_bill', \%hash )
1322     or return { 'error' => "Can't find legacyinvnum" };
1323
1324   #my %return;
1325
1326   return { 'error'        => '',
1327            'legacyinvnum' => $legacyinvnum,
1328            'legacyid'     => $legacy_cust_bill->legacyid,
1329            'invoice_html' => $legacy_cust_bill->content_html,
1330          };
1331
1332 }
1333
1334 sub legacy_invoice_pdf {
1335   my $p = shift;
1336   my $session = _cache->get($p->{'session_id'})
1337     or return { 'error' => "Can't resume session" }; #better error message
1338
1339   my $custnum = $session->{'custnum'};
1340
1341   my $legacyinvnum = $p->{'legacyinvnum'};
1342
1343   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1344     'legacyinvnum' => $legacyinvnum,
1345     'custnum'      => $custnum,
1346   }) or return { 'error' => "Can't find legacyinvnum" };
1347
1348   #my %return;
1349
1350   return { 'error'        => '',
1351            'legacyinvnum' => $legacyinvnum,
1352            'legacyid'     => $legacy_cust_bill->legacyid,
1353            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1354          };
1355
1356 }
1357
1358 sub invoice_logo {
1359   my $p = shift;
1360
1361   #sessioning for this?  how do we get the session id to the backend invoice
1362   # template so it can add it to the link, blah
1363
1364   my $agentnum = '';
1365   if ( $p->{'invnum'} ) {
1366     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1367       or return { 'error' => 'unknown invnum' };
1368     $agentnum = $cust_bill->cust_main->agentnum;
1369   }
1370
1371   my $templatename = $p->{'template'} || $p->{'templatename'};
1372
1373   #false laziness-ish w/view/cust_bill-logo.cgi
1374
1375   my $conf = new FS::Conf;
1376   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1377     $templatename = "_$1";
1378   } else {
1379     $templatename = '';
1380   }
1381
1382   my $filename = "logo$templatename.png";
1383
1384   return { 'error'        => '',
1385            'logo'         => $conf->config_binary($filename, $agentnum),
1386            'content_type' => 'image/png', #should allow gif, jpg too
1387          };
1388 }
1389
1390
1391 sub list_invoices {
1392   my $p = shift;
1393   my $session = _cache->get($p->{'session_id'})
1394     or return { 'error' => "Can't resume session" }; #better error message
1395
1396   my $custnum = $session->{'custnum'};
1397
1398   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1399     or return { 'error' => "unknown custnum $custnum" };
1400
1401   my $conf = new FS::Conf;
1402
1403   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1404
1405   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1406
1407   my $balance = 0;
1408
1409   return  { 'error'       => '',
1410             'balance'     => $cust_main->balance,
1411             'invoices'    => [
1412               map {
1413                     my $owed = $_->owed;
1414                     $balance += $owed;
1415                     +{ 'invnum'       => $_->invnum,
1416                        '_date'        => $_->_date,
1417                        'date'         => time2str("%b %o, %Y", $_->_date),
1418                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1419                        'previous'     => sprintf('%.2f', ($_->previous)[0]),
1420                        'charged'      => sprintf('%.2f', $_->charged),
1421                        'owed'         => sprintf('%.2f', $owed),
1422                        'balance'      => sprintf('%.2f', $balance),
1423                      }
1424                   }
1425                   @cust_bill
1426             ],
1427             'legacy_invoices' => [
1428               map {
1429                     +{ 'legacyinvnum' => $_->legacyinvnum,
1430                        'legacyid'     => $_->legacyid,
1431                        '_date'        => $_->_date,
1432                        'date'         => time2str("%b %o, %Y", $_->_date),
1433                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1434                        'charged'      => sprintf('%.2f', $_->charged),
1435                        'has_content'  => (    length($_->content_pdf)
1436                                            || length($_->content_html) ),
1437                      }
1438                   }
1439                   @legacy_cust_bill
1440             ],
1441           };
1442 }
1443
1444 sub cancel {
1445   my $p = shift;
1446   my $session = _cache->get($p->{'session_id'})
1447     or return { 'error' => "Can't resume session" }; #better error message
1448
1449   my $custnum = $session->{'custnum'};
1450
1451   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1452     or return { 'error' => "unknown custnum $custnum" };
1453
1454   my @errors = $cust_main->cancel( 'quiet'=>1 );
1455
1456   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1457
1458   return { 'error' => $error };
1459
1460 }
1461
1462 sub list_pkgs {
1463   my $p = shift;
1464
1465   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1466   return { 'error' => $session } if $context eq 'error';
1467
1468   my $search = { 'custnum' => $custnum };
1469   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1470   my $cust_main = qsearchs('cust_main', $search )
1471     or return { 'error' => "unknown custnum $custnum" };
1472
1473   my $conf = new FS::Conf;
1474   
1475 # the duplication below is necessary:
1476 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1477 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1478 # non-backwards-compatible change breaking the software of anyone using the API
1479 # instead of the stock selfservice
1480 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1481   if( $conf->exists('selfservice_server-view-wholesale') ) {
1482     return { 'svcnum'   => $session->{'svcnum'},
1483             'custnum'  => $custnum,
1484             'cust_pkg' => [ map {
1485                           { $_->hash,
1486                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1487                             part_svc =>
1488                               [ map $_->hashref, $_->available_part_svc ],
1489                             cust_svc => 
1490                               [ map { my $ref = { $_->hash,
1491                                                   label => [ $_->label ],
1492                                                 };
1493                                       $ref->{_password} = $_->svc_x->_password
1494                                         if $context eq 'agent'
1495                                         && $conf->exists('agent-showpasswords')
1496                                         && $_->part_svc->svcdb eq 'svc_acct';
1497                                       $ref;
1498                                     } $_->cust_svc
1499                               ],
1500                           };
1501                         } $cust_main->cust_pkg
1502                   ],
1503     'small_custview' =>
1504       small_custview( $cust_main, $conf->config('countrydefault') ),
1505     'wholesale_view' => 1,
1506     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1507     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1508     'lnp' => $conf->exists('svc_phone-lnp'),
1509       };
1510   }
1511
1512   { 'svcnum'   => $session->{'svcnum'},
1513     'custnum'  => $custnum,
1514     'cust_pkg' => [ map {
1515                           my $primary_cust_svc = $_->primary_cust_svc;
1516                           +{ $_->hash,
1517                             $_->part_pkg->hash,
1518                             pkg_label => $_->pkg_label,
1519                             status => $_->status,
1520                             part_svc =>
1521                               [ map $_->hashref, $_->available_part_svc ],
1522                             cust_svc => 
1523                               [ map { my $ref = { $_->hash,
1524                                                   label => [ $_->label ],
1525                                                 };
1526                                       $ref->{_password} = $_->svc_x->_password
1527                                         if $context eq 'agent'
1528                                         && $conf->exists('agent-showpasswords')
1529                                         && $_->part_svc->svcdb eq 'svc_acct';
1530                                       $ref->{svchash} = { $_->svc_x->hash } if 
1531                                         $_->part_svc->svcdb eq 'svc_phone';
1532                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1533                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1534                                       $ref;
1535                                     } $_->cust_svc
1536                               ],
1537                             primary_cust_svc =>
1538                               $primary_cust_svc
1539                                 ? { $primary_cust_svc->hash,
1540                                     label => [ $primary_cust_svc->label ],
1541                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1542                                     $primary_cust_svc->part_svc->hash,
1543                                   }
1544                                 : {}, #'' ?
1545                           };
1546                         } $cust_main->ncancelled_pkgs
1547                   ],
1548     'small_custview' =>
1549       small_custview( $cust_main, $conf->config('countrydefault') ),
1550   };
1551
1552 }
1553
1554 sub list_svcs {
1555   my $p = shift;
1556
1557   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1558   return { 'error' => $session } if $context eq 'error';
1559
1560   my $search = { 'custnum' => $custnum };
1561   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1562   my $cust_main = qsearchs('cust_main', $search )
1563     or return { 'error' => "unknown custnum $custnum" };
1564
1565   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1566   if ( ! $pkgnum && $p->{'svcnum'} ) {
1567     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1568     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1569   }
1570
1571   my @cust_svc = ();
1572   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1573   foreach my $cust_pkg ( $p->{'ncancelled'} 
1574                          ? $cust_main->ncancelled_pkgs
1575                          : $cust_main->unsuspended_pkgs ) {
1576     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1577     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1578   }
1579
1580   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1581
1582   if ( $p->{'svcdb'} ) {
1583     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1584                   ? $p->{'svcdb'}
1585                   : ref($p->{'svcdb'}) eq 'ARRAY'
1586                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1587                     : { $p->{'svcdb'} => 1 };
1588     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1589   }
1590
1591   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1592   #              @svc_x;
1593
1594     my $conf = new FS::Conf;
1595
1596   { 
1597     'svcnum'   => $session->{'svcnum'},
1598     'custnum'  => $custnum,
1599     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1600     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1601     'svcs'     => [
1602       map { 
1603             my $svc_x = $_->svc_x;
1604             my($label, $value) = $_->label;
1605             my $part_svc = $_->part_svc;
1606             my $svcdb = $part_svc->svcdb;
1607             my $cust_pkg = $_->cust_pkg;
1608             my $part_pkg = $cust_pkg->part_pkg;
1609
1610             my %hash = (
1611               'svcnum'         => $_->svcnum,
1612               'display_svcnum' => $_->display_svcnum,
1613               'svcdb'          => $svcdb,
1614               'label'          => $label,
1615               'value'          => $value,
1616               'pkg_label'      => $cust_pkg->pkg_label,
1617               'pkg_status'     => $cust_pkg->status,
1618               'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
1619             );
1620
1621             if ( $svcdb eq 'svc_acct' ) {
1622               %hash = (
1623                 %hash,
1624                 'username'   => $svc_x->username,
1625                 'email'      => $svc_x->email,
1626                 'finger'     => $svc_x->finger,
1627                 'seconds'    => $svc_x->seconds,
1628                 'upbytes'    => display_bytecount($svc_x->upbytes),
1629                 'downbytes'  => display_bytecount($svc_x->downbytes),
1630                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1631
1632                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1633                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1634                 'recharge_upbytes'    =>
1635                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1636                 'recharge_downbytes'  =>
1637                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1638                 'recharge_totalbytes' =>
1639                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1640                 # more...
1641               );
1642
1643             } elsif ( $svcdb eq 'svc_dsl' ) {
1644               $hash{'phonenum'} = $svc_x->phonenum;
1645               if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1646                 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1647                 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1648                   if $svc_x->company;
1649               } else {
1650                 $hash{'name'} = $cust_main->name;
1651               }
1652             }
1653             # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1654             #  %hash = (
1655             #    %hash,
1656             #  );
1657             #}
1658
1659             \%hash;
1660           }
1661           @cust_svc
1662     ],
1663   };
1664
1665 }
1666
1667 sub _customer_svc_x {
1668   my($custnum, $svcnum, $table) = (shift, shift, shift);
1669   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1670
1671   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1672   my $search = " AND custnum = $1";
1673   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1674
1675   qsearchs( {
1676     'table'     => ($table || 'svc_acct'),
1677     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1678                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1679                    #'LEFT JOIN cust_main USING ( custnum ) ',
1680     'hashref'   => $hashref,
1681     'extra_sql' => $search, #important
1682   } );
1683
1684 }
1685
1686 sub svc_status_html {
1687   my $p = shift;
1688
1689   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1690   return { 'error' => $session } if $context eq 'error';
1691
1692   #XXX only svc_dsl for now
1693   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1694     or return { 'error' => "Service not found" };
1695
1696   my $html = $svc_x->getstatus_html;
1697
1698   return { 'html' => $html };
1699
1700 }
1701
1702 sub svc_status_hash {
1703   my $p = shift;
1704
1705   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1706   return { 'error' => $session } if $context eq 'error';
1707
1708   #XXX only svc_acct for now
1709   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1710     or return { 'error' => "Service not found" };
1711
1712   my ( $html, $hashref ) = $svc_x->export_getstatus;
1713   return $hashref;
1714
1715 }
1716
1717 sub set_svc_status_hash {
1718   my $p = shift;
1719
1720   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1721   return { 'error' => $session } if $context eq 'error';
1722
1723   #XXX only svc_acct for now
1724   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1725     or return { 'error' => "Service not found" };
1726
1727   warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1728     if $DEBUG;
1729   my $error = $svc_x->export_setstatus($p); #$p? returns error?
1730   return { 'error' => $error } if $error;
1731
1732   return {}; #? { 'error' => '' }
1733
1734 }
1735
1736
1737 sub acct_forward_info {
1738   my $p = shift;
1739
1740   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1741   return { 'error' => $session } if $context eq 'error';
1742
1743   my $svc_forward = _customer_svc_x( $custnum,
1744                                      { 'srcsvc' => $p->{'svcnum'} },
1745                                      'svc_forward',
1746                                    )
1747     or return { 'error' => '',
1748                 'dst'   => '',
1749               };
1750
1751   return { 'error' => '',
1752            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1753          };
1754
1755 }
1756
1757 sub process_acct_forward {
1758   my $p = shift;
1759   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1760   return { 'error' => $session } if $context eq 'error';
1761
1762   my $old = _customer_svc_x( $custnum,
1763                              { 'srcsvc' => $p->{'svcnum'} },
1764                              'svc_forward',
1765                            );
1766
1767   if ( $p->{'dst'} eq '' ) {
1768     if ( $old ) {
1769       my $error = $old->delete;
1770       return { 'error' => $error };
1771     }
1772     return { 'error' => '' };
1773   }
1774
1775   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1776                                   'dst'    => $p->{'dst'},
1777                                 };
1778
1779   my $error;
1780   if ( $old ) {
1781     $new->svcnum($old->svcnum);
1782     my $cust_svc = $old->cust_svc;
1783     $new->svcpart($old->svcpart);
1784     $new->pkgnuym($old->pkgnum);
1785     $error = $new->replace($old);
1786   } else {
1787     my $conf = new FS::Conf;
1788     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1789
1790     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1791       or return { 'error' => 'No service' }; #how would we even get here?
1792
1793     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1794
1795     $error = $new->insert;
1796   }
1797
1798   return { 'error' => $error };
1799
1800 }
1801
1802 sub list_dsl_devices {
1803   my $p = shift;
1804
1805   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1806   return { 'error' => $session } if $context eq 'error';
1807
1808   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1809     or return { 'error' => "Service not found" };
1810
1811   return {
1812     'devices' => [ map {
1813                          +{ 'mac_addr' => $_->mac_addr };
1814                        } $svc_dsl->dsl_device
1815                  ],
1816   };
1817
1818 }
1819
1820 sub add_dsl_device {
1821   my $p = shift;
1822
1823   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1824   return { 'error' => $session } if $context eq 'error';
1825
1826   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1827     or return { 'error' => "Service not found" };
1828
1829   return { 'error' => 'No MAC address supplied' }
1830     unless length($p->{'mac_addr'});
1831
1832   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
1833                                         'mac_addr' => scalar($p->{'mac_addr'}),
1834                                       };
1835   my $error = $dsl_device->insert;
1836   return { 'error' => $error };
1837
1838 }
1839
1840 sub delete_dsl_device {
1841   my $p = shift;
1842
1843   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1844   return { 'error' => $session } if $context eq 'error';
1845
1846   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1847     or return { 'error' => "Service not found" };
1848
1849   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
1850                                             'mac_addr' => scalar($p->{'mac_addr'}),
1851                                           }
1852                            )
1853     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1854
1855   my $error = $dsl_device->delete;
1856   return { 'error' => $error };
1857
1858 }
1859
1860 sub port_graph {
1861   my $p = shift;
1862   _usage_details( \&_port_graph, $p,
1863                   'svcdb' => 'svc_port',
1864                 );
1865 }
1866
1867 sub _port_graph {
1868   my($svc_port, $begin, $end) = @_;
1869   my @usage = ();
1870   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1871   push @usage, { 'png' => $pngOrError };
1872   (@usage);
1873 }
1874
1875 sub _list_svc_usage {
1876   my($svc_acct, $begin, $end) = @_;
1877   my @usage = ();
1878   foreach my $part_export ( 
1879     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1880     qw( sqlradius sqlradius_withdomain )
1881   ) {
1882     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1883   }
1884   (@usage);
1885 }
1886
1887 sub list_svc_usage {
1888   _usage_details(\&_list_svc_usage, @_);
1889 }
1890
1891 sub _list_support_usage {
1892   my($svc_acct, $begin, $end) = @_;
1893   my @usage = ();
1894   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1895             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1896           ) {
1897     push @usage, { 'seconds'  => $_->seconds,
1898                    'support'  => $_->support,
1899                    '_date'    => $_->_date,
1900                    'id'       => $_->transaction_id,
1901                    'creator'  => $_->creator,
1902                    'subject'  => $_->subject,
1903                    'status'   => $_->status,
1904                    'ticketid' => $_->ticketid,
1905                  };
1906   }
1907   (@usage);
1908 }
1909
1910 sub list_support_usage {
1911   _usage_details(\&_list_support_usage, @_);
1912 }
1913
1914 sub _list_cdr_usage {
1915   # XXX CDR type support...
1916   my($svc_phone, $begin, $end, %opt) = @_;
1917   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1918     $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1919 }
1920
1921 sub list_cdr_usage {
1922   my $p = shift;
1923   _usage_details( \&_list_cdr_usage, $p,
1924                   'svcdb' => 'svc_phone',
1925                 );
1926 }
1927
1928 sub _usage_details {
1929   my($callback, $p, %opt) = @_;
1930
1931   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1932   return { 'error' => $session } if $context eq 'error';
1933
1934   my $search = { 'svcnum' => $p->{'svcnum'} };
1935   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1936
1937   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1938
1939   my $svc_x = qsearchs( $svcdb, $search );
1940   return { 'error' => 'No service selected in list_svc_usage' } 
1941     unless $svc_x;
1942
1943   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1944   my $freq     = $cust_pkg->part_pkg->freq;
1945   my %callback_opt;
1946   my $header = [];
1947   if ( $svcdb eq 'svc_phone' ) {
1948     my $format   = $cust_pkg->part_pkg->option('output_format') || '';
1949     $format = '' if $format =~ /^sum_/;
1950     # sensible default if there is no format or it's a summary format
1951     if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
1952       $format ||= 'source_default';
1953       $callback_opt{inbound} = 1;
1954     }
1955     else {
1956       $format ||= 'default';
1957     }
1958     
1959     $callback_opt{format} = $format;
1960     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
1961   }
1962
1963   my $start    = $cust_pkg->setup;
1964   #my $end      = $cust_pkg->bill; # or time?
1965   my $end      = time;
1966
1967   unless ( $p->{beginning} ) {
1968     $p->{beginning} = $cust_pkg->last_bill;
1969     $p->{ending}    = $end;
1970   }
1971
1972   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
1973     %callback_opt
1974   );
1975
1976   #kinda false laziness with FS::cust_main::bill, but perhaps
1977   #we should really change this bit to DateTime and DateTime::Duration
1978   #
1979   #change this bit to use Date::Manip? CAREFUL with timezones (see
1980   # mailing list archive)
1981   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1982     (localtime($p->{ending}) )[0,1,2,3,4,5];
1983   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1984     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1985
1986   if ( $freq =~ /^\d+$/ ) {
1987     $nmon += $freq;
1988     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1989     $pmon -= $freq;
1990     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1991   } elsif ( $freq =~ /^(\d+)w$/ ) {
1992     my $weeks = $1;
1993     $nmday += $weeks * 7;
1994     $pmday -= $weeks * 7;
1995   } elsif ( $freq =~ /^(\d+)d$/ ) {
1996     my $days = $1;
1997     $nmday += $days;
1998     $pmday -= $days;
1999   } elsif ( $freq =~ /^(\d+)h$/ ) {
2000     my $hours = $1;
2001     $nhour += $hours;
2002     $phour -= $hours;
2003   } else {
2004     return { 'error' => "unparsable frequency: ". $freq };
2005   }
2006   
2007   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2008   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2009
2010   { 
2011     'error'     => '',
2012     'svcnum'    => $p->{svcnum},
2013     'beginning' => $p->{beginning},
2014     'ending'    => $p->{ending},
2015     'previous'  => ($previous > $start) ? $previous : $start,
2016     'next'      => ($next < $end) ? $next : $end,
2017     'header'    => $header,
2018     'usage'     => \@usage,
2019   };
2020 }
2021
2022 sub order_pkg {
2023   my $p = shift;
2024
2025   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2026   return { 'error' => $session } if $context eq 'error';
2027
2028   my $search = { 'custnum' => $custnum };
2029   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2030   my $cust_main = qsearchs('cust_main', $search )
2031     or return { 'error' => "unknown custnum $custnum" };
2032
2033   my $status = $cust_main->status;
2034   #false laziness w/ClientAPI/Signup.pm
2035
2036   my $cust_pkg = new FS::cust_pkg ( {
2037     'custnum' => $custnum,
2038     'pkgpart' => $p->{'pkgpart'},
2039   } );
2040   my $error = $cust_pkg->check;
2041   return { 'error' => $error } if $error;
2042
2043   my @svc = ();
2044   unless ( $p->{'svcpart'} eq 'none' ) {
2045
2046     my $svcdb;
2047     my $svcpart = '';
2048     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2049       $svcpart = $1;
2050       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2051       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2052       $svcdb = $part_svc->svcdb;
2053     } else {
2054       $svcdb = 'svc_acct';
2055     }
2056     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2057
2058     my %fields = (
2059       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2060       'svc_domain'   => [ qw( domain ) ],
2061       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2062       'svc_external' => [ qw( id title ) ],
2063       'svc_pbx'      => [ qw( id title ) ],
2064     );
2065   
2066     my $svc_x = "FS::$svcdb"->new( {
2067       'svcpart'   => $svcpart,
2068       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2069     } );
2070     
2071     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2072       my @acct_snarf;
2073       my $snarfnum = 1;
2074       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2075         my $acct_snarf = new FS::acct_snarf ( {
2076           'machine'   => $p->{"snarf_machine$snarfnum"},
2077           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2078           'username'  => $p->{"snarf_username$snarfnum"},
2079           '_password' => $p->{"snarf_password$snarfnum"},
2080         } );
2081         $snarfnum++;
2082         push @acct_snarf, $acct_snarf;
2083       }
2084       $svc_x->child_objects( \@acct_snarf );
2085     }
2086     
2087     my $y = $svc_x->setdefault; # arguably should be in new method
2088     return { 'error' => $y } if $y && !ref($y);
2089   
2090     $error = $svc_x->check;
2091     return { 'error' => $error } if $error;
2092
2093     push @svc, $svc_x;
2094
2095   }
2096
2097   use Tie::RefHash;
2098   tie my %hash, 'Tie::RefHash';
2099   %hash = ( $cust_pkg => \@svc );
2100   #msgcat
2101   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2102   return { 'error' => $error } if $error;
2103
2104   my $conf = new FS::Conf;
2105   if ( $conf->exists('signup_server-realtime') ) {
2106
2107     my $bill_error = _do_bop_realtime( $cust_main, $status );
2108
2109     if ($bill_error) {
2110       $cust_pkg->cancel('quiet'=>1);
2111       return $bill_error;
2112     } else {
2113       $cust_pkg->reexport;
2114     }
2115
2116   } else {
2117     $cust_pkg->reexport;
2118   }
2119
2120   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2121
2122   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2123
2124 }
2125
2126 sub change_pkg {
2127   my $p = shift;
2128
2129   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2130   return { 'error' => $session } if $context eq 'error';
2131
2132   my $search = { 'custnum' => $custnum };
2133   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2134   my $cust_main = qsearchs('cust_main', $search )
2135     or return { 'error' => "unknown custnum $custnum" };
2136
2137   my $status = $cust_main->status;
2138   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2139     or return { 'error' => "unknown package $p->{pkgnum}" };
2140
2141   my @newpkg;
2142   my $error = FS::cust_pkg::order( $custnum,
2143                                    [$p->{pkgpart}],
2144                                    [$p->{pkgnum}],
2145                                    \@newpkg,
2146                                  );
2147
2148   my $conf = new FS::Conf;
2149   if ( $conf->exists('signup_server-realtime') ) {
2150
2151     my $bill_error = _do_bop_realtime( $cust_main, $status );
2152
2153     if ($bill_error) {
2154       $newpkg[0]->suspend;
2155       return $bill_error;
2156     } else {
2157       $newpkg[0]->reexport;
2158     }
2159
2160   } else {  
2161     $newpkg[0]->reexport;
2162   }
2163
2164   return { error => '', pkgnum => $cust_pkg->pkgnum };
2165
2166 }
2167
2168 sub order_recharge {
2169   my $p = shift;
2170
2171   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2172   return { 'error' => $session } if $context eq 'error';
2173
2174   my $search = { 'custnum' => $custnum };
2175   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2176   my $cust_main = qsearchs('cust_main', $search )
2177     or return { 'error' => "unknown custnum $custnum" };
2178
2179   my $status = $cust_main->status;
2180   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2181     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2182
2183   my $svc_x = $cust_svc->svc_x;
2184   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2185
2186   my %vhash =
2187     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2188     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2189          recharge_totalbytes );
2190   my $amount = $part_pkg->option('recharge_amount', 1); 
2191   
2192   my ($l, $v, $d) = $cust_svc->label;  # blah
2193   my $pkg = "Recharge $v"; 
2194
2195   my $bill_error = $cust_main->charge($amount, $pkg,
2196      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2197      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2198      $part_pkg->taxclass); #meh
2199
2200   my $conf = new FS::Conf;
2201   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2202
2203     $bill_error = _do_bop_realtime( $cust_main, $status );
2204
2205     if ($bill_error) {
2206       return $bill_error;
2207     } else {
2208       my $error = $svc_x->recharge (\%vhash);
2209       return { 'error' => $error } if $error;
2210     }
2211
2212   } else {  
2213     my $error = $bill_error;
2214     $error ||= $svc_x->recharge (\%vhash);
2215     return { 'error' => $error } if $error;
2216   }
2217
2218   return { error => '', svc => $cust_svc->part_svc->svc };
2219
2220 }
2221
2222 sub _do_bop_realtime {
2223   my ($cust_main, $status) = (shift, shift);
2224
2225     my $old_balance = $cust_main->balance;
2226
2227     my $bill_error =    $cust_main->bill
2228                      || $cust_main->apply_payments_and_credits
2229                      || $cust_main->realtime_collect('selfservice' => 1);
2230
2231     if (    $cust_main->balance > $old_balance
2232          && $cust_main->balance > 0
2233          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2234               1 : $status eq 'suspended' ) ) {
2235       #this makes sense.  credit is "un-doing" the invoice
2236       my $conf = new FS::Conf;
2237       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2238                           'self-service decline',
2239                           'reason_type' => $conf->config('signup_credit_type'),
2240                         );
2241       $cust_main->apply_credits( 'order' => 'newest' );
2242
2243       return { 'error' => '_decline', 'bill_error' => $bill_error };
2244     }
2245
2246     '';
2247 }
2248
2249 sub renew_info {
2250   my $p = shift;
2251
2252   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2253   return { 'error' => $session } if $context eq 'error';
2254
2255   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2256     or return { 'error' => "unknown custnum $custnum" };
2257
2258   my @cust_pkg = sort { $a->bill <=> $b->bill }
2259                  grep { $_->part_pkg->freq ne '0' }
2260                  $cust_main->ncancelled_pkgs;
2261
2262   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2263
2264   my $total = $cust_main->balance;
2265
2266   my @array = map {
2267                     my $bill = $_->bill;
2268                     $total += $_->part_pkg->base_recur($_, \$bill);
2269                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2270                     {
2271                       'pkgnum'             => $_->pkgnum,
2272                       'amount'             => sprintf('%.2f', $total),
2273                       'bill_date'          => $_->bill,
2274                       'bill_date_pretty'   => time2str('%x', $_->bill),
2275                       'renew_date'         => $renew_date,
2276                       'renew_date_pretty'  => time2str('%x', $renew_date),
2277                       'expire_date'        => $_->expire,
2278                       'expire_date_pretty' => time2str('%x', $_->expire),
2279                     };
2280                   }
2281                   @cust_pkg;
2282
2283   return { 'dates' => \@array };
2284
2285 }
2286
2287 sub payment_info_renew_info {
2288   my $p = shift;
2289   my $renew_info   = renew_info($p);
2290   my $payment_info = payment_info($p);
2291   return { %$renew_info,
2292            %$payment_info,
2293          };
2294 }
2295
2296 sub order_renew {
2297   my $p = shift;
2298
2299   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2300   return { 'error' => $session } if $context eq 'error';
2301
2302   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2303     or return { 'error' => "unknown custnum $custnum" };
2304
2305   my $date = $p->{'date'};
2306
2307   my $now = time;
2308
2309   #freeside-daily -n -d $date fs_daily $custnum
2310   $cust_main->bill_and_collect( 'time'         => $date,
2311                                 'invoice_time' => $now,
2312                                 'actual_time'  => $now,
2313                                 'check_freq'   => '1d',
2314                               );
2315
2316   return { 'error' => '' };
2317
2318 }
2319
2320 sub suspend_pkg {
2321   my $p = shift;
2322   my $session = _cache->get($p->{'session_id'})
2323     or return { 'error' => "Can't resume session" }; #better error message
2324
2325   my $custnum = $session->{'custnum'};
2326
2327   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2328     or return { 'error' => "unknown custnum $custnum" };
2329
2330   my $conf = new FS::Conf;
2331   my $reasonnum = 
2332     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2333       or return { 'error' => 'Permission denied' };
2334
2335   my $pkgnum = $p->{'pkgnum'};
2336
2337   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2338                                         'pkgnum'  => $pkgnum,   } )
2339     or return { 'error' => "unknown pkgnum $pkgnum" };
2340
2341   my $error = $cust_pkg->suspend(reason => $reasonnum);
2342   return { 'error' => $error };
2343
2344 }
2345
2346 sub cancel_pkg {
2347   my $p = shift;
2348   my $session = _cache->get($p->{'session_id'})
2349     or return { 'error' => "Can't resume session" }; #better error message
2350
2351   my $custnum = $session->{'custnum'};
2352
2353   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2354     or return { 'error' => "unknown custnum $custnum" };
2355
2356   my $pkgnum = $p->{'pkgnum'};
2357
2358   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2359                                         'pkgnum'  => $pkgnum,   } )
2360     or return { 'error' => "unknown pkgnum $pkgnum" };
2361
2362   my $error = $cust_pkg->cancel('quiet' => 1);
2363   return { 'error' => $error };
2364
2365 }
2366
2367 sub provision_phone {
2368  my $p = shift;
2369  my @bulkdid;
2370  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2371
2372  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2373       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2374       return { 'error' => $session } if $context eq 'error';
2375     
2376       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2377       return { 'error' => 'service not found' } unless $svc_phone;
2378       return { 'error' => 'invalid svcnum' } 
2379         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2380
2381       $svc_phone->email($p->{'email'}) 
2382         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2383       $svc_phone->forwarddst($p->{'forwarddst'}) 
2384         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2385             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2386       return { 'error' => $svc_phone->replace };
2387  }
2388
2389 # single DID LNP
2390  unless($p->{'lnp'}) {
2391     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2392     $p->{'lnp_status'} = "portingin";
2393     return _provision( 'FS::svc_phone',
2394                   [qw(lnp_desired_due_date lnp_other_provider 
2395                     lnp_other_provider_account phonenum countrycode lnp_status)],
2396                   [qw(phonenum countrycode)],
2397                   $p,
2398                   @_
2399                 );
2400  }
2401
2402 # single DID order
2403  unless (scalar(@bulkdid)) {
2404     return _provision( 'FS::svc_phone',
2405                   [qw(phonenum countrycode)],
2406                   [qw(phonenum countrycode)],
2407                   $p,
2408                   @_
2409                 );
2410  }
2411
2412 # bulk DID order case
2413   my $error;
2414   foreach my $did ( @bulkdid ) {
2415     $did =~ s/[^0-9]//g;
2416     $error = _provision( 'FS::svc_phone',
2417               [qw(phonenum countrycode)],
2418               [qw(phonenum countrycode)],
2419               {
2420                 'pkgnum' => $p->{'pkgnum'},
2421                 'svcpart' => $p->{'svcpart'},
2422                 'phonenum' => $did,
2423                 'countrycode' => $p->{'countrycode'},
2424                 'session_id' => $p->{'session_id'},
2425               }
2426             );
2427     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2428   }
2429   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2430 }
2431
2432 sub provision_acct {
2433   my $p = shift;
2434   warn "provision_acct called\n"
2435     if $DEBUG;
2436
2437   return { 'error' => gettext('passwords_dont_match') }
2438     if $p->{'_password'} ne $p->{'_password2'};
2439   return { 'error' => gettext('empty_password') }
2440     unless length($p->{'_password'});
2441  
2442   if ($p->{'domsvc'}) {
2443     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2444                                                   qw ( svcpart pkgnum ) );
2445     return { 'error' => gettext('invalid_domain') }
2446       unless ($domains{$p->{'domsvc'}});
2447   }
2448
2449   warn "provision_acct calling _provision\n"
2450     if $DEBUG;
2451   _provision( 'FS::svc_acct',
2452               [qw(username _password domsvc)],
2453               [qw(username _password domsvc)],
2454               $p,
2455               @_
2456             );
2457 }
2458
2459 sub provision_external {
2460   my $p = shift;
2461   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2462   _provision( 'FS::svc_external',
2463               [],
2464               [qw(id title)],
2465               $p,
2466               @_
2467             );
2468 }
2469
2470 sub _provision {
2471   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2472   warn "_provision called for $class\n"
2473     if $DEBUG;
2474
2475   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2476   return { 'error' => $session } if $context eq 'error';
2477
2478   my $search = { 'custnum' => $custnum };
2479   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2480   my $cust_main = qsearchs('cust_main', $search )
2481     or return { 'error' => "unknown custnum $custnum" };
2482
2483   my $pkgnum = $p->{'pkgnum'};
2484
2485   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2486     if $DEBUG;
2487   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2488                                         'pkgnum'  => $pkgnum,
2489                                                                } )
2490     or return { 'error' => "unknown pkgnum $pkgnum" };
2491
2492   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2493     if $DEBUG;
2494   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2495     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2496
2497   warn "creating $class record\n"
2498     if $DEBUG;
2499   my $svc_x = $class->new( {
2500     'pkgnum'  => $p->{'pkgnum'},
2501     'svcpart' => $p->{'svcpart'},
2502     map { $_ => $p->{$_} } @$fields
2503   } );
2504   warn "inserting $class record\n"
2505     if $DEBUG;
2506   my $error = $svc_x->insert;
2507
2508   unless ( $error ) {
2509     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2510       if $DEBUG;
2511     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2512   }
2513
2514   my $return = { 'svc'   => $part_svc->svc,
2515                  'error' => $error,
2516                  map { $_ => $svc_x->get($_) } @$return_fields
2517                };
2518   warn "_provision returning ". Dumper($return). "\n"
2519     if $DEBUG;
2520   return $return;
2521
2522 }
2523
2524 sub part_svc_info {
2525   my $p = shift;
2526
2527   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2528   return { 'error' => $session } if $context eq 'error';
2529
2530   my $search = { 'custnum' => $custnum };
2531   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2532   my $cust_main = qsearchs('cust_main', $search )
2533     or return { 'error' => "unknown custnum $custnum" };
2534
2535   my $pkgnum = $p->{'pkgnum'};
2536
2537   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2538                                         'pkgnum'  => $pkgnum,
2539                                                                } )
2540     or return { 'error' => "unknown pkgnum $pkgnum" };
2541
2542   my $svcpart = $p->{'svcpart'};
2543
2544   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2545                                       'svcpart' => $svcpart,           } )
2546     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2547   my $part_svc = $pkg_svc->part_svc;
2548
2549   my $conf = new FS::Conf;
2550
2551   my $ret = {
2552     'svc'     => $part_svc->svc,
2553     'svcdb'   => $part_svc->svcdb,
2554     'pkgnum'  => $pkgnum,
2555     'svcpart' => $svcpart,
2556     'custnum' => $custnum,
2557
2558     'security_phrase' => 0, #XXX !
2559     'svc_acct_pop'    => [], #XXX !
2560     'popnum'          => '',
2561     'init_popstate'   => '',
2562     'popac'           => '',
2563     'acstate'         => '',
2564
2565     'small_custview' =>
2566       small_custview( $cust_main, $conf->config('countrydefault') ),
2567
2568   };
2569
2570   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2571                      && $ret->{'svcdb'} eq 'svc_phone') {
2572         $ret->{'svcnum'} = $p->{'svcnum'};
2573         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2574         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2575             $ret->{'email'} = $svc_phone->email;
2576             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2577         }
2578   }
2579
2580   $ret;
2581 }
2582
2583 sub unprovision_svc {
2584   my $p = shift;
2585
2586   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2587   return { 'error' => $session } if $context eq 'error';
2588
2589   my $search = { 'custnum' => $custnum };
2590   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2591   my $cust_main = qsearchs('cust_main', $search )
2592     or return { 'error' => "unknown custnum $custnum" };
2593
2594   my $svcnum = $p->{'svcnum'};
2595
2596   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2597     or return { 'error' => "unknown svcnum $svcnum" };
2598
2599   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2600     unless $cust_svc->cust_pkg->custnum == $custnum;
2601
2602   my $conf = new FS::Conf;
2603
2604   return { 'svc'   => $cust_svc->part_svc->svc,
2605            'error' => $cust_svc->cancel,
2606            'small_custview' =>
2607              small_custview( $cust_main, $conf->config('countrydefault') ),
2608          };
2609
2610 }
2611
2612 sub myaccount_passwd {
2613   my $p = shift;
2614   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2615   return { 'error' => $session } if $context eq 'error';
2616
2617   return { 'error' => "New passwords don't match." }
2618     if $p->{'new_password'} ne $p->{'new_password2'};
2619
2620   return { 'error' => 'Enter new password' }
2621     unless length($p->{'new_password'});
2622
2623   #my $search = { 'custnum' => $custnum };
2624   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2625   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2626   my $search = " AND custnum = $1";
2627   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2628
2629   my $svc_acct = qsearchs( {
2630     'table'     => 'svc_acct',
2631     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2632                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2633                    'LEFT JOIN cust_main USING ( custnum ) ',
2634     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2635     'extra_sql' => $search, #important
2636   } )
2637     or return { 'error' => "Service not found" };
2638
2639   if ( exists($p->{'old_password'}) ) {
2640     return { 'error' => "Incorrect password." }
2641       unless $svc_acct->check_password($p->{'old_password'});
2642   }
2643
2644   $svc_acct->set_password($p->{'new_password'});
2645   my $error = $svc_acct->replace();
2646
2647   my($label, $value) = $svc_acct->cust_svc->label;
2648
2649   return { 'error' => $error,
2650            'label' => $label,
2651            'value' => $value,
2652          };
2653
2654 }
2655
2656 sub reset_passwd {
2657   my $p = shift;
2658
2659   my $conf = new FS::Conf;
2660   my $verification = $conf->config('selfservice-password_reset_verification')
2661     or return { 'error' => 'Password resets disabled' };
2662
2663   my $username = $p->{'username'};
2664
2665   my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2666     or return { 'error' => 'Account not found' };
2667
2668   my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2669                                         'domsvc'   => $svc_domain->svcnum  }
2670                          )
2671     or return { 'error' => 'Account not found' };
2672
2673   my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2674     or return { 'error' => 'Account not found' };
2675
2676   my $cust_main = $cust_pkg->cust_main;
2677
2678   my %verify = (
2679     'paymask' => sub { 
2680       my( $p, $cust_main ) = @_;
2681       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2682         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2683     },
2684     'amount'  => sub {
2685       my( $p, $cust_main ) = @_;
2686       my $cust_pay = qsearchs({
2687         'table' => 'cust_pay',
2688         'hashref' => { 'custnum' => $cust_main->custnum },
2689         'order_by' => 'ORDER BY _date DESC LIMIT 1',
2690       })
2691         or return 0;
2692
2693       $p->{'amount'} == $cust_pay->paid;
2694     },
2695     'zip'     => sub {
2696       my( $p, $cust_main ) = @_;
2697       $p->{'zip'} eq $cust_main->zip
2698         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2699     },
2700   );
2701
2702   foreach my $verify ( split(',', $verification) ) {
2703
2704     &{ $verify{$verify} }( $p, $cust_main )
2705       or return { 'error' => 'Account not found' };
2706
2707   }
2708
2709   #okay, we're verified, now create a unique session
2710
2711   my $reset_session = {
2712     'svcnum' => $svc_acct->svcnum,
2713   };
2714
2715   my $timeout = '1 hour'; #?
2716
2717   my $reset_session_id;
2718   do {
2719     $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2720   } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2721
2722   _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2723
2724   #email it
2725
2726   my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2727   #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2728   return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2729   my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2730   my $error = $msg_template->send( 'cust_main'     => $cust_main,
2731                                    'object'        => $svc_acct,
2732                                    'substitutions' => {
2733                                      'session_id' => $reset_session_id,
2734                                    }
2735                                  );
2736   if ( $error ) {
2737     return { 'error' => $error }; #????
2738   }
2739
2740   return { 'error' => '' };
2741 }
2742
2743 sub check_reset_passwd {
2744   my $p = shift;
2745
2746   my $conf = new FS::Conf;
2747   my $verification = $conf->config('selfservice-password_reset_verification')
2748     or return { 'error' => 'Password resets disabled' };
2749
2750   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2751     or return { 'error' => "Can't resume session" }; #better error message
2752
2753   my $svcnum = $reset_session->{'svcnum'};
2754
2755   my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2756     or return { 'error' => "Service not found" };
2757
2758   return { 'error'    => '',
2759            'username' => $svc_acct->username,
2760          };
2761
2762 }
2763
2764 sub process_reset_passwd {
2765   my $p = shift;
2766
2767   my $conf = new FS::Conf;
2768   my $verification = $conf->config('selfservice-password_reset_verification')
2769     or return { 'error' => 'Password resets disabled' };
2770
2771   return { 'error' => "New passwords don't match." }
2772     if $p->{'new_password'} ne $p->{'new_password2'};
2773
2774   return { 'error' => 'Enter new password' }
2775     unless length($p->{'new_password'});
2776
2777   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2778     or return { 'error' => "Can't resume session" }; #better error message
2779
2780   my $svcnum = $reset_session->{'svcnum'};
2781
2782   my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2783     or return { 'error' => "Service not found" };
2784
2785   $svc_acct->set_password($p->{'new_password'});
2786   my $error = $svc_acct->replace();
2787
2788   my($label, $value) = $svc_acct->cust_svc->label;
2789
2790   return { 'error' => $error,
2791            #'label' => $label,
2792            #'value' => $value,
2793          };
2794
2795 }
2796
2797 sub create_ticket {
2798   my $p = shift;
2799   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2800   return { 'error' => $session } if $context eq 'error';
2801
2802   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2803   FS::TicketSystem->init();
2804
2805   my $conf = new FS::Conf;
2806   my $queue = $p->{'queue'}
2807               || $conf->config('ticket_system-selfservice_queueid')
2808               || $conf->config('ticket_system-default_queueid');
2809
2810   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2811   my $err_or_ticket = FS::TicketSystem->create_ticket(
2812     '', #create RT session based on FS CurrentUser (fs_selfservice)
2813     'queue'   => $queue,
2814     'custnum' => $custnum,
2815     'svcnum'  => $session->{'svcnum'},
2816     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2817   );
2818
2819   if ( ref($err_or_ticket) ) {
2820     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2821       if $DEBUG;
2822     return { 'error'     => '',
2823              'ticket_id' => $err_or_ticket->id,
2824            };
2825   } else {
2826     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2827       if $DEBUG;
2828     return { 'error' => $err_or_ticket };
2829   }
2830
2831
2832 }
2833
2834 sub did_report {
2835   my $p = shift;
2836   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2837   return { 'error' => $session } if $context eq 'error';
2838  
2839   return { error => 'requested format not implemented' } 
2840     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2841
2842   my $conf = new FS::Conf;
2843   my $age_threshold = 0;
2844   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2845     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2846
2847   my $search = { 'custnum' => $custnum };
2848   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2849   my $cust_main = qsearchs('cust_main', $search )
2850     or return { 'error' => "unknown custnum $custnum" };
2851
2852 # does it make more sense to just run one sql query for this instead of all the
2853 # insanity below? would increase performance greately for large data sets?
2854   my @svc_phone = ();
2855   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2856         my @part_svc = $cust_pkg->part_svc;
2857         foreach my $part_svc ( @part_svc ) {
2858             if($part_svc->svcdb eq 'svc_phone'){
2859                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2860                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2861                     push @svc_phone, $cust_pkg_svc->svc_x
2862                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2863                 }
2864             }
2865         }
2866   }
2867
2868   my $csv;
2869   my $xls;
2870   my($xls_r,$xls_c) = (0,0);
2871   my $xls_workbook;
2872   my $content = '';
2873   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2874   if($p->{'format'} eq 'csv') {
2875     $csv = new Text::CSV_XS { 'always_quote' => 1,
2876                                  'eol'          => "\n",
2877                                 };
2878     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2879     $content .= $csv->string;
2880   }
2881   elsif($p->{'format'} eq 'xls') {
2882     my $XLS1 = new IO::Scalar \$content;
2883     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2884         or return { 'error' => "Error opening .xls file: $!" };
2885     $xls = $xls_workbook->add_worksheet('DIDs');
2886     foreach ( @fields ) {
2887         $xls->write(0,$xls_c++,$_);
2888     }
2889     $xls_r++;
2890   }
2891
2892   foreach my $svc_phone ( @svc_phone ) {
2893     my @cols = map { $svc_phone->$_ } @fields;
2894     if($p->{'format'} eq 'csv') {
2895         return { 'error' => 'Unable to create CSV' } 
2896             unless $csv->combine(@cols);
2897         $content .= $csv->string;
2898     }
2899     elsif($p->{'format'} eq 'xls') {
2900         $xls_c = 0;
2901         foreach ( @cols ) {
2902             $xls->write($xls_r,$xls_c++,$_);
2903         }
2904         $xls_r++;
2905     }
2906   }
2907
2908   $xls_workbook->close() if $p->{'format'} eq 'xls';
2909   
2910   { content => $content, format => $p->{'format'}, };
2911 }
2912
2913 sub get_ticket {
2914   my $p = shift;
2915   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2916   return { 'error' => $session } if $context eq 'error';
2917
2918   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2919   FS::TicketSystem->init();
2920   return { 'error' => 'get_ticket configuration error' }
2921     if $FS::TicketSystem::system ne 'RT_Internal';
2922
2923   # check existence and ownership as part of this
2924   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2925   my $rt_session = FS::TicketSystem->session('');
2926   my $Ticket = FS::TicketSystem->get_ticket_object(
2927     $rt_session, 
2928     ticket_id => $p->{'ticket_id'},
2929     custnum => $custnum
2930   );
2931   return { 'error' => 'ticket not found' } if !$Ticket;
2932
2933   if ( length( $p->{'subject'} || '' ) ) {
2934     # subject change
2935     if ( $p->{'subject'} ne $Ticket->Subject ) {
2936       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2937       return { 'error' => "unable to set subject: $msg" } if !$val;
2938     }
2939   }
2940
2941   if(length($p->{'reply'})) {
2942     my @err_or_res = FS::TicketSystem->correspond_ticket(
2943       $rt_session,
2944       'ticket_id' => $p->{'ticket_id'},
2945       'content' => $p->{'reply'},
2946     );
2947
2948     return { 'error' => 'unable to reply to ticket' } 
2949     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2950   }
2951
2952   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2953   my $err_or_ticket = FS::TicketSystem->get_ticket(
2954     $rt_session,
2955     'ticket_id' => $p->{'ticket_id'},
2956   );
2957
2958   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2959     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2960       if $DEBUG;
2961     return { 'error' => $err_or_ticket };
2962   }
2963
2964   my @custs = @{$err_or_ticket->{'custs'}};
2965   my @txns = @{$err_or_ticket->{'txns'}};
2966   my @filtered_txns;
2967
2968   # superseded by check in get_ticket_object
2969   #return { 'error' => 'invalid ticket requested' } 
2970   #unless grep($_ eq $custnum, @custs);
2971
2972   foreach my $txn ( @txns ) {
2973     push @filtered_txns, $txn 
2974     if ($txn->{'type'} eq 'EmailRecord' 
2975       || $txn->{'type'} eq 'Correspond'
2976       || $txn->{'type'} eq 'Create');
2977   }
2978
2979   warn "$me get_ticket: successful: \n"
2980   if $DEBUG;
2981   return { 'error'     => '',
2982     'transactions' => \@filtered_txns,
2983     'ticket_fields' => $err_or_ticket->{'fields'},
2984     'ticket_id' => $p->{'ticket_id'},
2985   };
2986 }
2987
2988 sub adjust_ticket_priority {
2989   my $p = shift;
2990   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2991   return { 'error' => $session } if $context eq 'error';
2992
2993   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2994   FS::TicketSystem->init;
2995   my $ss_priority = FS::TicketSystem->selfservice_priority;
2996
2997   return { 'error' => 'adjust_ticket_priority configuration error' }
2998     if $FS::TicketSystem::system ne 'RT_Internal'
2999       or !$ss_priority;
3000
3001   my $values = $p->{'values'}; #hashref, id => priority value
3002   my %ticket_error;
3003
3004   foreach my $id (keys %$values) {
3005     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3006     my $Ticket = FS::TicketSystem->get_ticket_object('',
3007       'ticket_id' => $id,
3008       'custnum'   => $custnum,
3009     );
3010     if ( !$Ticket ) {
3011       $ticket_error{$id} = 'ticket not found';
3012       next;
3013     }
3014     
3015   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3016   # We're not going to implement it for RT_External.
3017     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3018     my $new_value = $values->{$id};
3019     next if $old_value eq $new_value;
3020
3021     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3022
3023     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3024     # a single-valued custom field, which it should be.  If it's not, you're 
3025     # doing something wrong.
3026     my ($val, $msg);
3027     if ( length($new_value) ) {
3028       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3029         Field => $ss_priority,
3030         Value => $new_value,
3031       );
3032     }
3033     else {
3034       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3035         Field => $ss_priority,
3036         Value => $old_value,
3037       );
3038     }
3039
3040     $ticket_error{$id} = $msg if !$val;
3041     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3042   }
3043   return { 'error' => '',
3044            'ticket_error' => \%ticket_error,
3045            %{ customer_info($p) } # send updated customer info back
3046          }
3047 }
3048
3049 #--
3050
3051 sub _custoragent_session_custnum {
3052   my $p = shift;
3053
3054   my($context, $session, $custnum);
3055   if ( $p->{'session_id'} ) {
3056
3057     $context = 'customer';
3058     $session = _cache->get($p->{'session_id'})
3059       or return ( 'error' => "Can't resume session" ); #better error message
3060     $custnum = $session->{'custnum'};
3061
3062   } elsif ( $p->{'agent_session_id'} ) {
3063
3064     $context = 'agent';
3065     my $agent_cache = new FS::ClientAPI_SessionCache( {
3066       'namespace' => 'FS::ClientAPI::Agent',
3067     } );
3068     $session = $agent_cache->get($p->{'agent_session_id'})
3069       or return ( 'error' => "Can't resume session" ); #better error message
3070     $custnum = $p->{'custnum'};
3071
3072   } else {
3073     $context = 'error';
3074     return ( 'error' => "Can't resume session" ); #better error message
3075   }
3076
3077   ($context, $session, $custnum);
3078
3079 }
3080
3081 1;
3082