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