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