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