RT# 39340 - fixed skin_info caching issue
[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   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
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, $timeout);
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   foreach my $field (
1851     qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1852   ) {
1853     next unless exists($p->{$field});
1854     $cust_payby->set($field,$p->{$field});
1855   }
1856
1857   my $error = $cust_payby->replace;
1858   if ( $error ) {
1859     return { 'error' => $error };
1860   } else {
1861     return { 'custpaybynum' => $cust_payby->custpaybynum };
1862   }
1863   
1864 }
1865
1866 sub verify_payby {
1867   my $p = shift;
1868
1869   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1870   return { 'error' => $session } if $context eq 'error';
1871
1872   my $cust_payby = qsearchs('cust_payby', {
1873                               'custnum'      => $custnum,
1874                               'custpaybynum' => $p->{'custpaybynum'},
1875                            })
1876     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1877
1878   return { 'error' => $cust_payby->verify };
1879   
1880 }
1881
1882 sub delete_payby {
1883   my $p = shift;
1884
1885   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1886   return { 'error' => $session } if $context eq 'error';
1887
1888   my $cust_payby = qsearchs('cust_payby', {
1889                               'custnum'      => $custnum,
1890                               'custpaybynum' => $p->{'custpaybynum'},
1891                            })
1892     or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1893
1894   my $conf = new FS::Conf;
1895   if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1896     return { 'error' => "Sorry you do not have permission to delete bank information." };
1897   }
1898   else {
1899     return { 'error' => $cust_payby->delete };
1900   }
1901 }
1902
1903 sub cancel {
1904   my $p = shift;
1905   my $session = _cache->get($p->{'session_id'})
1906     or return { 'error' => "Can't resume session" }; #better error message
1907
1908   my $custnum = $session->{'custnum'};
1909
1910   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1911     or return { 'error' => "unknown custnum $custnum" };
1912
1913   my @errors = $cust_main->cancel( 'quiet'=>1 );
1914
1915   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1916
1917   return { 'error' => $error };
1918
1919 }
1920
1921 sub pkg_info {
1922   my $p = shift;
1923
1924   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1925   return { 'error' => $session } if $context eq 'error';
1926
1927   my $pkg = qsearchs({
1928     'table'     => 'cust_pkg',
1929     'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1930     'hashref'   => {
1931                       'custnum' => $custnum,
1932                       'pkgnum'  => $p->{'pkgnum'},
1933                    },
1934   })
1935     or return {'error' => 'unknown pkg num $pkgnum'};
1936
1937   return {
1938         pkg_label => $pkg->pkg,
1939         pkgpart   => $pkg->pkgpart,
1940         classnum  => $pkg->classnum,
1941   };
1942
1943 }
1944
1945 sub list_pkgs {
1946   my $p = shift;
1947
1948   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1949   return { 'error' => $session } if $context eq 'error';
1950
1951   my $search = { 'custnum' => $custnum };
1952   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1953   my $cust_main = qsearchs('cust_main', $search )
1954     or return { 'error' => "unknown custnum $custnum" };
1955
1956   my $conf = new FS::Conf;
1957   my $immutable = $conf->exists('selfservice_immutable-package');
1958   
1959 # the duplication below is necessary:
1960 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1961 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1962 # non-backwards-compatible change breaking the software of anyone using the API
1963 # instead of the stock selfservice
1964 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1965   if( $conf->exists('selfservice_server-view-wholesale') ) {
1966     return { 'svcnum'   => $session->{'svcnum'},
1967             'custnum'  => $custnum,
1968             'cust_pkg' => [ map {
1969                           { $_->hash,
1970                             immutable => $immutable,
1971                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1972                             part_svc =>
1973                               [ map $_->hashref, $_->available_part_svc ],
1974                             cust_svc => 
1975                               [ map { my $ref = { $_->hash,
1976                                                   label => [ $_->label ],
1977                                                 };
1978                                       $ref->{_password} = $_->svc_x->_password
1979                                         if $context eq 'agent'
1980                                         && $conf->exists('agent-showpasswords')
1981                                         && $_->part_svc->svcdb eq 'svc_acct';
1982                                       $ref;
1983                                     } $_->cust_svc
1984                               ],
1985                           };
1986                         } $cust_main->cust_pkg
1987                   ],
1988     'small_custview' =>
1989       small_custview( $cust_main, $conf->config('countrydefault') ),
1990     'wholesale_view' => 1,
1991     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1992     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1993     'lnp' => $conf->exists('svc_phone-lnp'),
1994       };
1995   }
1996
1997   { 'svcnum'   => $session->{'svcnum'},
1998     'custnum'  => $custnum,
1999     'cust_pkg' => [ map {
2000                           my $primary_cust_svc = $_->primary_cust_svc;
2001                           +{ $_->hash,
2002                             $_->part_pkg->hash,
2003                             immutable   => $immutable,
2004                             pkg_label   => $_->pkg_locale,
2005                             status      => $_->status,
2006                             statuscolor => $_->statuscolor,
2007                             part_svc =>
2008                               [ map { $_->hashref }
2009                                   grep { $_->selfservice_access ne 'hidden' }
2010                                     $_->available_part_svc
2011                               ],
2012                             cust_svc => 
2013                               [ map { my $ref = { $_->hash,
2014                                                   label => [ $_->label ],
2015                                                 };
2016                                       $ref->{_password} = $_->svc_x->_password
2017                                         if $context eq 'agent'
2018                                         && $conf->exists('agent-showpasswords')
2019                                         && $_->part_svc->svcdb eq 'svc_acct';
2020                                       $ref->{svchash} = { $_->svc_x->hash } if 
2021                                         $_->part_svc->svcdb eq 'svc_phone';
2022                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
2023                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
2024                                       $ref;
2025                                     }
2026                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
2027                                     $_->cust_svc
2028                               ],
2029                             primary_cust_svc =>
2030                               $primary_cust_svc
2031                                 ? { $primary_cust_svc->hash,
2032                                     label => [ $primary_cust_svc->label ],
2033                                     finger => $primary_cust_svc->svc_x->finger, #uuh
2034                                     $primary_cust_svc->part_svc->hash,
2035                                   }
2036                                 : {}, #'' ?
2037                           };
2038                         } $cust_main->ncancelled_pkgs
2039                   ],
2040     'small_custview' =>
2041       small_custview( $cust_main, $conf->config('countrydefault') ),
2042     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2043   };
2044
2045 }
2046
2047 sub list_svcs {
2048   my $p = shift;
2049
2050   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2051   return { 'error' => $session } if $context eq 'error';
2052
2053   my $conf = new FS::Conf;
2054
2055   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
2056   my $search = { 'custnum' => $custnum };
2057   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2058   my $cust_main = qsearchs('cust_main', $search )
2059     or return { 'error' => "unknown custnum $custnum" };
2060
2061   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
2062   if ( ! $pkgnum && $p->{'svcnum'} ) {
2063     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
2064     $pkgnum = $cust_svc->pkgnum if $cust_svc;
2065   }
2066
2067   my @cust_svc = ();
2068   my @cust_pkg_usage = ();
2069   foreach my $cust_pkg ( $p->{'ncancelled'} 
2070                          ? $cust_main->ncancelled_pkgs
2071                          : $cust_main->unsuspended_pkgs ) {
2072     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2073     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2074     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2075   }
2076
2077   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2078   my %usage_pools;
2079   if (!$hide_usage) {
2080     foreach (@cust_pkg_usage) {
2081       my $part = $_->part_pkg_usage;
2082       my $tag = $part->description . ($part->shared ? 1 : 0);
2083       my $row = $usage_pools{$tag} 
2084             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2085       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2086       $row->[2] += $part->minutes; # minutes total
2087     }
2088   } # otherwise just leave them empty
2089
2090   if ( $p->{'svcdb'} ) {
2091     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2092                   ? $p->{'svcdb'}
2093                   : ref($p->{'svcdb'}) eq 'ARRAY'
2094                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2095                     : { $p->{'svcdb'} => 1 };
2096     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2097   }
2098
2099   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2100   #              @svc_x;
2101
2102   my @svcs; # stuff to return to the client
2103   my %bytes_used_total; # for _used columns only
2104   foreach my $cust_svc (@cust_svc) {
2105     my $svc_x = $cust_svc->svc_x;
2106     my($label, $value) = $cust_svc->label;
2107     my $part_svc = $cust_svc->part_svc;
2108     my $svcdb = $part_svc->svcdb;
2109     my $cust_pkg = $cust_svc->cust_pkg;
2110     my $part_pkg = $cust_pkg->part_pkg;
2111
2112     my %hash = (
2113       'svcnum'         => $cust_svc->svcnum,
2114       'display_svcnum' => $cust_svc->display_svcnum,
2115       'svcdb'          => $svcdb,
2116       'label'          => $label,
2117       'value'          => $value,
2118       'pkg_label'      => $cust_pkg->pkg_locale,
2119       'pkg_status'     => $cust_pkg->status,
2120       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
2121     );
2122
2123     # would it make sense to put this in a svc_* method?
2124
2125     if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2126       my $last_bill = $cust_pkg->last_bill || 0;
2127       my $now = time;
2128       my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2129       my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2130       %hash = (
2131         %hash,
2132         'seconds_used'    => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2133         'upbytes_used'    => display_bytecount($up_used),
2134         'downbytes_used'  => display_bytecount($down_used),
2135         'totalbytes_used' => display_bytecount($up_used + $down_used)
2136       );
2137       $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2138       $bytes_used_total{'upbytes_used'} += $up_used;
2139       $bytes_used_total{'downbytes_used'} += $down_used;
2140       $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2141     }
2142
2143     if ( $svcdb eq 'svc_acct' ) {
2144       foreach (qw(username email finger seconds)) {
2145         $hash{$_} = $svc_x->$_;
2146       }
2147
2148       if (!$hide_usage) {
2149         %hash = (
2150           %hash,
2151           'upbytes'    => display_bytecount($svc_x->upbytes),
2152           'downbytes'  => display_bytecount($svc_x->downbytes),
2153           'totalbytes' => display_bytecount($svc_x->totalbytes),
2154
2155           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
2156           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2157           'recharge_upbytes'    =>
2158             display_bytecount($part_pkg->option('recharge_upbytes',1)),
2159           'recharge_downbytes'  =>
2160             display_bytecount($part_pkg->option('recharge_downbytes',1)),
2161           'recharge_totalbytes' =>
2162             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2163           # more...
2164         );
2165       }
2166
2167     } elsif ( $svcdb eq 'svc_dsl' ) {
2168
2169       $hash{'phonenum'} = $svc_x->phonenum;
2170       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2171         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2172         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2173           if $svc_x->company;
2174       } else {
2175         $hash{'name'} = $cust_main->name;
2176       }
2177       # no usage to hide here
2178
2179     } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2180       if (!$hide_usage) {
2181         # could potentially show lots of things...
2182         $hash{'outbound'} = 1;
2183         $hash{'inbound'}  = 0;
2184         if ( $svcdb eq 'svc_phone' ) {
2185           if ( $part_pkg->plan eq 'voip_inbound' ) {
2186             $hash{'outbound'} = 0;
2187             $hash{'inbound'}  = 1;
2188           } elsif ( $part_pkg->option('selfservice_inbound_format')
2189                 or  $conf->config('selfservice-default_inbound_cdr_format')
2190           ) {
2191             $hash{'inbound'}  = 1;
2192           }
2193         }
2194         foreach (qw(inbound outbound)) {
2195           # hmm...we can't filter by status here, because there might
2196           # not be cdr_terminations at all.  have to go by date.
2197           # find all since the last bill date.
2198           # XXX cdr types?  we are going to need them.
2199           if ( $hash{$_} ) {
2200             my $sum_cdr = $svc_x->sum_cdrs(
2201               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2202               'begin'   => ($cust_pkg->last_bill || 0),
2203               'nonzero' => 1,
2204               'disable_charged_party' => 1,
2205             );
2206             $hash{$_} = $sum_cdr->hashref;
2207           }
2208         }
2209       } # not hiding usage
2210     } # svcdb
2211
2212     push @svcs, \%hash;
2213   } # foreach $cust_svc
2214
2215   foreach my $field (keys %bytes_used_total) {
2216     if ($field =~ /bytes/) {
2217       $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2218     }
2219   }
2220
2221   return { 
2222     'svcnum'   => $session->{'svcnum'},
2223     'custnum'  => $custnum,
2224     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2225     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2226     'svcs'     => \@svcs,
2227     'bytes_used_total' => \%bytes_used_total,
2228     'usage_pools' => [
2229       map { $usage_pools{$_} }
2230       sort { $a cmp $b }
2231       keys %usage_pools
2232     ],
2233     'hide_usage' => $hide_usage,
2234   };
2235
2236 }
2237
2238 sub _customer_svc_x {
2239   my($custnum, $svcnum, $table) = (shift, shift, shift);
2240   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2241
2242   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2243   my $search = " AND custnum = $1";
2244   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2245
2246   qsearchs( {
2247     'table'     => ($table || 'svc_acct'),
2248     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2249                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
2250                    #'LEFT JOIN cust_main USING ( custnum ) ',
2251     'hashref'   => $hashref,
2252     'extra_sql' => $search, #important
2253   } );
2254
2255 }
2256
2257 sub svc_status_html {
2258   my $p = shift;
2259
2260   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2261   return { 'error' => $session } if $context eq 'error';
2262
2263   #XXX only svc_dsl for now
2264   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2265     or return { 'error' => "Service not found" };
2266
2267   my $html = $svc_x->getstatus_html;
2268
2269   return { 'html' => $html };
2270
2271 }
2272
2273 sub svc_status_hash {
2274   my $p = shift;
2275
2276   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2277   return { 'error' => $session } if $context eq 'error';
2278
2279   #XXX only svc_acct for now
2280   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2281     or return { 'error' => "Service not found" };
2282
2283   my ( $html, $hashref ) = $svc_x->export_getstatus;
2284   return $hashref;
2285
2286 }
2287
2288 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
2289 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2290 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2291 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2292 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2293
2294 sub _svc_method_X {
2295   my( $p, $method ) = @_;
2296
2297   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2298   return { 'error' => $session } if $context eq 'error';
2299
2300   #XXX only svc_acct for now
2301   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2302     or return { 'error' => "Service not found" };
2303
2304   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2305     if $DEBUG;
2306   my $error = $svc_x->$method($p); #$p? returns error?
2307   return { 'error' => $error } if $error;
2308
2309   return {}; #? { 'error' => '' }
2310
2311 }
2312
2313 sub acct_forward_info {
2314   my $p = shift;
2315
2316   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2317   return { 'error' => $session } if $context eq 'error';
2318
2319   my $svc_forward = _customer_svc_x( $custnum,
2320                                      { 'srcsvc' => $p->{'svcnum'} },
2321                                      'svc_forward',
2322                                    )
2323     or return { 'error' => '',
2324                 'dst'   => '',
2325               };
2326
2327   return { 'error' => '',
2328            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2329          };
2330
2331 }
2332
2333 sub process_acct_forward {
2334   my $p = shift;
2335   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2336   return { 'error' => $session } if $context eq 'error';
2337
2338   my $old = _customer_svc_x( $custnum,
2339                              { 'srcsvc' => $p->{'svcnum'} },
2340                              'svc_forward',
2341                            );
2342
2343   if ( $p->{'dst'} eq '' ) {
2344     if ( $old ) {
2345       my $error = $old->delete;
2346       return { 'error' => $error };
2347     }
2348     return { 'error' => '' };
2349   }
2350
2351   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2352                                   'dst'    => $p->{'dst'},
2353                                 };
2354
2355   my $error;
2356   if ( $old ) {
2357     $new->svcnum($old->svcnum);
2358     my $cust_svc = $old->cust_svc;
2359     $new->svcpart($old->svcpart);
2360     $new->pkgnuym($old->pkgnum);
2361     $error = $new->replace($old);
2362   } else {
2363     my $conf = new FS::Conf;
2364     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2365
2366     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2367       or return { 'error' => 'No service' }; #how would we even get here?
2368
2369     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2370
2371     $error = $new->insert;
2372   }
2373
2374   return { 'error' => $error };
2375
2376 }
2377
2378 sub list_dsl_devices {
2379   my $p = shift;
2380
2381   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2382   return { 'error' => $session } if $context eq 'error';
2383
2384   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2385     or return { 'error' => "Service not found" };
2386
2387   return {
2388     'devices' => [ map {
2389                          +{ 'mac_addr' => $_->mac_addr };
2390                        } $svc_dsl->dsl_device
2391                  ],
2392   };
2393
2394 }
2395
2396 sub add_dsl_device {
2397   my $p = shift;
2398
2399   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2400   return { 'error' => $session } if $context eq 'error';
2401
2402   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2403     or return { 'error' => "Service not found" };
2404
2405   return { 'error' => 'No MAC address supplied' }
2406     unless length($p->{'mac_addr'});
2407
2408   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2409                                         'mac_addr' => scalar($p->{'mac_addr'}),
2410                                       };
2411   my $error = $dsl_device->insert;
2412   return { 'error' => $error };
2413
2414 }
2415
2416 sub delete_dsl_device {
2417   my $p = shift;
2418
2419   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2420   return { 'error' => $session } if $context eq 'error';
2421
2422   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2423     or return { 'error' => "Service not found" };
2424
2425   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2426                                             'mac_addr' => scalar($p->{'mac_addr'}),
2427                                           }
2428                            )
2429     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2430
2431   my $error = $dsl_device->delete;
2432   return { 'error' => $error };
2433
2434 }
2435
2436 sub port_graph {
2437   my $p = shift;
2438   _usage_details( \&_port_graph, $p,
2439                   'svcdb' => 'svc_port',
2440                 );
2441 }
2442
2443 sub _port_graph {
2444   my($svc_port, $begin, $end) = @_;
2445   my @usage = ();
2446   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2447   push @usage, { 'png' => $pngOrError };
2448   (@usage);
2449 }
2450
2451 sub _list_svc_usage {
2452   my($svc_acct, $begin, $end) = @_;
2453   my @usage = ();
2454   foreach my $part_export ( 
2455     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2456     qw( sqlradius sqlradius_withdomain )
2457   ) {
2458     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2459   }
2460   (@usage);
2461 }
2462
2463 sub list_svc_usage {
2464   _usage_details(\&_list_svc_usage, @_);
2465 }
2466
2467 sub _list_support_usage {
2468   my($svc_acct, $begin, $end) = @_;
2469   my @usage = ();
2470   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2471             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2472           ) {
2473     push @usage, { 'seconds'  => $_->seconds,
2474                    'support'  => $_->support,
2475                    '_date'    => $_->_date,
2476                    'id'       => $_->transaction_id,
2477                    'creator'  => $_->creator,
2478                    'subject'  => $_->subject,
2479                    'status'   => $_->status,
2480                    'ticketid' => $_->ticketid,
2481                  };
2482   }
2483   (@usage);
2484 }
2485
2486 sub list_support_usage {
2487   _usage_details(\&_list_support_usage, @_);
2488 }
2489
2490 sub _list_cdr_usage {
2491   # XXX CDR type support...
2492   # XXX any way to do a paged search on this?
2493   # we have to return the results all at once...
2494   my($svc_x, $begin, $end, %opt) = @_;
2495   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2496     $svc_x->get_cdrs(
2497       'begin' => $begin,
2498       'end'   => $end,
2499       'disable_charged_party' => 1,
2500       %opt
2501     );
2502 }
2503
2504 sub list_cdr_usage {
2505   my $p = shift;
2506   _usage_details( \&_list_cdr_usage, $p );
2507 }
2508
2509 sub _usage_details {
2510   my($callback, $p, %opt) = @_;
2511   my $conf = FS::Conf->new;
2512
2513   if ( $conf->exists('selfservice_hide-usage') ) {
2514     return { 'error' => 'Viewing usage is not allowed.' };
2515   }
2516
2517   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2518   return { 'error' => $session } if $context eq 'error';
2519
2520   my $search = { 'svcnum' => $p->{'svcnum'} };
2521   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2522
2523   my $cust_svc = qsearchs( 'cust_svc', $search );
2524   return { 'error' => 'No service selected in list_svc_usage' } 
2525     unless $cust_svc;
2526
2527   my $svc_x = $cust_svc->svc_x;
2528   my $svcdb = $svc_x->table;
2529   my $cust_pkg = $cust_svc->cust_pkg;
2530   my $freq     = $cust_pkg->part_pkg->freq;
2531   my %callback_opt;
2532   my $header = [];
2533   if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2534     my $format = '';
2535     if ( $p->{inbound} ) {
2536       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2537                 || $conf->config('selfservice-default_inbound_cdr_format')
2538                 || 'source_default';
2539       $callback_opt{inbound} = 1;
2540     } else {
2541       $format = $cust_pkg->part_pkg->option('selfservice_format')
2542                 || $conf->config('selfservice-default_cdr_format')
2543                 || 'default';
2544     }
2545
2546     $callback_opt{format} = $format;
2547     $callback_opt{use_clid} = 1;
2548     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2549   }
2550
2551   my $start    = $cust_pkg->setup;
2552   #my $end      = $cust_pkg->bill; # or time?
2553   my $end      = time;
2554
2555   unless ( $p->{beginning} ) {
2556     $p->{beginning} = $cust_pkg->last_bill;
2557     $p->{ending}    = $end;
2558   }
2559
2560   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2561   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2562
2563   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2564     %callback_opt
2565   );
2566
2567   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2568     # ugly kludge, I know
2569     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2570     if (defined $delete_col) {
2571       delete($_->[$delete_col]) foreach ($header, @usage);
2572     }
2573   }
2574
2575   #kinda false laziness with FS::cust_main::bill, but perhaps
2576   #we should really change this bit to DateTime and DateTime::Duration
2577   #
2578   #change this bit to use Date::Manip? CAREFUL with timezones (see
2579   # mailing list archive)
2580   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2581     (localtime($p->{ending}) )[0,1,2,3,4,5];
2582   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2583     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2584
2585   if ( $freq =~ /^\d+$/ ) {
2586     $nmon += $freq;
2587     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2588     $pmon -= $freq;
2589     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2590   } elsif ( $freq =~ /^(\d+)w$/ ) {
2591     my $weeks = $1;
2592     $nmday += $weeks * 7;
2593     $pmday -= $weeks * 7;
2594   } elsif ( $freq =~ /^(\d+)d$/ ) {
2595     my $days = $1;
2596     $nmday += $days;
2597     $pmday -= $days;
2598   } elsif ( $freq =~ /^(\d+)h$/ ) {
2599     my $hours = $1;
2600     $nhour += $hours;
2601     $phour -= $hours;
2602   } else {
2603     return { 'error' => "unparsable frequency: ". $freq };
2604   }
2605   
2606   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2607   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2608
2609   { 
2610     'error'     => '',
2611     'svcnum'    => $p->{svcnum},
2612     'beginning' => $p->{beginning},
2613     'ending'    => $p->{ending},
2614     'inbound'   => $p->{inbound},
2615     'previous'  => ($previous > $start) ? $previous : $start,
2616     'next'      => ($next < $end) ? $next : $end,
2617     'header'    => $header,
2618     'usage'     => \@usage,
2619   };
2620 }
2621
2622 sub order_pkg {
2623   my $p = shift;
2624
2625   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2626   return { 'error' => $session } if $context eq 'error';
2627
2628   my $search = { 'custnum' => $custnum };
2629   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2630   my $cust_main = qsearchs('cust_main', $search )
2631     or return { 'error' => "unknown custnum $custnum" };
2632
2633   my $status = $cust_main->status;
2634
2635   my %order_pkg_options = ();
2636   if ( $p->{locationnum} > 0 ) {
2637     $order_pkg_options{locationnum} = delete($p->{locationnum});
2638   } elsif ( $p->{address1} ) {
2639     $order_pkg_options{'cust_location'} = new FS::cust_location {
2640       map { $_ => $p->{$_} }
2641         qw( address1 address2 city county state zip country )
2642     };
2643   }
2644
2645   #false laziness w/ClientAPI/Signup.pm
2646
2647   my $cust_pkg = new FS::cust_pkg ( {
2648     'custnum'  => $custnum,
2649     'pkgpart'  => $p->{'pkgpart'},
2650     'quantity' => $p->{'quantity'} || 1,
2651   } );
2652   my $error = $cust_pkg->check;
2653   return { 'error' => $error } if $error;
2654
2655   my @svc = ();
2656   unless ( $p->{'svcpart'} eq 'none' ) {
2657
2658     my $svcdb;
2659     my $svcpart = '';
2660     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2661       $svcpart = $1;
2662       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2663       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2664       $svcdb = $part_svc->svcdb;
2665     } else {
2666       $svcdb = 'svc_acct';
2667     }
2668     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2669
2670     my %fields = (
2671       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2672       'svc_domain'   => [ qw( domain ) ],
2673       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2674       'svc_external' => [ qw( id title ) ],
2675       'svc_pbx'      => [ qw( id title ) ],
2676     );
2677   
2678     my $svc_x = "FS::$svcdb"->new( {
2679       'svcpart'   => $svcpart,
2680       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2681     } );
2682     
2683     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2684       my @acct_snarf;
2685       my $snarfnum = 1;
2686       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2687         my $acct_snarf = new FS::acct_snarf ( {
2688           'machine'   => $p->{"snarf_machine$snarfnum"},
2689           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2690           'username'  => $p->{"snarf_username$snarfnum"},
2691           '_password' => $p->{"snarf_password$snarfnum"},
2692         } );
2693         $snarfnum++;
2694         push @acct_snarf, $acct_snarf;
2695       }
2696       $svc_x->child_objects( \@acct_snarf );
2697     }
2698     
2699     my $y = $svc_x->setdefault; # arguably should be in new method
2700     return { 'error' => $y } if $y && !ref($y);
2701   
2702     $error = $svc_x->check;
2703     return { 'error' => $error } if $error;
2704
2705     push @svc, $svc_x;
2706
2707   }
2708
2709   $error = $cust_main->order_pkg(
2710     'cust_pkg' => $cust_pkg,
2711     'svcs'     => \@svc,
2712     'noexport' => 1,
2713     %order_pkg_options,
2714   );
2715   return { 'error' => $error } if $error;
2716
2717   my $conf = new FS::Conf;
2718   if ( $conf->exists('signup_server-realtime') ) {
2719
2720     my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2721
2722     if ($bill_error) {
2723       $cust_pkg->cancel('quiet'=>1);
2724       return $bill_error;
2725     } else {
2726       $cust_pkg->reexport;
2727     }
2728
2729   } else {
2730     $cust_pkg->reexport;
2731   }
2732
2733   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2734
2735   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2736
2737 }
2738
2739 sub change_pkg {
2740   my $p = shift;
2741
2742   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2743   return { 'error' => $session } if $context eq 'error';
2744
2745   my $conf = new FS::Conf;
2746   my $immutable = $conf->exists('selfservice_immutable-package');
2747   return { 'error' => "Package modification disabled" } if $immutable;
2748
2749   my $search = { 'custnum' => $custnum };
2750   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2751   my $cust_main = qsearchs('cust_main', $search )
2752     or return { 'error' => "unknown custnum $custnum" };
2753
2754   my $status = $cust_main->status;
2755   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2756     or return { 'error' => "unknown package $p->{pkgnum}" };
2757
2758   #if someone does need self-service package change of suspended packages,
2759   # figure out how to be more discriminating
2760   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2761     if $cust_pkg->status eq 'suspended';
2762
2763   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2764                                            'quantity' => $p->{'quantity'} || 1,
2765                                          );
2766   
2767   my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2768     or return { 'error' => "unknown package $p->{pkgpart}" };
2769
2770   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2771     unless ref($err_or_cust_pkg);
2772
2773
2774   if ( $conf->exists('signup_server-realtime') ) {
2775
2776     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2777
2778     if ($bill_error) {
2779       $err_or_cust_pkg->suspend;
2780       return $bill_error;
2781     } else {
2782       $err_or_cust_pkg->reexport;
2783     }
2784
2785   } else {  
2786     $err_or_cust_pkg->reexport;
2787   }
2788
2789   return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2790
2791 }
2792
2793 sub order_recharge {
2794   my $p = shift;
2795
2796   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2797   return { 'error' => $session } if $context eq 'error';
2798
2799   my $search = { 'custnum' => $custnum };
2800   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2801   my $cust_main = qsearchs('cust_main', $search )
2802     or return { 'error' => "unknown custnum $custnum" };
2803
2804   my $status = $cust_main->status;
2805   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2806     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2807
2808   my $svc_x = $cust_svc->svc_x;
2809   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2810
2811   my %vhash =
2812     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2813     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2814          recharge_totalbytes );
2815   my $amount = $part_pkg->option('recharge_amount', 1); 
2816   
2817   my ($l, $v, $d) = $cust_svc->label;  # blah
2818   my $pkg = "Recharge $v"; 
2819
2820   my $bill_error = $cust_main->charge($amount, $pkg,
2821      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2822      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2823      $part_pkg->taxclass); #meh
2824
2825   my $conf = new FS::Conf;
2826   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2827
2828     $bill_error = _do_bop_realtime( $cust_main, $status );
2829
2830     if ($bill_error) {
2831       return $bill_error;
2832     } else {
2833       my $error = $svc_x->recharge (\%vhash);
2834       return { 'error' => $error } if $error;
2835     }
2836
2837   } else {  
2838     my $error = $bill_error;
2839     $error ||= $svc_x->recharge (\%vhash);
2840     return { 'error' => $error } if $error;
2841   }
2842
2843   return { error => '', svc => $cust_svc->part_svc->svc };
2844
2845 }
2846
2847 sub _do_bop_realtime {
2848   my ($cust_main, $status, %opt) = @_;
2849
2850   my $old_balance = $cust_main->balance;
2851
2852   my @cust_bill;
2853   my $bill_error = $cust_main->bill(
2854     'return_bill'   => \@cust_bill,
2855   );
2856
2857   $bill_error ||= $cust_main->apply_payments_and_credits;
2858
2859   $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2860
2861   if (    $cust_main->balance > $old_balance
2862        && $cust_main->balance > 0
2863        && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2864      )
2865   {
2866     unless ( $opt{'no_invoice_void'} ) {
2867
2868       #this used to apply a credit, but now we can void invoices...
2869       foreach my $cust_bill (@cust_bill) {
2870         my $voiderror = $cust_bill->void('automatic payment failed');
2871         warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2872       }
2873
2874     }
2875
2876     return { 'error' => '_decline', 'bill_error' => $bill_error };
2877   }
2878
2879   if ( $opt{'collect'} ) {
2880     my $collect_error = $cust_main->collect();
2881     return { 'error' => '_decline', 'bill_error' => $collect_error }
2882      if $collect_error; #?
2883   }
2884
2885   '';
2886 }
2887
2888 sub renew_info {
2889   my $p = shift;
2890
2891   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2892   return { 'error' => $session } if $context eq 'error';
2893
2894   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2895     or return { 'error' => "unknown custnum $custnum" };
2896
2897   my @cust_pkg = sort { $a->bill <=> $b->bill }
2898                  grep { $_->part_pkg->freq ne '0' }
2899                  $cust_main->ncancelled_pkgs;
2900
2901   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2902
2903   my $total = $cust_main->balance;
2904
2905   my @array = map {
2906                     my $bill = $_->bill;
2907                     $total += $_->part_pkg->base_recur($_, \$bill);
2908                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2909                     {
2910                       'pkgnum'             => $_->pkgnum,
2911                       'amount'             => sprintf('%.2f', $total),
2912                       'bill_date'          => $_->bill,
2913                       'bill_date_pretty'   => time2str('%x', $_->bill),
2914                       'renew_date'         => $renew_date,
2915                       'renew_date_pretty'  => time2str('%x', $renew_date),
2916                       'expire_date'        => $_->expire,
2917                       'expire_date_pretty' => time2str('%x', $_->expire),
2918                     };
2919                   }
2920                   @cust_pkg;
2921
2922   return { 'dates' => \@array };
2923
2924 }
2925
2926 sub payment_info_renew_info {
2927   my $p = shift;
2928   my $renew_info   = renew_info($p);
2929   my $payment_info = payment_info($p);
2930   return { %$renew_info,
2931            %$payment_info,
2932          };
2933 }
2934
2935 sub order_renew {
2936   my $p = shift;
2937
2938   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2939   return { 'error' => $session } if $context eq 'error';
2940
2941   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2942     or return { 'error' => "unknown custnum $custnum" };
2943
2944   my $date = $p->{'date'};
2945
2946   my $now = time;
2947
2948   #freeside-daily -n -d $date fs_daily $custnum
2949   $cust_main->bill_and_collect( 'time'         => $date,
2950                                 'invoice_time' => $now,
2951                                 'actual_time'  => $now,
2952                                 'check_freq'   => '1d',
2953                               );
2954
2955   return { 'error' => '' };
2956
2957 }
2958
2959 sub suspend_pkg {
2960   my $p = shift;
2961   my $session = _cache->get($p->{'session_id'})
2962     or return { 'error' => "Can't resume session" }; #better error message
2963
2964   my $custnum = $session->{'custnum'};
2965
2966   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2967     or return { 'error' => "unknown custnum $custnum" };
2968
2969   my $conf = new FS::Conf;
2970   my $reasonnum = 
2971     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2972       or return { 'error' => 'Permission denied' };
2973
2974   my $pkgnum = $p->{'pkgnum'};
2975
2976   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2977                                         'pkgnum'  => $pkgnum,   } )
2978     or return { 'error' => "unknown pkgnum $pkgnum" };
2979
2980   my $error = $cust_pkg->suspend(reason => $reasonnum);
2981   return { 'error' => $error };
2982
2983 }
2984
2985 sub cancel_pkg {
2986   my $p = shift;
2987   my $session = _cache->get($p->{'session_id'})
2988     or return { 'error' => "Can't resume session" }; #better error message
2989
2990   my $custnum = $session->{'custnum'};
2991   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2992     or return { 'error' => "unknown custnum $custnum" };
2993
2994   my $pkgnum = $p->{'pkgnum'};
2995   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2996                                         'pkgnum'  => $pkgnum,   } )
2997     or return { 'error' => "unknown pkgnum $pkgnum" };
2998
2999   my $error = $cust_pkg->cancel( 'quiet' => 1,
3000                                  'date'  => $p->{'date'},
3001                                );
3002   return { 'error' => $error };
3003 }
3004
3005 sub provision_phone {
3006   my $p = shift;
3007   my @bulkdid;
3008   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
3009
3010   #editing an existing phone number
3011   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
3012       my($context, $session, $custnum) = _custoragent_session_custnum($p);
3013       return { 'error' => $session } if $context eq 'error';
3014     
3015       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3016       return { 'error' => 'service not found' } unless $svc_phone;
3017       return { 'error' => 'invalid svcnum' } 
3018         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
3019
3020       $svc_phone->email($p->{'email'}) 
3021         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
3022       $svc_phone->forwarddst($p->{'forwarddst'}) 
3023         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
3024             && $p->{'forwarddst'} =~ /^(\d+|)$/;
3025       return { 'error' => $svc_phone->replace };
3026  }
3027
3028   # single DID LNP
3029   unless ( $p->{'lnp'} ) {
3030     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
3031     $p->{'lnp_status'} = "portingin";
3032     return _provision( 'FS::svc_phone',
3033                   [qw(lnp_desired_due_date lnp_other_provider 
3034                     lnp_other_provider_account phonenum countrycode lnp_status)],
3035                   [qw(phonenum countrycode)],
3036                   $p,
3037                   @_
3038                 );
3039   }
3040
3041   # single DID order (the usual case)
3042   unless (scalar(@bulkdid)) {
3043     return _provision( 'FS::svc_phone',
3044                   [qw(phonenum countrycode)],
3045                   [qw(phonenum countrycode)],
3046                   $p,
3047                   @_
3048                 );
3049   }
3050
3051   # bulk DID order case
3052   my $error;
3053   foreach my $did ( @bulkdid ) {
3054     $did =~ s/[^0-9]//g;
3055     $error = _provision( 'FS::svc_phone',
3056               [qw(phonenum countrycode)],
3057               [qw(phonenum countrycode)],
3058               {
3059                 'pkgnum' => $p->{'pkgnum'},
3060                 'svcpart' => $p->{'svcpart'},
3061                 'phonenum' => $did,
3062                 'countrycode' => $p->{'countrycode'},
3063                 'session_id' => $p->{'session_id'},
3064               }
3065             );
3066     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3067   }
3068   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3069 }
3070
3071 sub provision_pbx {
3072   my $p = shift;
3073   warn "provision_pbx called\n"
3074     if $DEBUG;
3075
3076   warn "provision_pbx calling _provision\n"
3077     if $DEBUG;
3078   _provision( 'FS::svc_pbx',
3079               [qw(id title max_extensions max_simultaneous ip_addr)],
3080               [qw(id title max_extensions max_simultaneous ip_addr)],
3081               $p,
3082               @_
3083             );
3084 }
3085
3086 sub provision_acct {
3087   my $p = shift;
3088   warn "provision_acct called\n"
3089     if $DEBUG;
3090
3091   return { 'error' => gettext('passwords_dont_match') }
3092     if $p->{'_password'} ne $p->{'_password2'};
3093   return { 'error' => gettext('empty_password') }
3094     unless length($p->{'_password'});
3095  
3096   if ($p->{'domsvc'}) {
3097     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3098                                                   qw ( svcpart pkgnum ) );
3099     return { 'error' => gettext('invalid_domain') }
3100       unless ($domains{$p->{'domsvc'}});
3101   }
3102
3103   warn "provision_acct calling _provision\n"
3104     if $DEBUG;
3105   _provision( 'FS::svc_acct',
3106               [qw(username _password domsvc)],
3107               [qw(username _password domsvc)],
3108               $p,
3109               @_
3110             );
3111 }
3112
3113 sub provision_external {
3114   my $p = shift;
3115   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3116   _provision( 'FS::svc_external',
3117               [],
3118               [qw(id title)],
3119               $p,
3120               @_
3121             );
3122 }
3123
3124 sub provision_forward {
3125   my $p = shift;
3126   _provision( 'FS::svc_forward',
3127               ['srcsvc','src','dstsvc','dst'],
3128               [],
3129               $p,
3130             );
3131 }
3132
3133 sub _provision {
3134   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3135   warn "_provision called for $class\n"
3136     if $DEBUG;
3137
3138   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3139   return { 'error' => $session } if $context eq 'error';
3140
3141   my $search = { 'custnum' => $custnum };
3142   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3143   my $cust_main = qsearchs('cust_main', $search )
3144     or return { 'error' => "unknown custnum $custnum" };
3145
3146   my $pkgnum = $p->{'pkgnum'};
3147
3148   warn "searching for custnum $custnum pkgnum $pkgnum\n"
3149     if $DEBUG;
3150   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3151                                         'pkgnum'  => $pkgnum,
3152                                                                } )
3153     or return { 'error' => "unknown pkgnum $pkgnum" };
3154
3155   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3156     if $DEBUG;
3157   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3158     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3159
3160   return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3161     if $class ne 'FS::'. $part_svc->svcdb;
3162
3163   warn "creating $class record\n"
3164     if $DEBUG;
3165   my $svc_x = $class->new( {
3166     'pkgnum'  => $p->{'pkgnum'},
3167     'svcpart' => $p->{'svcpart'},
3168     map { $_ => $p->{$_} } @$fields
3169   } );
3170
3171   my %insert_args = ();
3172   #i shouldn't be a special case here (pass an option or something)
3173   if ( $class eq 'FS::svc_phone'
3174          && grep length($p->{$_}), @location_editable_fields
3175      )
3176   {
3177     $insert_args{'cust_location'} = new FS::cust_location {
3178       map { $_ => $p->{$_} } @location_editable_fields
3179     };
3180   }
3181
3182   warn "inserting $class record\n"
3183     if $DEBUG;
3184   my $error = $svc_x->insert(%insert_args);
3185
3186   unless ( $error ) {
3187     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3188       if $DEBUG;
3189     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3190   }
3191
3192   my $return = { 'svc'   => $part_svc->svc,
3193                  'error' => $error,
3194                  map { $_ => $svc_x->get($_) } @$return_fields
3195                };
3196   warn "_provision returning ". Dumper($return). "\n"
3197     if $DEBUG;
3198   return $return;
3199
3200 }
3201
3202 sub part_svc_info {
3203   my $p = shift;
3204
3205   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3206   return { 'error' => $session } if $context eq 'error';
3207
3208   my $search = { 'custnum' => $custnum };
3209   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3210   my $cust_main = qsearchs('cust_main', $search )
3211     or return { 'error' => "unknown custnum $custnum" };
3212
3213   my $pkgnum = $p->{'pkgnum'};
3214
3215   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3216                                         'pkgnum'  => $pkgnum,
3217                                                                } )
3218     or return { 'error' => "unknown pkgnum $pkgnum" };
3219
3220   my $svcpart = $p->{'svcpart'};
3221
3222   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3223                                       'svcpart' => $svcpart,           } )
3224     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3225   my $part_svc = $pkg_svc->part_svc;
3226
3227   my $conf = new FS::Conf;
3228
3229   my $ret = {
3230     'svc'     => $part_svc->svc,
3231     'svcdb'   => $part_svc->svcdb,
3232     'pkgnum'  => $pkgnum,
3233     'svcpart' => $svcpart,
3234     'custnum' => $custnum,
3235
3236     'security_phrase' => 0, #XXX !
3237     'svc_acct_pop'    => [], #XXX !
3238     'popnum'          => '',
3239     'init_popstate'   => '',
3240     'popac'           => '',
3241     'acstate'         => '',
3242
3243     'small_custview' =>
3244       small_custview( $cust_main, $conf->config('countrydefault') ),
3245
3246   };
3247
3248   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
3249                      && $ret->{'svcdb'} eq 'svc_phone') {
3250         $ret->{'svcnum'} = $p->{'svcnum'};
3251         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3252         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3253             $ret->{'email'} = $svc_phone->email;
3254             $ret->{'forwarddst'} = $svc_phone->forwarddst;
3255         }
3256   }
3257
3258   if ($ret->{'svcdb'} eq 'svc_forward') {
3259     $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3260   }
3261
3262   $ret;
3263 }
3264
3265 sub unprovision_svc {
3266   my $p = shift;
3267
3268   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3269   return { 'error' => $session } if $context eq 'error';
3270
3271   my $search = { 'custnum' => $custnum };
3272   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3273   my $cust_main = qsearchs('cust_main', $search )
3274     or return { 'error' => "unknown custnum $custnum" };
3275
3276   my $svcnum = $p->{'svcnum'};
3277
3278   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
3279     or return { 'error' => "unknown svcnum $svcnum" };
3280
3281   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3282     unless $cust_svc->cust_pkg->custnum == $custnum;
3283
3284   my $conf = new FS::Conf;
3285
3286   return { 'svc'   => $cust_svc->part_svc->svc,
3287            'error' => $cust_svc->cancel,
3288            'small_custview' =>
3289              small_custview( $cust_main, $conf->config('countrydefault') ),
3290          };
3291
3292 }
3293
3294 sub myaccount_passwd {
3295   my $p = shift;
3296   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3297   return { 'error' => $session } if $context eq 'error';
3298
3299   return { 'error' => "New passwords don't match." }
3300     if $p->{'new_password'} ne $p->{'new_password2'};
3301
3302   return { 'error' => 'Enter new password' }
3303     unless length($p->{'new_password'});
3304
3305   #my $search = { 'custnum' => $custnum };
3306   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3307   $custnum =~ /^(\d+)$/ or die "illegal custnum";
3308   my $search = " AND custnum = $1";
3309   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3310
3311   my $svc_acct = qsearchs( {
3312     'table'     => 'svc_acct',
3313     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3314                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3315                    'LEFT JOIN cust_main USING ( custnum ) ',
3316     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3317     'extra_sql' => $search, #important
3318   } )
3319     or return { 'error' => "Service not found" };
3320
3321   my $error = '';
3322
3323   my $conf = new FS::Conf;
3324
3325   return { 'error' => 'Incorrect current password.' }
3326     if  ( exists($p->{'old_password'})
3327           || $conf->exists('selfservice-password_change_oldpass')
3328         )
3329     && ! $svc_acct->check_password($p->{'old_password'});
3330
3331   $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3332          ||  $svc_acct->set_password($p->{'new_password'})
3333          ||  $svc_acct->replace();
3334
3335   #regular pw change in self-service should change contact pw too, otherwise its
3336   #way too confusing.  hell its confusing they're separate at all, but alas.
3337   #need to support the "ISP provides email that's used as a contact email" case
3338   #as well as we can.
3339   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3340   if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3341                                               custnum   => $custnum,
3342                                               selfservice_access => 'Y',
3343                                             }
3344                            )
3345   ) {
3346     #svc_acct was successful but this one returns an error?  "shouldn't happen"
3347     #don't recheck is_password_allowed here; if the svc_acct password was
3348     #legal, that's good enough
3349     $error ||= $contact->change_password($p->{'new_password'});
3350   }
3351
3352   my($label, $value) = $svc_acct->cust_svc->label;
3353
3354   return { 'error' => $error,
3355            'label' => $label,
3356            'value' => $value,
3357          };
3358
3359 }
3360
3361 sub reset_passwd {
3362   my $p = shift;
3363
3364   my $info = skin_info($p);
3365
3366   my $conf = new FS::Conf;
3367   my $verification = $conf->config('selfservice-password_reset_verification')
3368     or return { %$info, 'error' => 'Password resets disabled' };
3369
3370   my $contact = '';
3371   my $svc_acct = '';
3372   my $cust_main = '';
3373   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3374   
3375     $contact = FS::contact->by_selfservice_email($p->{'email'});
3376
3377     if ( $contact ) {
3378       my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3379       $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3380     }
3381
3382     #also look for an svc_acct, otherwise it would be super confusing
3383
3384     my($username, $domain) = split('@', $p->{'email'});
3385     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3386     if ( $svc_domain ) {
3387       $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3388                                          'domsvc'   => $svc_domain->svcnum  }
3389                           );
3390       if ( $svc_acct ) {
3391         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3392         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3393
3394         #precaution: don't change svc_acct password not part of the same
3395         # customer as contact
3396         $svc_acct = '' if ! $cust_pkg
3397                        || $cust_pkg->custnum != $cust_main->custnum;
3398       }
3399       
3400     }
3401
3402     return { %$info, 'error' => 'Email address not found' }
3403       unless $contact || $svc_acct;
3404
3405   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3406
3407     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3408       or return { %$info, 'error' => 'Account not found' };
3409
3410     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3411                                        'domsvc'   => $svc_domain->svcnum  }
3412                         )
3413       or return { %$info, 'error' => 'Account not found' };
3414
3415     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3416       or return { %$info, 'error' => 'Account not found' };
3417
3418     $cust_main = $cust_pkg->cust_main;
3419
3420   }
3421
3422   return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3423     if ! $cust_main && $verification ne 'email';
3424
3425   my %verify = (
3426     'email'   => sub { 1; },
3427     'paymask' => sub { 
3428       my( $p, $cust_main ) = @_;
3429       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3430         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3431     },
3432     'amount'  => sub {
3433       my( $p, $cust_main ) = @_;
3434       my $cust_pay = qsearchs({
3435         'table' => 'cust_pay',
3436         'hashref' => { 'custnum' => $cust_main->custnum },
3437         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3438       })
3439         or return 0;
3440
3441       $p->{'amount'} == $cust_pay->paid;
3442     },
3443     'zip'     => sub {
3444       my( $p, $cust_main ) = @_;
3445       $p->{'zip'} eq $cust_main->zip
3446         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3447     },
3448   );
3449
3450   foreach my $verify ( split(',', $verification) ) {
3451
3452     &{ $verify{$verify} }( $p, $cust_main )
3453       or return { %$info, 'error' => 'Account not found' };
3454
3455   }
3456
3457   #okay, we're verified
3458
3459   if ( $contact ) {
3460
3461     my $error = $contact->send_reset_email(
3462                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3463                           );
3464
3465     if ( $error ) {
3466       return { %$info, 'error' => $error }; #????
3467     }
3468
3469   } elsif ( $svc_acct ) {
3470
3471     #create a unique session
3472
3473     my $reset_session = {
3474       'svcnum'   => $svc_acct->svcnum,
3475       'agentnum' => $svc_acct->cust_main->agentnum,
3476     };
3477
3478     my $timeout = '1 hour'; #?
3479
3480     my $reset_session_id;
3481     do {
3482       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3483     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3484       #just in case
3485
3486     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3487
3488     #email it
3489
3490     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3491                                $cust_main->agentnum);
3492     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3493     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3494       unless $msgnum;
3495     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3496     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3497                                      'object'        => $svc_acct,
3498                                      'substitutions' => {
3499                                        'session_id' => $reset_session_id,
3500                                      }
3501                                    );
3502     if ( $error ) {
3503       return { %$info, 'error' => $error }; #????
3504     }
3505
3506   }
3507
3508   return { %$info, 'error' => '' };
3509 }
3510
3511 sub check_reset_passwd {
3512   my $p = shift;
3513
3514   my $conf = new FS::Conf;
3515   my $verification = $conf->config('selfservice-password_reset_verification')
3516     or return { 'error' => 'Password resets disabled' };
3517
3518   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3519     or return { 'error' => "Can't resume session" }; #better error message
3520
3521   if ( $reset_session->{'svcnum'} ) {
3522
3523     my $svcnum = $reset_session->{'svcnum'};
3524
3525     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3526       or return { 'error' => "Service not found" };
3527
3528     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3529     my $info = skin_info($p);
3530
3531     return { %$info,
3532              'error'      => '',
3533              'session_id' => $p->{'session_id'},
3534              'username'   => $svc_acct->username,
3535            };
3536
3537   } elsif ( $reset_session->{'contactnum'} ) {
3538
3539     my $contactnum = $reset_session->{'contactnum'};
3540
3541     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3542       or return { 'error' => "Contact not found" };
3543
3544     my @contact_email = $contact->contact_email;
3545     return { 'error' => 'No contact email' } unless @contact_email;
3546
3547     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3548     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3549       if scalar(@cust_contact) == 1;
3550     my $info = skin_info($p);
3551
3552     return { %$info,
3553              'error'      => '',
3554              'session_id' => $p->{'session_id'},
3555              'email'      => $contact_email[0]->email, #the first?
3556            };
3557
3558   } else {
3559
3560     return { 'error' => 'No svcnum or contactnum in session' }; #??
3561
3562   }
3563
3564 }
3565
3566 sub process_reset_passwd {
3567   my $p = shift;
3568
3569   my $conf = new FS::Conf;
3570   my $verification = $conf->config('selfservice-password_reset_verification')
3571     or return { 'error' => 'Password resets disabled' };
3572
3573   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3574     or return { 'error' => "Can't resume session" }; #better error message
3575
3576   my $info = '';
3577
3578   my $svc_acct = '';
3579   if ( $reset_session->{'svcnum'} ) {
3580
3581     my $svcnum = $reset_session->{'svcnum'};
3582
3583     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3584       or return { 'error' => "Service not found" };
3585
3586     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3587     $info ||= skin_info($p);
3588
3589   }
3590
3591   my $contact = '';
3592   if ( $reset_session->{'contactnum'} ) {
3593
3594     my $contactnum = $reset_session->{'contactnum'};
3595
3596     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3597       or return { 'error' => "Contact not found" };
3598
3599     my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3600     $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3601       if scalar(@cust_contact) == 1;
3602     $info ||= skin_info($p);
3603
3604   }
3605
3606   return { %$info, 'error' => "New passwords don't match." }
3607     if $p->{'new_password'} ne $p->{'new_password2'};
3608
3609   return { %$info, 'error' => 'Enter new password' }
3610     unless length($p->{'new_password'});
3611
3612   if ( $svc_acct ) {
3613
3614     my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3615               ||  $svc_acct->set_password($p->{'new_password'})
3616               ||  $svc_acct->replace();
3617
3618     return { %$info, 'error' => $error } if $error;
3619
3620     #my($label, $value) = $svc_acct->cust_svc->label;
3621     #return { 'error' => $error,
3622     #         #'label' => $label,
3623     #         #'value' => $value,
3624     #       };
3625
3626   }
3627
3628   if ( $contact ) {
3629
3630     my $error = $contact->is_password_allowed($p->{'new_password'})
3631             ||  $contact->change_password($p->{'new_password'});
3632
3633     return { %$info, 'error' => $error }; # if $error;
3634
3635   }
3636
3637   #password changed ,so remove session, don't want it reused
3638   _cache->remove($p->{'session_id'});
3639
3640   return { %$info, 'error' => '' };
3641
3642 }
3643
3644 sub validate_passwd {
3645   my $p = shift;
3646
3647   my %result;
3648   %result = ( 'fieldid' => $p->{'fieldid'} )
3649     if $p->{'fieldid'} =~ /^\w+$/;
3650
3651   return { %result, 'password_invalid' => 'Enter new password' }
3652     unless length($p->{'check_password'});
3653
3654   my $svc_acct;
3655   if ($p->{'svcnum'}) {
3656     # false laziness with myaccount_passwd
3657     my($context, $session, $custnum) = _custoragent_session_custnum($p);
3658     return { %result, 'error' => $session } if $context eq 'error';
3659
3660     $custnum =~ /^(\d+)$/ or die "illegal custnum";
3661     my $search = " AND custnum = $1";
3662     $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3663
3664     $svc_acct = qsearchs( {
3665       'table'     => 'svc_acct',
3666       'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
3667                      'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
3668                      'LEFT JOIN cust_main USING ( custnum ) ',
3669       'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
3670       'extra_sql' => $search, #important
3671     } )
3672       or return { %result, 'error' => "Service not found" };
3673     # end false laziness
3674   }
3675
3676   $svc_acct ||= new FS::svc_acct {};
3677
3678   my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3679   return { %result, 'password_invalid' => $error } if $error;
3680   return { %result, 'password_valid' => 1 };
3681 }
3682
3683 sub list_tickets {
3684   my $p = shift;
3685   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3686   return { 'error' => $session } if $context eq 'error';
3687
3688   my @tickets = ();
3689   if ( $session->{'pkgnum'} ) { 
3690
3691     #tickets for specific service with pkg-balances on
3692     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3693                                           'pkgnum'  => $session->{'pkgnum'} })
3694                      or return { 'error' => 'unknown package' };
3695     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3696       push @tickets, $cust_svc->tickets( $p->{status} );
3697     }
3698
3699   } else {
3700
3701     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3702       or return { 'error' => "unknown custnum $custnum" };
3703
3704     @tickets = $cust_main->tickets( $p->{status} );
3705   }
3706
3707   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3708   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3709
3710     @tickets = grep { $_->{'_selfservice_priority'}
3711                         !~ /^\s*(closed?|resolved?|done)\s*/i }
3712                  @tickets;
3713
3714     my $conf = new FS::Conf;
3715     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3716     +{ tickets => [ 
3717          sort { 
3718            (
3719              ($a->{'_selfservice_priority'} eq '') <=>
3720              ($b->{'_selfservice_priority'} eq '')
3721            ) ||
3722            ( $dir * 
3723              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3724            )
3725          } @tickets
3726        ]
3727     };
3728   } else {
3729     +{ tickets => \@tickets };
3730   }
3731
3732 }
3733
3734 sub create_ticket {
3735   my $p = shift;
3736   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3737   return { 'error' => $session } if $context eq 'error';
3738
3739   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3740   FS::TicketSystem->init();
3741
3742   my $conf = new FS::Conf;
3743   my $queue = $p->{'queue'}
3744               || $conf->config('ticket_system-selfservice_queueid')
3745               || $conf->config('ticket_system-default_queueid');
3746
3747   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3748   my $err_or_ticket = FS::TicketSystem->create_ticket(
3749     '', #create RT session based on FS CurrentUser (fs_selfservice)
3750     'queue'   => $queue,
3751     'custnum' => $custnum,
3752     'svcnum'  => $session->{'svcnum'},
3753     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3754   );
3755
3756   if ( ref($err_or_ticket) ) {
3757     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3758       if $DEBUG;
3759     return { 'error'     => '',
3760              'ticket_id' => $err_or_ticket->id,
3761            };
3762   } else {
3763     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3764       if $DEBUG;
3765     return { 'error' => $err_or_ticket };
3766   }
3767
3768
3769 }
3770
3771 sub did_report {
3772   my $p = shift;
3773   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3774   return { 'error' => $session } if $context eq 'error';
3775  
3776   return { error => 'requested format not implemented' } 
3777     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3778
3779   my $conf = new FS::Conf;
3780   my $age_threshold = 0;
3781   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3782     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3783
3784   my $search = { 'custnum' => $custnum };
3785   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3786   my $cust_main = qsearchs('cust_main', $search )
3787     or return { 'error' => "unknown custnum $custnum" };
3788
3789 # does it make more sense to just run one sql query for this instead of all the
3790 # insanity below? would increase performance greately for large data sets?
3791   my @svc_phone = ();
3792   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3793         my @part_svc = $cust_pkg->part_svc;
3794         foreach my $part_svc ( @part_svc ) {
3795             if($part_svc->svcdb eq 'svc_phone'){
3796                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3797                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3798                     push @svc_phone, $cust_pkg_svc->svc_x
3799                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3800                 }
3801             }
3802         }
3803   }
3804
3805   my $csv;
3806   my $xls;
3807   my($xls_r,$xls_c) = (0,0);
3808   my $xls_workbook;
3809   my $content = '';
3810   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3811   if($p->{'format'} eq 'csv') {
3812     $csv = new Text::CSV_XS { 'always_quote' => 1,
3813                                  'eol'          => "\n",
3814                                 };
3815     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3816     $content .= $csv->string;
3817   }
3818   elsif($p->{'format'} eq 'xls') {
3819     my $XLS1 = new IO::Scalar \$content;
3820     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3821         or return { 'error' => "Error opening .xls file: $!" };
3822     $xls = $xls_workbook->add_worksheet('DIDs');
3823     foreach ( @fields ) {
3824         $xls->write(0,$xls_c++,$_);
3825     }
3826     $xls_r++;
3827   }
3828
3829   foreach my $svc_phone ( @svc_phone ) {
3830     my @cols = map { $svc_phone->$_ } @fields;
3831     if($p->{'format'} eq 'csv') {
3832         return { 'error' => 'Unable to create CSV' } 
3833             unless $csv->combine(@cols);
3834         $content .= $csv->string;
3835     }
3836     elsif($p->{'format'} eq 'xls') {
3837         $xls_c = 0;
3838         foreach ( @cols ) {
3839             $xls->write($xls_r,$xls_c++,$_);
3840         }
3841         $xls_r++;
3842     }
3843   }
3844
3845   $xls_workbook->close() if $p->{'format'} eq 'xls';
3846   
3847   { content => $content, format => $p->{'format'}, };
3848 }
3849
3850 sub get_ticket {
3851   my $p = shift;
3852   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3853   return { 'error' => $session } if $context eq 'error';
3854
3855 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3856 #  FS::TicketSystem->init();
3857 #  return { 'error' => 'get_ticket configuration error' }
3858 #    if $FS::TicketSystem::system ne 'RT_Internal';
3859
3860   # check existence and ownership as part of this
3861   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3862   my $rt_session = FS::TicketSystem->session('');
3863   my $Ticket = FS::TicketSystem->get_ticket_object(
3864     $rt_session, 
3865     ticket_id => $p->{'ticket_id'},
3866     custnum => $custnum
3867   );
3868   return { 'error' => 'ticket not found' } if !$Ticket;
3869
3870   if ( length( $p->{'subject'} || '' ) ) {
3871     # subject change
3872     if ( $p->{'subject'} ne $Ticket->Subject ) {
3873       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3874       return { 'error' => "unable to set subject: $msg" } if !$val;
3875     }
3876   }
3877
3878   if(length($p->{'reply'})) {
3879     my @err_or_res = FS::TicketSystem->correspond_ticket(
3880       $rt_session,
3881       'ticket_id' => $p->{'ticket_id'},
3882       'content' => $p->{'reply'},
3883     );
3884
3885     return { 'error' => 'unable to reply to ticket' } 
3886     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3887   }
3888
3889   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3890   my $err_or_ticket = FS::TicketSystem->get_ticket(
3891     $rt_session,
3892     'ticket_id' => $p->{'ticket_id'},
3893   );
3894
3895   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3896     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3897       if $DEBUG;
3898     return { 'error' => $err_or_ticket };
3899   }
3900
3901   my @custs = @{$err_or_ticket->{'custs'}};
3902   my @txns = @{$err_or_ticket->{'txns'}};
3903   my @filtered_txns;
3904
3905   # superseded by check in get_ticket_object
3906   #return { 'error' => 'invalid ticket requested' } 
3907   #unless grep($_ eq $custnum, @custs);
3908
3909   foreach my $txn ( @txns ) {
3910     push @filtered_txns, $txn 
3911     if ($txn->{'type'} eq 'EmailRecord' 
3912       || $txn->{'type'} eq 'Correspond'
3913       || $txn->{'type'} eq 'Create');
3914   }
3915
3916   warn "$me get_ticket: successful: \n"
3917   if $DEBUG;
3918   return { 'error'     => '',
3919     'transactions' => \@filtered_txns,
3920     'ticket_fields' => $err_or_ticket->{'fields'},
3921     'ticket_id' => $p->{'ticket_id'},
3922   };
3923 }
3924
3925 sub adjust_ticket_priority {
3926   my $p = shift;
3927   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3928   return { 'error' => $session } if $context eq 'error';
3929
3930 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3931 #  FS::TicketSystem->init;
3932   my $ss_priority = FS::TicketSystem->selfservice_priority;
3933
3934   return { 'error' => 'adjust_ticket_priority configuration error' }
3935     if $FS::TicketSystem::system ne 'RT_Internal'
3936       or !$ss_priority;
3937
3938   my $values = $p->{'values'}; #hashref, id => priority value
3939   my %ticket_error;
3940
3941   foreach my $id (keys %$values) {
3942     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3943     my $Ticket = FS::TicketSystem->get_ticket_object('',
3944       'ticket_id' => $id,
3945       'custnum'   => $custnum,
3946     );
3947     if ( !$Ticket ) {
3948       $ticket_error{$id} = 'ticket not found';
3949       next;
3950     }
3951     
3952   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3953   # We're not going to implement it for RT_External.
3954     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3955     my $new_value = $values->{$id};
3956     next if $old_value eq $new_value;
3957
3958     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3959
3960     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3961     # a single-valued custom field, which it should be.  If it's not, you're 
3962     # doing something wrong.
3963     my ($val, $msg);
3964     if ( length($new_value) ) {
3965       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3966         Field => $ss_priority,
3967         Value => $new_value,
3968       );
3969     }
3970     else {
3971       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3972         Field => $ss_priority,
3973         Value => $old_value,
3974       );
3975     }
3976
3977     $ticket_error{$id} = $msg if !$val;
3978     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3979   }
3980   return { 'error' => '',
3981            'ticket_error' => \%ticket_error,
3982            %{ customer_info($p) } # send updated customer info back
3983          }
3984 }
3985
3986 #--
3987
3988 sub _custoragent_session_custnum {
3989   my $p = shift;
3990
3991   my($context, $session, $custnum);
3992   if ( $p->{'session_id'} ) {
3993
3994     $context = 'customer';
3995     $session = _cache->get($p->{'session_id'})
3996       or return ( 'error' => "Can't resume session" ); #better error message
3997     $custnum = $session->{'custnum'};
3998
3999   } elsif ( $p->{'agent_session_id'} ) {
4000
4001     $context = 'agent';
4002     my $agent_cache = new FS::ClientAPI_SessionCache( {
4003       'namespace' => 'FS::ClientAPI::Agent',
4004     } );
4005     $session = $agent_cache->get($p->{'agent_session_id'})
4006       or return ( 'error' => "Can't resume session" ); #better error message
4007     $custnum = $p->{'custnum'};
4008
4009   } else {
4010     $context = 'error';
4011     return ( 'error' => "Can't resume session" ); #better error message
4012   }
4013
4014   ($context, $session, $custnum);
4015
4016 }
4017
4018 1;