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