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