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