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