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