add invoice_pdf to selfservice, 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 edit_info {
447   my $p = shift;
448   my $session = _cache->get($p->{'session_id'})
449     or return { 'error' => "Can't resume session" }; #better error message
450
451   my $custnum = $session->{'custnum'}
452     or return { 'error' => "no customer record" };
453
454   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
455     or return { 'error' => "unknown custnum $custnum" };
456
457   my $new = new FS::cust_main { $cust_main->hash };
458   $new->set( $_ => $p->{$_} )
459     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
460
461   my $payby = '';
462   if (exists($p->{'payby'})) {
463     $p->{'payby'} =~ /^([A-Z]{4})$/
464       or return { 'error' => "illegal_payby " . $p->{'payby'} };
465     $payby = $1;
466   }
467
468   if ( $payby =~ /^(CARD|DCRD)$/ ) {
469
470     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
471
472     if ( $new->payinfo eq $cust_main->paymask ) {
473       $new->payinfo($cust_main->payinfo);
474     } else {
475       $new->payinfo($p->{'payinfo'});
476     }
477
478     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
479
480   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
481
482     my $payinfo;
483     $p->{'payinfo1'} =~ /^([\dx]+)$/
484       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
485     my $payinfo1 = $1;
486      $p->{'payinfo2'} =~ /^([\dx]+)$/
487       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
488     my $payinfo2 = $1;
489     $payinfo = $payinfo1. '@'. $payinfo2;
490
491     $new->payinfo( ($payinfo eq $cust_main->paymask)
492                      ? $cust_main->payinfo
493                      : $payinfo
494                  );
495
496     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
497
498   } elsif ( $payby =~ /^(BILL)$/ ) {
499     #no-op
500   } elsif ( $payby ) {  #notyet ready
501     return { 'error' => "unknown payby $payby" };
502   }
503
504   my @invoicing_list;
505   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
506     #false laziness with httemplate/edit/process/cust_main.cgi
507     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
508     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
509   } else {
510     @invoicing_list = $cust_main->invoicing_list;
511   }
512
513   my $error = $new->replace($cust_main, \@invoicing_list);
514   return { 'error' => $error } if $error;
515   #$cust_main = $new;
516   
517   return { 'error' => '' };
518 }
519
520 sub payment_info {
521   my $p = shift;
522   my $session = _cache->get($p->{'session_id'})
523     or return { 'error' => "Can't resume session" }; #better error message
524
525   ##
526   #generic
527   ##
528
529   my $conf = new FS::Conf;
530   use vars qw($payment_info); #cache for performance
531   unless ( $payment_info ) {
532
533     my %states = map { $_->state => 1 }
534                    qsearch('cust_main_county', {
535                      'country' => $conf->config('countrydefault') || 'US'
536                    } );
537
538     my %cust_paybys = map { $_ => 1 }
539                       map { FS::payby->payby2payment($_) }
540                           $conf->config('signup_server-payby');
541
542     my @cust_paybys = keys %cust_paybys;
543
544     $payment_info = {
545
546       #list all counties/states/countries
547       'cust_main_county' => 
548         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
549
550       #shortcut for one-country folks
551       'states' =>
552         [ sort { $a cmp $b } keys %states ],
553
554       'card_types' => card_types(),
555
556       'paytypes' => [ @FS::cust_main::paytypes ],
557
558       'paybys' => [ $conf->config('signup_server-payby') ],
559       'cust_paybys' => \@cust_paybys,
560
561       'stateid_label' => FS::Msgcat::_gettext('stateid'),
562       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
563
564       'show_ss'  => $conf->exists('show_ss'),
565       'show_stateid' => $conf->exists('show_stateid'),
566       'show_paystate' => $conf->exists('show_bankstate'),
567
568       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
569
570       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
571     };
572
573   }
574
575   ##
576   #customer-specific
577   ##
578
579   my %return = %$payment_info;
580
581   my $custnum = $session->{'custnum'};
582
583   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
584     or return { 'error' => "unknown custnum $custnum" };
585
586   $return{'hide_payment_fields'} = [
587     map { 
588       my $pg = payment_gateway($cust_main, $_);
589       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
590     } @{ $return{cust_paybys} }
591   ];
592
593   $return{balance} = $cust_main->balance; #XXX pkg-balances?
594
595   $return{payname} = $cust_main->payname
596                      || ( $cust_main->first. ' '. $cust_main->get('last') );
597
598   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
599
600   $return{payby} = $cust_main->payby;
601   $return{stateid_state} = $cust_main->stateid_state;
602
603   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
604     $return{card_type} = cardtype($cust_main->payinfo);
605     $return{payinfo} = $cust_main->paymask;
606
607     @return{'month', 'year'} = $cust_main->paydate_monthyear;
608
609   }
610
611   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
612     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
613     $return{payinfo1} = $payinfo1;
614     $return{payinfo2} = $payinfo2;
615     $return{paytype}  = $cust_main->paytype;
616     $return{paystate} = $cust_main->paystate;
617
618   }
619
620   if ( $conf->config('prepayment_discounts-credit_type') ) {
621     #need to eval?
622     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
623   }
624
625   #doubleclick protection
626   my $_date = time;
627   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
628
629   return { 'error' => '',
630            %return,
631          };
632
633 };
634
635 #some false laziness with httemplate/process/payment.cgi - look there for
636 #ACH and CVV support stuff
637 sub process_payment {
638
639   my $p = shift;
640
641   my $session = _cache->get($p->{'session_id'})
642     or return { 'error' => "Can't resume session" }; #better error message
643
644   my %return;
645
646   my $custnum = $session->{'custnum'};
647
648   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
649     or return { 'error' => "unknown custnum $custnum" };
650
651   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
652     or return { 'error' => gettext('illegal_amount') };
653   my $amount = $1;
654   return { error => 'Amount must be greater than 0' } unless $amount > 0;
655
656   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
657     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
658   my $discount_term = $1;
659
660   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
661     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
662   my $payname = $1;
663
664   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
665     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
666   my $paybatch = $1;
667
668   $p->{'payby'} ||= 'CARD';
669   $p->{'payby'} =~ /^([A-Z]{4})$/
670     or return { 'error' => "illegal_payby " . $p->{'payby'} };
671   my $payby = $1;
672
673   #false laziness w/process/payment.cgi
674   my $payinfo;
675   my $paycvv = '';
676   my $paynum = '';
677   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
678   
679     $p->{'payinfo1'} =~ /^([\dx]+)$/
680       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
681     my $payinfo1 = $1;
682      $p->{'payinfo2'} =~ /^([\dx]+)$/
683       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
684     my $payinfo2 = $1;
685     $payinfo = $payinfo1. '@'. $payinfo2;
686
687     $payinfo = $cust_main->payinfo
688       if $cust_main->paymask eq $payinfo;
689    
690   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
691    
692     $payinfo = $p->{'payinfo'};
693
694     #more intelligent mathing will be needed here if you change
695     #card_masking_method and don't remove existing paymasks
696     $payinfo = $cust_main->payinfo
697       if $cust_main->paymask eq $payinfo;
698
699     $payinfo =~ s/\D//g;
700     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
701       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
702     $payinfo = $1;
703
704     validate($payinfo)
705       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
706     return { 'error' => gettext('unknown_card_type') }
707       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
708
709     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
710       if ( cardtype($payinfo) eq 'American Express card' ) {
711         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
712           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
713         $paycvv = $1;
714       } else {
715         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
716           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
717         $paycvv = $1;
718       }
719     }
720   
721   } else {
722     die "unknown payby $payby";
723   }
724
725   my %payby2fields = (
726     'CARD' => [ qw( paystart_month paystart_year payissue payip
727                     address1 address2 city state zip country    ) ],
728     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
729   );
730
731   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
732     'quiet'    => 1,
733     'payinfo'  => $payinfo,
734     'paydate'  => $p->{'year'}. '-'. $p->{'month'}. '-01',
735     'payname'  => $payname,
736     'paybatch' => $paybatch, #this doesn't actually do anything
737     'paycvv'   => $paycvv,
738     'paynum_ref' => \$paynum,
739     'pkgnum'   => $session->{'pkgnum'},
740     'discount_term' => $discount_term,
741     'selfservice' => 1,
742     map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
743   );
744   return { 'error' => $error } if $error;
745
746   $cust_main->apply_payments;
747
748   if ( $p->{'save'} ) {
749     my $new = new FS::cust_main { $cust_main->hash };
750     if ($payby eq 'CARD' || $payby eq 'DCRD') {
751       $new->set( $_ => $p->{$_} )
752         foreach qw( payname paystart_month paystart_year payissue payip
753                     address1 address2 city state zip country );
754       $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
755     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
756       $new->set( $_ => $p->{$_} )
757         foreach qw( payname payip paytype paystate
758                     stateid stateid_state );
759       $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
760     }
761     $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
762     $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
763     my $error = $new->replace($cust_main);
764     if ( $error ) {
765       #no, this causes customers to process their payments again
766       #return { 'error' => $error };
767       #XXX just warn verosely for now so i can figure out how these happen in
768       # the first place, eventually should redirect them to the "change
769       #address" page but indicate the payment did process??
770       delete($p->{'payinfo'}); #don't want to log this!
771       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
772            "NEW: ". Dumper($new)."\n".
773            "OLD: ". Dumper($cust_main)."\n".
774            "PACKET: ". Dumper($p)."\n";
775     #} else {
776       #not needed...
777       #$cust_main = $new;
778     }
779   }
780
781   my $receipt_html = '';
782   if($paynum) { 
783       # currently supported for realtime CC only; send receipt data to SS
784       my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
785       if($cust_pay) {
786         $receipt_html = qq!
787 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
788
789 <TR>
790   <TD ALIGN="right">Payment#</TD>
791   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
792 </TR>
793
794 <TR>
795   <TD ALIGN="right">Date</TD>
796
797   <TD BGCOLOR="#FFFFFF"><B>! . 
798         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
799                                                             . qq!</B></TD>
800 </TR>
801
802
803 <TR>
804   <TD ALIGN="right">Amount</TD>
805   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
806
807 </TR>
808
809 <TR>
810   <TD ALIGN="right">Payment method</TD>
811   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
812                                                                 . qq!</B></TD>
813 </TR>
814
815 </TABLE>
816 !;
817       }
818   }
819
820   return { 'error' => '', 'receipt_html' => $receipt_html, };
821
822 }
823
824 sub realtime_collect {
825   my $p = shift;
826
827   my $session = _cache->get($p->{'session_id'})
828     or return { 'error' => "Can't resume session" }; #better error message
829
830   my $custnum = $session->{'custnum'};
831
832   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
833     or return { 'error' => "unknown custnum $custnum" };
834
835   my $amount;
836   if ( $p->{'amount'} ) {
837     $amount = $p->{'amount'};
838   }
839   elsif ( $session->{'pkgnum'} ) {
840     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
841   }
842   else {
843     $amount = $cust_main->balance;
844   }
845
846   my $error = $cust_main->realtime_collect(
847     'method'     => $p->{'method'},
848     'amount'     => $amount,
849     'pkgnum'     => $session->{'pkgnum'},
850     'session_id' => $p->{'session_id'},
851     'apply'      => 1,
852     'selfservice'=> 1,
853   );
854   return { 'error' => $error } unless ref( $error );
855
856   return { 'error' => '', amount => $amount, %$error };
857 }
858
859 sub process_payment_order_pkg {
860   my $p = shift;
861
862   my $hr = process_payment($p);
863   return $hr if $hr->{'error'};
864
865   order_pkg($p);
866 }
867
868 sub process_payment_order_renew {
869   my $p = shift;
870
871   my $hr = process_payment($p);
872   return $hr if $hr->{'error'};
873
874   order_renew($p);
875 }
876
877 sub process_prepay {
878
879   my $p = shift;
880
881   my $session = _cache->get($p->{'session_id'})
882     or return { 'error' => "Can't resume session" }; #better error message
883
884   my %return;
885
886   my $custnum = $session->{'custnum'};
887
888   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
889     or return { 'error' => "unknown custnum $custnum" };
890
891   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
892   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
893                                            \$amount,
894                                            \$seconds,
895                                            \$upbytes,
896                                            \$downbytes,
897                                            \$totalbytes,
898                                          );
899
900   return { 'error' => $error } if $error;
901
902   return { 'error'     => '',
903            'amount'    => $amount,
904            'seconds'   => $seconds,
905            'duration'  => duration_exact($seconds),
906            'upbytes'   => $upbytes,
907            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
908            'downbytes' => $downbytes,
909            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
910            'totalbytes'=> $totalbytes,
911            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
912          };
913
914 }
915
916 sub invoice {
917   my $p = shift;
918   my $session = _cache->get($p->{'session_id'})
919     or return { 'error' => "Can't resume session" }; #better error message
920
921   my $custnum = $session->{'custnum'};
922
923   my $invnum = $p->{'invnum'};
924
925   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
926                                           'custnum' => $custnum } )
927     or return { 'error' => "Can't find invnum" };
928
929   #my %return;
930
931   return { 'error'        => '',
932            'invnum'       => $invnum,
933            'invoice_text' => join('', $cust_bill->print_text ),
934            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
935          };
936
937 }
938
939 sub invoice_pdf {
940   my $p = shift;
941   my $session = _cache->get($p->{'session_id'})
942     or return { 'error' => "Can't resume session" }; #better error message
943
944   my $custnum = $session->{'custnum'};
945
946   my $invnum = $p->{'invnum'};
947
948   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
949                                           'custnum' => $custnum } )
950     or return { 'error' => "Can't find invnum" };
951
952   #my %return;
953
954   return { 'error'       => '',
955            'invnum'      => $invnum,
956            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
957          };
958
959 }
960
961 sub invoice_logo {
962   my $p = shift;
963
964   #sessioning for this?  how do we get the session id to the backend invoice
965   # template so it can add it to the link, blah
966
967   my $agentnum = '';
968   if ( $p->{'invnum'} ) {
969     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
970       or return { 'error' => 'unknown invnum' };
971     $agentnum = $cust_bill->cust_main->agentnum;
972   }
973
974   my $templatename = $p->{'template'} || $p->{'templatename'};
975
976   #false laziness-ish w/view/cust_bill-logo.cgi
977
978   my $conf = new FS::Conf;
979   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
980     $templatename = "_$1";
981   } else {
982     $templatename = '';
983   }
984
985   my $filename = "logo$templatename.png";
986
987   return { 'error'        => '',
988            'logo'         => $conf->config_binary($filename, $agentnum),
989            'content_type' => 'image/png', #should allow gif, jpg too
990          };
991 }
992
993
994 sub list_invoices {
995   my $p = shift;
996   my $session = _cache->get($p->{'session_id'})
997     or return { 'error' => "Can't resume session" }; #better error message
998
999   my $custnum = $session->{'custnum'};
1000
1001   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1002     or return { 'error' => "unknown custnum $custnum" };
1003
1004   my @cust_bill = $cust_main->cust_bill;
1005
1006   my $balance = 0;
1007
1008   return  { 'error'       => '',
1009             'invoices'    => [
1010               map {
1011                     my $owed = $_->owed;
1012                     $balance += $owed;
1013                     +{ 'invnum'     => $_->invnum,
1014                        '_date'      => $_->_date,
1015                        'date'       => time2str("%b %o, %Y", $_->_date),
1016                        'date_short' => time2str("%m-%d-%Y",  $_->_date),
1017                        'previous'   => sprintf('%.2f', ($_->previous)[0]),
1018                        'charged'    => sprintf('%.2f', $_->charged),
1019                        'owed'       => sprintf('%.2f', $owed),
1020                        'balance'    => sprintf('%.2f', $balance),
1021                      }
1022                   }
1023                   @cust_bill
1024             ]
1025           };
1026 }
1027
1028 sub cancel {
1029   my $p = shift;
1030   my $session = _cache->get($p->{'session_id'})
1031     or return { 'error' => "Can't resume session" }; #better error message
1032
1033   my $custnum = $session->{'custnum'};
1034
1035   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1036     or return { 'error' => "unknown custnum $custnum" };
1037
1038   my @errors = $cust_main->cancel( 'quiet'=>1 );
1039
1040   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1041
1042   return { 'error' => $error };
1043
1044 }
1045
1046 sub list_pkgs {
1047   my $p = shift;
1048
1049   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1050   return { 'error' => $session } if $context eq 'error';
1051
1052   my $search = { 'custnum' => $custnum };
1053   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1054   my $cust_main = qsearchs('cust_main', $search )
1055     or return { 'error' => "unknown custnum $custnum" };
1056
1057   my $conf = new FS::Conf;
1058   
1059 # the duplication below is necessary:
1060 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1061 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1062 # non-backwards-compatible change breaking the software of anyone using the API
1063 # instead of the stock selfservice
1064 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1065   if( $conf->exists('selfservice_server-view-wholesale') ) {
1066     return { 'svcnum'   => $session->{'svcnum'},
1067             'custnum'  => $custnum,
1068             'cust_pkg' => [ map {
1069                           { $_->hash,
1070                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1071                             part_svc =>
1072                               [ map $_->hashref, $_->available_part_svc ],
1073                             cust_svc => 
1074                               [ map { my $ref = { $_->hash,
1075                                                   label => [ $_->label ],
1076                                                 };
1077                                       $ref->{_password} = $_->svc_x->_password
1078                                         if $context eq 'agent'
1079                                         && $conf->exists('agent-showpasswords')
1080                                         && $_->part_svc->svcdb eq 'svc_acct';
1081                                       $ref;
1082                                     } $_->cust_svc
1083                               ],
1084                           };
1085                         } $cust_main->cust_pkg
1086                   ],
1087     'small_custview' =>
1088       small_custview( $cust_main, $conf->config('countrydefault') ),
1089     'wholesale_view' => 1,
1090     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1091     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1092     'lnp' => $conf->exists('svc_phone-lnp'),
1093       };
1094   }
1095
1096   { 'svcnum'   => $session->{'svcnum'},
1097     'custnum'  => $custnum,
1098     'cust_pkg' => [ map {
1099                           my $primary_cust_svc = $_->primary_cust_svc;
1100                           +{ $_->hash,
1101                             $_->part_pkg->hash,
1102                             status => $_->status,
1103                             part_svc =>
1104                               [ map $_->hashref, $_->available_part_svc ],
1105                             cust_svc => 
1106                               [ map { my $ref = { $_->hash,
1107                                                   label => [ $_->label ],
1108                                                 };
1109                                       $ref->{_password} = $_->svc_x->_password
1110                                         if $context eq 'agent'
1111                                         && $conf->exists('agent-showpasswords')
1112                                         && $_->part_svc->svcdb eq 'svc_acct';
1113                                       $ref->{svchash} = { $_->svc_x->hash } if 
1114                                         $_->part_svc->svcdb eq 'svc_phone';
1115                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1116                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1117                                       $ref;
1118                                     } $_->cust_svc
1119                               ],
1120                             primary_cust_svc =>
1121                               $primary_cust_svc
1122                                 ? { $primary_cust_svc->hash,
1123                                     label => [ $primary_cust_svc->label ],
1124                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1125                                     $primary_cust_svc->part_svc->hash,
1126                                   }
1127                                 : {}, #'' ?
1128                           };
1129                         } $cust_main->ncancelled_pkgs
1130                   ],
1131     'small_custview' =>
1132       small_custview( $cust_main, $conf->config('countrydefault') ),
1133   };
1134
1135 }
1136
1137 sub list_svcs {
1138   my $p = shift;
1139
1140   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1141   return { 'error' => $session } if $context eq 'error';
1142
1143   my $search = { 'custnum' => $custnum };
1144   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1145   my $cust_main = qsearchs('cust_main', $search )
1146     or return { 'error' => "unknown custnum $custnum" };
1147
1148   my @cust_svc = ();
1149   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1150   foreach my $cust_pkg ( $p->{'ncancelled'} 
1151                          ? $cust_main->ncancelled_pkgs
1152                          : $cust_main->unsuspended_pkgs ) {
1153     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1154     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1155   }
1156   if ( $p->{'svcdb'} ) {
1157     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1158                   ? $p->{'svcdb'}
1159                   : ref($p->{'svcdb'}) eq 'ARRAY'
1160                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1161                     : { $p->{'svcdb'} => 1 };
1162     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1163   }
1164
1165   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1166   #              @svc_x;
1167
1168     my $conf = new FS::Conf;
1169
1170   { 
1171     'svcnum'   => $session->{'svcnum'},
1172     'custnum'  => $custnum,
1173     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1174     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1175     'svcs'     => [
1176       map { 
1177             my $svc_x = $_->svc_x;
1178             my($label, $value) = $_->label;
1179             my $svcdb = $_->part_svc->svcdb;
1180             my $part_pkg = $_->cust_pkg->part_pkg;
1181
1182             my %hash = (
1183               'svcnum' => $_->svcnum,
1184               'svcdb'  => $svcdb,
1185               'label'  => $label,
1186               'value'  => $value,
1187             );
1188
1189             if ( $svcdb eq 'svc_acct' ) {
1190               %hash = (
1191                 %hash,
1192                 'username'   => $svc_x->username,
1193                 'email'      => $svc_x->email,
1194                 'seconds'    => $svc_x->seconds,
1195                 'upbytes'    => display_bytecount($svc_x->upbytes),
1196                 'downbytes'  => display_bytecount($svc_x->downbytes),
1197                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1198
1199                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1200                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1201                 'recharge_upbytes'    =>
1202                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1203                 'recharge_downbytes'  =>
1204                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1205                 'recharge_totalbytes' =>
1206                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1207                 # more...
1208               );
1209
1210             } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1211               %hash = (
1212                 %hash,
1213               );
1214             }
1215
1216             \%hash;
1217           }
1218           @cust_svc
1219     ],
1220   };
1221
1222 }
1223
1224 sub port_graph {
1225   my $p = shift;
1226   _usage_details( \&_port_graph, $p,
1227                   'svcdb' => 'svc_port',
1228                 );
1229 }
1230
1231 sub _port_graph {
1232   my($svc_port, $begin, $end) = @_;
1233   my @usage = ();
1234   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1235   push @usage, { 'png' => $pngOrError };
1236   (@usage);
1237 }
1238
1239 sub _list_svc_usage {
1240   my($svc_acct, $begin, $end) = @_;
1241   my @usage = ();
1242   foreach my $part_export ( 
1243     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1244     qw( sqlradius sqlradius_withdomain )
1245   ) {
1246     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1247   }
1248   (@usage);
1249 }
1250
1251 sub list_svc_usage {
1252   _usage_details(\&_list_svc_usage, @_);
1253 }
1254
1255 sub _list_support_usage {
1256   my($svc_acct, $begin, $end) = @_;
1257   my @usage = ();
1258   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1259             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1260           ) {
1261     push @usage, { 'seconds'  => $_->seconds,
1262                    'support'  => $_->support,
1263                    '_date'    => $_->_date,
1264                    'id'       => $_->transaction_id,
1265                    'creator'  => $_->creator,
1266                    'subject'  => $_->subject,
1267                    'status'   => $_->status,
1268                    'ticketid' => $_->ticketid,
1269                  };
1270   }
1271   (@usage);
1272 }
1273
1274 sub list_support_usage {
1275   _usage_details(\&_list_support_usage, @_);
1276 }
1277
1278 sub _list_cdr_usage {
1279   my($svc_phone, $begin, $end) = @_;
1280   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1281                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1282 }
1283
1284 sub list_cdr_usage {
1285   my $p = shift;
1286   _usage_details( \&_list_cdr_usage, $p,
1287                   'svcdb' => 'svc_phone',
1288                 );
1289 }
1290
1291 sub _usage_details {
1292   my($callback, $p, %opt) = @_;
1293
1294   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1295   return { 'error' => $session } if $context eq 'error';
1296
1297   my $search = { 'svcnum' => $p->{'svcnum'} };
1298   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1299
1300   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1301
1302   my $svc_x = qsearchs( $svcdb, $search );
1303   return { 'error' => 'No service selected in list_svc_usage' } 
1304     unless $svc_x;
1305
1306   my $header = $svcdb eq 'svc_phone'
1307                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1308                  : [];
1309
1310   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1311   my $freq     = $cust_pkg->part_pkg->freq;
1312   my $start    = $cust_pkg->setup;
1313   #my $end      = $cust_pkg->bill; # or time?
1314   my $end      = time;
1315
1316   unless ( $p->{beginning} ) {
1317     $p->{beginning} = $cust_pkg->last_bill;
1318     $p->{ending}    = $end;
1319   }
1320
1321   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1322
1323   #kinda false laziness with FS::cust_main::bill, but perhaps
1324   #we should really change this bit to DateTime and DateTime::Duration
1325   #
1326   #change this bit to use Date::Manip? CAREFUL with timezones (see
1327   # mailing list archive)
1328   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1329     (localtime($p->{ending}) )[0,1,2,3,4,5];
1330   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1331     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1332
1333   if ( $freq =~ /^\d+$/ ) {
1334     $nmon += $freq;
1335     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1336     $pmon -= $freq;
1337     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1338   } elsif ( $freq =~ /^(\d+)w$/ ) {
1339     my $weeks = $1;
1340     $nmday += $weeks * 7;
1341     $pmday -= $weeks * 7;
1342   } elsif ( $freq =~ /^(\d+)d$/ ) {
1343     my $days = $1;
1344     $nmday += $days;
1345     $pmday -= $days;
1346   } elsif ( $freq =~ /^(\d+)h$/ ) {
1347     my $hours = $1;
1348     $nhour += $hours;
1349     $phour -= $hours;
1350   } else {
1351     return { 'error' => "unparsable frequency: ". $freq };
1352   }
1353   
1354   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1355   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1356
1357   { 
1358     'error'     => '',
1359     'svcnum'    => $p->{svcnum},
1360     'beginning' => $p->{beginning},
1361     'ending'    => $p->{ending},
1362     'previous'  => ($previous > $start) ? $previous : $start,
1363     'next'      => ($next < $end) ? $next : $end,
1364     'header'    => $header,
1365     'usage'     => \@usage,
1366   };
1367 }
1368
1369 sub order_pkg {
1370   my $p = shift;
1371
1372   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1373   return { 'error' => $session } if $context eq 'error';
1374
1375   my $search = { 'custnum' => $custnum };
1376   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1377   my $cust_main = qsearchs('cust_main', $search )
1378     or return { 'error' => "unknown custnum $custnum" };
1379
1380   my $status = $cust_main->status;
1381   #false laziness w/ClientAPI/Signup.pm
1382
1383   my $cust_pkg = new FS::cust_pkg ( {
1384     'custnum' => $custnum,
1385     'pkgpart' => $p->{'pkgpart'},
1386   } );
1387   my $error = $cust_pkg->check;
1388   return { 'error' => $error } if $error;
1389
1390   my @svc = ();
1391   unless ( $p->{'svcpart'} eq 'none' ) {
1392
1393     my $svcdb;
1394     my $svcpart = '';
1395     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1396       $svcpart = $1;
1397       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1398       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1399       $svcdb = $part_svc->svcdb;
1400     } else {
1401       $svcdb = 'svc_acct';
1402     }
1403     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1404
1405     my %fields = (
1406       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1407       'svc_domain'   => [ qw( domain ) ],
1408       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1409       'svc_external' => [ qw( id title ) ],
1410       'svc_pbx'      => [ qw( id title ) ],
1411     );
1412   
1413     my $svc_x = "FS::$svcdb"->new( {
1414       'svcpart'   => $svcpart,
1415       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1416     } );
1417     
1418     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1419       my @acct_snarf;
1420       my $snarfnum = 1;
1421       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1422         my $acct_snarf = new FS::acct_snarf ( {
1423           'machine'   => $p->{"snarf_machine$snarfnum"},
1424           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1425           'username'  => $p->{"snarf_username$snarfnum"},
1426           '_password' => $p->{"snarf_password$snarfnum"},
1427         } );
1428         $snarfnum++;
1429         push @acct_snarf, $acct_snarf;
1430       }
1431       $svc_x->child_objects( \@acct_snarf );
1432     }
1433     
1434     my $y = $svc_x->setdefault; # arguably should be in new method
1435     return { 'error' => $y } if $y && !ref($y);
1436   
1437     $error = $svc_x->check;
1438     return { 'error' => $error } if $error;
1439
1440     push @svc, $svc_x;
1441
1442   }
1443
1444   use Tie::RefHash;
1445   tie my %hash, 'Tie::RefHash';
1446   %hash = ( $cust_pkg => \@svc );
1447   #msgcat
1448   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1449   return { 'error' => $error } if $error;
1450
1451   my $conf = new FS::Conf;
1452   if ( $conf->exists('signup_server-realtime') ) {
1453
1454     my $bill_error = _do_bop_realtime( $cust_main, $status );
1455
1456     if ($bill_error) {
1457       $cust_pkg->cancel('quiet'=>1);
1458       return $bill_error;
1459     } else {
1460       $cust_pkg->reexport;
1461     }
1462
1463   } else {
1464     $cust_pkg->reexport;
1465   }
1466
1467   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1468
1469   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1470
1471 }
1472
1473 sub change_pkg {
1474   my $p = shift;
1475
1476   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1477   return { 'error' => $session } if $context eq 'error';
1478
1479   my $search = { 'custnum' => $custnum };
1480   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1481   my $cust_main = qsearchs('cust_main', $search )
1482     or return { 'error' => "unknown custnum $custnum" };
1483
1484   my $status = $cust_main->status;
1485   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1486     or return { 'error' => "unknown package $p->{pkgnum}" };
1487
1488   my @newpkg;
1489   my $error = FS::cust_pkg::order( $custnum,
1490                                    [$p->{pkgpart}],
1491                                    [$p->{pkgnum}],
1492                                    \@newpkg,
1493                                  );
1494
1495   my $conf = new FS::Conf;
1496   if ( $conf->exists('signup_server-realtime') ) {
1497
1498     my $bill_error = _do_bop_realtime( $cust_main, $status );
1499
1500     if ($bill_error) {
1501       $newpkg[0]->suspend;
1502       return $bill_error;
1503     } else {
1504       $newpkg[0]->reexport;
1505     }
1506
1507   } else {  
1508     $newpkg[0]->reexport;
1509   }
1510
1511   return { error => '', pkgnum => $cust_pkg->pkgnum };
1512
1513 }
1514
1515 sub order_recharge {
1516   my $p = shift;
1517
1518   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1519   return { 'error' => $session } if $context eq 'error';
1520
1521   my $search = { 'custnum' => $custnum };
1522   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1523   my $cust_main = qsearchs('cust_main', $search )
1524     or return { 'error' => "unknown custnum $custnum" };
1525
1526   my $status = $cust_main->status;
1527   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1528     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1529
1530   my $svc_x = $cust_svc->svc_x;
1531   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1532
1533   my %vhash =
1534     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1535     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1536          recharge_totalbytes );
1537   my $amount = $part_pkg->option('recharge_amount', 1); 
1538   
1539   my ($l, $v, $d) = $cust_svc->label;  # blah
1540   my $pkg = "Recharge $v"; 
1541
1542   my $bill_error = $cust_main->charge($amount, $pkg,
1543      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1544      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1545      $part_pkg->taxclass); #meh
1546
1547   my $conf = new FS::Conf;
1548   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1549
1550     $bill_error = _do_bop_realtime( $cust_main, $status );
1551
1552     if ($bill_error) {
1553       return $bill_error;
1554     } else {
1555       my $error = $svc_x->recharge (\%vhash);
1556       return { 'error' => $error } if $error;
1557     }
1558
1559   } else {  
1560     my $error = $bill_error;
1561     $error ||= $svc_x->recharge (\%vhash);
1562     return { 'error' => $error } if $error;
1563   }
1564
1565   return { error => '', svc => $cust_svc->part_svc->svc };
1566
1567 }
1568
1569 sub _do_bop_realtime {
1570   my ($cust_main, $status) = (shift, shift);
1571
1572     my $old_balance = $cust_main->balance;
1573
1574     my $bill_error =    $cust_main->bill
1575                      || $cust_main->apply_payments_and_credits
1576                      || $cust_main->realtime_collect('selfservice' => 1);
1577
1578     if (    $cust_main->balance > $old_balance
1579          && $cust_main->balance > 0
1580          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1581               1 : $status eq 'suspended' ) ) {
1582       #this makes sense.  credit is "un-doing" the invoice
1583       my $conf = new FS::Conf;
1584       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1585                           'self-service decline',
1586                           'reason_type' => $conf->config('signup_credit_type'),
1587                         );
1588       $cust_main->apply_credits( 'order' => 'newest' );
1589
1590       return { 'error' => '_decline', 'bill_error' => $bill_error };
1591     }
1592
1593     '';
1594 }
1595
1596 sub renew_info {
1597   my $p = shift;
1598
1599   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1600   return { 'error' => $session } if $context eq 'error';
1601
1602   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1603     or return { 'error' => "unknown custnum $custnum" };
1604
1605   my @cust_pkg = sort { $a->bill <=> $b->bill }
1606                  grep { $_->part_pkg->freq ne '0' }
1607                  $cust_main->ncancelled_pkgs;
1608
1609   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1610
1611   my $total = $cust_main->balance;
1612
1613   my @array = map {
1614                     my $bill = $_->bill;
1615                     $total += $_->part_pkg->base_recur($_, \$bill);
1616                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1617                     {
1618                       'pkgnum'             => $_->pkgnum,
1619                       'amount'             => sprintf('%.2f', $total),
1620                       'bill_date'          => $_->bill,
1621                       'bill_date_pretty'   => time2str('%x', $_->bill),
1622                       'renew_date'         => $renew_date,
1623                       'renew_date_pretty'  => time2str('%x', $renew_date),
1624                       'expire_date'        => $_->expire,
1625                       'expire_date_pretty' => time2str('%x', $_->expire),
1626                     };
1627                   }
1628                   @cust_pkg;
1629
1630   return { 'dates' => \@array };
1631
1632 }
1633
1634 sub payment_info_renew_info {
1635   my $p = shift;
1636   my $renew_info   = renew_info($p);
1637   my $payment_info = payment_info($p);
1638   return { %$renew_info,
1639            %$payment_info,
1640          };
1641 }
1642
1643 sub order_renew {
1644   my $p = shift;
1645
1646   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1647   return { 'error' => $session } if $context eq 'error';
1648
1649   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1650     or return { 'error' => "unknown custnum $custnum" };
1651
1652   my $date = $p->{'date'};
1653
1654   my $now = time;
1655
1656   #freeside-daily -n -d $date fs_daily $custnum
1657   $cust_main->bill_and_collect( 'time'         => $date,
1658                                 'invoice_time' => $now,
1659                                 'actual_time'  => $now,
1660                                 'check_freq'   => '1d',
1661                               );
1662
1663   return { 'error' => '' };
1664
1665 }
1666
1667 sub suspend_pkg {
1668   my $p = shift;
1669   my $session = _cache->get($p->{'session_id'})
1670     or return { 'error' => "Can't resume session" }; #better error message
1671
1672   my $custnum = $session->{'custnum'};
1673
1674   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1675     or return { 'error' => "unknown custnum $custnum" };
1676
1677   my $conf = new FS::Conf;
1678   my $reasonnum = 
1679     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1680       or return { 'error' => 'Permission denied' };
1681
1682   my $pkgnum = $p->{'pkgnum'};
1683
1684   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1685                                         'pkgnum'  => $pkgnum,   } )
1686     or return { 'error' => "unknown pkgnum $pkgnum" };
1687
1688   my $error = $cust_pkg->suspend(reason => $reasonnum);
1689   return { 'error' => $error };
1690
1691 }
1692
1693 sub cancel_pkg {
1694   my $p = shift;
1695   my $session = _cache->get($p->{'session_id'})
1696     or return { 'error' => "Can't resume session" }; #better error message
1697
1698   my $custnum = $session->{'custnum'};
1699
1700   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1701     or return { 'error' => "unknown custnum $custnum" };
1702
1703   my $pkgnum = $p->{'pkgnum'};
1704
1705   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1706                                         'pkgnum'  => $pkgnum,   } )
1707     or return { 'error' => "unknown pkgnum $pkgnum" };
1708
1709   my $error = $cust_pkg->cancel('quiet' => 1);
1710   return { 'error' => $error };
1711
1712 }
1713
1714 sub provision_phone {
1715  my $p = shift;
1716  my @bulkdid;
1717  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1718
1719  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1720       my($context, $session, $custnum) = _custoragent_session_custnum($p);
1721       return { 'error' => $session } if $context eq 'error';
1722     
1723       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1724       return { 'error' => 'service not found' } unless $svc_phone;
1725       return { 'error' => 'invalid svcnum' } 
1726         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1727
1728       $svc_phone->email($p->{'email'}) 
1729         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1730       $svc_phone->forwarddst($p->{'forwarddst'}) 
1731         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
1732             && $p->{'forwarddst'} =~ /^(\d+|)$/;
1733       return { 'error' => $svc_phone->replace };
1734  }
1735
1736 # single DID LNP
1737  unless($p->{'lnp'}) {
1738     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1739     $p->{'lnp_status'} = "portingin";
1740     return _provision( 'FS::svc_phone',
1741                   [qw(lnp_desired_due_date lnp_other_provider 
1742                     lnp_other_provider_account phonenum countrycode lnp_status)],
1743                   [qw(phonenum countrycode)],
1744                   $p,
1745                   @_
1746                 );
1747  }
1748
1749 # single DID order
1750  unless (scalar(@bulkdid)) {
1751     return _provision( 'FS::svc_phone',
1752                   [qw(phonenum countrycode)],
1753                   [qw(phonenum countrycode)],
1754                   $p,
1755                   @_
1756                 );
1757  }
1758
1759 # bulk DID order case
1760   my $error;
1761   foreach my $did ( @bulkdid ) {
1762     $did =~ s/[^0-9]//g;
1763     $error = _provision( 'FS::svc_phone',
1764               [qw(phonenum countrycode)],
1765               [qw(phonenum countrycode)],
1766               {
1767                 'pkgnum' => $p->{'pkgnum'},
1768                 'svcpart' => $p->{'svcpart'},
1769                 'phonenum' => $did,
1770                 'countrycode' => $p->{'countrycode'},
1771                 'session_id' => $p->{'session_id'},
1772               }
1773             );
1774     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1775   }
1776   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1777 }
1778
1779 sub provision_acct {
1780   my $p = shift;
1781   warn "provision_acct called\n"
1782     if $DEBUG;
1783
1784   return { 'error' => gettext('passwords_dont_match') }
1785     if $p->{'_password'} ne $p->{'_password2'};
1786   return { 'error' => gettext('empty_password') }
1787     unless length($p->{'_password'});
1788  
1789   if ($p->{'domsvc'}) {
1790     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1791                                                   qw ( svcpart pkgnum ) );
1792     return { 'error' => gettext('invalid_domain') }
1793       unless ($domains{$p->{'domsvc'}});
1794   }
1795
1796   warn "provision_acct calling _provision\n"
1797     if $DEBUG;
1798   _provision( 'FS::svc_acct',
1799               [qw(username _password domsvc)],
1800               [qw(username _password domsvc)],
1801               $p,
1802               @_
1803             );
1804 }
1805
1806 sub provision_external {
1807   my $p = shift;
1808   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1809   _provision( 'FS::svc_external',
1810               [],
1811               [qw(id title)],
1812               $p,
1813               @_
1814             );
1815 }
1816
1817 sub _provision {
1818   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1819   warn "_provision called for $class\n"
1820     if $DEBUG;
1821
1822   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1823   return { 'error' => $session } if $context eq 'error';
1824
1825   my $search = { 'custnum' => $custnum };
1826   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1827   my $cust_main = qsearchs('cust_main', $search )
1828     or return { 'error' => "unknown custnum $custnum" };
1829
1830   my $pkgnum = $p->{'pkgnum'};
1831
1832   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1833     if $DEBUG;
1834   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1835                                         'pkgnum'  => $pkgnum,
1836                                                                } )
1837     or return { 'error' => "unknown pkgnum $pkgnum" };
1838
1839   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1840     if $DEBUG;
1841   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1842     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1843
1844   warn "creating $class record\n"
1845     if $DEBUG;
1846   my $svc_x = $class->new( {
1847     'pkgnum'  => $p->{'pkgnum'},
1848     'svcpart' => $p->{'svcpart'},
1849     map { $_ => $p->{$_} } @$fields
1850   } );
1851   warn "inserting $class record\n"
1852     if $DEBUG;
1853   my $error = $svc_x->insert;
1854
1855   unless ( $error ) {
1856     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1857       if $DEBUG;
1858     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1859   }
1860
1861   my $return = { 'svc'   => $part_svc->svc,
1862                  'error' => $error,
1863                  map { $_ => $svc_x->get($_) } @$return_fields
1864                };
1865   warn "_provision returning ". Dumper($return). "\n"
1866     if $DEBUG;
1867   return $return;
1868
1869 }
1870
1871 sub part_svc_info {
1872   my $p = shift;
1873
1874   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1875   return { 'error' => $session } if $context eq 'error';
1876
1877   my $search = { 'custnum' => $custnum };
1878   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1879   my $cust_main = qsearchs('cust_main', $search )
1880     or return { 'error' => "unknown custnum $custnum" };
1881
1882   my $pkgnum = $p->{'pkgnum'};
1883
1884   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1885                                         'pkgnum'  => $pkgnum,
1886                                                                } )
1887     or return { 'error' => "unknown pkgnum $pkgnum" };
1888
1889   my $svcpart = $p->{'svcpart'};
1890
1891   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1892                                       'svcpart' => $svcpart,           } )
1893     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1894   my $part_svc = $pkg_svc->part_svc;
1895
1896   my $conf = new FS::Conf;
1897
1898   my $ret = {
1899     'svc'     => $part_svc->svc,
1900     'svcdb'   => $part_svc->svcdb,
1901     'pkgnum'  => $pkgnum,
1902     'svcpart' => $svcpart,
1903     'custnum' => $custnum,
1904
1905     'security_phrase' => 0, #XXX !
1906     'svc_acct_pop'    => [], #XXX !
1907     'popnum'          => '',
1908     'init_popstate'   => '',
1909     'popac'           => '',
1910     'acstate'         => '',
1911
1912     'small_custview' =>
1913       small_custview( $cust_main, $conf->config('countrydefault') ),
1914
1915   };
1916
1917   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
1918                      && $ret->{'svcdb'} eq 'svc_phone') {
1919         $ret->{'svcnum'} = $p->{'svcnum'};
1920         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1921         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1922             $ret->{'email'} = $svc_phone->email;
1923             $ret->{'forwarddst'} = $svc_phone->forwarddst;
1924         }
1925   }
1926
1927   $ret;
1928 }
1929
1930 sub unprovision_svc {
1931   my $p = shift;
1932
1933   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1934   return { 'error' => $session } if $context eq 'error';
1935
1936   my $search = { 'custnum' => $custnum };
1937   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1938   my $cust_main = qsearchs('cust_main', $search )
1939     or return { 'error' => "unknown custnum $custnum" };
1940
1941   my $svcnum = $p->{'svcnum'};
1942
1943   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
1944     or return { 'error' => "unknown svcnum $svcnum" };
1945
1946   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1947     unless $cust_svc->cust_pkg->custnum == $custnum;
1948
1949   my $conf = new FS::Conf;
1950
1951   return { 'svc'   => $cust_svc->part_svc->svc,
1952            'error' => $cust_svc->cancel,
1953            'small_custview' =>
1954              small_custview( $cust_main, $conf->config('countrydefault') ),
1955          };
1956
1957 }
1958
1959 sub myaccount_passwd {
1960   my $p = shift;
1961   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1962   return { 'error' => $session } if $context eq 'error';
1963
1964   return { 'error' => "New passwords don't match." }
1965     if $p->{'new_password'} ne $p->{'new_password2'};
1966
1967   return { 'error' => 'Enter new password' }
1968     unless length($p->{'new_password'});
1969
1970   #my $search = { 'custnum' => $custnum };
1971   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1972   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1973   my $search = " AND custnum = $1";
1974   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1975
1976   my $svc_acct = qsearchs( {
1977     'table'     => 'svc_acct',
1978     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1979                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
1980                    'LEFT JOIN cust_main USING ( custnum ) ',
1981     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
1982     'extra_sql' => $search, #important
1983   } )
1984     or return { 'error' => "Service not found" };
1985
1986   $svc_acct->_password($p->{'new_password'});
1987   my $error = $svc_acct->replace();
1988
1989   my($label, $value) = $svc_acct->cust_svc->label;
1990
1991   return { 'error' => $error,
1992            'label' => $label,
1993            'value' => $value,
1994          };
1995
1996 }
1997
1998 sub create_ticket {
1999   my $p = shift;
2000   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2001   return { 'error' => $session } if $context eq 'error';
2002
2003   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2004   FS::TicketSystem->init();
2005
2006   my $conf = new FS::Conf;
2007   my $queue = $p->{'queue'}
2008               || $conf->config('ticket_system-selfservice_queueid')
2009               || $conf->config('ticket_system-default_queueid');
2010
2011   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2012   my $err_or_ticket = FS::TicketSystem->create_ticket(
2013     '', #create RT session based on FS CurrentUser (fs_selfservice)
2014     'queue'   => $queue,
2015     'custnum' => $custnum,
2016     'svcnum'  => $session->{'svcnum'},
2017     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2018   );
2019
2020   if ( ref($err_or_ticket) ) {
2021     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2022       if $DEBUG;
2023     return { 'error'     => '',
2024              'ticket_id' => $err_or_ticket->id,
2025            };
2026   } else {
2027     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2028       if $DEBUG;
2029     return { 'error' => $err_or_ticket };
2030   }
2031
2032
2033 }
2034
2035 sub did_report {
2036   my $p = shift;
2037   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2038   return { 'error' => $session } if $context eq 'error';
2039  
2040   return { error => 'requested format not implemented' } 
2041     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2042
2043   my $conf = new FS::Conf;
2044   my $age_threshold = 0;
2045   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2046     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2047
2048   my $search = { 'custnum' => $custnum };
2049   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2050   my $cust_main = qsearchs('cust_main', $search )
2051     or return { 'error' => "unknown custnum $custnum" };
2052
2053 # does it make more sense to just run one sql query for this instead of all the
2054 # insanity below? would increase performance greately for large data sets?
2055   my @svc_phone = ();
2056   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2057         my @part_svc = $cust_pkg->part_svc;
2058         foreach my $part_svc ( @part_svc ) {
2059             if($part_svc->svcdb eq 'svc_phone'){
2060                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2061                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2062                     push @svc_phone, $cust_pkg_svc->svc_x
2063                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2064                 }
2065             }
2066         }
2067   }
2068
2069   my $csv;
2070   my $xls;
2071   my($xls_r,$xls_c) = (0,0);
2072   my $xls_workbook;
2073   my $content = '';
2074   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2075   if($p->{'format'} eq 'csv') {
2076     $csv = new Text::CSV_XS { 'always_quote' => 1,
2077                                  'eol'          => "\n",
2078                                 };
2079     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2080     $content .= $csv->string;
2081   }
2082   elsif($p->{'format'} eq 'xls') {
2083     my $XLS1 = new IO::Scalar \$content;
2084     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2085         or return { 'error' => "Error opening .xls file: $!" };
2086     $xls = $xls_workbook->add_worksheet('DIDs');
2087     foreach ( @fields ) {
2088         $xls->write(0,$xls_c++,$_);
2089     }
2090     $xls_r++;
2091   }
2092
2093   foreach my $svc_phone ( @svc_phone ) {
2094     my @cols = map { $svc_phone->$_ } @fields;
2095     if($p->{'format'} eq 'csv') {
2096         return { 'error' => 'Unable to create CSV' } 
2097             unless $csv->combine(@cols);
2098         $content .= $csv->string;
2099     }
2100     elsif($p->{'format'} eq 'xls') {
2101         $xls_c = 0;
2102         foreach ( @cols ) {
2103             $xls->write($xls_r,$xls_c++,$_);
2104         }
2105         $xls_r++;
2106     }
2107   }
2108
2109   $xls_workbook->close() if $p->{'format'} eq 'xls';
2110   
2111   { content => $content, format => $p->{'format'}, };
2112 }
2113
2114 sub get_ticket {
2115   my $p = shift;
2116   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2117   return { 'error' => $session } if $context eq 'error';
2118
2119   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2120   FS::TicketSystem->init();
2121   return { 'error' => 'get_ticket configuration error' }
2122     if $FS::TicketSystem::system ne 'RT_Internal';
2123
2124   # check existence and ownership as part of this
2125   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2126   my $rt_session = FS::TicketSystem->session('');
2127   my $Ticket = FS::TicketSystem->get_ticket_object(
2128     $rt_session, 
2129     ticket_id => $p->{'ticket_id'},
2130     custnum => $custnum
2131   );
2132   return { 'error' => 'ticket not found' } if !$Ticket;
2133
2134   if ( length( $p->{'subject'} || '' ) ) {
2135     # subject change
2136     if ( $p->{'subject'} ne $Ticket->Subject ) {
2137       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2138       return { 'error' => "unable to set subject: $msg" } if !$val;
2139     }
2140   }
2141
2142   if(length($p->{'reply'})) {
2143     my @err_or_res = FS::TicketSystem->correspond_ticket(
2144       $rt_session,
2145       'ticket_id' => $p->{'ticket_id'},
2146       'content' => $p->{'reply'},
2147     );
2148
2149     return { 'error' => 'unable to reply to ticket' } 
2150     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2151   }
2152
2153   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2154   my $err_or_ticket = FS::TicketSystem->get_ticket(
2155     $rt_session,
2156     'ticket_id' => $p->{'ticket_id'},
2157   );
2158
2159   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2160     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2161       if $DEBUG;
2162     return { 'error' => $err_or_ticket };
2163   }
2164
2165   my @custs = @{$err_or_ticket->{'custs'}};
2166   my @txns = @{$err_or_ticket->{'txns'}};
2167   my @filtered_txns;
2168
2169   # superseded by check in get_ticket_object
2170   #return { 'error' => 'invalid ticket requested' } 
2171   #unless grep($_ eq $custnum, @custs);
2172
2173   foreach my $txn ( @txns ) {
2174     push @filtered_txns, $txn 
2175     if ($txn->{'type'} eq 'EmailRecord' 
2176       || $txn->{'type'} eq 'Correspond'
2177       || $txn->{'type'} eq 'Create');
2178   }
2179
2180   warn "$me get_ticket: successful: \n"
2181   if $DEBUG;
2182   return { 'error'     => '',
2183     'transactions' => \@filtered_txns,
2184     'ticket_fields' => $err_or_ticket->{'fields'},
2185     'ticket_id' => $p->{'ticket_id'},
2186   };
2187 }
2188
2189 sub adjust_ticket_priority {
2190   my $p = shift;
2191   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2192   return { 'error' => $session } if $context eq 'error';
2193
2194   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2195   FS::TicketSystem->init;
2196   my $ss_priority = FS::TicketSystem->selfservice_priority;
2197
2198   return { 'error' => 'adjust_ticket_priority configuration error' }
2199     if $FS::TicketSystem::system ne 'RT_Internal'
2200       or !$ss_priority;
2201
2202   my $values = $p->{'values'}; #hashref, id => priority value
2203   my %ticket_error;
2204
2205   foreach my $id (keys %$values) {
2206     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2207     my $Ticket = FS::TicketSystem->get_ticket_object('',
2208       'ticket_id' => $id,
2209       'custnum'   => $custnum,
2210     );
2211     if ( !$Ticket ) {
2212       $ticket_error{$id} = 'ticket not found';
2213       next;
2214     }
2215     
2216   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2217   # We're not going to implement it for RT_External.
2218     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2219     my $new_value = $values->{$id};
2220     next if $old_value eq $new_value;
2221
2222     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2223
2224     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2225     # a single-valued custom field, which it should be.  If it's not, you're 
2226     # doing something wrong.
2227     my ($val, $msg);
2228     if ( length($new_value) ) {
2229       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2230         Field => $ss_priority,
2231         Value => $new_value,
2232       );
2233     }
2234     else {
2235       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2236         Field => $ss_priority,
2237         Value => $old_value,
2238       );
2239     }
2240
2241     $ticket_error{$id} = $msg if !$val;
2242     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2243   }
2244   return { 'error' => '',
2245            'ticket_error' => \%ticket_error,
2246            %{ customer_info($p) } # send updated customer info back
2247          }
2248 }
2249
2250 #--
2251
2252 sub _custoragent_session_custnum {
2253   my $p = shift;
2254
2255   my($context, $session, $custnum);
2256   if ( $p->{'session_id'} ) {
2257
2258     $context = 'customer';
2259     $session = _cache->get($p->{'session_id'})
2260       or return ( 'error' => "Can't resume session" ); #better error message
2261     $custnum = $session->{'custnum'};
2262
2263   } elsif ( $p->{'agent_session_id'} ) {
2264
2265     $context = 'agent';
2266     my $agent_cache = new FS::ClientAPI_SessionCache( {
2267       'namespace' => 'FS::ClientAPI::Agent',
2268     } );
2269     $session = $agent_cache->get($p->{'agent_session_id'})
2270       or return ( 'error' => "Can't resume session" ); #better error message
2271     $custnum = $p->{'custnum'};
2272
2273   } else {
2274     $context = 'error';
2275     return ( 'error' => "Can't resume session" ); #better error message
2276   }
2277
2278   ($context, $session, $custnum);
2279
2280 }
2281
2282 1;
2283