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