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