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