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