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