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