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