RT# 39340 - removed min_selfservice dir and merged into ng_selfservice
[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 Digest::SHA qw(sha512_hex);
11 use Date::Format;
12 use Time::Duration;
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
15 use HTML::Entities;
16 use Text::CSV_XS;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
20 use FS::UI::Web;
21 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Conf;
23 #use FS::UID qw(dbh);
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
28 use FS::TicketSystem;
29 use FS::ClientAPI_SessionCache;
30 use FS::cust_svc;
31 use FS::svc_acct;
32 use FS::svc_forward;
33 use FS::svc_domain;
34 use FS::svc_phone;
35 use FS::svc_external;
36 use FS::svc_dsl;
37 use FS::dsl_device;
38 use FS::part_svc;
39 use FS::cust_main;
40 use FS::cust_bill;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
43 use FS::part_pkg;
44 use FS::cust_pkg;
45 use FS::payby;
46 use FS::acct_rt_transaction;
47 use FS::msg_template;
48 use FS::contact;
49 use FS::cust_contact;
50 use FS::cust_location;
51 use FS::cust_payby;
52
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
56
57 $DEBUG = 0;
58 $me = '[FS::ClientAPI::MyAccount]';
59
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62   first last company daytime night fax mobile
63   locale
64   ss stateid stateid_state
65 );
66 @location_editable_fields = qw(
67   address1 address2 city county state zip country
68 );
69
70
71 BEGIN { #preload to reduce time customer_info takes
72   if ( $FS::TicketSystem::system ) {
73     warn "$me: initializing ticket system\n" if $DEBUG;
74     FS::TicketSystem->init();
75   }
76 }
77
78 sub _cache {
79   $cache ||= new FS::ClientAPI_SessionCache( {
80                'namespace' => 'FS::ClientAPI::MyAccount',
81              } );
82 }
83
84 sub skin_info {
85   my $p = shift;
86
87   my($context, $session, $custnum) = _custoragent_session_custnum($p);
88   #return { 'error' => $session } if $context eq 'error';
89
90   my $domain = $session->{'domain'};
91
92   my $agentnum = '';
93   if ( $context eq 'customer' && $custnum ) {
94
95     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
96       or die dbh->errstr;
97
98     $sth->execute($custnum) or die $sth->errstr;
99
100     $agentnum = $sth->fetchrow_arrayref->[0]
101       or die "no agentnum for custnum $custnum";
102
103   #} elsif ( $context eq 'agent' ) {
104   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
105     $agentnum = $1;
106   }
107   $p->{'agentnum'} = $agentnum;
108
109   my $conf = new FS::Conf;
110
111   #false laziness w/Signup.pm
112
113   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
114
115   if ( $skin_info_cache_agent ) {
116
117     warn "$me loading cached skin info for agentnum $agentnum\n"
118       if $DEBUG > 1;
119
120   } else {
121
122     warn "$me populating skin info cache for agentnum $agentnum\n"
123       if $DEBUG > 1;
124
125     my $menu = $conf->config("ng_selfservice-menu", $agentnum );
126
127     $skin_info_cache_agent = {
128       'agentnum' => $agentnum,
129       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
130         qw( company_name date_format ) ),
131       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
132         qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
133             text_color link_color vlink_color hlink_color alink_color
134             font title_color title_align title_size menu_bgcolor menu_fontsize
135           )
136       ),
137       'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
138       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
139         qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
140       ),
141       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
142         qw( title_left_image title_right_image
143             menu_top_image menu_body_image menu_bottom_image
144           )
145       ),
146       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
147       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
148         qw( head body_header body_footer company_address ) ),
149       'money_char' => $conf->config("money_char") || '$',
150       'menu'  => _menu($domain,$menu),
151     };
152
153     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
154
155   }
156
157   #{ %$skin_info_cache_agent };
158   $skin_info_cache_agent;
159
160 }
161
162 ## checks if page is in menu listing, if not sends to main with error.
163 sub check_access {
164  my $p = shift;
165  my $error;
166
167  return if $p->{'page'} eq "index.php";
168  return if $p->{'page'} eq "ip_login.php";
169
170  return if substr($p->{'page'}, 0, length("process_")) eq "process_";
171
172  my $conf = new FS::Conf;
173
174  my($context, $session, $custnum) = _custoragent_session_custnum($p);
175
176  my $domain = ref($session) ? $session->{'domain'} : '';
177
178  my $agentnum = '';
179  if ( $context eq 'customer' && $custnum ) {
180
181   my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
182     or die dbh->errstr;
183
184   $sth->execute($custnum) or die $sth->errstr;
185
186   $agentnum = $sth->fetchrow_arrayref->[0]
187     or die "no agentnum for custnum $custnum";
188
189   #} elsif ( $context eq 'agent' ) {
190   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
191     $agentnum = $1;
192   }
193   $p->{'agentnum'} = $agentnum;
194
195  my $menu = $conf->config("ng_selfservice-menu", $agentnum );
196
197  my $allowed_pages = _menu($domain,$menu);
198
199  my %allowed;
200  my @lines = split /\n/, $allowed_pages;
201  foreach my $line (@lines) {
202   chomp; # remove newlines
203   $line =~ s/^\s+//;  # remove leading whitespace
204   next unless length($line);
205   my (@pages) = split(/ /, $line, 2);
206   $allowed{$pages[0]} = $pages[1];
207  }
208
209  $error = "You do not have access to the page ".$allowed{$p->{page}} unless $allowed{$p->{page}};
210
211  return { 'error' => $error, };
212
213 }
214
215 sub _menu {
216  my $p = shift;
217  my $m = shift;
218
219  my $menu;
220
221  if ($p eq 'ip_mac') {
222    $menu =       'main.php Home
223
224                  payment.php Payments
225                  payment_cc.php Credit Card Payment
226                  payment_ach.php Electronic Check Payment
227                  payment_paypal.php PayPal Payment
228                  payment_webpay.php Webpay Payments
229
230                  docs.php FAQs
231
232                  logout.php Logout
233                 ';
234  }
235  else {
236    $menu = join("\n", $m ) ||
237                 'main.php Home
238
239                  services.php Services
240                  services.php My Services
241                  services_new.php Order a new service
242
243                  personal.php Profile
244                  personal.php Personal Information
245                  password.php Change Password
246
247                  payment.php Payments
248                  payment_cc.php Credit Card Payment
249                  payment_ach.php Electronic Check Payment
250                  payment_paypal.php PayPal Payment
251                  payment_webpay.php Webpay Payments
252
253                  usage.php Usage
254                  usage_data.php Data usage
255                  usage_cdr.php Call usage
256
257                  tickets.php Help Desk
258                  tickets.php Open Tickets
259                  tickets_resolved.php Resolved Tickets
260                  ticket_create.php Create a new ticket
261
262                  docs.php FAQs
263
264                  logout.php Logout
265                 ';
266  }
267  return $menu;
268 }
269
270 sub get_mac_address {
271   my $p = shift;
272
273 ## access radius exports acct tables to get mac
274   my @part_export = ();
275   @part_export = (
276     qsearch( 'part_export', { 'exporttype' => 'sqlradius' } ),
277     qsearch( 'part_export', { 'exporttype' => 'sqlradius_withdomain' } ),
278     qsearch( 'part_export', { 'exporttype' => 'broadband_sqlradius' } ),
279   );
280
281   my @sessions;
282   foreach my $part_export (@part_export) {
283     push @sessions, ( @{ $part_export->usage_sessions( {
284       'ip' => $p->{'ip'},
285       'session_status' => 'open',
286     } ) } );
287   }
288
289   return { 'mac_address' => $sessions[0]->{'callingstationid'}, };
290 }
291
292 sub login_info {
293   my $p = shift;
294
295   my $conf = new FS::Conf;
296
297   my %info = (
298     %{ skin_info($p) },
299     'phone_login'      => $conf->exists('selfservice_server-phone_login'),
300     'single_domain'    => scalar($conf->config('selfservice_server-single_domain')),
301     'banner_url'       => scalar($conf->config('selfservice-login_banner_url')),
302     'banner_image_md5' => 
303       md5_hex($conf->config_binary('selfservice-login_banner_image')),
304   );
305
306   return \%info;
307
308 }
309
310 sub login_banner_image {
311   my $p = shift;
312   my $conf = new FS::Conf;
313   my $image = $conf->config_binary('selfservice-login_banner_image');
314   return { 
315     'md5'   => md5_hex($image),
316     'image' => $image,
317   };
318 }
319
320 #false laziness w/FS::ClientAPI::passwd::passwd
321 sub login {
322   my $p = shift;
323
324   my $conf = new FS::Conf;
325
326   my $svc_x = '';
327   my $session = {};
328   if ( $p->{'domain'} eq 'svc_phone'
329        && $conf->exists('selfservice_server-phone_login') ) { 
330
331     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
332     return { error => 'Number not found.' } unless $svc_phone;
333
334     #XXX?
335     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
336     #return { error => 'Only primary user may log in.' } 
337     #  if $conf->exists('selfservice_server-primary_only')
338     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
339
340     return { error => 'Incorrect PIN.' }
341       unless $svc_phone->check_pin($p->{'password'});
342
343     $svc_x = $svc_phone;
344
345   } elsif ( $p->{'domain'} eq 'ip_mac' ) {
346
347       return { error => 'MAC address empty '.$p->{'username'} }
348         unless $p->{'username'};
349
350       my $mac_address = $p->{'username'};
351       $mac_address =~ s/[\:\,\-\. ]//g;
352       $mac_address =~ tr/[a-z]/[A-Z/;
353
354       my $svc_broadband = qsearchs( 'svc_broadband', { 'mac_addr' => $mac_address } );
355       return { error => 'MAC address not found '.$p->{'username'} }
356         unless $svc_broadband;
357       $svc_x = $svc_broadband;
358
359       $session->{'domain'} = $p->{'domain'};
360
361   } elsif ( $p->{email}
362               && (my $contact = FS::contact->by_selfservice_email($p->{email}))
363           )
364   {
365     return { error => 'Incorrect contact password.' }
366       unless $contact->authenticate_password($p->{'password'});
367
368     $session->{'contactnum'} = $contact->contactnum;
369
370     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
371     if ( scalar(@cust_contact) == 1 ) {
372       $session->{'custnum'} = $cust_contact[0]->custnum;
373     } elsif ( scalar(@cust_contact) ) {
374       $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
375                                     @cust_contact
376                                 };
377     } else {
378       return { error => 'No customer self-service access for contact' }; #??
379     }
380
381   } else {
382
383     ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
384
385     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
386       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
387
388     my @svc_acct = qsearch( 'svc_acct', { 'username'  => $p->{'username'},
389                                           'domsvc'    => $svc_domain->svcnum, }
390                           );
391
392     if ( $conf->exists('selfservice_server-login_svcpart') ) {
393       my @svcpart = $conf->config('selfservice_server-login_svcpart');
394       @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
395                          scalar( grep( $_ eq $svcpart, @svcpart ) );
396                        }
397                     @svc_acct;
398     }
399
400     if ( $conf->exists('selfservice_server-primary_only') ) {
401         @svc_acct =
402           grep {
403             my $cust_svc = $_->cust_svc;
404             $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
405               == $cust_svc->svcpart
406           }
407           @svc_acct;
408     }
409
410     return { error => 'User not found.' } unless @svc_acct;
411
412     return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
413
414     my $svc_acct = $svc_acct[0];
415
416     if ( $conf->exists('selfservice_server-login_svcpart') ) {
417       my @svcpart = $conf->config('selfservice_server-login_svcpart');
418       my $svcpart = $svc_acct->cust_svc->svcpart;
419       return { error => 'Invalid user.' } 
420         unless grep($_ eq $svcpart, @svcpart);
421     }
422
423     return { error => 'Incorrect password.' }
424       unless $svc_acct->check_password($p->{'password'});
425
426     $svc_x = $svc_acct;
427
428   }
429
430   if ( $svc_x ) {
431
432     $session->{'svcnum'} = $svc_x->svcnum;
433
434     my $cust_svc = $svc_x->cust_svc;
435     my $cust_pkg = $cust_svc->cust_pkg;
436     if ( $cust_pkg ) {
437       my $cust_main = $cust_pkg->cust_main;
438       $session->{'custnum'} = $cust_main->custnum;
439       if ( $conf->exists('pkg-balances') ) {
440         my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
441                             $cust_main->ncancelled_pkgs;
442         $session->{'pkgnum'} = $cust_pkg->pkgnum
443           if scalar(@cust_pkg) > 1;
444       }
445     }
446
447     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
448     #return { error => 'Only primary user may log in.' } 
449     #  if $conf->exists('selfservice_server-primary_only')
450     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
451     my $part_pkg = $cust_pkg->part_pkg;
452     return { error => 'Only primary user may log in.' }
453       if $conf->exists('selfservice_server-primary_only')
454          && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
455
456   }
457
458   my $session_id;
459   do {
460     $session_id = sha512_hex(time(). {}. rand(). $$)
461   } until ( ! defined _cache->get($session_id) ); #just in case
462
463   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
464   _cache->set( $session_id, $session, $timeout );
465
466   return { 'error'      => '',
467            'session_id' => $session_id,
468            %$session,
469          };
470 }
471
472 sub logout {
473   my $p = shift;
474   my $skin_info = skin_info($p);
475   if ( $p->{'session_id'} ) {
476     _cache->remove($p->{'session_id'});
477     return { %$skin_info, 'error' => '' };
478   } else {
479     return { %$skin_info, 'error' => "Can't resume session" }; #better error message
480   }
481 }
482
483 sub switch_acct {
484   my $p = shift;
485
486   my($context, $session, $custnum) = _custoragent_session_custnum($p);
487   return { 'error' => $session } if $context eq 'error';
488
489   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
490     or return { 'error' => "Service not found" };
491
492   $session->{'svcnum'} = $svc_acct->svcnum;
493
494   my $conf = new FS::Conf;
495   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
496   _cache->set( $p->{'session_id'}, $session, $timeout );
497
498   return { 'error' => '' };
499
500 }
501
502 sub switch_cust {
503   my $p = shift;
504   my($context, $session, $custnum) = _custoragent_session_custnum($p);
505   return { 'error' => $session } if $context eq 'error';
506
507   $session->{'custnum'} = $p->{'custnum'}
508     if exists $session->{'customers'}{ $p->{'custnum'} };
509
510   my $conf = new FS::Conf;
511   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
512   _cache->set( $p->{'session_id'}, $session, $timeout );
513
514   return { 'error'      => '',
515            %{ customer_info( { session_id=>$p->{'session_id'} } ) },
516          };
517 }
518
519 sub payment_gateway {
520   # internal use only
521   # takes a cust_main and a cust_payby entry, returns the payment_gateway
522   my $conf = new FS::Conf;
523   my $cust_main = shift;
524   my $cust_payby = shift;
525   return '' if ! FS::payby->realtime($cust_payby);
526   my $pg = $cust_main->agent->payment_gateway(
527     'method'  => FS::payby->payby2bop($cust_payby),
528     'nofatal' => 1
529   );
530   return $pg;
531 }
532
533 sub access_info {
534   my $p = shift;
535
536   my $conf = new FS::Conf;
537
538   my $info = skin_info($p);
539
540   use vars qw( $cust_paybys ); #cache for performance
541   unless ( $cust_paybys ) {
542
543     my %cust_paybys = map { $_ => 1 }
544                       map { FS::payby->payby2payment($_) }
545                           $conf->config('signup_server-payby');
546
547     $cust_paybys = [ keys %cust_paybys ];
548
549   }
550   $info->{'cust_paybys'} = $cust_paybys;
551
552   my($context, $session, $custnum) = _custoragent_session_custnum($p);
553   return { 'error' => $session } if $context eq 'error';
554
555   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
556
557   $info->{'hide_payment_fields'} = [ 
558     map { 
559       my $pg = $cust_main && payment_gateway($cust_main, $_);
560       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
561     } @{ $info->{cust_paybys} }
562   ];
563
564   $info->{'self_suspend_reason'} = 
565       $conf->config('selfservice-self_suspend_reason',
566                       $cust_main ? $cust_main->agentnum : ''
567                    );
568
569   $info->{'edit_ticket_subject'} =
570       $conf->exists('ticket_system-selfservice_edit_subject') && 
571       $cust_main && $cust_main->edit_subject;
572
573   $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
574
575   $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
576
577   return { %$info,
578            'custnum'       => $custnum,
579            'access_pkgnum' => $session->{'pkgnum'},
580            'access_svcnum' => $session->{'svcnum'},
581          };
582 }
583
584 sub customer_info {
585   my $p = shift;
586
587   my($context, $session, $custnum) = _custoragent_session_custnum($p);
588   return { 'error' => $session } if $context eq 'error';
589
590   my %return;
591
592   my $conf = new FS::Conf;
593   $return{'require_address2'} = $conf->exists('cust_main-require_address2');
594
595 #  if ( $FS::TicketSystem::system ) {
596 #    warn "$me customer_info: initializing ticket system\n" if $DEBUG;
597 #    FS::TicketSystem->init();
598 #  }
599  
600   if ( $custnum ) { #customer record
601
602     %return = ( %return, %{ customer_info_short($p) } );
603
604     #redundant with customer_info_short, but we need it for several things below
605     my $search = { 'custnum' => $custnum };
606     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
607     my $cust_main = qsearchs('cust_main', $search )
608       or return { 'error' => "customer_info: unknown custnum $custnum" };
609
610     my $list_tickets = list_tickets($p);
611     $return{'tickets'} = $list_tickets->{'tickets'};
612
613     if ( $session->{'pkgnum'} ) {
614       #XXX open invoices in the pkg-balances case
615     } else {
616       $return{'money_char'} = $conf->config("money_char") || '$';
617       my @open = map {
618                        {
619                          invnum     => $_->invnum,
620                          date       => time2str("%b %o, %Y", $_->_date),
621                          owed       => $_->owed,
622                          charged    => $_->charged,
623                        };
624                      } $cust_main->open_cust_bill;
625       $return{open_invoices} = \@open;
626
627       my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
628       my $sth = dbh->prepare($sql) or die  dbh->errstr;
629       $sth->execute($custnum)      or die $sth->errstr;
630       $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
631       $return{'last_invoice_date_pretty'} =
632         time2str('%m/%d/%Y', $return{'last_invoice_date'} );
633     }
634
635     #customer_info_short always has nobalance on..
636     $return{small_custview} =
637       small_custview( $cust_main,
638                       $return{countrydefault},
639                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
640                     );
641
642     $return{has_ship_address} = $cust_main->has_ship_address;
643     $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
644     $return{statuscolor} = $cust_main->statuscolor;
645     $return{status_label} = $cust_main->status_label;
646
647     # compatibility: some places in selfservice use this to determine
648     # if there's a ship address
649     if ( $return{has_ship_address} ) {
650       $return{ship_last}  = $cust_main->last;
651       $return{ship_first} = $cust_main->first;
652     }
653
654     if (scalar($conf->config('support_packages'))) {
655       my @support_services = ();
656       foreach ($cust_main->support_services) {
657         my $seconds = $_->svc_x->seconds || 0;
658         my $time_remaining = (($seconds < 0) ? '-' : '' ).
659                              int(abs($seconds)/3600)."h".
660                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
661         my $cust_pkg = $_->cust_pkg;
662         my $pkgnum = '';
663         my $pkg = '';
664         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
665         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
666         push @support_services, { svcnum => $_->svcnum,
667                                   time => $time_remaining,
668                                   pkgnum => $pkgnum,
669                                   pkg => $pkg,
670                                 };
671       }
672       $return{support_services} = \@support_services;
673     }
674
675     if ( $conf->config('prepayment_discounts-credit_type') ) {
676       #need to eval?
677       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
678     }
679
680   } elsif ( $session->{'svcnum'} ) { #no customer record
681
682     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
683       or die "unknown svcnum";
684     $return{name} = $svc_acct->email;
685
686   } else {
687
688     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
689
690   }
691
692   return { 'error'   => '',
693            'custnum' => $custnum,
694            %return,
695          };
696
697 }
698
699 sub customer_info_short {
700   my $p = shift;
701
702   my($context, $session, $custnum) = _custoragent_session_custnum($p);
703   return { 'error' => $session } if $context eq 'error';
704
705   my %return;
706
707   my $conf = new FS::Conf;
708
709   if ( $custnum ) { #customer record
710
711     my $search = { 'custnum' => $custnum };
712     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
713     my $cust_main = qsearchs('cust_main', $search )
714       or return { 'error' => "customer_info_short: unknown custnum $custnum" };
715
716     $return{display_custnum} = $cust_main->display_custnum;
717     $return{max_invnum}      = $cust_main->max_invnum;
718
719     if ( $session->{'pkgnum'} ) { 
720       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
721       #next_bill_date from cust_pkg?
722     } else {
723       $return{balance} = $cust_main->balance;
724       $return{next_bill_date} = $cust_main->next_bill_date;
725       $return{next_bill_date_pretty} =
726         $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
727                                 : '(none)';
728     }
729     $return{balance_pretty} = money_pretty($return{balance});
730
731     $return{countrydefault} = scalar($conf->config('countrydefault'));
732
733     $return{small_custview} =
734       small_custview( $cust_main,
735                       $return{countrydefault},
736                       1, ##nobalance
737                     );
738
739     $return{first}  = $cust_main->first;
740     $return{'last'} = $cust_main->get('last');
741     $return{name}   = $cust_main->first. ' '. $cust_main->get('last');
742
743     #none of these are terribly expensive if we want 'em...
744     for (@cust_main_editable_fields) {
745       $return{$_} = $cust_main->get($_);
746     }
747     $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
748
749     #maybe a little more expensive, but it should be cached by now
750     for (@location_editable_fields) {
751       $return{$_} = $cust_main->bill_location->get($_)
752         if $cust_main->bill_locationnum;
753       $return{'ship_'.$_} = $cust_main->ship_location->get($_)
754         if $cust_main->ship_locationnum;
755     }
756  
757     my @invoicing_list = $cust_main->invoicing_list;
758     $return{'invoicing_list'} =
759       join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
760     $return{'postal_invoicing'} =
761       0 < ( grep { $_ eq 'POST' } @invoicing_list );
762
763     if ( $session->{'svcnum'} ) {
764       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
765       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
766       $return{'svcnum'} = $session->{'svcnum'};
767     }
768
769   } elsif ( $session->{'svcnum'} ) { #no customer record
770
771     #uuh, not supproted yet... die?
772     return { 'error' => 'customer_info_short not yet supported as agent' };
773
774   } else {
775
776     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
777
778   }
779
780   # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
781   # it is not customer-specific, though it is only shown to authenticated customers
782   # it is not currently agent-specific, though at some point it might be
783   $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
784
785   return { 'error'          => '',
786            'custnum'        => $custnum,
787            %return,
788          };
789 }
790
791 sub customer_recurring {
792   my $p = shift;
793
794   my($context, $session, $custnum) = _custoragent_session_custnum($p);
795   return { 'error' => $session } if $context eq 'error';
796
797   my %return;
798
799   my $conf = new FS::Conf;
800
801   my $search = { 'custnum' => $custnum };
802   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
803   my $cust_main = qsearchs('cust_main', $search )
804     or return { 'error' => "customer_info_short: unknown custnum $custnum" };
805
806   $return{'display_recurring'} = [ $cust_main->display_recurring ];
807
808   return { 'error'          => '',
809            'custnum'        => $custnum,
810            %return,
811          };
812 }
813
814 sub billing_history {
815   my $p = shift;
816
817   my($context, $session, $custnum) = _custoragent_session_custnum($p);
818   return { 'error' => $session } if $context eq 'error';
819
820   return { 'error' => 'No customer' } unless $custnum;
821
822   my $search = { 'custnum' => $custnum };
823   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
824   my $cust_main = qsearchs('cust_main', $search )
825     or return { 'error' => "unknown custnum $custnum" };
826
827   my %return = ();
828
829   if ( $session->{'pkgnum'} ) { 
830     #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
831     #next_bill_date from cust_pkg?
832     return { 'error' => 'No history for package' };
833   }
834
835   $return{balance} = $cust_main->balance;
836   $return{balance_pretty} = money_pretty($return{balance});
837   $return{next_bill_date} = $cust_main->next_bill_date;
838   $return{next_bill_date_pretty} =
839     $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
840                             : '(none)';
841
842   my $conf = new FS::Conf;
843
844   $return{'history'} = [
845     $cust_main->payment_history(
846       'line_items' => $conf->exists('selfservice-billing_history-line_items'),
847       'reverse_sort' => 1,
848     )
849   ];
850
851   $return{'money_char'} = $conf->config("money_char") || '$',
852
853   return \%return;
854
855 }
856
857 sub edit_info {
858   my $p = shift;
859   my $session = _cache->get($p->{'session_id'})
860     or return { 'error' => "Can't resume session" }; #better error message
861
862   my $custnum = $session->{'custnum'}
863     or return { 'error' => "no customer record" };
864
865   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
866     or return { 'error' => "unknown custnum $custnum" };
867
868   my $conf = new FS::Conf;
869   if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
870     return { 'error' => "You do not have authority to add a bank account" };
871   }
872
873   my $new = new FS::cust_main { $cust_main->hash };
874
875   $new->set( $_ => $p->{$_} )
876     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
877
878   if ( exists($p->{address1}) ) {
879     my $bill_location = FS::cust_location->new({
880         map { $_ => $p->{$_} } @location_editable_fields
881     });
882     # if this is unchanged from before, cust_main::replace will ignore it
883     $new->set('bill_location' => $bill_location);
884   }
885
886   if ( exists($p->{ship_address1}) ) {
887     my $ship_location = FS::cust_location->new({
888         map { $_ => $p->{"ship_$_"} } @location_editable_fields
889     });
890     if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
891       # Selfservice unfortunately tries to indicate "same as billing 
892       # address" by sending all fields empty.  Did this ever work?
893       $ship_location = $cust_main->bill_location;
894     }
895     $new->set('ship_location' => $ship_location);
896   }
897   # but if it hasn't been passed in at all, leave ship_location alone--
898   # DON'T change it to match bill_location.
899
900   my @invoicing_list;
901   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
902     #false laziness with httemplate/edit/process/cust_main.cgi
903     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
904     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
905   } else {
906     @invoicing_list = $cust_main->invoicing_list;
907   }
908
909   my $error = $new->replace($cust_main, \@invoicing_list);
910   return { 'error' => $error } if $error;
911   #$cust_main = $new;
912   
913   return { 'error' => '' };
914 }
915
916 sub payment_info {
917   my $p = shift;
918   my $session = _cache->get($p->{'session_id'})
919     or return { 'error' => "Can't resume session" }; #better error message
920
921   ##
922   #generic
923   ##
924
925   my $conf = new FS::Conf;
926   use vars qw($payment_info); #cache for performance
927   unless ( $payment_info ) {
928
929     my %states = map { $_->state => 1 }
930                    qsearch('cust_main_county', {
931                      'country' => $conf->config('countrydefault') || 'US'
932                    } );
933
934     my %cust_paybys = map { $_ => 1 }
935                       map { FS::payby->payby2payment($_) }
936                           $conf->config('signup_server-payby');
937
938     my @cust_paybys = keys %cust_paybys;
939
940     $payment_info = {
941
942       #list all counties/states/countries
943       'cust_main_county' => 
944         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
945
946       #shortcut for one-country folks
947       'states' =>
948         [ sort { $a cmp $b } keys %states ],
949
950       'card_types' => card_types(),
951
952       'withcvv'            => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
953       'require_cvv'        => $conf->exists('selfservice-require_cvv'),
954       'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
955
956       'paytypes' => [ FS::cust_payby::paytypes ],
957
958       'paybys' => [ $conf->config('signup_server-payby') ],
959       'cust_paybys' => \@cust_paybys,
960
961       'stateid_label' => FS::Msgcat::_gettext('stateid'),
962       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
963
964       'show_ss'  => $conf->exists('show_ss'),
965       'show_stateid' => $conf->exists('show_stateid'),
966       'show_paystate' => $conf->exists('show_bankstate'),
967
968       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
969       'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
970
971     };
972
973   }
974
975   ##
976   #customer-specific
977   ##
978
979   my %return = %$payment_info;
980
981   delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
982
983   my $custnum = $session->{'custnum'};
984
985   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
986     or return { 'error' => "unknown custnum $custnum" };
987
988   $return{'hide_payment_fields'} = [
989     map { 
990       my $pg = payment_gateway($cust_main, $_);
991       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
992     } @{ $return{cust_paybys} }
993   ];
994
995   $return{balance} = $cust_main->balance; #XXX pkg-balances?
996
997   $return{$_} = $cust_main->bill_location->get($_) 
998     for qw(address1 address2 city state zip);
999
1000   # look for stored cust_payby info
1001   #   only if we've been given a clear payment_payby (to avoid payname conflicts)
1002   if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/) {
1003     my @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK');
1004     my ($cust_payby) = $cust_main->cust_payby(@search_payby);
1005     if ($cust_payby) {
1006       $return{payname} = $cust_payby->payname
1007                          || ( $cust_main->first. ' '. $cust_main->get('last') );
1008       $return{custpaybynum} = $cust_payby->custpaybynum;
1009
1010       if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
1011         $return{card_type} = cardtype($cust_payby->payinfo);
1012         $return{payinfo} = $cust_payby->paymask;
1013
1014         @return{'month', 'year'} = $cust_payby->paydate_monthyear;
1015
1016       }
1017
1018       if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
1019         my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
1020         $return{payinfo1} = $payinfo1;
1021         $return{payinfo2} = $payinfo2;
1022         $return{paytype}  = $cust_payby->paytype;
1023         $return{paystate} = $cust_payby->paystate;
1024         $return{payname}  = $cust_payby->payname;       # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
1025       }
1026     }
1027   }
1028
1029   if ( $conf->config('prepayment_discounts-credit_type') ) {
1030     #need to eval?
1031     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
1032   }
1033
1034   #doubleclick protection
1035   my $_date = time;
1036   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
1037   $return{paybatch} = $return{payunique};  #back compat
1038
1039   $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
1040   $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
1041
1042   return { 'error' => '',
1043            %return,
1044          };
1045
1046 }
1047
1048 #some false laziness with httemplate/process/payment.cgi - look there for
1049 #ACH and CVV support stuff
1050
1051 sub validate_payment {
1052   my $p = shift;
1053
1054   my $session = _cache->get($p->{'session_id'})
1055     or return { 'error' => "Can't resume session" }; #better error message
1056
1057   my $custnum = $session->{'custnum'};
1058
1059   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1060     or return { 'error' => "unknown custnum $custnum" };
1061
1062   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
1063     or return { 'error' => gettext('illegal_amount') };
1064   my $amount = $1;
1065   return { error => 'Amount must be greater than 0' } unless $amount > 0;
1066
1067   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
1068   #changing the hidden form values
1069   my $conf = new FS::Conf;
1070   my $fee_display = $conf->config('selfservice_process-display') || 'add';
1071   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1072   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1073   if ( $fee_display eq 'add'
1074          and $fee_pkgpart
1075          and ! $fee_skip_first || scalar($cust_main->cust_pay)
1076      )
1077   {
1078     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1079     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1080   }
1081
1082   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1083     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1084   my $discount_term = $1;
1085
1086   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1087     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1088   my $payname = $1;
1089
1090   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1091     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1092   my $payunique = $1;
1093
1094   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1095     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1096   my $paybatch = $1;
1097
1098   $payunique = $paybatch if ! length($payunique) && length($paybatch);
1099
1100   $p->{'payby'} ||= 'CARD';
1101   $p->{'payby'} =~ /^([A-Z]{4})$/
1102     or return { 'error' => "illegal_payby " . $p->{'payby'} };
1103   my $payby = $1;
1104
1105   #false laziness w/process/payment.cgi
1106   my $payinfo;
1107   my $paycvv = '';
1108   my $replace_cust_payby;
1109   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1110   
1111     $p->{'payinfo1'} =~ /^([\dx]+)$/
1112       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1113     my $payinfo1 = $1;
1114      $p->{'payinfo2'} =~ /^([\dx]+)$/
1115       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1116     my $payinfo2 = $1;
1117     $payinfo = $payinfo1. '@'. $payinfo2;
1118
1119     my $achonfile = 0;
1120     foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
1121       if ( $cust_payby->paymask eq $payinfo ) {
1122         $payinfo = $cust_payby->payinfo;
1123         $replace_cust_payby = $cust_payby;
1124         $achonfile = 1;
1125         last;
1126       }
1127     }
1128
1129     if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1130       return { 'error' => "You are not allowed to change your payment information." };
1131     }
1132    
1133   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1134    
1135     $payinfo = $p->{'payinfo'};
1136
1137     my $onfile = 0;
1138
1139     #more intelligent matching will be needed here if you change
1140     #card_masking_method and don't remove existing paymasks
1141     foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1142       if ( $cust_payby->paymask eq $payinfo ) {
1143         $payinfo = $cust_payby->payinfo;
1144         $replace_cust_payby = $cust_payby;
1145         $onfile = 1;
1146         last;
1147       }
1148     }
1149
1150     $payinfo =~ s/\D//g;
1151     $payinfo =~ /^(\d{13,19}|\d{8,9})$/
1152       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1153     $payinfo = $1;
1154
1155     validate($payinfo)
1156       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1157     return { 'error' => gettext('unknown_card_type') }
1158       if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1159
1160     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1161       if ( cardtype($payinfo) eq 'American Express card' ) {
1162         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1163           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1164         $paycvv = $1;
1165       } else {
1166         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1167           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1168         $paycvv = $1;
1169       }
1170     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1171       return { 'error' => 'CVV2 is required' };
1172     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1173       return { 'error' => 'CVV2 is required' };
1174     }
1175   
1176   } else {
1177     die "unknown payby $payby";
1178   }
1179
1180   my %payby2fields = (
1181     'CARD' => [ qw( paystart_month paystart_year payissue payip
1182                     address1 address2 city state zip country    ) ],
1183     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1184   );
1185
1186   my %replace = ( 'replace' => $replace_cust_payby, );
1187
1188   my $card_type = '';
1189   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1190
1191   { 
1192     'cust_main'      => $cust_main, #XXX or just custnum??
1193     'amount'         => sprintf('%.2f', $amount),
1194     'payby'          => $payby,
1195     'payinfo'        => $payinfo,
1196     'paymask'        => FS::payinfo_Mixin->mask_payinfo( $payby, $payinfo ),
1197     'card_type'      => $card_type,
1198     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1199     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1200     'month'          => $p->{'month'},
1201     'year'           => $p->{'year'},
1202     'payname'        => $payname,
1203     'payunique'      => $payunique,
1204     'paybatch'       => $paybatch,
1205     'paycvv'         => $paycvv,
1206     'payname'        => $payname,
1207     'discount_term'  => $discount_term,
1208     'pkgnum'         => $session->{'pkgnum'},
1209     %replace,
1210     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1211                              qw( save auto ),
1212                            )
1213   };
1214
1215 }
1216
1217 sub store_payment {
1218   my $p = shift;
1219
1220   my $validate = validate_payment($p);
1221   return $validate if $validate->{'error'};
1222
1223   my $conf = new FS::Conf;
1224   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1225   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1226
1227   +{ map { $_=>$validate->{$_} }
1228       qw( card_type paymask payname paydate_pretty month year amount
1229           address1 address2 city state zip country
1230         )
1231   };
1232
1233 }
1234
1235 sub process_stored_payment {
1236   my $p = shift;
1237
1238   my $session_id = $p->{'session_id'};
1239
1240   my $payment_info = _cache->get( "payment_$session_id" )
1241     or return { 'error' => "Can't resume session" }; #better error message
1242
1243   do_process_payment($payment_info);
1244
1245 }
1246
1247 sub process_payment {
1248   my $p = shift;
1249
1250   my $payment_info = validate_payment($p);
1251   return $payment_info if $payment_info->{'error'};
1252
1253   do_process_payment($payment_info);
1254
1255 }
1256
1257 sub do_process_payment {
1258   my $validate = shift;
1259
1260   my $cust_main = $validate->{'cust_main'};
1261
1262   my $amount = delete $validate->{'amount'};
1263   my $paynum = '';
1264
1265   my $payby = delete $validate->{'payby'};
1266
1267   if ( $validate->{'save'} ) {
1268
1269     my %saveopt;
1270     foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1271       $saveopt{$field} = $validate->{$field};
1272     }
1273
1274     if ( $payby eq 'CARD' ) {
1275       my $bill_location = FS::cust_location->new({
1276           map { $_ => $validate->{$_} } 
1277           qw(address1 address2 city state country zip)
1278       });
1279       $saveopt{'bill_location'} = $bill_location;
1280       foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1281         $saveopt{$field} = $validate->{$field};
1282       }
1283     } else {
1284       # stateid/stateid_state won't be saved, might be broken as of 4.x
1285       foreach my $field ( qw( paytype paystate ) ) {
1286         $saveopt{$field} = $validate->{$field};
1287       }
1288     }
1289
1290     my $error = $cust_main->save_cust_payby(
1291       'payment_payby' => $payby,
1292       'replace'       => $validate->{'replace'}, # cust_payby object to replace
1293       %saveopt
1294     );
1295
1296     if ( $error ) {
1297       #no, this causes customers to process their payments again
1298       #return { 'error' => $error };
1299       #XXX just warn verosely for now so i can figure out how these happen in
1300       # the first place, eventually should redirect them to the "change
1301       #address" page but indicate if the payment processed?
1302       delete($validate->{'payinfo'}); #don't want to log this!
1303       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1304            "PAYBY: $payby\n".
1305            "SAVEOPT: ".Dumper(\%saveopt)."\n".
1306            "CUST_MAIN: ". Dumper($cust_main)."\n".
1307            "PACKET: ". Dumper($validate)."\n";
1308     }
1309   }
1310
1311   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1312     'quiet'       => 1,
1313     'manual'      => 1,
1314     'selfservice' => 1,
1315     'paynum_ref'  => \$paynum,
1316     %$validate,
1317   );
1318   return { 'error' => $error } if $error;
1319
1320   #no error, so order the fee package if applicable...
1321   my $conf = new FS::Conf;
1322   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1323   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1324   
1325   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1326
1327     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1328
1329     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1330     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1331       if $error;
1332
1333     #and generate an invoice for it now too
1334     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1335     return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1336       if $error;
1337
1338   }
1339
1340   $cust_main->apply_payments;
1341
1342   my $cust_pay = '';
1343   my $receipt_html = '';
1344   if ($paynum) {
1345       # currently supported for realtime CC only; send receipt data to SS
1346       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1347       if($cust_pay) {
1348         $receipt_html = qq!
1349 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1350
1351 <TR>
1352   <TD ALIGN="right">Payment#</TD>
1353   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1354 </TR>
1355
1356 <TR>
1357   <TD ALIGN="right">Date</TD>
1358
1359   <TD BGCOLOR="#FFFFFF"><B>! . 
1360         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1361                                                             . qq!</B></TD>
1362 </TR>
1363
1364
1365 <TR>
1366   <TD ALIGN="right">Amount</TD>
1367   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1368
1369 </TR>
1370
1371 <TR>
1372   <TD ALIGN="right">Payment method</TD>
1373   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1374                                                                 . qq!</B></TD>
1375 </TR>
1376
1377 </TABLE>
1378 !;
1379       }
1380   }
1381
1382   if ( $cust_pay ) {
1383
1384     return {
1385       'error'        => '',
1386       'amount'       => sprintf('%.2f', $cust_pay->paid),
1387       'date'         => $cust_pay->_date,
1388       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1389       'time_pretty'  => time2str('%T', $cust_pay->_date),
1390       'auth_num'     => $cust_pay->auth,
1391       'order_num'    => $cust_pay->order_number,
1392       'receipt_html' => $receipt_html,
1393     };
1394
1395   } else {
1396
1397     return {
1398       'error'        => '',
1399       'receipt_html' => '',
1400     };
1401
1402   }
1403
1404 }
1405
1406 sub realtime_collect {
1407   my $p = shift;
1408
1409   my $session = _cache->get($p->{'session_id'})
1410     or return { 'error' => "Can't resume session" }; #better error message
1411
1412   my $custnum = $session->{'custnum'};
1413
1414   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1415     or return { 'error' => "unknown custnum $custnum" };
1416
1417   my $amount;
1418   if ( $p->{'amount'} ) {
1419     $amount = $p->{'amount'};
1420   }
1421   elsif ( $session->{'pkgnum'} ) {
1422     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1423   }
1424   else {
1425     $amount = $cust_main->balance;
1426   }
1427
1428   my $error = $cust_main->realtime_collect(
1429     'method'     => $p->{'method'},
1430     'amount'     => $amount,
1431     'pkgnum'     => $session->{'pkgnum'},
1432     'session_id' => $p->{'session_id'},
1433     'apply'      => 1,
1434     'selfservice'=> 1,
1435   );
1436   return { 'error' => $error } unless ref( $error );
1437
1438   return { 'error' => '', amount => $amount, %$error };
1439 }
1440
1441 sub start_thirdparty {
1442   my $p = shift;
1443   my $session = _cache->get($p->{'session_id'})
1444     or return { 'error' => "Can't resume session" }; #better error message
1445   my $custnum = $session->{'custnum'};
1446   my $cust_main = FS::cust_main->by_key($custnum);
1447   
1448   my $amount = $p->{'amount'}
1449     or return { error => 'no amount' };
1450
1451   my $result = $cust_main->create_payment(
1452     'method'      => $p->{'method'},
1453     'amount'      => $p->{'amount'},
1454     'pkgnum'      => $session->{'pkgnum'},
1455     'session_id'  => $p->{'session_id'},
1456   );
1457   
1458   if ( ref($result) ) { # hashref or error
1459     return $result;
1460   } else {
1461     return { error => $result };
1462   }
1463 }
1464
1465 sub finish_thirdparty {
1466   my $p = shift;
1467   my $session_id = delete $p->{'session_id'};
1468   my $session = _cache->get($session_id)
1469     or return { 'error' => "Can't resume session" };
1470   my $custnum = $session->{'custnum'};
1471   my $cust_main = FS::cust_main->by_key($custnum);
1472
1473   if ( $p->{_cancel} ) {
1474     # customer backed out of making a payment
1475     return $cust_main->cancel_payment( $session_id );
1476   }
1477   my $result = $cust_main->execute_payment( $session_id, %$p );
1478   if ( ref($result) ) {
1479     return $result;
1480   } else {
1481     return { error => $result };
1482   }
1483 }
1484
1485 sub process_payment_order_pkg {
1486   my $p = shift;
1487
1488   my $hr = process_payment($p);
1489   return $hr if $hr->{'error'};
1490
1491   order_pkg($p);
1492 }
1493
1494 sub process_payment_order_renew {
1495   my $p = shift;
1496
1497   my $hr = process_payment($p);
1498   return $hr if $hr->{'error'};
1499
1500   order_renew($p);
1501 }
1502
1503 sub process_prepay {
1504
1505   my $p = shift;
1506
1507   my $session = _cache->get($p->{'session_id'})
1508     or return { 'error' => "Can't resume session" }; #better error message
1509
1510   my %return;
1511
1512   my $custnum = $session->{'custnum'};
1513
1514   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1515     or return { 'error' => "unknown custnum $custnum" };
1516
1517   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1518   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1519                                            \$amount,
1520                                            \$seconds,
1521                                            \$upbytes,
1522                                            \$downbytes,
1523                                            \$totalbytes,
1524                                          );
1525
1526   return { 'error' => $error } if $error;
1527
1528   return { 'error'     => '',
1529            'amount'    => $amount,
1530            'seconds'   => $seconds,
1531            'duration'  => duration_exact($seconds),
1532            'upbytes'   => $upbytes,
1533            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1534            'downbytes' => $downbytes,
1535            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1536            'totalbytes'=> $totalbytes,
1537            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1538          };
1539
1540 }
1541
1542 sub invoice {
1543   my $p = shift;
1544   my $session = _cache->get($p->{'session_id'})
1545     or return { 'error' => "Can't resume session" }; #better error message
1546
1547   my $custnum = $session->{'custnum'};
1548
1549   my $invnum = $p->{'invnum'};
1550
1551   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1552                                           'custnum' => $custnum } )
1553     or return { 'error' => "Can't find invnum" };
1554
1555   #my %return;
1556
1557   return { 'error'        => '',
1558            'invnum'       => $invnum,
1559            'invoice_text' => join('', $cust_bill->print_text ),
1560            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1561          };
1562
1563 }
1564
1565 sub invoice_pdf {
1566   my $p = shift;
1567   my $session = _cache->get($p->{'session_id'})
1568     or return { 'error' => "Can't resume session" }; #better error message
1569
1570   my $custnum = $session->{'custnum'};
1571
1572   my $invnum = $p->{'invnum'};
1573
1574   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1575                                           'custnum' => $custnum } )
1576     or return { 'error' => "Can't find invnum" };
1577
1578   #my %return;
1579
1580   return { 'error'       => '',
1581            'invnum'      => $invnum,
1582            'invoice_pdf' => $cust_bill->print_pdf({
1583                               'unsquelch_cdr' => 1,
1584                               'locale'        => $p->{'locale'},
1585                             }),
1586          };
1587
1588 }
1589
1590 sub legacy_invoice {
1591   my $p = shift;
1592   my $session = _cache->get($p->{'session_id'})
1593     or return { 'error' => "Can't resume session" }; #better error message
1594
1595   my $custnum = $session->{'custnum'};
1596
1597   my $legacyinvnum = $p->{'legacyinvnum'};
1598
1599   my %hash = (
1600     'legacyinvnum' => $legacyinvnum,
1601     'custnum'      => $custnum,
1602   );
1603
1604   my $legacy_cust_bill =
1605          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1606       || qsearchs('legacy_cust_bill', \%hash )
1607     or return { 'error' => "Can't find legacyinvnum" };
1608
1609   #my %return;
1610
1611   return { 'error'        => '',
1612            'legacyinvnum' => $legacyinvnum,
1613            'legacyid'     => $legacy_cust_bill->legacyid,
1614            'invoice_html' => $legacy_cust_bill->content_html,
1615          };
1616
1617 }
1618
1619 sub legacy_invoice_pdf {
1620   my $p = shift;
1621   my $session = _cache->get($p->{'session_id'})
1622     or return { 'error' => "Can't resume session" }; #better error message
1623
1624   my $custnum = $session->{'custnum'};
1625
1626   my $legacyinvnum = $p->{'legacyinvnum'};
1627
1628   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1629     'legacyinvnum' => $legacyinvnum,
1630     'custnum'      => $custnum,
1631   }) or return { 'error' => "Can't find legacyinvnum" };
1632
1633   #my %return;
1634
1635   return { 'error'        => '',
1636            'legacyinvnum' => $legacyinvnum,
1637            'legacyid'     => $legacy_cust_bill->legacyid,
1638            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1639          };
1640
1641 }
1642
1643 sub invoice_logo {
1644   my $p = shift;
1645
1646   #sessioning for this?  how do we get the session id to the backend invoice
1647   # template so it can add it to the link, blah
1648
1649   my $agentnum = '';
1650   if ( $p->{'invnum'} ) {
1651     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1652       or return { 'error' => 'unknown invnum' };
1653     $agentnum = $cust_bill->cust_main->agentnum;
1654   }
1655
1656   my $templatename = $p->{'template'} || $p->{'templatename'};
1657
1658   #false laziness-ish w/view/cust_bill-logo.cgi
1659
1660   my $conf = new FS::Conf;
1661   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1662     $templatename = "_$1";
1663   } else {
1664     $templatename = '';
1665   }
1666
1667   my $filename = "logo$templatename.png";
1668
1669   return { 'error'        => '',
1670            'logo'         => $conf->config_binary($filename, $agentnum),
1671            'content_type' => 'image/png', #should allow gif, jpg too
1672          };
1673 }
1674
1675 sub list_invoices {
1676   my $p = shift;
1677   my $session = _cache->get($p->{'session_id'})
1678     or return { 'error' => "Can't resume session" }; #better error message
1679
1680   my $custnum = $session->{'custnum'};
1681
1682   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1683     or return { 'error' => "unknown custnum $custnum" };
1684
1685   my $conf = new FS::Conf;
1686
1687   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1688
1689   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1690
1691   my $balance = 0;
1692   my $invoices = [
1693     map {
1694       #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1695       my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1696       my $owed = $_->owed;
1697       $balance += $owed;
1698       +{ 'invnum'       => $_->invnum,
1699          '_date'        => $_->_date,
1700          'date'         => time2str("%b %o, %Y", $_->_date),
1701          'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1702          'previous'     => sprintf('%.2f', ($_->previous)[0]),
1703          'charged'      => sprintf('%.2f', $_->charged),
1704          'owed'         => sprintf('%.2f', $owed),
1705          'balance'      => sprintf('%.2f', $balance),
1706          'lastpay'      => @payments_and_credits 
1707                            ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1708                            : '',
1709       }
1710     } @cust_bill
1711   ];
1712
1713   return  { 'error'       => '',
1714             'balance'     => $cust_main->balance,
1715             'money_char'  => $conf->config("money_char") || '$',
1716             'invoices'    => $invoices,
1717             'legacy_invoices' => [
1718               map {
1719                     +{ 'legacyinvnum' => $_->legacyinvnum,
1720                        'legacyid'     => $_->legacyid,
1721                        '_date'        => $_->_date,
1722                        'date'         => time2str("%b %o, %Y", $_->_date),
1723                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1724                        'charged'      => sprintf('%.2f', $_->charged),
1725                        'has_content'  => (    length($_->content_pdf)
1726                                            || length($_->content_html) ),
1727                      }
1728                   }
1729                   @legacy_cust_bill
1730             ],
1731           };
1732 }
1733
1734 sub list_payments {
1735   my $p = shift;
1736   my $session = _cache->get($p->{'session_id'})
1737     or return { 'error' => "Can't resume session" }; #better error message
1738
1739   my $custnum = $session->{'custnum'};
1740
1741   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1742     or return { 'error' => "unknown custnum $custnum" };
1743
1744   return  { 'error'       => '',
1745             'balance'     => $cust_main->balance,
1746             'money_char'  => FS::Conf->new->config("money_char") || '$',
1747             'payments'    => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1748           };
1749 }
1750
1751 sub payment_receipt {
1752   my $p = shift;
1753   my $session = _cache->get($p->{'session_id'})
1754     or return { 'error' => "Can't resume session" }; #better error message
1755
1756   my $custnum = $session->{'custnum'};
1757
1758   my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1759                                         'paynum'  => $p->{'paynum'},
1760                                       }
1761                          )
1762     or return { 'error' => "unknown payment ". $p->{'paynum'} };
1763
1764   return { 
1765            'error' => '',
1766            %{ $cust_pay->SSAPI_getinfo },
1767          };
1768 }
1769
1770 sub list_payby {
1771   my $p = shift;
1772
1773   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1774   return { 'error' => $session } if $context eq 'error';
1775
1776   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1777     or return { 'error' => "unknown custnum $custnum" };
1778
1779   return {
1780     'payby' => [ map {
1781                        my $cust_payby = $_;
1782                        +{
1783                           map { $_ => $cust_payby->$_ }
1784                             qw( custpaybynum weight payby paymask paydate
1785                                 payname paystate paytype
1786                               )
1787                         };
1788                      }
1789                    $cust_main->cust_payby
1790                ],
1791   };
1792 }
1793
1794 sub insert_payby {
1795   my $p = shift;
1796
1797   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1798   return { 'error' => $session } if $context eq 'error';
1799
1800   #XXX payinfo1 + payinfo2 for CHEK?
1801   #or take the opportunity to use separate, more well- named fields?
1802    if ($p->{'payby'} eq 'CHEK') {
1803      $p->{'payinfo1'} =~ /^([\dx]+)$/
1804        or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1805      my $payinfo1 = $1;
1806       $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1807        or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1808      my $payinfo2 = $1;
1809      $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1810    }
1811
1812   my $cust_payby = new FS::cust_payby {
1813     'custnum' => $custnum,
1814     map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1815                                paystate paytype payip 
1816                              ),
1817   };
1818
1819   my $error = $cust_payby->insert;
1820   if ( $error ) {
1821     return { 'error' => $error };
1822   } else {
1823     return { 'custpaybynum' => $cust_payby->custpaybynum };
1824   }
1825   
1826 }
1827
1828 sub update_payby {
1829   my $p = shift;
1830
1831   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1832   return { 'error' => $session } if $context eq 'error';
1833
1834   if ($p->{'payby'} eq 'CHEK') {
1835      $p->{'payinfo1'} =~ /^([\dx]+)$/
1836        or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1837      my $payinfo1 = $1;
1838       $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1839        or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1840      my $payinfo2 = $1;
1841      $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1842    }
1843
1844   my $cust_payby = qsearchs('cust_payby', {
1845                               'custnum'      => $custnum,
1846                               'custpaybynum' => $p->{'custpaybynum'},
1847                            })
1848     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1849
1850   my $cust_main = qsearchs( 'cust_main', {custnum => $cust_payby->custnum} )
1851     or return { 'error' => 'unknown custnum '.$cust_payby->custnum };
1852
1853   foreach my $field (
1854     qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1855   ) {
1856     next unless exists($p->{$field});
1857     $cust_payby->set($field,$p->{$field});
1858   }
1859   $cust_payby->set( 'paymask' => $cust_payby->mask_payinfo );
1860
1861   # Update column if given a value, and the given value wasn't
1862   # the value generated by $cust_main->masked($column);
1863   $cust_main->set( $_, $p->{$_} )
1864     for grep{ $p->{$_} !~ /^x/i; }
1865         grep{ exists $p->{$_} }
1866         qw/ss stateid/;
1867
1868   # Perform updates within a transaction
1869   local $FS::UID::AutoCommit = 0;
1870
1871   if ( my $error = $cust_payby->replace || $cust_main->replace ) {
1872     dbh->rollback;
1873     return { error => $error };
1874   }
1875
1876   dbh->commit;
1877   return { custpaybynum => $cust_payby->custpaybynum };
1878 }
1879
1880 sub verify_payby {
1881   my $p = shift;
1882
1883   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1884   return { 'error' => $session } if $context eq 'error';
1885
1886   my $cust_payby = qsearchs('cust_payby', {
1887                               'custnum'      => $custnum,
1888                               'custpaybynum' => $p->{'custpaybynum'},
1889                            })
1890     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1891
1892   return { 'error' => $cust_payby->verify };
1893   
1894 }
1895
1896 sub delete_payby {
1897   my $p = shift;
1898
1899   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1900   return { 'error' => $session } if $context eq 'error';
1901
1902   my $cust_payby = qsearchs('cust_payby', {
1903                               'custnum'      => $custnum,
1904                               'custpaybynum' => $p->{'custpaybynum'},
1905                            })
1906     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1907
1908   my $conf = new FS::Conf;
1909   if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1910     return { 'error' => "Sorry you do not have permission to delete bank information." };
1911   }
1912   else {
1913     return { 'error' => $cust_payby->delete };
1914   }
1915 }
1916
1917 sub cancel {
1918   my $p = shift;
1919   my $session = _cache->get($p->{'session_id'})
1920     or return { 'error' => "Can't resume session" }; #better error message
1921
1922   my $custnum = $session->{'custnum'};
1923
1924   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1925     or return { 'error' => "unknown custnum $custnum" };
1926
1927   my @errors = $cust_main->cancel( 'quiet'=>1 );
1928
1929   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1930
1931   return { 'error' => $error };
1932
1933 }
1934
1935 sub pkg_info {
1936   my $p = shift;
1937
1938   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1939   return { 'error' => $session } if $context eq 'error';
1940
1941   my $pkg = qsearchs({
1942     'table'     => 'cust_pkg',
1943     'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1944     'hashref'   => {
1945                       'custnum' => $custnum,
1946                       'pkgnum'  => $p->{'pkgnum'},
1947                    },
1948   })
1949     or return {'error' => 'unknown pkg num $pkgnum'};
1950
1951   return {
1952         pkg_label => $pkg->pkg,
1953         pkgpart   => $pkg->pkgpart,
1954         classnum  => $pkg->classnum,
1955   };
1956
1957 }
1958
1959 sub list_pkgs {
1960   my $p = shift;
1961
1962   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1963   return { 'error' => $session } if $context eq 'error';
1964
1965   my $search = { 'custnum' => $custnum };
1966   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1967   my $cust_main = qsearchs('cust_main', $search )
1968     or return { 'error' => "unknown custnum $custnum" };
1969
1970   my $conf = new FS::Conf;
1971   my $immutable = $conf->exists('selfservice_immutable-package');
1972   
1973 # the duplication below is necessary:
1974 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1975 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1976 # non-backwards-compatible change breaking the software of anyone using the API
1977 # instead of the stock selfservice
1978 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1979   if( $conf->exists('selfservice_server-view-wholesale') ) {
1980     return { 'svcnum'   => $session->{'svcnum'},
1981             'custnum'  => $custnum,
1982             'cust_pkg' => [ map {
1983                           { $_->hash,
1984                             immutable => $immutable,
1985                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1986                             part_svc =>
1987                               [ map $_->hashref, $_->available_part_svc ],
1988                             cust_svc => 
1989                               [ map { my $ref = { $_->hash,
1990                                                   label => [ $_->label ],
1991                                                 };
1992                                       $ref->{_password} = $_->svc_x->_password
1993                                         if $context eq 'agent'
1994                                         && $conf->exists('agent-showpasswords')
1995                                         && $_->part_svc->svcdb eq 'svc_acct';
1996                                       $ref;
1997                                     } $_->cust_svc
1998                               ],
1999                           };
2000                         } $cust_main->cust_pkg
2001                   ],
2002     'small_custview' =>
2003       small_custview( $cust_main, $conf->config('countrydefault') ),
2004     'wholesale_view' => 1,
2005     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
2006     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2007     'lnp' => $conf->exists('svc_phone-lnp'),
2008       };
2009   }
2010
2011   { 'svcnum'   => $session->{'svcnum'},
2012     'custnum'  => $custnum,
2013     'cust_pkg' => [ map {
2014                           my $primary_cust_svc = $_->primary_cust_svc;
2015                           +{ $_->hash,
2016                             $_->part_pkg->hash,
2017                             immutable   => $immutable,
2018                             pkg_label   => $_->pkg_locale,
2019                             status      => $_->status,
2020                             statuscolor => $_->statuscolor,
2021                             part_svc =>
2022                               [ map { $_->hashref }
2023                                   grep { $_->selfservice_access ne 'hidden' }
2024                                     $_->available_part_svc
2025                               ],
2026                             cust_svc => 
2027                               [ map { my $ref = { $_->hash,
2028                                                   label => [ $_->label ],
2029                                                 };
2030                                       $ref->{_password} = $_->svc_x->_password
2031                                         if $context eq 'agent'
2032                                         && $conf->exists('agent-showpasswords')
2033                                         && $_->part_svc->svcdb eq 'svc_acct';
2034                                       $ref->{svchash} = { $_->svc_x->hash } if 
2035                                         $_->part_svc->svcdb eq 'svc_phone';
2036                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
2037                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
2038                                       $ref;
2039                                     }
2040                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
2041                                     $_->cust_svc
2042                               ],
2043                             primary_cust_svc =>
2044                               $primary_cust_svc
2045                                 ? { $primary_cust_svc->hash,
2046                                     label => [ $primary_cust_svc->label ],
2047                                     finger => $primary_cust_svc->svc_x->finger, #uuh
2048                                     $primary_cust_svc->part_svc->hash,
2049                                   }
2050                                 : {}, #'' ?
2051                           };
2052                         } $cust_main->ncancelled_pkgs
2053                   ],
2054     'small_custview' =>
2055       small_custview( $cust_main, $conf->config('countrydefault') ),
2056     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2057   };
2058
2059 }
2060
2061 sub list_svcs {
2062   my $p = shift;
2063
2064   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2065   return { 'error' => $session } if $context eq 'error';
2066
2067   my $conf = new FS::Conf;
2068
2069   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
2070   my $search = { 'custnum' => $custnum };
2071   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2072   my $cust_main = qsearchs('cust_main', $search )
2073     or return { 'error' => "unknown custnum $custnum" };
2074
2075   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
2076   if ( ! $pkgnum && $p->{'svcnum'} ) {
2077     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
2078     $pkgnum = $cust_svc->pkgnum if $cust_svc;
2079   }
2080
2081   my @cust_svc = ();
2082   my @cust_pkg_usage = ();
2083   foreach my $cust_pkg ( $p->{'ncancelled'} 
2084                          ? $cust_main->ncancelled_pkgs
2085                          : $cust_main->unsuspended_pkgs ) {
2086     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2087     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2088     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2089   }
2090
2091   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2092   my %usage_pools;
2093   if (!$hide_usage) {
2094     foreach (@cust_pkg_usage) {
2095       my $part = $_->part_pkg_usage;
2096       my $tag = $part->description . ($part->shared ? 1 : 0);
2097       my $row = $usage_pools{$tag} 
2098             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2099       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2100       $row->[2] += $part->minutes; # minutes total
2101     }
2102   } # otherwise just leave them empty
2103
2104   if ( $p->{'svcdb'} ) {
2105     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2106                   ? $p->{'svcdb'}
2107                   : ref($p->{'svcdb'}) eq 'ARRAY'
2108                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2109                     : { $p->{'svcdb'} => 1 };
2110     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2111   }
2112
2113   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2114   #              @svc_x;
2115
2116   my @svcs; # stuff to return to the client
2117   my %bytes_used_total; # for _used columns only
2118   foreach my $cust_svc (@cust_svc) {
2119     my $svc_x = $cust_svc->svc_x;
2120     my($label, $value) = $cust_svc->label;
2121     my $part_svc = $cust_svc->part_svc;
2122     my $svcdb = $part_svc->svcdb;
2123     my $cust_pkg = $cust_svc->cust_pkg;
2124     my $part_pkg = $cust_pkg->part_pkg;
2125
2126     my %hash = (
2127       'svcnum'         => $cust_svc->svcnum,
2128       'display_svcnum' => $cust_svc->display_svcnum,
2129       'svcdb'          => $svcdb,
2130       'label'          => $label,
2131       'value'          => $value,
2132       'pkg_label'      => $cust_pkg->pkg_locale,
2133       'pkg_status'     => $cust_pkg->status,
2134       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
2135     );
2136
2137     # would it make sense to put this in a svc_* method?
2138
2139     if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2140       my $last_bill = $cust_pkg->last_bill || 0;
2141       my $now = time;
2142       my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2143       my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2144       %hash = (
2145         %hash,
2146         'seconds_used'    => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2147         'upbytes_used'    => display_bytecount($up_used),
2148         'downbytes_used'  => display_bytecount($down_used),
2149         'totalbytes_used' => display_bytecount($up_used + $down_used)
2150       );
2151       $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2152       $bytes_used_total{'upbytes_used'} += $up_used;
2153       $bytes_used_total{'downbytes_used'} += $down_used;
2154       $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2155     }
2156
2157     if ( $svcdb eq 'svc_acct' ) {
2158       foreach (qw(username email finger seconds)) {
2159         $hash{$_} = $svc_x->$_;
2160       }
2161
2162       if (!$hide_usage) {
2163         %hash = (
2164           %hash,
2165           'upbytes'    => display_bytecount($svc_x->upbytes),
2166           'downbytes'  => display_bytecount($svc_x->downbytes),
2167           'totalbytes' => display_bytecount($svc_x->totalbytes),
2168
2169           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
2170           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2171           'recharge_upbytes'    =>
2172             display_bytecount($part_pkg->option('recharge_upbytes',1)),
2173           'recharge_downbytes'  =>
2174             display_bytecount($part_pkg->option('recharge_downbytes',1)),
2175           'recharge_totalbytes' =>
2176             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2177           # more...
2178         );
2179       }
2180
2181     } elsif ( $svcdb eq 'svc_dsl' ) {
2182
2183       $hash{'phonenum'} = $svc_x->phonenum;
2184       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2185         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2186         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2187           if $svc_x->company;
2188       } else {
2189         $hash{'name'} = $cust_main->name;
2190       }
2191       # no usage to hide here
2192
2193     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2194       if (!$hide_usage) {
2195         # could potentially show lots of things...
2196         $hash{'outbound'} = 1;
2197         $hash{'inbound'}  = 0;
2198         if ( $svcdb eq 'svc_phone' ) {
2199           if ( $part_pkg->plan eq 'voip_inbound' ) {
2200             $hash{'outbound'} = 0;
2201             $hash{'inbound'}  = 1;
2202           } elsif ( $part_pkg->option('selfservice_inbound_format')
2203                 or  $conf->config('selfservice-default_inbound_cdr_format')
2204           ) {
2205             $hash{'inbound'}  = 1;
2206           }
2207         }
2208         foreach (qw(inbound outbound)) {
2209           # hmm...we can't filter by status here, because there might
2210           # not be cdr_terminations at all.  have to go by date.
2211           # find all since the last bill date.
2212           # XXX cdr types?  we are going to need them.
2213           if ( $hash{$_} ) {
2214             my $sum_cdr = $svc_x->sum_cdrs(
2215               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2216               'begin'   => ($cust_pkg->last_bill || 0),
2217               'nonzero' => 1,
2218               'disable_charged_party' => 1,
2219             );
2220             $hash{$_} = $sum_cdr->hashref;
2221           }
2222         }
2223       } # not hiding usage
2224     } # svcdb
2225
2226     push @svcs, \%hash;
2227   } # foreach $cust_svc
2228
2229   foreach my $field (keys %bytes_used_total) {
2230     if ($field =~ /bytes/) {
2231       $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2232     }
2233   }
2234
2235   return { 
2236     'svcnum'   => $session->{'svcnum'},
2237     'custnum'  => $custnum,
2238     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2239     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2240     'svcs'     => \@svcs,
2241     'bytes_used_total' => \%bytes_used_total,
2242     'usage_pools' => [
2243       map { $usage_pools{$_} }
2244       sort { $a cmp $b }
2245       keys %usage_pools
2246     ],
2247     'hide_usage' => $hide_usage,
2248   };
2249
2250 }
2251
2252 sub _customer_svc_x {
2253   my($custnum, $svcnum, $table) = (shift, shift, shift);
2254   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2255
2256   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2257   my $search = " AND custnum = $1";
2258   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2259
2260   qsearchs( {
2261     'table'     => ($table || 'svc_acct'),
2262     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2263                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
2264                    #'LEFT JOIN cust_main USING ( custnum ) ',
2265     'hashref'   => $hashref,
2266     'extra_sql' => $search, #important
2267   } );
2268
2269 }
2270
2271 sub svc_status_html {
2272   my $p = shift;
2273
2274   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2275   return { 'error' => $session } if $context eq 'error';
2276
2277   #XXX only svc_dsl for now
2278   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2279     or return { 'error' => "Service not found" };
2280
2281   my $html = $svc_x->getstatus_html;
2282
2283   return { 'html' => $html };
2284
2285 }
2286
2287 sub svc_status_hash {
2288   my $p = shift;
2289
2290   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2291   return { 'error' => $session } if $context eq 'error';
2292
2293   #XXX only svc_acct for now
2294   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2295     or return { 'error' => "Service not found" };
2296
2297   my ( $html, $hashref ) = $svc_x->export_getstatus;
2298   return $hashref;
2299
2300 }
2301
2302 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
2303 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2304 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2305 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2306 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2307
2308 sub _svc_method_X {
2309   my( $p, $method ) = @_;
2310
2311   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2312   return { 'error' => $session } if $context eq 'error';
2313
2314   #XXX only svc_acct for now
2315   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2316     or return { 'error' => "Service not found" };
2317
2318   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2319     if $DEBUG;
2320   my $error = $svc_x->$method($p); #$p? returns error?
2321   return { 'error' => $error } if $error;
2322
2323   return {}; #? { 'error' => '' }
2324
2325 }
2326
2327 sub acct_forward_info {
2328   my $p = shift;
2329
2330   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2331   return { 'error' => $session } if $context eq 'error';
2332
2333   my $svc_forward = _customer_svc_x( $custnum,
2334                                      { 'srcsvc' => $p->{'svcnum'} },
2335                                      'svc_forward',
2336                                    )
2337     or return { 'error' => '',
2338                 'dst'   => '',
2339               };
2340
2341   return { 'error' => '',
2342            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2343          };
2344
2345 }
2346
2347 sub process_acct_forward {
2348   my $p = shift;
2349   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2350   return { 'error' => $session } if $context eq 'error';
2351
2352   my $old = _customer_svc_x( $custnum,
2353                              { 'srcsvc' => $p->{'svcnum'} },
2354                              'svc_forward',
2355                            );
2356
2357   if ( $p->{'dst'} eq '' ) {
2358     if ( $old ) {
2359       my $error = $old->delete;
2360       return { 'error' => $error };
2361     }
2362     return { 'error' => '' };
2363   }
2364
2365   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2366                                   'dst'    => $p->{'dst'},
2367                                 };
2368
2369   my $error;
2370   if ( $old ) {
2371     $new->svcnum($old->svcnum);
2372     my $cust_svc = $old->cust_svc;
2373     $new->svcpart($old->svcpart);
2374     $new->pkgnuym($old->pkgnum);
2375     $error = $new->replace($old);
2376   } else {
2377     my $conf = new FS::Conf;
2378     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2379
2380     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2381       or return { 'error' => 'No service' }; #how would we even get here?
2382
2383     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2384
2385     $error = $new->insert;
2386   }
2387
2388   return { 'error' => $error };
2389
2390 }
2391
2392 sub list_dsl_devices {
2393   my $p = shift;
2394
2395   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2396   return { 'error' => $session } if $context eq 'error';
2397
2398   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2399     or return { 'error' => "Service not found" };
2400
2401   return {
2402     'devices' => [ map {
2403                          +{ 'mac_addr' => $_->mac_addr };
2404                        } $svc_dsl->dsl_device
2405                  ],
2406   };
2407
2408 }
2409
2410 sub add_dsl_device {
2411   my $p = shift;
2412
2413   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2414   return { 'error' => $session } if $context eq 'error';
2415
2416   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2417     or return { 'error' => "Service not found" };
2418
2419   return { 'error' => 'No MAC address supplied' }
2420     unless length($p->{'mac_addr'});
2421
2422   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2423                                         'mac_addr' => scalar($p->{'mac_addr'}),
2424                                       };
2425   my $error = $dsl_device->insert;
2426   return { 'error' => $error };
2427
2428 }
2429
2430 sub delete_dsl_device {
2431   my $p = shift;
2432
2433   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2434   return { 'error' => $session } if $context eq 'error';
2435
2436   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2437     or return { 'error' => "Service not found" };
2438
2439   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2440                                             'mac_addr' => scalar($p->{'mac_addr'}),
2441                                           }
2442                            )
2443     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2444
2445   my $error = $dsl_device->delete;
2446   return { 'error' => $error };
2447
2448 }
2449
2450 sub port_graph {
2451   my $p = shift;
2452   _usage_details( \&_port_graph, $p,
2453                   'svcdb' => 'svc_port',
2454                 );
2455 }
2456
2457 sub _port_graph {
2458   my($svc_port, $begin, $end) = @_;
2459   my @usage = ();
2460   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2461   push @usage, { 'png' => $pngOrError };
2462   (@usage);
2463 }
2464
2465 sub _list_svc_usage {
2466   my($svc_acct, $begin, $end) = @_;
2467   my @usage = ();
2468   foreach my $part_export ( 
2469     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2470     qw( sqlradius sqlradius_withdomain )
2471   ) {
2472     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2473   }
2474   (@usage);
2475 }
2476
2477 sub list_svc_usage {
2478   _usage_details(\&_list_svc_usage, @_);
2479 }
2480
2481 sub _list_support_usage {
2482   my($svc_acct, $begin, $end) = @_;
2483   my @usage = ();
2484   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2485             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2486           ) {
2487     push @usage, { 'seconds'  => $_->seconds,
2488                    'support'  => $_->support,
2489                    '_date'    => $_->_date,
2490                    'id'       => $_->transaction_id,
2491                    'creator'  => $_->creator,
2492                    'subject'  => $_->subject,
2493                    'status'   => $_->status,
2494                    'ticketid' => $_->ticketid,
2495                  };
2496   }
2497   (@usage);
2498 }
2499
2500 sub list_support_usage {
2501   _usage_details(\&_list_support_usage, @_);
2502 }
2503
2504 sub _list_cdr_usage {
2505   # XXX CDR type support...
2506   # XXX any way to do a paged search on this?
2507   # we have to return the results all at once...
2508   my($svc_x, $begin, $end, %opt) = @_;
2509   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2510     $svc_x->get_cdrs(
2511       'begin' => $begin,
2512       'end'   => $end,
2513       'disable_charged_party' => 1,
2514       %opt
2515     );
2516 }
2517
2518 sub list_cdr_usage {
2519   my $p = shift;
2520   _usage_details( \&_list_cdr_usage, $p );
2521 }
2522
2523 sub _usage_details {
2524   my($callback, $p, %opt) = @_;
2525   my $conf = FS::Conf->new;
2526
2527   if ( $conf->exists('selfservice_hide-usage') ) {
2528     return { 'error' => 'Viewing usage is not allowed.' };
2529   }
2530
2531   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2532   return { 'error' => $session } if $context eq 'error';
2533
2534   my $search = { 'svcnum' => $p->{'svcnum'} };
2535   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2536
2537   my $cust_svc = qsearchs( 'cust_svc', $search );
2538   return { 'error' => 'No service selected in list_svc_usage' } 
2539     unless $cust_svc;
2540
2541   my $svc_x = $cust_svc->svc_x;
2542   my $svcdb = $svc_x->table;
2543   my $cust_pkg = $cust_svc->cust_pkg;
2544   my $freq     = $cust_pkg->part_pkg->freq;
2545   my %callback_opt;
2546   my $header = [];
2547   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2548     my $format = '';
2549     if ( $p->{inbound} ) {
2550       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2551                 || $conf->config('selfservice-default_inbound_cdr_format')
2552                 || 'source_default';
2553       $callback_opt{inbound} = 1;
2554     } else {
2555       $format = $cust_pkg->part_pkg->option('selfservice_format')
2556                 || $conf->config('selfservice-default_cdr_format')
2557                 || 'default';
2558     }
2559
2560     $callback_opt{format} = $format;
2561     $callback_opt{use_clid} = 1;
2562     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2563   }
2564
2565   my $start    = $cust_pkg->setup;
2566   #my $end      = $cust_pkg->bill; # or time?
2567   my $end      = time;
2568
2569   unless ( $p->{beginning} ) {
2570     $p->{beginning} = $cust_pkg->last_bill;
2571     $p->{ending}    = $end;
2572   }
2573
2574   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2575   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2576
2577   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2578     %callback_opt
2579   );
2580
2581   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2582     # ugly kludge, I know
2583     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2584     if (defined $delete_col) {
2585       delete($_->[$delete_col]) foreach ($header, @usage);
2586     }
2587   }
2588
2589   #kinda false laziness with FS::cust_main::bill, but perhaps
2590   #we should really change this bit to DateTime and DateTime::Duration
2591   #
2592   #change this bit to use Date::Manip? CAREFUL with timezones (see
2593   # mailing list archive)
2594   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2595     (localtime($p->{ending}) )[0,1,2,3,4,5];
2596   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2597     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2598
2599   if ( $freq =~ /^\d+$/ ) {
2600     $nmon += $freq;
2601     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2602     $pmon -= $freq;
2603     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2604   } elsif ( $freq =~ /^(\d+)w$/ ) {
2605     my $weeks = $1;
2606     $nmday += $weeks * 7;
2607     $pmday -= $weeks * 7;
2608   } elsif ( $freq =~ /^(\d+)d$/ ) {
2609     my $days = $1;
2610     $nmday += $days;
2611     $pmday -= $days;
2612   } elsif ( $freq =~ /^(\d+)h$/ ) {
2613     my $hours = $1;
2614     $nhour += $hours;
2615     $phour -= $hours;
2616   } else {
2617     return { 'error' => "unparsable frequency: ". $freq };
2618   }
2619   
2620   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2621   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2622
2623   { 
2624     'error'     => '',
2625     'svcnum'    => $p->{svcnum},
2626     'beginning' => $p->{beginning},
2627     'ending'    => $p->{ending},
2628     'inbound'   => $p->{inbound},
2629     'previous'  => ($previous > $start) ? $previous : $start,
2630     'next'      => ($next < $end) ? $next : $end,
2631     'header'    => $header,
2632     'usage'     => \@usage,
2633   };
2634 }
2635
2636 sub order_pkg {
2637   my $p = shift;
2638
2639   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2640   return { 'error' => $session } if $context eq 'error';
2641
2642   my $search = { 'custnum' => $custnum };
2643   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2644   my $cust_main = qsearchs('cust_main', $search )
2645     or return { 'error' => "unknown custnum $custnum" };
2646
2647   my $status = $cust_main->status;
2648
2649   my %order_pkg_options = ();
2650   if ( $p->{locationnum} > 0 ) {
2651     $order_pkg_options{locationnum} = delete($p->{locationnum});
2652   } elsif ( $p->{address1} ) {
2653     $order_pkg_options{'cust_location'} = new FS::cust_location {
2654       map { $_ => $p->{$_} }
2655         qw( address1 address2 city county state zip country )
2656     };
2657   }
2658
2659   #false laziness w/ClientAPI/Signup.pm
2660
2661   my $cust_pkg = new FS::cust_pkg ( {
2662     'custnum'  => $custnum,
2663     'pkgpart'  => $p->{'pkgpart'},
2664     'quantity' => $p->{'quantity'} || 1,
2665   } );
2666   my $error = $cust_pkg->check;
2667   return { 'error' => $error } if $error;
2668
2669   my @svc = ();
2670   unless ( $p->{'svcpart'} eq 'none' ) {
2671
2672     my $svcdb;
2673     my $svcpart = '';
2674     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2675       $svcpart = $1;
2676       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2677       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2678       $svcdb = $part_svc->svcdb;
2679     } else {
2680       $svcdb = 'svc_acct';
2681     }
2682     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2683
2684     my %fields = (
2685       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2686       'svc_domain'   => [ qw( domain ) ],
2687       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2688       'svc_external' => [ qw( id title ) ],
2689       'svc_pbx'      => [ qw( id title ) ],
2690     );
2691   
2692     my $svc_x = "FS::$svcdb"->new( {
2693       'svcpart'   => $svcpart,
2694       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2695     } );
2696     
2697     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2698       my @acct_snarf;
2699       my $snarfnum = 1;
2700       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2701         my $acct_snarf = new FS::acct_snarf ( {
2702           'machine'   => $p->{"snarf_machine$snarfnum"},
2703           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2704           'username'  => $p->{"snarf_username$snarfnum"},
2705           '_password' => $p->{"snarf_password$snarfnum"},
2706         } );
2707         $snarfnum++;
2708         push @acct_snarf, $acct_snarf;
2709       }
2710       $svc_x->child_objects( \@acct_snarf );
2711     }
2712     
2713     my $y = $svc_x->setdefault; # arguably should be in new method
2714     return { 'error' => $y } if $y && !ref($y);
2715   
2716     $error = $svc_x->check;
2717     return { 'error' => $error } if $error;
2718
2719     push @svc, $svc_x;
2720
2721   }
2722
2723   $error = $cust_main->order_pkg(
2724     'cust_pkg' => $cust_pkg,
2725     'svcs'     => \@svc,
2726     'noexport' => 1,
2727     %order_pkg_options,
2728   );
2729   return { 'error' => $error } if $error;
2730
2731   my $conf = new FS::Conf;
2732   if ( $conf->exists('signup_server-realtime') ) {
2733
2734     my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2735
2736     if ($bill_error) {
2737       $cust_pkg->cancel('quiet'=>1);
2738       return $bill_error;
2739     } else {
2740       $cust_pkg->reexport;
2741     }
2742
2743   } else {
2744     $cust_pkg->reexport;
2745   }
2746
2747   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2748
2749   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2750
2751 }
2752
2753 sub change_pkg {
2754   my $p = shift;
2755
2756   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2757   return { 'error' => $session } if $context eq 'error';
2758
2759   my $conf = new FS::Conf;
2760   my $immutable = $conf->exists('selfservice_immutable-package');
2761   return { 'error' => "Package modification disabled" } if $immutable;
2762
2763   my $search = { 'custnum' => $custnum };
2764   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2765   my $cust_main = qsearchs('cust_main', $search )
2766     or return { 'error' => "unknown custnum $custnum" };
2767
2768   my $status = $cust_main->status;
2769   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2770     or return { 'error' => "unknown package $p->{pkgnum}" };
2771
2772   #if someone does need self-service package change of suspended packages,
2773   # figure out how to be more discriminating
2774   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2775     if $cust_pkg->status eq 'suspended';
2776
2777   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2778                                            'quantity' => $p->{'quantity'} || 1,
2779                                          );
2780   
2781   my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2782     or return { 'error' => "unknown package $p->{pkgpart}" };
2783
2784   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2785     unless ref($err_or_cust_pkg);
2786
2787
2788   if ( $conf->exists('signup_server-realtime') ) {
2789
2790     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2791
2792     if ($bill_error) {
2793       $err_or_cust_pkg->suspend;
2794       return $bill_error;
2795     } else {
2796       $err_or_cust_pkg->reexport;
2797     }
2798
2799   } else {  
2800     $err_or_cust_pkg->reexport;
2801   }
2802
2803   return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2804
2805 }
2806
2807 sub order_recharge {
2808   my $p = shift;
2809
2810   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2811   return { 'error' => $session } if $context eq 'error';
2812
2813   my $search = { 'custnum' => $custnum };
2814   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2815   my $cust_main = qsearchs('cust_main', $search )
2816     or return { 'error' => "unknown custnum $custnum" };
2817
2818   my $status = $cust_main->status;
2819   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2820     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2821
2822   my $svc_x = $cust_svc->svc_x;
2823   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2824
2825   my %vhash =
2826     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2827     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2828          recharge_totalbytes );
2829   my $amount = $part_pkg->option('recharge_amount', 1); 
2830   
2831   my ($l, $v, $d) = $cust_svc->label;  # blah
2832   my $pkg = "Recharge $v"; 
2833
2834   my $bill_error = $cust_main->charge($amount, $pkg,
2835      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2836      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2837      $part_pkg->taxclass); #meh
2838
2839   my $conf = new FS::Conf;
2840   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2841
2842     $bill_error = _do_bop_realtime( $cust_main, $status );
2843
2844     if ($bill_error) {
2845       return $bill_error;
2846     } else {
2847       my $error = $svc_x->recharge (\%vhash);
2848       return { 'error' => $error } if $error;
2849     }
2850
2851   } else {  
2852     my $error = $bill_error;
2853     $error ||= $svc_x->recharge (\%vhash);
2854     return { 'error' => $error } if $error;
2855   }
2856
2857   return { error => '', svc => $cust_svc->part_svc->svc };
2858
2859 }
2860
2861 sub _do_bop_realtime {
2862   my ($cust_main, $status, %opt) = @_;
2863
2864   my $old_balance = $cust_main->balance;
2865
2866   my @cust_bill;
2867   my $bill_error = $cust_main->bill(
2868     'return_bill'   => \@cust_bill,
2869   );
2870
2871   $bill_error ||= $cust_main->apply_payments_and_credits;
2872
2873   $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2874
2875   if (    $cust_main->balance > $old_balance
2876        && $cust_main->balance > 0
2877        && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2878      )
2879   {
2880     unless ( $opt{'no_invoice_void'} ) {
2881
2882       #this used to apply a credit, but now we can void invoices...
2883       foreach my $cust_bill (@cust_bill) {
2884         my $voiderror = $cust_bill->void('automatic payment failed');
2885         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2886       }
2887
2888     }
2889
2890     return { 'error' => '_decline', 'bill_error' => $bill_error };
2891   }
2892
2893   if ( $opt{'collect'} ) {
2894     my $collect_error = $cust_main->collect();
2895     return { 'error' => '_decline', 'bill_error' => $collect_error }
2896      if $collect_error; #?
2897   }
2898
2899   '';
2900 }
2901
2902 sub renew_info {
2903   my $p = shift;
2904
2905   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2906   return { 'error' => $session } if $context eq 'error';
2907
2908   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2909     or return { 'error' => "unknown custnum $custnum" };
2910
2911   my @cust_pkg = sort { $a->bill <=> $b->bill }
2912                  grep { $_->part_pkg->freq ne '0' }
2913                  $cust_main->ncancelled_pkgs;
2914
2915   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2916
2917   my $total = $cust_main->balance;
2918
2919   my @array = map {
2920                     my $bill = $_->bill;
2921                     $total += $_->part_pkg->base_recur($_, \$bill);
2922                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2923                     {
2924                       'pkgnum'             => $_->pkgnum,
2925                       'amount'             => sprintf('%.2f', $total),
2926                       'bill_date'          => $_->bill,
2927                       'bill_date_pretty'   => time2str('%x', $_->bill),
2928                       'renew_date'         => $renew_date,
2929                       'renew_date_pretty'  => time2str('%x', $renew_date),
2930                       'expire_date'        => $_->expire,
2931                       'expire_date_pretty' => time2str('%x', $_->expire),
2932                     };
2933                   }
2934                   @cust_pkg;
2935
2936   return { 'dates' => \@array };
2937
2938 }
2939
2940 sub payment_info_renew_info {
2941   my $p = shift;
2942   my $renew_info   = renew_info($p);
2943   my $payment_info = payment_info($p);
2944   return { %$renew_info,
2945            %$payment_info,
2946          };
2947 }
2948
2949 sub order_renew {
2950   my $p = shift;
2951
2952   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2953   return { 'error' => $session } if $context eq 'error';
2954
2955   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2956     or return { 'error' => "unknown custnum $custnum" };
2957
2958   my $date = $p->{'date'};
2959
2960   my $now = time;
2961
2962   #freeside-daily -n -d $date fs_daily $custnum
2963   $cust_main->bill_and_collect( 'time'         => $date,
2964                                 'invoice_time' => $now,
2965                                 'actual_time'  => $now,
2966                                 'check_freq'   => '1d',
2967                               );
2968
2969   return { 'error' => '' };
2970
2971 }
2972
2973 sub suspend_pkg {
2974   my $p = shift;
2975   my $session = _cache->get($p->{'session_id'})
2976     or return { 'error' => "Can't resume session" }; #better error message
2977
2978   my $custnum = $session->{'custnum'};
2979
2980   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2981     or return { 'error' => "unknown custnum $custnum" };
2982
2983   my $conf = new FS::Conf;
2984   my $reasonnum = 
2985     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2986       or return { 'error' => 'Permission denied' };
2987
2988   my $pkgnum = $p->{'pkgnum'};
2989
2990   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2991                                         'pkgnum'  => $pkgnum,   } )
2992     or return { 'error' => "unknown pkgnum $pkgnum" };
2993
2994   my $error = $cust_pkg->suspend(reason => $reasonnum);
2995   return { 'error' => $error };
2996
2997 }
2998
2999 sub cancel_pkg {
3000   my $p = shift;
3001   my $session = _cache->get($p->{'session_id'})
3002     or return { 'error' => "Can't resume session" }; #better error message
3003
3004   my $custnum = $session->{'custnum'};
3005   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3006     or return { 'error' => "unknown custnum $custnum" };
3007
3008   my $pkgnum = $p->{'pkgnum'};
3009   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3010                                         'pkgnum'  => $pkgnum,   } )
3011     or return { 'error' => "unknown pkgnum $pkgnum" };
3012
3013   my $error = $cust_pkg->cancel( 'quiet' => 1,
3014                                  'date'  => $p->{'date'},
3015                                );
3016   return { 'error' => $error };
3017 }
3018
3019 sub provision_phone {
3020   my $p = shift;
3021   my @bulkdid;
3022   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
3023
3024   #editing an existing phone number
3025   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
3026       my($context, $session, $custnum) = _custoragent_session_custnum($p);
3027       return { 'error' => $session } if $context eq 'error';
3028     
3029       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3030       return { 'error' => 'service not found' } unless $svc_phone;
3031       return { 'error' => 'invalid svcnum' } 
3032         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
3033
3034       $svc_phone->email($p->{'email'}) 
3035         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
3036       $svc_phone->forwarddst($p->{'forwarddst'}) 
3037         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
3038             && $p->{'forwarddst'} =~ /^(\d+|)$/;
3039       return { 'error' => $svc_phone->replace };
3040  }
3041
3042   # single DID LNP
3043   unless ( $p->{'lnp'} ) {
3044     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
3045     $p->{'lnp_status'} = "portingin";
3046     return _provision( 'FS::svc_phone',
3047                   [qw(lnp_desired_due_date lnp_other_provider 
3048                     lnp_other_provider_account phonenum countrycode lnp_status)],
3049                   [qw(phonenum countrycode)],
3050                   $p,
3051                   @_
3052                 );
3053   }
3054
3055   # single DID order (the usual case)
3056   unless (scalar(@bulkdid)) {
3057     return _provision( 'FS::svc_phone',
3058                   [qw(phonenum countrycode)],
3059                   [qw(phonenum countrycode)],
3060                   $p,
3061                   @_
3062                 );
3063   }
3064
3065   # bulk DID order case
3066   my $error;
3067   foreach my $did ( @bulkdid ) {
3068     $did =~ s/[^0-9]//g;
3069     $error = _provision( 'FS::svc_phone',
3070               [qw(phonenum countrycode)],
3071               [qw(phonenum countrycode)],
3072               {
3073                 'pkgnum' => $p->{'pkgnum'},
3074                 'svcpart' => $p->{'svcpart'},
3075                 'phonenum' => $did,
3076                 'countrycode' => $p->{'countrycode'},
3077                 'session_id' => $p->{'session_id'},
3078               }
3079             );
3080     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3081   }
3082   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3083 }
3084
3085 sub provision_pbx {
3086   my $p = shift;
3087   warn "provision_pbx called\n"
3088     if $DEBUG;
3089
3090   warn "provision_pbx calling _provision\n"
3091     if $DEBUG;
3092   _provision( 'FS::svc_pbx',
3093               [qw(id title max_extensions max_simultaneous ip_addr)],
3094               [qw(id title max_extensions max_simultaneous ip_addr)],
3095               $p,
3096               @_
3097             );
3098 }
3099
3100 sub provision_acct {
3101   my $p = shift;
3102   warn "provision_acct called\n"
3103     if $DEBUG;
3104
3105   return { 'error' => gettext('passwords_dont_match') }
3106     if $p->{'_password'} ne $p->{'_password2'};
3107   return { 'error' => gettext('empty_password') }
3108     unless length($p->{'_password'});
3109  
3110   if ($p->{'domsvc'}) {
3111     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3112                                                   qw ( svcpart pkgnum ) );
3113     return { 'error' => gettext('invalid_domain') }
3114       unless ($domains{$p->{'domsvc'}});
3115   }
3116
3117   warn "provision_acct calling _provision\n"
3118     if $DEBUG;
3119   _provision( 'FS::svc_acct',
3120               [qw(username _password domsvc)],
3121               [qw(username _password domsvc)],
3122               $p,
3123               @_
3124             );
3125 }
3126
3127 sub provision_external {
3128   my $p = shift;
3129   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3130   _provision( 'FS::svc_external',
3131               [],
3132               [qw(id title)],
3133               $p,
3134               @_
3135             );
3136 }
3137
3138 sub provision_forward {
3139   my $p = shift;
3140   _provision( 'FS::svc_forward',
3141               ['srcsvc','src','dstsvc','dst'],
3142               [],
3143               $p,
3144             );
3145 }
3146
3147 sub _provision {
3148   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3149   warn "_provision called for $class\n"
3150     if $DEBUG;
3151
3152   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3153   return { 'error' => $session } if $context eq 'error';
3154
3155   my $search = { 'custnum' => $custnum };
3156   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3157   my $cust_main = qsearchs('cust_main', $search )
3158     or return { 'error' => "unknown custnum $custnum" };
3159
3160   my $pkgnum = $p->{'pkgnum'};
3161
3162   warn "searching for custnum $custnum pkgnum $pkgnum\n"
3163     if $DEBUG;
3164   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3165                                         'pkgnum'  => $pkgnum,
3166                                                                } )
3167     or return { 'error' => "unknown pkgnum $pkgnum" };
3168
3169   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3170     if $DEBUG;
3171   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3172     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3173
3174   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3175     if $class ne 'FS::'. $part_svc->svcdb;
3176
3177   warn "creating $class record\n"
3178     if $DEBUG;
3179   my $svc_x = $class->new( {
3180     'pkgnum'  => $p->{'pkgnum'},
3181     'svcpart' => $p->{'svcpart'},
3182     map { $_ => $p->{$_} } @$fields
3183   } );
3184
3185   my %insert_args = ();
3186   #i shouldn't be a special case here (pass an option or something)
3187   if ( $class eq 'FS::svc_phone'
3188          && grep length($p->{$_}), @location_editable_fields
3189      )
3190   {
3191     $insert_args{'cust_location'} = new FS::cust_location {
3192       map { $_ => $p->{$_} } @location_editable_fields
3193     };
3194   }
3195
3196   warn "inserting $class record\n"
3197     if $DEBUG;
3198   my $error = $svc_x->insert(%insert_args);
3199
3200   unless ( $error ) {
3201     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3202       if $DEBUG;
3203     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3204   }
3205
3206   my $return = { 'svc'   => $part_svc->svc,
3207                  'error' => $error,
3208                  map { $_ => $svc_x->get($_) } @$return_fields
3209                };
3210   warn "_provision returning ". Dumper($return). "\n"
3211     if $DEBUG;
3212   return $return;
3213
3214 }
3215
3216 sub part_svc_info {
3217   my $p = shift;
3218
3219   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3220   return { 'error' => $session } if $context eq 'error';
3221
3222   my $search = { 'custnum' => $custnum };
3223   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3224   my $cust_main = qsearchs('cust_main', $search )
3225     or return { 'error' => "unknown custnum $custnum" };
3226
3227   my $pkgnum = $p->{'pkgnum'};
3228
3229   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3230                                         'pkgnum'  => $pkgnum,
3231                                                                } )
3232     or return { 'error' => "unknown pkgnum $pkgnum" };
3233
3234   my $svcpart = $p->{'svcpart'};
3235
3236   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3237                                       'svcpart' => $svcpart,           } )
3238     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3239   my $part_svc = $pkg_svc->part_svc;
3240
3241   my $conf = new FS::Conf;
3242
3243   my $ret = {
3244     'svc'     => $part_svc->svc,
3245     'svcdb'   => $part_svc->svcdb,
3246     'pkgnum'  => $pkgnum,
3247     'svcpart' => $svcpart,
3248     'custnum' => $custnum,
3249
3250     'security_phrase' => 0, #XXX !
3251     'svc_acct_pop'    => [], #XXX !
3252     'popnum'          => '',
3253     'init_popstate'   => '',
3254     'popac'           => '',
3255     'acstate'         => '',
3256
3257     'small_custview' =>
3258       small_custview( $cust_main, $conf->config('countrydefault') ),
3259
3260   };
3261
3262   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
3263                      && $ret->{'svcdb'} eq 'svc_phone') {
3264         $ret->{'svcnum'} = $p->{'svcnum'};
3265         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3266         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3267             $ret->{'email'} = $svc_phone->email;
3268             $ret->{'forwarddst'} = $svc_phone->forwarddst;
3269         }
3270   }
3271
3272   if ($ret->{'svcdb'} eq 'svc_forward') {
3273     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3274   }
3275
3276   $ret;
3277 }
3278
3279 sub unprovision_svc {
3280   my $p = shift;
3281
3282   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3283   return { 'error' => $session } if $context eq 'error';
3284
3285   my $search = { 'custnum' => $custnum };
3286   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3287   my $cust_main = qsearchs('cust_main', $search )
3288     or return { 'error' => "unknown custnum $custnum" };
3289
3290   my $svcnum = $p->{'svcnum'};
3291
3292   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
3293     or return { 'error' => "unknown svcnum $svcnum" };
3294
3295   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3296     unless $cust_svc->cust_pkg->custnum == $custnum;
3297
3298   my $conf = new FS::Conf;
3299
3300   return { 'svc'   => $cust_svc->part_svc->svc,
3301            'error' => $cust_svc->cancel,
3302            'small_custview' =>
3303              small_custview( $cust_main, $conf->config('countrydefault') ),
3304          };
3305
3306 }
3307
3308 sub myaccount_passwd {
3309   my $p = shift;
3310   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3311   return { 'error' => $session } if $context eq 'error';
3312
3313   return { 'error' => "New passwords don't match." }
3314     if $p->{'new_password'} ne $p->{'new_password2'};
3315
3316   return { 'error' => 'Enter new password' }
3317     unless length($p->{'new_password'});
3318
3319   #my $search = { 'custnum' => $custnum };
3320   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3321   $custnum =~ /^(\d+)$/ or die "illegal custnum";
3322   my $search = " AND custnum = $1";
3323   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3324
3325   my $svc_acct = qsearchs( {
3326     'table'     => 'svc_acct',
3327     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3328                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3329                    'LEFT JOIN cust_main USING ( custnum ) ',
3330     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3331     'extra_sql' => $search, #important
3332   } )
3333     or return { 'error' => "Service not found" };
3334
3335   my $error = '';
3336
3337   my $conf = new FS::Conf;
3338
3339   return { 'error' => 'Incorrect current password.' }
3340     if  ( exists($p->{'old_password'})
3341           || $conf->exists('selfservice-password_change_oldpass')
3342         )
3343     && ! $svc_acct->check_password($p->{'old_password'});
3344
3345   $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3346          ||  $svc_acct->set_password($p->{'new_password'})
3347          ||  $svc_acct->replace();
3348
3349   #regular pw change in self-service should change contact pw too, otherwise its
3350   #way too confusing.  hell its confusing they're separate at all, but alas.
3351   #need to support the "ISP provides email that's used as a contact email" case
3352   #as well as we can.
3353   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3354   if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3355                                               custnum   => $custnum,
3356                                               selfservice_access => 'Y',
3357                                             }
3358                            )
3359   ) {
3360     #svc_acct was successful but this one returns an error?  "shouldn't happen"
3361     #don't recheck is_password_allowed here; if the svc_acct password was
3362     #legal, that's good enough
3363     $error ||= $contact->change_password($p->{'new_password'});
3364   }
3365
3366   my($label, $value) = $svc_acct->cust_svc->label;
3367
3368   return { 'error' => $error,
3369            'label' => $label,
3370            'value' => $value,
3371          };
3372
3373 }
3374
3375 sub reset_passwd {
3376   my $p = shift;
3377
3378   my $info = skin_info($p);
3379
3380   my $conf = new FS::Conf;
3381   my $verification = $conf->config('selfservice-password_reset_verification')
3382     or return { %$info, 'error' => 'Password resets disabled' };
3383
3384   my $contact = '';
3385   my $svc_acct = '';
3386   my $cust_main = '';
3387   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3388   
3389     $contact = FS::contact->by_selfservice_email($p->{'email'});
3390
3391     if ( $contact ) {
3392       my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3393       $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3394     }
3395
3396     #also look for an svc_acct, otherwise it would be super confusing
3397
3398     my($username, $domain) = split('@', $p->{'email'});
3399     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3400     if ( $svc_domain ) {
3401       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3402                                          'domsvc'   => $svc_domain->svcnum  }
3403                           );
3404       if ( $svc_acct ) {
3405         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3406         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3407
3408         #precaution: don't change svc_acct password not part of the same
3409         # customer as contact
3410         $svc_acct = '' if ! $cust_pkg
3411                        || $cust_pkg->custnum != $cust_main->custnum;
3412       }
3413       
3414     }
3415
3416     return { %$info, 'error' => 'Email address not found' }
3417       unless $contact || $svc_acct;
3418
3419   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3420
3421     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3422       or return { %$info, 'error' => 'Account not found' };
3423
3424     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3425                                        'domsvc'   => $svc_domain->svcnum  }
3426                         )
3427       or return { %$info, 'error' => 'Account not found' };
3428
3429     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3430       or return { %$info, 'error' => 'Account not found' };
3431
3432     $cust_main = $cust_pkg->cust_main;
3433
3434   }
3435
3436   return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3437     if ! $cust_main && $verification ne 'email';
3438
3439   my %verify = (
3440     'email'   => sub { 1; },
3441     'paymask' => sub { 
3442       my( $p, $cust_main ) = @_;
3443       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3444         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3445     },
3446     'amount'  => sub {
3447       my( $p, $cust_main ) = @_;
3448       my $cust_pay = qsearchs({
3449         'table' => 'cust_pay',
3450         'hashref' => { 'custnum' => $cust_main->custnum },
3451         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3452       })
3453         or return 0;
3454
3455       $p->{'amount'} == $cust_pay->paid;
3456     },
3457     'zip'     => sub {
3458       my( $p, $cust_main ) = @_;
3459       $p->{'zip'} eq $cust_main->zip
3460         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3461     },
3462   );
3463
3464   foreach my $verify ( split(',', $verification) ) {
3465
3466     &{ $verify{$verify} }( $p, $cust_main )
3467       or return { %$info, 'error' => 'Account not found' };
3468
3469   }
3470
3471   #okay, we're verified
3472
3473   if ( $contact ) {
3474
3475     my $error = $contact->send_reset_email(
3476                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3477                           );
3478
3479     if ( $error ) {
3480       return { %$info, 'error' => $error }; #????
3481     }
3482
3483   } elsif ( $svc_acct ) {
3484
3485     #create a unique session
3486
3487     my $reset_session = {
3488       'svcnum'   => $svc_acct->svcnum,
3489       'agentnum' => $svc_acct->cust_main->agentnum,
3490     };
3491
3492     my $timeout = '1 hour'; #?
3493
3494     my $reset_session_id;
3495     do {
3496       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3497     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3498       #just in case
3499
3500     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3501
3502     #email it
3503
3504     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3505                                $cust_main->agentnum);
3506     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3507     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3508       unless $msgnum;
3509     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3510     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3511                                      'object'        => $svc_acct,
3512                                      'substitutions' => {
3513                                        'session_id' => $reset_session_id,
3514                                      }
3515                                    );
3516     if ( $error ) {
3517       return { %$info, 'error' => $error }; #????
3518     }
3519
3520   }
3521
3522   return { %$info, 'error' => '' };
3523 }
3524
3525 sub check_reset_passwd {
3526   my $p = shift;
3527
3528   my $conf = new FS::Conf;
3529   my $verification = $conf->config('selfservice-password_reset_verification')
3530     or return { 'error' => 'Password resets disabled' };
3531
3532   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3533     or return { 'error' => "Can't resume session" }; #better error message
3534
3535   if ( $reset_session->{'svcnum'} ) {
3536
3537     my $svcnum = $reset_session->{'svcnum'};
3538
3539     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3540       or return { 'error' => "Service not found" };
3541
3542     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3543     my $info = skin_info($p);
3544
3545     return { %$info,
3546              'error'      => '',
3547              'session_id' => $p->{'session_id'},
3548              'username'   => $svc_acct->username,
3549            };
3550
3551   } elsif ( $reset_session->{'contactnum'} ) {
3552
3553     my $contactnum = $reset_session->{'contactnum'};
3554
3555     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3556       or return { 'error' => "Contact not found" };
3557
3558     my @contact_email = $contact->contact_email;
3559     return { 'error' => 'No contact email' } unless @contact_email;
3560
3561     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3562     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3563       if scalar(@cust_contact) == 1;
3564     my $info = skin_info($p);
3565
3566     return { %$info,
3567              'error'      => '',
3568              'session_id' => $p->{'session_id'},
3569              'email'      => $contact_email[0]->email, #the first?
3570            };
3571
3572   } else {
3573
3574     return { 'error' => 'No svcnum or contactnum in session' }; #??
3575
3576   }
3577
3578 }
3579
3580 sub process_reset_passwd {
3581   my $p = shift;
3582
3583   my $conf = new FS::Conf;
3584   my $verification = $conf->config('selfservice-password_reset_verification')
3585     or return { 'error' => 'Password resets disabled' };
3586
3587   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3588     or return { 'error' => "Can't resume session" }; #better error message
3589
3590   my $info = '';
3591
3592   my $svc_acct = '';
3593   if ( $reset_session->{'svcnum'} ) {
3594
3595     my $svcnum = $reset_session->{'svcnum'};
3596
3597     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3598       or return { 'error' => "Service not found" };
3599
3600     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3601     $info ||= skin_info($p);
3602
3603   }
3604
3605   my $contact = '';
3606   if ( $reset_session->{'contactnum'} ) {
3607
3608     my $contactnum = $reset_session->{'contactnum'};
3609
3610     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3611       or return { 'error' => "Contact not found" };
3612
3613     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3614     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3615       if scalar(@cust_contact) == 1;
3616     $info ||= skin_info($p);
3617
3618   }
3619
3620   return { %$info, 'error' => "New passwords don't match." }
3621     if $p->{'new_password'} ne $p->{'new_password2'};
3622
3623   return { %$info, 'error' => 'Enter new password' }
3624     unless length($p->{'new_password'});
3625
3626   if ( $svc_acct ) {
3627
3628     my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3629               ||  $svc_acct->set_password($p->{'new_password'})
3630               ||  $svc_acct->replace();
3631
3632     return { %$info, 'error' => $error } if $error;
3633
3634     #my($label, $value) = $svc_acct->cust_svc->label;
3635     #return { 'error' => $error,
3636     #         #'label' => $label,
3637     #         #'value' => $value,
3638     #       };
3639
3640   }
3641
3642   if ( $contact ) {
3643
3644     my $error = $contact->is_password_allowed($p->{'new_password'})
3645             ||  $contact->change_password($p->{'new_password'});
3646
3647     return { %$info, 'error' => $error }; # if $error;
3648
3649   }
3650
3651   #password changed ,so remove session, don't want it reused
3652   _cache->remove($p->{'session_id'});
3653
3654   return { %$info, 'error' => '' };
3655
3656 }
3657
3658 sub validate_passwd {
3659   my $p = shift;
3660
3661   my %result;
3662   %result = ( 'fieldid' => $p->{'fieldid'} )
3663     if $p->{'fieldid'} =~ /^\w+$/;
3664
3665   return { %result, 'password_invalid' => 'Enter new password' }
3666     unless length($p->{'check_password'});
3667
3668   my $svc_acct;
3669   if ($p->{'svcnum'}) {
3670     # false laziness with myaccount_passwd
3671     my($context, $session, $custnum) = _custoragent_session_custnum($p);
3672     return { %result, 'error' => $session } if $context eq 'error';
3673
3674     $custnum =~ /^(\d+)$/ or die "illegal custnum";
3675     my $search = " AND custnum = $1";
3676     $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3677
3678     $svc_acct = qsearchs( {
3679       'table'     => 'svc_acct',
3680       'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3681                      'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3682                      'LEFT JOIN cust_main USING ( custnum ) ',
3683       'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3684       'extra_sql' => $search, #important
3685     } )
3686       or return { %result, 'error' => "Service not found" };
3687     # end false laziness
3688   }
3689
3690   $svc_acct ||= new FS::svc_acct {};
3691
3692   my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3693   return { %result, 'password_invalid' => $error } if $error;
3694   return { %result, 'password_valid' => 1 };
3695 }
3696
3697 sub list_tickets {
3698   my $p = shift;
3699   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3700   return { 'error' => $session } if $context eq 'error';
3701
3702   my @tickets = ();
3703   if ( $session->{'pkgnum'} ) { 
3704
3705     #tickets for specific service with pkg-balances on
3706     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3707                                           'pkgnum'  => $session->{'pkgnum'} })
3708                      or return { 'error' => 'unknown package' };
3709     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3710       push @tickets, $cust_svc->tickets( $p->{status} );
3711     }
3712
3713   } else {
3714
3715     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3716       or return { 'error' => "unknown custnum $custnum" };
3717
3718     @tickets = $cust_main->tickets( $p->{status} );
3719   }
3720
3721   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3722   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3723
3724     @tickets = grep { $_->{'_selfservice_priority'}
3725                         !~ /^\s*(closed?|resolved?|done)\s*/i }
3726                  @tickets;
3727
3728     my $conf = new FS::Conf;
3729     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3730     +{ tickets => [ 
3731          sort { 
3732            (
3733              ($a->{'_selfservice_priority'} eq '') <=>
3734              ($b->{'_selfservice_priority'} eq '')
3735            ) ||
3736            ( $dir * 
3737              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3738            )
3739          } @tickets
3740        ]
3741     };
3742   } else {
3743     +{ tickets => \@tickets };
3744   }
3745
3746 }
3747
3748 sub create_ticket {
3749   my $p = shift;
3750   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3751   return { 'error' => $session } if $context eq 'error';
3752
3753   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3754   FS::TicketSystem->init();
3755
3756   my $conf = new FS::Conf;
3757   my $queue = $p->{'queue'}
3758               || $conf->config('ticket_system-selfservice_queueid')
3759               || $conf->config('ticket_system-default_queueid');
3760
3761   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3762   my $err_or_ticket = FS::TicketSystem->create_ticket(
3763     '', #create RT session based on FS CurrentUser (fs_selfservice)
3764     'queue'   => $queue,
3765     'custnum' => $custnum,
3766     'svcnum'  => $session->{'svcnum'},
3767     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3768   );
3769
3770   if ( ref($err_or_ticket) ) {
3771     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3772       if $DEBUG;
3773     return { 'error'     => '',
3774              'ticket_id' => $err_or_ticket->id,
3775            };
3776   } else {
3777     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3778       if $DEBUG;
3779     return { 'error' => $err_or_ticket };
3780   }
3781
3782
3783 }
3784
3785 sub did_report {
3786   my $p = shift;
3787   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3788   return { 'error' => $session } if $context eq 'error';
3789  
3790   return { error => 'requested format not implemented' } 
3791     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3792
3793   my $conf = new FS::Conf;
3794   my $age_threshold = 0;
3795   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3796     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3797
3798   my $search = { 'custnum' => $custnum };
3799   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3800   my $cust_main = qsearchs('cust_main', $search )
3801     or return { 'error' => "unknown custnum $custnum" };
3802
3803 # does it make more sense to just run one sql query for this instead of all the
3804 # insanity below? would increase performance greately for large data sets?
3805   my @svc_phone = ();
3806   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3807         my @part_svc = $cust_pkg->part_svc;
3808         foreach my $part_svc ( @part_svc ) {
3809             if($part_svc->svcdb eq 'svc_phone'){
3810                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3811                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3812                     push @svc_phone, $cust_pkg_svc->svc_x
3813                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3814                 }
3815             }
3816         }
3817   }
3818
3819   my $csv;
3820   my $xls;
3821   my($xls_r,$xls_c) = (0,0);
3822   my $xls_workbook;
3823   my $content = '';
3824   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3825   if($p->{'format'} eq 'csv') {
3826     $csv = new Text::CSV_XS { 'always_quote' => 1,
3827                                  'eol'          => "\n",
3828                                 };
3829     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3830     $content .= $csv->string;
3831   }
3832   elsif($p->{'format'} eq 'xls') {
3833     my $XLS1 = new IO::Scalar \$content;
3834     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3835         or return { 'error' => "Error opening .xls file: $!" };
3836     $xls = $xls_workbook->add_worksheet('DIDs');
3837     foreach ( @fields ) {
3838         $xls->write(0,$xls_c++,$_);
3839     }
3840     $xls_r++;
3841   }
3842
3843   foreach my $svc_phone ( @svc_phone ) {
3844     my @cols = map { $svc_phone->$_ } @fields;
3845     if($p->{'format'} eq 'csv') {
3846         return { 'error' => 'Unable to create CSV' } 
3847             unless $csv->combine(@cols);
3848         $content .= $csv->string;
3849     }
3850     elsif($p->{'format'} eq 'xls') {
3851         $xls_c = 0;
3852         foreach ( @cols ) {
3853             $xls->write($xls_r,$xls_c++,$_);
3854         }
3855         $xls_r++;
3856     }
3857   }
3858
3859   $xls_workbook->close() if $p->{'format'} eq 'xls';
3860   
3861   { content => $content, format => $p->{'format'}, };
3862 }
3863
3864 sub get_ticket {
3865   my $p = shift;
3866   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3867   return { 'error' => $session } if $context eq 'error';
3868
3869 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3870 #  FS::TicketSystem->init();
3871 #  return { 'error' => 'get_ticket configuration error' }
3872 #    if $FS::TicketSystem::system ne 'RT_Internal';
3873
3874   # check existence and ownership as part of this
3875   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3876   my $rt_session = FS::TicketSystem->session('');
3877   my $Ticket = FS::TicketSystem->get_ticket_object(
3878     $rt_session, 
3879     ticket_id => $p->{'ticket_id'},
3880     custnum => $custnum
3881   );
3882   return { 'error' => 'ticket not found' } if !$Ticket;
3883
3884   if ( length( $p->{'subject'} || '' ) ) {
3885     # subject change
3886     if ( $p->{'subject'} ne $Ticket->Subject ) {
3887       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3888       return { 'error' => "unable to set subject: $msg" } if !$val;
3889     }
3890   }
3891
3892   if(length($p->{'reply'})) {
3893     my @err_or_res = FS::TicketSystem->correspond_ticket(
3894       $rt_session,
3895       'ticket_id' => $p->{'ticket_id'},
3896       'content' => $p->{'reply'},
3897     );
3898
3899     return { 'error' => 'unable to reply to ticket' } 
3900     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3901   }
3902
3903   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3904   my $err_or_ticket = FS::TicketSystem->get_ticket(
3905     $rt_session,
3906     'ticket_id' => $p->{'ticket_id'},
3907   );
3908
3909   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3910     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3911       if $DEBUG;
3912     return { 'error' => $err_or_ticket };
3913   }
3914
3915   my @custs = @{$err_or_ticket->{'custs'}};
3916   my @txns = @{$err_or_ticket->{'txns'}};
3917   my @filtered_txns;
3918
3919   # superseded by check in get_ticket_object
3920   #return { 'error' => 'invalid ticket requested' } 
3921   #unless grep($_ eq $custnum, @custs);
3922
3923   foreach my $txn ( @txns ) {
3924     push @filtered_txns, $txn 
3925     if ($txn->{'type'} eq 'EmailRecord' 
3926       || $txn->{'type'} eq 'Correspond'
3927       || $txn->{'type'} eq 'Create');
3928   }
3929
3930   warn "$me get_ticket: successful: \n"
3931   if $DEBUG;
3932   return { 'error'     => '',
3933     'transactions' => \@filtered_txns,
3934     'ticket_fields' => $err_or_ticket->{'fields'},
3935     'ticket_id' => $p->{'ticket_id'},
3936   };
3937 }
3938
3939 sub adjust_ticket_priority {
3940   my $p = shift;
3941   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3942   return { 'error' => $session } if $context eq 'error';
3943
3944 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3945 #  FS::TicketSystem->init;
3946   my $ss_priority = FS::TicketSystem->selfservice_priority;
3947
3948   return { 'error' => 'adjust_ticket_priority configuration error' }
3949     if $FS::TicketSystem::system ne 'RT_Internal'
3950       or !$ss_priority;
3951
3952   my $values = $p->{'values'}; #hashref, id => priority value
3953   my %ticket_error;
3954
3955   foreach my $id (keys %$values) {
3956     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3957     my $Ticket = FS::TicketSystem->get_ticket_object('',
3958       'ticket_id' => $id,
3959       'custnum'   => $custnum,
3960     );
3961     if ( !$Ticket ) {
3962       $ticket_error{$id} = 'ticket not found';
3963       next;
3964     }
3965     
3966   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3967   # We're not going to implement it for RT_External.
3968     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3969     my $new_value = $values->{$id};
3970     next if $old_value eq $new_value;
3971
3972     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3973
3974     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3975     # a single-valued custom field, which it should be.  If it's not, you're 
3976     # doing something wrong.
3977     my ($val, $msg);
3978     if ( length($new_value) ) {
3979       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3980         Field => $ss_priority,
3981         Value => $new_value,
3982       );
3983     }
3984     else {
3985       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3986         Field => $ss_priority,
3987         Value => $old_value,
3988       );
3989     }
3990
3991     $ticket_error{$id} = $msg if !$val;
3992     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3993   }
3994   return { 'error' => '',
3995            'ticket_error' => \%ticket_error,
3996            %{ customer_info($p) } # send updated customer info back
3997          }
3998 }
3999
4000 #--
4001
4002 sub _custoragent_session_custnum {
4003   my $p = shift;
4004
4005   my($context, $session, $custnum);
4006   if ( $p->{'session_id'} ) {
4007
4008     $context = 'customer';
4009     $session = _cache->get($p->{'session_id'})
4010       or return ( 'error' => "Can't resume session" ); #better error message
4011     $custnum = $session->{'custnum'};
4012
4013   } elsif ( $p->{'agent_session_id'} ) {
4014
4015     $context = 'agent';
4016     my $agent_cache = new FS::ClientAPI_SessionCache( {
4017       'namespace' => 'FS::ClientAPI::Agent',
4018     } );
4019     $session = $agent_cache->get($p->{'agent_session_id'})
4020       or return ( 'error' => "Can't resume session" ); #better error message
4021     $custnum = $p->{'custnum'};
4022
4023   } else {
4024     $context = 'error';
4025     return ( 'error' => "Can't resume session" ); #better error message
4026   }
4027
4028   ($context, $session, $custnum);
4029
4030 }
4031
4032 1;