fix per-agent portal branding on logout, RT#32139
[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     'selfservice' => 1,
1135     'paynum_ref'  => \$paynum,
1136     %$validate,
1137   );
1138   return { 'error' => $error } if $error;
1139
1140   #no error, so order the fee package if applicable...
1141   my $conf = new FS::Conf;
1142   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1143   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1144   
1145   if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1146
1147     my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1148
1149     $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1150     return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1151       if $error;
1152
1153     #and generate an invoice for it now too
1154     $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1155     return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1156       if $error;
1157
1158   }
1159
1160   $cust_main->apply_payments;
1161
1162   if ( $validate->{'save'} ) {
1163     my $new = new FS::cust_main { $cust_main->hash };
1164     if ($payby eq 'CARD' || $payby eq 'DCRD') {
1165       $new->set( $_ => $validate->{$_} )
1166         foreach qw( payname paystart_month paystart_year payissue payip );
1167       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1168
1169       my $bill_location = FS::cust_location->new({
1170           map { $_ => $validate->{$_} } 
1171           qw(address1 address2 city state country zip)
1172       }); # county?
1173       $new->set('bill_location' => $bill_location);
1174       # but don't allow the service address to change this way.
1175
1176     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1177       $new->set( $_ => $validate->{$_} )
1178         foreach qw( payname payip paytype paystate
1179                     stateid stateid_state );
1180       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1181     }
1182     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1183     $new->set( 'paydate' => $validate->{'paydate'} );
1184     my $error = $new->replace($cust_main);
1185     if ( $error ) {
1186       #no, this causes customers to process their payments again
1187       #return { 'error' => $error };
1188       #XXX just warn verosely for now so i can figure out how these happen in
1189       # the first place, eventually should redirect them to the "change
1190       #address" page but indicate the payment did process??
1191       delete($validate->{'payinfo'}); #don't want to log this!
1192       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1193            "NEW: ". Dumper($new)."\n".
1194            "OLD: ". Dumper($cust_main)."\n".
1195            "PACKET: ". Dumper($validate)."\n";
1196     #} else {
1197       #not needed...
1198       #$cust_main = $new;
1199     }
1200   }
1201
1202   my $cust_pay = '';
1203   my $receipt_html = '';
1204   if ($paynum) {
1205       # currently supported for realtime CC only; send receipt data to SS
1206       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1207       if($cust_pay) {
1208         $receipt_html = qq!
1209 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1210
1211 <TR>
1212   <TD ALIGN="right">Payment#</TD>
1213   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1214 </TR>
1215
1216 <TR>
1217   <TD ALIGN="right">Date</TD>
1218
1219   <TD BGCOLOR="#FFFFFF"><B>! . 
1220         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
1221                                                             . qq!</B></TD>
1222 </TR>
1223
1224
1225 <TR>
1226   <TD ALIGN="right">Amount</TD>
1227   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1228
1229 </TR>
1230
1231 <TR>
1232   <TD ALIGN="right">Payment method</TD>
1233   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1234                                                                 . qq!</B></TD>
1235 </TR>
1236
1237 </TABLE>
1238 !;
1239       }
1240   }
1241
1242   if ( $cust_pay ) {
1243
1244     return {
1245       'error'        => '',
1246       'amount'       => sprintf('%.2f', $cust_pay->paid),
1247       'date'         => $cust_pay->_date,
1248       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
1249       'time_pretty'  => time2str('%T', $cust_pay->_date),
1250       'auth_num'     => $cust_pay->auth,
1251       'order_num'    => $cust_pay->order_number,
1252       'receipt_html' => $receipt_html,
1253     };
1254
1255   } else {
1256
1257     return {
1258       'error'        => '',
1259       'receipt_html' => '',
1260     };
1261
1262   }
1263
1264 }
1265
1266 sub realtime_collect {
1267   my $p = shift;
1268
1269   my $session = _cache->get($p->{'session_id'})
1270     or return { 'error' => "Can't resume session" }; #better error message
1271
1272   my $custnum = $session->{'custnum'};
1273
1274   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1275     or return { 'error' => "unknown custnum $custnum" };
1276
1277   my $amount;
1278   if ( $p->{'amount'} ) {
1279     $amount = $p->{'amount'};
1280   }
1281   elsif ( $session->{'pkgnum'} ) {
1282     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1283   }
1284   else {
1285     $amount = $cust_main->balance;
1286   }
1287
1288   my $error = $cust_main->realtime_collect(
1289     'method'     => $p->{'method'},
1290     'amount'     => $amount,
1291     'pkgnum'     => $session->{'pkgnum'},
1292     'session_id' => $p->{'session_id'},
1293     'apply'      => 1,
1294     'selfservice'=> 1,
1295   );
1296   return { 'error' => $error } unless ref( $error );
1297
1298   return { 'error' => '', amount => $amount, %$error };
1299 }
1300
1301 sub start_thirdparty {
1302   my $p = shift;
1303   my $session = _cache->get($p->{'session_id'})
1304     or return { 'error' => "Can't resume session" }; #better error message
1305   my $custnum = $session->{'custnum'};
1306   my $cust_main = FS::cust_main->by_key($custnum);
1307   
1308   my $amount = $p->{'amount'}
1309     or return { error => 'no amount' };
1310
1311   my $result = $cust_main->create_payment(
1312     'method'      => $p->{'method'},
1313     'amount'      => $p->{'amount'},
1314     'pkgnum'      => $session->{'pkgnum'},
1315     'session_id'  => $p->{'session_id'},
1316   );
1317   
1318   if ( ref($result) ) { # hashref or error
1319     return $result;
1320   } else {
1321     return { error => $result };
1322   }
1323 }
1324
1325 sub finish_thirdparty {
1326   my $p = shift;
1327   my $session_id = delete $p->{'session_id'};
1328   my $session = _cache->get($session_id)
1329     or return { 'error' => "Can't resume session" };
1330   my $custnum = $session->{'custnum'};
1331   my $cust_main = FS::cust_main->by_key($custnum);
1332
1333   if ( $p->{_cancel} ) {
1334     # customer backed out of making a payment
1335     return $cust_main->cancel_payment( $session_id );
1336   }
1337   my $result = $cust_main->execute_payment( $session_id, %$p );
1338   if ( ref($result) ) {
1339     return $result;
1340   } else {
1341     return { error => $result };
1342   }
1343 }
1344
1345 sub process_payment_order_pkg {
1346   my $p = shift;
1347
1348   my $hr = process_payment($p);
1349   return $hr if $hr->{'error'};
1350
1351   order_pkg($p);
1352 }
1353
1354 sub process_payment_order_renew {
1355   my $p = shift;
1356
1357   my $hr = process_payment($p);
1358   return $hr if $hr->{'error'};
1359
1360   order_renew($p);
1361 }
1362
1363 sub process_prepay {
1364
1365   my $p = shift;
1366
1367   my $session = _cache->get($p->{'session_id'})
1368     or return { 'error' => "Can't resume session" }; #better error message
1369
1370   my %return;
1371
1372   my $custnum = $session->{'custnum'};
1373
1374   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1375     or return { 'error' => "unknown custnum $custnum" };
1376
1377   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1378   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1379                                            \$amount,
1380                                            \$seconds,
1381                                            \$upbytes,
1382                                            \$downbytes,
1383                                            \$totalbytes,
1384                                          );
1385
1386   return { 'error' => $error } if $error;
1387
1388   return { 'error'     => '',
1389            'amount'    => $amount,
1390            'seconds'   => $seconds,
1391            'duration'  => duration_exact($seconds),
1392            'upbytes'   => $upbytes,
1393            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1394            'downbytes' => $downbytes,
1395            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1396            'totalbytes'=> $totalbytes,
1397            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1398          };
1399
1400 }
1401
1402 sub invoice {
1403   my $p = shift;
1404   my $session = _cache->get($p->{'session_id'})
1405     or return { 'error' => "Can't resume session" }; #better error message
1406
1407   my $custnum = $session->{'custnum'};
1408
1409   my $invnum = $p->{'invnum'};
1410
1411   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1412                                           'custnum' => $custnum } )
1413     or return { 'error' => "Can't find invnum" };
1414
1415   #my %return;
1416
1417   return { 'error'        => '',
1418            'invnum'       => $invnum,
1419            'invoice_text' => join('', $cust_bill->print_text ),
1420            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1421          };
1422
1423 }
1424
1425 sub invoice_pdf {
1426   my $p = shift;
1427   my $session = _cache->get($p->{'session_id'})
1428     or return { 'error' => "Can't resume session" }; #better error message
1429
1430   my $custnum = $session->{'custnum'};
1431
1432   my $invnum = $p->{'invnum'};
1433
1434   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1435                                           'custnum' => $custnum } )
1436     or return { 'error' => "Can't find invnum" };
1437
1438   #my %return;
1439
1440   return { 'error'       => '',
1441            'invnum'      => $invnum,
1442            'invoice_pdf' => $cust_bill->print_pdf({
1443                               'unsquelch_cdr' => 1,
1444                               'locale'        => $p->{'locale'},
1445                             }),
1446          };
1447
1448 }
1449
1450 sub legacy_invoice {
1451   my $p = shift;
1452   my $session = _cache->get($p->{'session_id'})
1453     or return { 'error' => "Can't resume session" }; #better error message
1454
1455   my $custnum = $session->{'custnum'};
1456
1457   my $legacyinvnum = $p->{'legacyinvnum'};
1458
1459   my %hash = (
1460     'legacyinvnum' => $legacyinvnum,
1461     'custnum'      => $custnum,
1462   );
1463
1464   my $legacy_cust_bill =
1465          qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1466       || qsearchs('legacy_cust_bill', \%hash )
1467     or return { 'error' => "Can't find legacyinvnum" };
1468
1469   #my %return;
1470
1471   return { 'error'        => '',
1472            'legacyinvnum' => $legacyinvnum,
1473            'legacyid'     => $legacy_cust_bill->legacyid,
1474            'invoice_html' => $legacy_cust_bill->content_html,
1475          };
1476
1477 }
1478
1479 sub legacy_invoice_pdf {
1480   my $p = shift;
1481   my $session = _cache->get($p->{'session_id'})
1482     or return { 'error' => "Can't resume session" }; #better error message
1483
1484   my $custnum = $session->{'custnum'};
1485
1486   my $legacyinvnum = $p->{'legacyinvnum'};
1487
1488   my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1489     'legacyinvnum' => $legacyinvnum,
1490     'custnum'      => $custnum,
1491   }) or return { 'error' => "Can't find legacyinvnum" };
1492
1493   #my %return;
1494
1495   return { 'error'        => '',
1496            'legacyinvnum' => $legacyinvnum,
1497            'legacyid'     => $legacy_cust_bill->legacyid,
1498            'invoice_pdf'  => $legacy_cust_bill->content_pdf,
1499          };
1500
1501 }
1502
1503 sub invoice_logo {
1504   my $p = shift;
1505
1506   #sessioning for this?  how do we get the session id to the backend invoice
1507   # template so it can add it to the link, blah
1508
1509   my $agentnum = '';
1510   if ( $p->{'invnum'} ) {
1511     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1512       or return { 'error' => 'unknown invnum' };
1513     $agentnum = $cust_bill->cust_main->agentnum;
1514   }
1515
1516   my $templatename = $p->{'template'} || $p->{'templatename'};
1517
1518   #false laziness-ish w/view/cust_bill-logo.cgi
1519
1520   my $conf = new FS::Conf;
1521   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1522     $templatename = "_$1";
1523   } else {
1524     $templatename = '';
1525   }
1526
1527   my $filename = "logo$templatename.png";
1528
1529   return { 'error'        => '',
1530            'logo'         => $conf->config_binary($filename, $agentnum),
1531            'content_type' => 'image/png', #should allow gif, jpg too
1532          };
1533 }
1534
1535
1536 sub list_invoices {
1537   my $p = shift;
1538   my $session = _cache->get($p->{'session_id'})
1539     or return { 'error' => "Can't resume session" }; #better error message
1540
1541   my $custnum = $session->{'custnum'};
1542
1543   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1544     or return { 'error' => "unknown custnum $custnum" };
1545
1546   my $conf = new FS::Conf;
1547
1548   my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1549
1550   my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1551
1552   my $balance = 0;
1553
1554   return  { 'error'       => '',
1555             'balance'     => $cust_main->balance,
1556             'invoices'    => [
1557               map {
1558                     my $owed = $_->owed;
1559                     $balance += $owed;
1560                     +{ 'invnum'       => $_->invnum,
1561                        '_date'        => $_->_date,
1562                        'date'         => time2str("%b %o, %Y", $_->_date),
1563                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1564                        'previous'     => sprintf('%.2f', ($_->previous)[0]),
1565                        'charged'      => sprintf('%.2f', $_->charged),
1566                        'owed'         => sprintf('%.2f', $owed),
1567                        'balance'      => sprintf('%.2f', $balance),
1568                      }
1569                   }
1570                   @cust_bill
1571             ],
1572             'legacy_invoices' => [
1573               map {
1574                     +{ 'legacyinvnum' => $_->legacyinvnum,
1575                        'legacyid'     => $_->legacyid,
1576                        '_date'        => $_->_date,
1577                        'date'         => time2str("%b %o, %Y", $_->_date),
1578                        'date_short'   => time2str("%m-%d-%Y",  $_->_date),
1579                        'charged'      => sprintf('%.2f', $_->charged),
1580                        'has_content'  => (    length($_->content_pdf)
1581                                            || length($_->content_html) ),
1582                      }
1583                   }
1584                   @legacy_cust_bill
1585             ],
1586           };
1587 }
1588
1589 sub cancel {
1590   my $p = shift;
1591   my $session = _cache->get($p->{'session_id'})
1592     or return { 'error' => "Can't resume session" }; #better error message
1593
1594   my $custnum = $session->{'custnum'};
1595
1596   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1597     or return { 'error' => "unknown custnum $custnum" };
1598
1599   my @errors = $cust_main->cancel( 'quiet'=>1 );
1600
1601   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1602
1603   return { 'error' => $error };
1604
1605 }
1606
1607 sub list_pkgs {
1608   my $p = shift;
1609
1610   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1611   return { 'error' => $session } if $context eq 'error';
1612
1613   my $search = { 'custnum' => $custnum };
1614   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1615   my $cust_main = qsearchs('cust_main', $search )
1616     or return { 'error' => "unknown custnum $custnum" };
1617
1618   my $conf = new FS::Conf;
1619   my $immutable = $conf->exists('selfservice_immutable-package');
1620   
1621 # the duplication below is necessary:
1622 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1623 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1624 # non-backwards-compatible change breaking the software of anyone using the API
1625 # instead of the stock selfservice
1626 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1627   if( $conf->exists('selfservice_server-view-wholesale') ) {
1628     return { 'svcnum'   => $session->{'svcnum'},
1629             'custnum'  => $custnum,
1630             'cust_pkg' => [ map {
1631                           { $_->hash,
1632                             immutable => $immutable,
1633                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1634                             part_svc =>
1635                               [ map $_->hashref, $_->available_part_svc ],
1636                             cust_svc => 
1637                               [ map { my $ref = { $_->hash,
1638                                                   label => [ $_->label ],
1639                                                 };
1640                                       $ref->{_password} = $_->svc_x->_password
1641                                         if $context eq 'agent'
1642                                         && $conf->exists('agent-showpasswords')
1643                                         && $_->part_svc->svcdb eq 'svc_acct';
1644                                       $ref;
1645                                     } $_->cust_svc
1646                               ],
1647                           };
1648                         } $cust_main->cust_pkg
1649                   ],
1650     'small_custview' =>
1651       small_custview( $cust_main, $conf->config('countrydefault') ),
1652     'wholesale_view' => 1,
1653     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1654     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1655     'lnp' => $conf->exists('svc_phone-lnp'),
1656       };
1657   }
1658
1659   { 'svcnum'   => $session->{'svcnum'},
1660     'custnum'  => $custnum,
1661     'cust_pkg' => [ map {
1662                           my $primary_cust_svc = $_->primary_cust_svc;
1663                           +{ $_->hash,
1664                             $_->part_pkg->hash,
1665                             immutable   => $immutable,
1666                             pkg_label   => $_->pkg_locale,
1667                             status      => $_->status,
1668                             statuscolor => $_->statuscolor,
1669                             part_svc =>
1670                               [ map { $_->hashref }
1671                                   grep { $_->selfservice_access ne 'hidden' }
1672                                     $_->available_part_svc
1673                               ],
1674                             cust_svc => 
1675                               [ map { my $ref = { $_->hash,
1676                                                   label => [ $_->label ],
1677                                                 };
1678                                       $ref->{_password} = $_->svc_x->_password
1679                                         if $context eq 'agent'
1680                                         && $conf->exists('agent-showpasswords')
1681                                         && $_->part_svc->svcdb eq 'svc_acct';
1682                                       $ref->{svchash} = { $_->svc_x->hash } if 
1683                                         $_->part_svc->svcdb eq 'svc_phone';
1684                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1685                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1686                                       $ref;
1687                                     }
1688                                   grep { $_->part_svc->selfservice_access ne 'hidden' }
1689                                     $_->cust_svc
1690                               ],
1691                             primary_cust_svc =>
1692                               $primary_cust_svc
1693                                 ? { $primary_cust_svc->hash,
1694                                     label => [ $primary_cust_svc->label ],
1695                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1696                                     $primary_cust_svc->part_svc->hash,
1697                                   }
1698                                 : {}, #'' ?
1699                           };
1700                         } $cust_main->ncancelled_pkgs
1701                   ],
1702     'small_custview' =>
1703       small_custview( $cust_main, $conf->config('countrydefault') ),
1704     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1705   };
1706
1707 }
1708
1709 sub list_svcs {
1710   my $p = shift;
1711
1712   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1713   return { 'error' => $session } if $context eq 'error';
1714
1715   my $conf = new FS::Conf;
1716
1717   my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1718   my $search = { 'custnum' => $custnum };
1719   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1720   my $cust_main = qsearchs('cust_main', $search )
1721     or return { 'error' => "unknown custnum $custnum" };
1722
1723   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1724   if ( ! $pkgnum && $p->{'svcnum'} ) {
1725     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1726     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1727   }
1728
1729   my @cust_svc = ();
1730   my @cust_pkg_usage = ();
1731   foreach my $cust_pkg ( $p->{'ncancelled'} 
1732                          ? $cust_main->ncancelled_pkgs
1733                          : $cust_main->unsuspended_pkgs ) {
1734     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1735     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1736     push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1737   }
1738
1739   @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1740   my %usage_pools;
1741   if (!$hide_usage) {
1742     foreach (@cust_pkg_usage) {
1743       my $part = $_->part_pkg_usage;
1744       my $tag = $part->description . ($part->shared ? 1 : 0);
1745       my $row = $usage_pools{$tag} 
1746             ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1747       $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1748       $row->[2] += $part->minutes; # minutes total
1749     }
1750   } # otherwise just leave them empty
1751
1752   if ( $p->{'svcdb'} ) {
1753     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1754                   ? $p->{'svcdb'}
1755                   : ref($p->{'svcdb'}) eq 'ARRAY'
1756                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1757                     : { $p->{'svcdb'} => 1 };
1758     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1759   }
1760
1761   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1762   #              @svc_x;
1763
1764   my @svcs; # stuff to return to the client
1765   foreach my $cust_svc (@cust_svc) {
1766     my $svc_x = $cust_svc->svc_x;
1767     my($label, $value) = $cust_svc->label;
1768     my $part_svc = $cust_svc->part_svc;
1769     my $svcdb = $part_svc->svcdb;
1770     my $cust_pkg = $cust_svc->cust_pkg;
1771     my $part_pkg = $cust_pkg->part_pkg;
1772
1773     my %hash = (
1774       'svcnum'         => $cust_svc->svcnum,
1775       'display_svcnum' => $cust_svc->display_svcnum,
1776       'svcdb'          => $svcdb,
1777       'label'          => $label,
1778       'value'          => $value,
1779       'pkg_label'      => $cust_pkg->pkg_locale,
1780       'pkg_status'     => $cust_pkg->status,
1781       'readonly'       => ($part_svc->selfservice_access eq 'readonly'),
1782     );
1783
1784     # would it make sense to put this in a svc_* method?
1785
1786     if ( $svcdb eq 'svc_acct' ) {
1787       foreach (qw(username email finger seconds)) {
1788         $hash{$_} = $svc_x->$_;
1789       }
1790
1791       if (!$hide_usage) {
1792         %hash = (
1793           %hash,
1794           'upbytes'    => display_bytecount($svc_x->upbytes),
1795           'downbytes'  => display_bytecount($svc_x->downbytes),
1796           'totalbytes' => display_bytecount($svc_x->totalbytes),
1797
1798           'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1799           'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1800           'recharge_upbytes'    =>
1801             display_bytecount($part_pkg->option('recharge_upbytes',1)),
1802           'recharge_downbytes'  =>
1803             display_bytecount($part_pkg->option('recharge_downbytes',1)),
1804           'recharge_totalbytes' =>
1805             display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1806           # more...
1807         );
1808       }
1809
1810     } elsif ( $svcdb eq 'svc_dsl' ) {
1811
1812       $hash{'phonenum'} = $svc_x->phonenum;
1813       if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1814         $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1815         $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1816           if $svc_x->company;
1817       } else {
1818         $hash{'name'} = $cust_main->name;
1819       }
1820       # no usage to hide here
1821
1822     } elsif ( $svcdb eq 'svc_phone' ) {
1823       if (!$hide_usage) {
1824         # could potentially show lots of things...
1825         $hash{'outbound'} = 1;
1826         $hash{'inbound'}  = 0;
1827         if ( $part_pkg->plan eq 'voip_inbound' ) {
1828           $hash{'outbound'} = 0;
1829           $hash{'inbound'}  = 1;
1830         } elsif ( $part_pkg->option('selfservice_inbound_format')
1831               or  $conf->config('selfservice-default_inbound_cdr_format')
1832         ) {
1833           $hash{'inbound'}  = 1;
1834         }
1835         foreach (qw(inbound outbound)) {
1836           # hmm...we can't filter by status here, because there might
1837           # not be cdr_terminations at all.  have to go by date.
1838           # find all since the last bill date.
1839           # XXX cdr types?  we are going to need them.
1840           if ( $hash{$_} ) {
1841             my $sum_cdr = $svc_x->sum_cdrs(
1842               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1843               'begin'   => ($cust_pkg->last_bill || 0),
1844               'nonzero' => 1,
1845               'disable_charged_party' => 1,
1846             );
1847             $hash{$_} = $sum_cdr->hashref;
1848           }
1849         }
1850       } # not hiding usage
1851     } # svcdb
1852
1853     push @svcs, \%hash;
1854   } # foreach $cust_svc
1855
1856   return { 
1857     'svcnum'   => $session->{'svcnum'},
1858     'custnum'  => $custnum,
1859     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1860     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1861     'svcs'     => \@svcs,
1862     'usage_pools' => [
1863       map { $usage_pools{$_} }
1864       sort { $a cmp $b }
1865       keys %usage_pools
1866     ],
1867     'hide_usage' => $hide_usage,
1868   };
1869
1870 }
1871
1872 sub _customer_svc_x {
1873   my($custnum, $svcnum, $table) = (shift, shift, shift);
1874   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1875
1876   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1877   my $search = " AND custnum = $1";
1878   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1879
1880   qsearchs( {
1881     'table'     => ($table || 'svc_acct'),
1882     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1883                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1884                    #'LEFT JOIN cust_main USING ( custnum ) ',
1885     'hashref'   => $hashref,
1886     'extra_sql' => $search, #important
1887   } );
1888
1889 }
1890
1891 sub svc_status_html {
1892   my $p = shift;
1893
1894   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1895   return { 'error' => $session } if $context eq 'error';
1896
1897   #XXX only svc_dsl for now
1898   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1899     or return { 'error' => "Service not found" };
1900
1901   my $html = $svc_x->getstatus_html;
1902
1903   return { 'html' => $html };
1904
1905 }
1906
1907 sub svc_status_hash {
1908   my $p = shift;
1909
1910   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1911   return { 'error' => $session } if $context eq 'error';
1912
1913   #XXX only svc_acct for now
1914   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1915     or return { 'error' => "Service not found" };
1916
1917   my ( $html, $hashref ) = $svc_x->export_getstatus;
1918   return $hashref;
1919
1920 }
1921
1922 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
1923 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1924 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1925 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1926 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1927
1928 sub _svc_method_X {
1929   my( $p, $method ) = @_;
1930
1931   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1932   return { 'error' => $session } if $context eq 'error';
1933
1934   #XXX only svc_acct for now
1935   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1936     or return { 'error' => "Service not found" };
1937
1938   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1939     if $DEBUG;
1940   my $error = $svc_x->$method($p); #$p? returns error?
1941   return { 'error' => $error } if $error;
1942
1943   return {}; #? { 'error' => '' }
1944
1945 }
1946
1947 sub acct_forward_info {
1948   my $p = shift;
1949
1950   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1951   return { 'error' => $session } if $context eq 'error';
1952
1953   my $svc_forward = _customer_svc_x( $custnum,
1954                                      { 'srcsvc' => $p->{'svcnum'} },
1955                                      'svc_forward',
1956                                    )
1957     or return { 'error' => '',
1958                 'dst'   => '',
1959               };
1960
1961   return { 'error' => '',
1962            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1963          };
1964
1965 }
1966
1967 sub process_acct_forward {
1968   my $p = shift;
1969   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970   return { 'error' => $session } if $context eq 'error';
1971
1972   my $old = _customer_svc_x( $custnum,
1973                              { 'srcsvc' => $p->{'svcnum'} },
1974                              'svc_forward',
1975                            );
1976
1977   if ( $p->{'dst'} eq '' ) {
1978     if ( $old ) {
1979       my $error = $old->delete;
1980       return { 'error' => $error };
1981     }
1982     return { 'error' => '' };
1983   }
1984
1985   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1986                                   'dst'    => $p->{'dst'},
1987                                 };
1988
1989   my $error;
1990   if ( $old ) {
1991     $new->svcnum($old->svcnum);
1992     my $cust_svc = $old->cust_svc;
1993     $new->svcpart($old->svcpart);
1994     $new->pkgnuym($old->pkgnum);
1995     $error = $new->replace($old);
1996   } else {
1997     my $conf = new FS::Conf;
1998     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1999
2000     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2001       or return { 'error' => 'No service' }; #how would we even get here?
2002
2003     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2004
2005     $error = $new->insert;
2006   }
2007
2008   return { 'error' => $error };
2009
2010 }
2011
2012 sub list_dsl_devices {
2013   my $p = shift;
2014
2015   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2016   return { 'error' => $session } if $context eq 'error';
2017
2018   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2019     or return { 'error' => "Service not found" };
2020
2021   return {
2022     'devices' => [ map {
2023                          +{ 'mac_addr' => $_->mac_addr };
2024                        } $svc_dsl->dsl_device
2025                  ],
2026   };
2027
2028 }
2029
2030 sub add_dsl_device {
2031   my $p = shift;
2032
2033   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2034   return { 'error' => $session } if $context eq 'error';
2035
2036   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2037     or return { 'error' => "Service not found" };
2038
2039   return { 'error' => 'No MAC address supplied' }
2040     unless length($p->{'mac_addr'});
2041
2042   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2043                                         'mac_addr' => scalar($p->{'mac_addr'}),
2044                                       };
2045   my $error = $dsl_device->insert;
2046   return { 'error' => $error };
2047
2048 }
2049
2050 sub delete_dsl_device {
2051   my $p = shift;
2052
2053   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2054   return { 'error' => $session } if $context eq 'error';
2055
2056   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2057     or return { 'error' => "Service not found" };
2058
2059   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2060                                             'mac_addr' => scalar($p->{'mac_addr'}),
2061                                           }
2062                            )
2063     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2064
2065   my $error = $dsl_device->delete;
2066   return { 'error' => $error };
2067
2068 }
2069
2070 sub port_graph {
2071   my $p = shift;
2072   _usage_details( \&_port_graph, $p,
2073                   'svcdb' => 'svc_port',
2074                 );
2075 }
2076
2077 sub _port_graph {
2078   my($svc_port, $begin, $end) = @_;
2079   my @usage = ();
2080   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2081   push @usage, { 'png' => $pngOrError };
2082   (@usage);
2083 }
2084
2085 sub _list_svc_usage {
2086   my($svc_acct, $begin, $end) = @_;
2087   my @usage = ();
2088   foreach my $part_export ( 
2089     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2090     qw( sqlradius sqlradius_withdomain )
2091   ) {
2092     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2093   }
2094   (@usage);
2095 }
2096
2097 sub list_svc_usage {
2098   _usage_details(\&_list_svc_usage, @_);
2099 }
2100
2101 sub _list_support_usage {
2102   my($svc_acct, $begin, $end) = @_;
2103   my @usage = ();
2104   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2105             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2106           ) {
2107     push @usage, { 'seconds'  => $_->seconds,
2108                    'support'  => $_->support,
2109                    '_date'    => $_->_date,
2110                    'id'       => $_->transaction_id,
2111                    'creator'  => $_->creator,
2112                    'subject'  => $_->subject,
2113                    'status'   => $_->status,
2114                    'ticketid' => $_->ticketid,
2115                  };
2116   }
2117   (@usage);
2118 }
2119
2120 sub list_support_usage {
2121   _usage_details(\&_list_support_usage, @_);
2122 }
2123
2124 sub _list_cdr_usage {
2125   # XXX CDR type support...
2126   # XXX any way to do a paged search on this?
2127   # we have to return the results all at once...
2128   my($svc_phone, $begin, $end, %opt) = @_;
2129   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2130     $svc_phone->get_cdrs(
2131       'begin'=>$begin,
2132       'end'=>$end,
2133       'disable_charged_party' => 1,
2134       %opt
2135     );
2136 }
2137
2138 sub list_cdr_usage {
2139   my $p = shift;
2140   _usage_details( \&_list_cdr_usage, $p,
2141                   'svcdb' => 'svc_phone',
2142                 );
2143 }
2144
2145 sub _usage_details {
2146   my($callback, $p, %opt) = @_;
2147   my $conf = FS::Conf->new;
2148
2149   if ( $conf->exists('selfservice_hide-usage') ) {
2150     return { 'error' => 'Viewing usage is not allowed.' };
2151   }
2152
2153   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2154   return { 'error' => $session } if $context eq 'error';
2155
2156   my $search = { 'svcnum' => $p->{'svcnum'} };
2157   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2158
2159   my $svcdb = $opt{'svcdb'} || 'svc_acct';
2160
2161   my $svc_x = qsearchs( $svcdb, $search );
2162   return { 'error' => 'No service selected in list_svc_usage' } 
2163     unless $svc_x;
2164
2165   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2166   my $freq     = $cust_pkg->part_pkg->freq;
2167   my %callback_opt;
2168   my $header = [];
2169   if ( $svcdb eq 'svc_phone' ) {
2170     my $format = '';
2171     if ( $p->{inbound} ) {
2172       $format = $cust_pkg->part_pkg->option('selfservice_inbound_format') 
2173                 || $conf->config('selfservice-default_inbound_cdr_format')
2174                 || 'source_default';
2175       $callback_opt{inbound} = 1;
2176     } else {
2177       $format = $cust_pkg->part_pkg->option('selfservice_format')
2178                 || $conf->config('selfservice-default_cdr_format')
2179                 || 'default';
2180     }
2181
2182     $callback_opt{format} = $format;
2183     $callback_opt{use_clid} = 1;
2184     $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2185   }
2186
2187   my $start    = $cust_pkg->setup;
2188   #my $end      = $cust_pkg->bill; # or time?
2189   my $end      = time;
2190
2191   unless ( $p->{beginning} ) {
2192     $p->{beginning} = $cust_pkg->last_bill;
2193     $p->{ending}    = $end;
2194   }
2195
2196   die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2197   die "illegal ending"    if $p->{ending}    !~ /^\d*$/;
2198
2199   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending}, 
2200     %callback_opt
2201   );
2202
2203   if ( $conf->exists('selfservice-hide_cdr_price') ) {
2204     # ugly kludge, I know
2205     my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2206     if (defined $delete_col) {
2207       delete($_->[$delete_col]) foreach ($header, @usage);
2208     }
2209   }
2210
2211   #kinda false laziness with FS::cust_main::bill, but perhaps
2212   #we should really change this bit to DateTime and DateTime::Duration
2213   #
2214   #change this bit to use Date::Manip? CAREFUL with timezones (see
2215   # mailing list archive)
2216   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2217     (localtime($p->{ending}) )[0,1,2,3,4,5];
2218   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2219     (localtime($p->{beginning}) )[0,1,2,3,4,5];
2220
2221   if ( $freq =~ /^\d+$/ ) {
2222     $nmon += $freq;
2223     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2224     $pmon -= $freq;
2225     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2226   } elsif ( $freq =~ /^(\d+)w$/ ) {
2227     my $weeks = $1;
2228     $nmday += $weeks * 7;
2229     $pmday -= $weeks * 7;
2230   } elsif ( $freq =~ /^(\d+)d$/ ) {
2231     my $days = $1;
2232     $nmday += $days;
2233     $pmday -= $days;
2234   } elsif ( $freq =~ /^(\d+)h$/ ) {
2235     my $hours = $1;
2236     $nhour += $hours;
2237     $phour -= $hours;
2238   } else {
2239     return { 'error' => "unparsable frequency: ". $freq };
2240   }
2241   
2242   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2243   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2244
2245   { 
2246     'error'     => '',
2247     'svcnum'    => $p->{svcnum},
2248     'beginning' => $p->{beginning},
2249     'ending'    => $p->{ending},
2250     'inbound'   => $p->{inbound},
2251     'previous'  => ($previous > $start) ? $previous : $start,
2252     'next'      => ($next < $end) ? $next : $end,
2253     'header'    => $header,
2254     'usage'     => \@usage,
2255   };
2256 }
2257
2258 sub order_pkg {
2259   my $p = shift;
2260
2261   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2262   return { 'error' => $session } if $context eq 'error';
2263
2264   my $search = { 'custnum' => $custnum };
2265   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2266   my $cust_main = qsearchs('cust_main', $search )
2267     or return { 'error' => "unknown custnum $custnum" };
2268
2269   my $status = $cust_main->status;
2270   #false laziness w/ClientAPI/Signup.pm
2271
2272   my $cust_pkg = new FS::cust_pkg ( {
2273     'custnum' => $custnum,
2274     'pkgpart' => $p->{'pkgpart'},
2275   } );
2276   my $error = $cust_pkg->check;
2277   return { 'error' => $error } if $error;
2278
2279   my @svc = ();
2280   unless ( $p->{'svcpart'} eq 'none' ) {
2281
2282     my $svcdb;
2283     my $svcpart = '';
2284     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2285       $svcpart = $1;
2286       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2287       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2288       $svcdb = $part_svc->svcdb;
2289     } else {
2290       $svcdb = 'svc_acct';
2291     }
2292     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2293
2294     my %fields = (
2295       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2296       'svc_domain'   => [ qw( domain ) ],
2297       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2298       'svc_external' => [ qw( id title ) ],
2299       'svc_pbx'      => [ qw( id title ) ],
2300     );
2301   
2302     my $svc_x = "FS::$svcdb"->new( {
2303       'svcpart'   => $svcpart,
2304       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2305     } );
2306     
2307     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2308       my @acct_snarf;
2309       my $snarfnum = 1;
2310       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2311         my $acct_snarf = new FS::acct_snarf ( {
2312           'machine'   => $p->{"snarf_machine$snarfnum"},
2313           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2314           'username'  => $p->{"snarf_username$snarfnum"},
2315           '_password' => $p->{"snarf_password$snarfnum"},
2316         } );
2317         $snarfnum++;
2318         push @acct_snarf, $acct_snarf;
2319       }
2320       $svc_x->child_objects( \@acct_snarf );
2321     }
2322     
2323     my $y = $svc_x->setdefault; # arguably should be in new method
2324     return { 'error' => $y } if $y && !ref($y);
2325   
2326     $error = $svc_x->check;
2327     return { 'error' => $error } if $error;
2328
2329     push @svc, $svc_x;
2330
2331   }
2332
2333   use Tie::RefHash;
2334   tie my %hash, 'Tie::RefHash';
2335   %hash = ( $cust_pkg => \@svc );
2336   #msgcat
2337   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2338   return { 'error' => $error } if $error;
2339
2340   my $conf = new FS::Conf;
2341   if ( $conf->exists('signup_server-realtime') ) {
2342
2343     my $bill_error = _do_bop_realtime( $cust_main, $status );
2344
2345     if ($bill_error) {
2346       $cust_pkg->cancel('quiet'=>1);
2347       return $bill_error;
2348     } else {
2349       $cust_pkg->reexport;
2350     }
2351
2352   } else {
2353     $cust_pkg->reexport;
2354   }
2355
2356   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2357
2358   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2359
2360 }
2361
2362 sub change_pkg {
2363   my $p = shift;
2364
2365   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2366   return { 'error' => $session } if $context eq 'error';
2367
2368   my $conf = new FS::Conf;
2369   my $immutable = $conf->exists('selfservice_immutable-package');
2370   return { 'error' => "Package modification disabled" } if $immutable;
2371
2372   my $search = { 'custnum' => $custnum };
2373   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2374   my $cust_main = qsearchs('cust_main', $search )
2375     or return { 'error' => "unknown custnum $custnum" };
2376
2377   my $status = $cust_main->status;
2378   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2379     or return { 'error' => "unknown package $p->{pkgnum}" };
2380
2381   #if someone does need self-service package change of suspended packages,
2382   # figure out how to be more discriminating
2383   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2384     if $cust_pkg->status eq 'suspended';
2385
2386   my @newpkg;
2387   my $error = FS::cust_pkg::order( $custnum,
2388                                    [$p->{pkgpart}],
2389                                    [$p->{pkgnum}],
2390                                    \@newpkg,
2391                                  );
2392
2393   if ( $conf->exists('signup_server-realtime') ) {
2394
2395     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2396
2397     if ($bill_error) {
2398       $newpkg[0]->suspend;
2399       return $bill_error;
2400     } else {
2401       $newpkg[0]->reexport;
2402     }
2403
2404   } else {  
2405     $newpkg[0]->reexport;
2406   }
2407
2408   return { error => '', pkgnum => $cust_pkg->pkgnum };
2409
2410 }
2411
2412 sub order_recharge {
2413   my $p = shift;
2414
2415   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2416   return { 'error' => $session } if $context eq 'error';
2417
2418   my $search = { 'custnum' => $custnum };
2419   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2420   my $cust_main = qsearchs('cust_main', $search )
2421     or return { 'error' => "unknown custnum $custnum" };
2422
2423   my $status = $cust_main->status;
2424   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2425     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2426
2427   my $svc_x = $cust_svc->svc_x;
2428   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2429
2430   my %vhash =
2431     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2432     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2433          recharge_totalbytes );
2434   my $amount = $part_pkg->option('recharge_amount', 1); 
2435   
2436   my ($l, $v, $d) = $cust_svc->label;  # blah
2437   my $pkg = "Recharge $v"; 
2438
2439   my $bill_error = $cust_main->charge($amount, $pkg,
2440      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2441      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2442      $part_pkg->taxclass); #meh
2443
2444   my $conf = new FS::Conf;
2445   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2446
2447     $bill_error = _do_bop_realtime( $cust_main, $status );
2448
2449     if ($bill_error) {
2450       return $bill_error;
2451     } else {
2452       my $error = $svc_x->recharge (\%vhash);
2453       return { 'error' => $error } if $error;
2454     }
2455
2456   } else {  
2457     my $error = $bill_error;
2458     $error ||= $svc_x->recharge (\%vhash);
2459     return { 'error' => $error } if $error;
2460   }
2461
2462   return { error => '', svc => $cust_svc->part_svc->svc };
2463
2464 }
2465
2466 sub _do_bop_realtime {
2467   my ($cust_main, $status, %opt) = @_;
2468
2469     my $old_balance = $cust_main->balance;
2470
2471     my $bill_error =    $cust_main->bill
2472                      || $cust_main->apply_payments_and_credits;
2473
2474     $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2475       if $cust_main->payby =~ /^(CARD|CHEK)$/;
2476
2477     if (    $cust_main->balance > $old_balance
2478          && $cust_main->balance > 0
2479          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2480                 || $status eq 'suspended'
2481             )
2482        )
2483     {
2484       unless ( $opt{'no_credit'} ) {
2485         #this makes sense.  credit is "un-doing" the invoice
2486         my $conf = new FS::Conf;
2487         $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2488                             'self-service decline',
2489                             reason_type=>$conf->config('signup_credit_type'),
2490                           );
2491         $cust_main->apply_credits( 'order' => 'newest' );
2492       }
2493
2494       return { 'error' => '_decline', 'bill_error' => $bill_error };
2495     }
2496
2497     '';
2498 }
2499
2500 sub renew_info {
2501   my $p = shift;
2502
2503   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2504   return { 'error' => $session } if $context eq 'error';
2505
2506   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2507     or return { 'error' => "unknown custnum $custnum" };
2508
2509   my @cust_pkg = sort { $a->bill <=> $b->bill }
2510                  grep { $_->part_pkg->freq ne '0' }
2511                  $cust_main->ncancelled_pkgs;
2512
2513   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2514
2515   my $total = $cust_main->balance;
2516
2517   my @array = map {
2518                     my $bill = $_->bill;
2519                     $total += $_->part_pkg->base_recur($_, \$bill);
2520                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2521                     {
2522                       'pkgnum'             => $_->pkgnum,
2523                       'amount'             => sprintf('%.2f', $total),
2524                       'bill_date'          => $_->bill,
2525                       'bill_date_pretty'   => time2str('%x', $_->bill),
2526                       'renew_date'         => $renew_date,
2527                       'renew_date_pretty'  => time2str('%x', $renew_date),
2528                       'expire_date'        => $_->expire,
2529                       'expire_date_pretty' => time2str('%x', $_->expire),
2530                     };
2531                   }
2532                   @cust_pkg;
2533
2534   return { 'dates' => \@array };
2535
2536 }
2537
2538 sub payment_info_renew_info {
2539   my $p = shift;
2540   my $renew_info   = renew_info($p);
2541   my $payment_info = payment_info($p);
2542   return { %$renew_info,
2543            %$payment_info,
2544          };
2545 }
2546
2547 sub order_renew {
2548   my $p = shift;
2549
2550   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2551   return { 'error' => $session } if $context eq 'error';
2552
2553   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2554     or return { 'error' => "unknown custnum $custnum" };
2555
2556   my $date = $p->{'date'};
2557
2558   my $now = time;
2559
2560   #freeside-daily -n -d $date fs_daily $custnum
2561   $cust_main->bill_and_collect( 'time'         => $date,
2562                                 'invoice_time' => $now,
2563                                 'actual_time'  => $now,
2564                                 'check_freq'   => '1d',
2565                               );
2566
2567   return { 'error' => '' };
2568
2569 }
2570
2571 sub suspend_pkg {
2572   my $p = shift;
2573   my $session = _cache->get($p->{'session_id'})
2574     or return { 'error' => "Can't resume session" }; #better error message
2575
2576   my $custnum = $session->{'custnum'};
2577
2578   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2579     or return { 'error' => "unknown custnum $custnum" };
2580
2581   my $conf = new FS::Conf;
2582   my $reasonnum = 
2583     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2584       or return { 'error' => 'Permission denied' };
2585
2586   my $pkgnum = $p->{'pkgnum'};
2587
2588   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2589                                         'pkgnum'  => $pkgnum,   } )
2590     or return { 'error' => "unknown pkgnum $pkgnum" };
2591
2592   my $error = $cust_pkg->suspend(reason => $reasonnum);
2593   return { 'error' => $error };
2594
2595 }
2596
2597 sub cancel_pkg {
2598   my $p = shift;
2599   my $session = _cache->get($p->{'session_id'})
2600     or return { 'error' => "Can't resume session" }; #better error message
2601
2602   my $custnum = $session->{'custnum'};
2603
2604   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2605     or return { 'error' => "unknown custnum $custnum" };
2606
2607   my $pkgnum = $p->{'pkgnum'};
2608
2609   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2610                                         'pkgnum'  => $pkgnum,   } )
2611     or return { 'error' => "unknown pkgnum $pkgnum" };
2612
2613   my $error = $cust_pkg->cancel('quiet' => 1);
2614   return { 'error' => $error };
2615
2616 }
2617
2618 sub provision_phone {
2619  my $p = shift;
2620  my @bulkdid;
2621  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2622
2623  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2624       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2625       return { 'error' => $session } if $context eq 'error';
2626     
2627       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2628       return { 'error' => 'service not found' } unless $svc_phone;
2629       return { 'error' => 'invalid svcnum' } 
2630         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2631
2632       $svc_phone->email($p->{'email'}) 
2633         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2634       $svc_phone->forwarddst($p->{'forwarddst'}) 
2635         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2636             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2637       return { 'error' => $svc_phone->replace };
2638  }
2639
2640 # single DID LNP
2641  unless($p->{'lnp'}) {
2642     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2643     $p->{'lnp_status'} = "portingin";
2644     return _provision( 'FS::svc_phone',
2645                   [qw(lnp_desired_due_date lnp_other_provider 
2646                     lnp_other_provider_account phonenum countrycode lnp_status)],
2647                   [qw(phonenum countrycode)],
2648                   $p,
2649                   @_
2650                 );
2651  }
2652
2653 # single DID order
2654  unless (scalar(@bulkdid)) {
2655     return _provision( 'FS::svc_phone',
2656                   [qw(phonenum countrycode)],
2657                   [qw(phonenum countrycode)],
2658                   $p,
2659                   @_
2660                 );
2661  }
2662
2663 # bulk DID order case
2664   my $error;
2665   foreach my $did ( @bulkdid ) {
2666     $did =~ s/[^0-9]//g;
2667     $error = _provision( 'FS::svc_phone',
2668               [qw(phonenum countrycode)],
2669               [qw(phonenum countrycode)],
2670               {
2671                 'pkgnum' => $p->{'pkgnum'},
2672                 'svcpart' => $p->{'svcpart'},
2673                 'phonenum' => $did,
2674                 'countrycode' => $p->{'countrycode'},
2675                 'session_id' => $p->{'session_id'},
2676               }
2677             );
2678     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2679   }
2680   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2681 }
2682
2683 sub provision_acct {
2684   my $p = shift;
2685   warn "provision_acct called\n"
2686     if $DEBUG;
2687
2688   return { 'error' => gettext('passwords_dont_match') }
2689     if $p->{'_password'} ne $p->{'_password2'};
2690   return { 'error' => gettext('empty_password') }
2691     unless length($p->{'_password'});
2692  
2693   if ($p->{'domsvc'}) {
2694     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2695                                                   qw ( svcpart pkgnum ) );
2696     return { 'error' => gettext('invalid_domain') }
2697       unless ($domains{$p->{'domsvc'}});
2698   }
2699
2700   warn "provision_acct calling _provision\n"
2701     if $DEBUG;
2702   _provision( 'FS::svc_acct',
2703               [qw(username _password domsvc)],
2704               [qw(username _password domsvc)],
2705               $p,
2706               @_
2707             );
2708 }
2709
2710 sub provision_external {
2711   my $p = shift;
2712   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2713   _provision( 'FS::svc_external',
2714               [],
2715               [qw(id title)],
2716               $p,
2717               @_
2718             );
2719 }
2720
2721 sub _provision {
2722   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2723   warn "_provision called for $class\n"
2724     if $DEBUG;
2725
2726   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2727   return { 'error' => $session } if $context eq 'error';
2728
2729   my $search = { 'custnum' => $custnum };
2730   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2731   my $cust_main = qsearchs('cust_main', $search )
2732     or return { 'error' => "unknown custnum $custnum" };
2733
2734   my $pkgnum = $p->{'pkgnum'};
2735
2736   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2737     if $DEBUG;
2738   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2739                                         'pkgnum'  => $pkgnum,
2740                                                                } )
2741     or return { 'error' => "unknown pkgnum $pkgnum" };
2742
2743   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2744     if $DEBUG;
2745   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2746     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2747
2748   warn "creating $class record\n"
2749     if $DEBUG;
2750   my $svc_x = $class->new( {
2751     'pkgnum'  => $p->{'pkgnum'},
2752     'svcpart' => $p->{'svcpart'},
2753     map { $_ => $p->{$_} } @$fields
2754   } );
2755   warn "inserting $class record\n"
2756     if $DEBUG;
2757   my $error = $svc_x->insert;
2758
2759   unless ( $error ) {
2760     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2761       if $DEBUG;
2762     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2763   }
2764
2765   my $return = { 'svc'   => $part_svc->svc,
2766                  'error' => $error,
2767                  map { $_ => $svc_x->get($_) } @$return_fields
2768                };
2769   warn "_provision returning ". Dumper($return). "\n"
2770     if $DEBUG;
2771   return $return;
2772
2773 }
2774
2775 sub part_svc_info {
2776   my $p = shift;
2777
2778   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2779   return { 'error' => $session } if $context eq 'error';
2780
2781   my $search = { 'custnum' => $custnum };
2782   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2783   my $cust_main = qsearchs('cust_main', $search )
2784     or return { 'error' => "unknown custnum $custnum" };
2785
2786   my $pkgnum = $p->{'pkgnum'};
2787
2788   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2789                                         'pkgnum'  => $pkgnum,
2790                                                                } )
2791     or return { 'error' => "unknown pkgnum $pkgnum" };
2792
2793   my $svcpart = $p->{'svcpart'};
2794
2795   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2796                                       'svcpart' => $svcpart,           } )
2797     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2798   my $part_svc = $pkg_svc->part_svc;
2799
2800   my $conf = new FS::Conf;
2801
2802   my $ret = {
2803     'svc'     => $part_svc->svc,
2804     'svcdb'   => $part_svc->svcdb,
2805     'pkgnum'  => $pkgnum,
2806     'svcpart' => $svcpart,
2807     'custnum' => $custnum,
2808
2809     'security_phrase' => 0, #XXX !
2810     'svc_acct_pop'    => [], #XXX !
2811     'popnum'          => '',
2812     'init_popstate'   => '',
2813     'popac'           => '',
2814     'acstate'         => '',
2815
2816     'small_custview' =>
2817       small_custview( $cust_main, $conf->config('countrydefault') ),
2818
2819   };
2820
2821   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2822                      && $ret->{'svcdb'} eq 'svc_phone') {
2823         $ret->{'svcnum'} = $p->{'svcnum'};
2824         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2825         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2826             $ret->{'email'} = $svc_phone->email;
2827             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2828         }
2829   }
2830
2831   $ret;
2832 }
2833
2834 sub unprovision_svc {
2835   my $p = shift;
2836
2837   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2838   return { 'error' => $session } if $context eq 'error';
2839
2840   my $search = { 'custnum' => $custnum };
2841   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2842   my $cust_main = qsearchs('cust_main', $search )
2843     or return { 'error' => "unknown custnum $custnum" };
2844
2845   my $svcnum = $p->{'svcnum'};
2846
2847   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2848     or return { 'error' => "unknown svcnum $svcnum" };
2849
2850   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2851     unless $cust_svc->cust_pkg->custnum == $custnum;
2852
2853   my $conf = new FS::Conf;
2854
2855   return { 'svc'   => $cust_svc->part_svc->svc,
2856            'error' => $cust_svc->cancel,
2857            'small_custview' =>
2858              small_custview( $cust_main, $conf->config('countrydefault') ),
2859          };
2860
2861 }
2862
2863 sub myaccount_passwd {
2864   my $p = shift;
2865   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2866   return { 'error' => $session } if $context eq 'error';
2867
2868   return { 'error' => "New passwords don't match." }
2869     if $p->{'new_password'} ne $p->{'new_password2'};
2870
2871   return { 'error' => 'Enter new password' }
2872     unless length($p->{'new_password'});
2873
2874   #my $search = { 'custnum' => $custnum };
2875   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2876   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2877   my $search = " AND custnum = $1";
2878   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2879
2880   my $svc_acct = qsearchs( {
2881     'table'     => 'svc_acct',
2882     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2883                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2884                    'LEFT JOIN cust_main USING ( custnum ) ',
2885     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2886     'extra_sql' => $search, #important
2887   } )
2888     or return { 'error' => "Service not found" };
2889
2890   my $error = '';
2891
2892   my $conf = new FS::Conf;
2893
2894   return { 'error' => 'Incorrect current password.' }
2895     if  ( exists($p->{'old_password'})
2896           || $conf->exists('selfservice-password_change_oldpass')
2897         )
2898     && ! $svc_acct->check_password($p->{'old_password'});
2899
2900   $error = 'Password too short.'
2901     if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2902   $error = 'Password too long.'
2903     if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2904
2905   $svc_acct->set_password($p->{'new_password'});
2906   $error ||= $svc_acct->replace();
2907
2908   #regular pw change in self-service should change contact pw too, otherwise its
2909   #way too confusing.  hell its confusing they're separate at all, but alas.
2910   #need to support the "ISP provides email that's used as a contact email" case
2911   #as well as we can.
2912   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2913   if ( $contact && $contact->custnum == $custnum ) {
2914     #svc_acct was successful but this one returns an error?  "shouldn't happen"
2915     $error ||= $contact->change_password($p->{'new_password'});
2916   }
2917
2918   my($label, $value) = $svc_acct->cust_svc->label;
2919
2920   return { 'error' => $error,
2921            'label' => $label,
2922            'value' => $value,
2923          };
2924
2925 }
2926
2927 #  sub contact_passwd {
2928 #    my $p = shift;
2929 #    my($context, $session, $custnum) = _custoragent_session_custnum($p);
2930 #    return { 'error' => $session } if $context eq 'error';
2931 #  
2932 #    return { 'error' => 'Not logged in as a contact.' }
2933 #      unless $session->{'contactnum'};
2934 #  
2935 #    return { 'error' => "New passwords don't match." }
2936 #      if $p->{'new_password'} ne $p->{'new_password2'};
2937 #  
2938 #    return { 'error' => 'Enter new password' }
2939 #      unless length($p->{'new_password'});
2940 #  
2941 #    #my $search = { 'custnum' => $custnum };
2942 #    #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2943 #    $custnum =~ /^(\d+)$/ or die "illegal custnum";
2944 #    my $search = " AND selfservice_access IS NOT NULL ".
2945 #                 " AND selfservice_access = 'Y' ".
2946 #                 " AND ( disabled IS NULL OR disabled = '' )".
2947 #                 " AND custnum IS NOT NULL AND custnum = $1";
2948 #    $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2949 #  
2950 #    my $contact = qsearchs( {
2951 #      'table'     => 'contact',
2952 #      'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2953 #      'hashref'   => { 'contactnum' => $session->{'contactnum'}, },
2954 #      'extra_sql' => $search, #important
2955 #    } )
2956 #      or return { 'error' => "Email not found" }; #?  how did we get logged in?
2957 #                                                  # deleted since then?
2958 #  
2959 #    my $error = '';
2960 #  
2961 #    # use these svc_acct length restrictions??
2962 #    my $conf = new FS::Conf;
2963 #    $error = 'Password too short.'
2964 #      if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2965 #    $error = 'Password too long.'
2966 #      if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2967 #  
2968 #    $error ||= $contact->change_password($p->{'new_password'});
2969 #  
2970 #    return { 'error' => $error, };
2971 #  
2972 #  }
2973
2974 sub reset_passwd {
2975   my $p = shift;
2976
2977   my $info = skin_info($p);
2978
2979   my $conf = new FS::Conf;
2980   my $verification = $conf->config('selfservice-password_reset_verification')
2981     or return { %$info, 'error' => 'Password resets disabled' };
2982
2983   my $contact = '';
2984   my $svc_acct = '';
2985   my $cust_main = '';
2986   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2987   
2988     $contact = FS::contact->by_selfservice_email($p->{'email'});
2989
2990     $cust_main = $contact->cust_main if $contact;
2991
2992     #also look for an svc_acct, otherwise it would be super confusing
2993
2994     my($username, $domain) = split('@', $p->{'email'});
2995     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2996     if ( $svc_domain ) {
2997       $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2998                                          'domsvc'   => $svc_domain->svcnum  }
2999                           );
3000       if ( $svc_acct ) {
3001         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3002         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3003
3004         #precaution: don't change svc_acct password not part of the same
3005         # customer as contact
3006         $svc_acct = '' if ! $cust_pkg
3007                        || $cust_pkg->custnum != $cust_main->custnum;
3008       }
3009       
3010     }
3011
3012     return { %$info, 'error' => 'Email address not found' }
3013       unless $contact || $svc_acct;
3014
3015   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3016
3017     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3018       or return { %$info, 'error' => 'Account not found' };
3019
3020     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3021                                        'domsvc'   => $svc_domain->svcnum  }
3022                         )
3023       or return { %$info, 'error' => 'Account not found' };
3024
3025     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3026       or return { %$info, 'error' => 'Account not found' };
3027
3028     $cust_main = $cust_pkg->cust_main;
3029
3030   }
3031
3032   my %verify = (
3033     'email'   => sub { 1; },
3034     'paymask' => sub { 
3035       my( $p, $cust_main ) = @_;
3036       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3037         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3038     },
3039     'amount'  => sub {
3040       my( $p, $cust_main ) = @_;
3041       my $cust_pay = qsearchs({
3042         'table' => 'cust_pay',
3043         'hashref' => { 'custnum' => $cust_main->custnum },
3044         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3045       })
3046         or return 0;
3047
3048       $p->{'amount'} == $cust_pay->paid;
3049     },
3050     'zip'     => sub {
3051       my( $p, $cust_main ) = @_;
3052       $p->{'zip'} eq $cust_main->zip
3053         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3054     },
3055   );
3056
3057   foreach my $verify ( split(',', $verification) ) {
3058
3059     &{ $verify{$verify} }( $p, $cust_main )
3060       or return { %$info, 'error' => 'Account not found' };
3061
3062   }
3063
3064   #okay, we're verified
3065
3066   if ( $contact ) {
3067
3068     my $error = $contact->send_reset_email(
3069                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3070                           );
3071
3072     if ( $error ) {
3073       return { %$info, 'error' => $error }; #????
3074     }
3075
3076   } elsif ( $svc_acct ) {
3077
3078     #create a unique session
3079
3080     my $reset_session = {
3081       'svcnum'   => $svc_acct->svcnum,
3082       'agentnum' =>
3083     };
3084
3085     my $timeout = '1 hour'; #?
3086
3087     my $reset_session_id;
3088     do {
3089       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3090     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3091       #just in case
3092
3093     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3094
3095     #email it
3096
3097     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3098                                $cust_main->agentnum);
3099     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3100     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3101       unless $msgnum;
3102     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3103     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3104                                      'object'        => $svc_acct,
3105                                      'substitutions' => {
3106                                        'session_id' => $reset_session_id,
3107                                      }
3108                                    );
3109     if ( $error ) {
3110       return { %$info, 'error' => $error }; #????
3111     }
3112
3113   }
3114
3115   return { %$info, 'error' => '' };
3116 }
3117
3118 sub check_reset_passwd {
3119   my $p = shift;
3120
3121   my $conf = new FS::Conf;
3122   my $verification = $conf->config('selfservice-password_reset_verification')
3123     or return { 'error' => 'Password resets disabled' };
3124
3125   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3126     or return { 'error' => "Can't resume session" }; #better error message
3127
3128   if ( $reset_session->{'svcnum'} ) {
3129
3130     my $svcnum = $reset_session->{'svcnum'};
3131
3132     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3133       or return { 'error' => "Service not found" };
3134
3135     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3136     my $info = skin_info($p);
3137
3138     return { %$info,
3139              'error'      => '',
3140              'session_id' => $p->{'session_id'},
3141              'username'   => $svc_acct->username,
3142            };
3143
3144   } elsif ( $reset_session->{'contactnum'} ) {
3145
3146     my $contactnum = $reset_session->{'contactnum'};
3147
3148     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3149       or return { 'error' => "Contact not found" };
3150
3151     my @contact_email = $contact->contact_email;
3152     return { 'error' => 'No contact email' } unless @contact_email;
3153
3154     $p->{'agentnum'} = $contact->cust_main->agentnum;
3155     my $info = skin_info($p);
3156
3157     return { %$info,
3158              'error'      => '',
3159              'session_id' => $p->{'session_id'},
3160              'email'      => $contact_email[0]->email, #the first?
3161            };
3162
3163   } else {
3164
3165     return { 'error' => 'No svcnum or contactnum in session' }; #??
3166
3167   }
3168
3169 }
3170
3171 sub process_reset_passwd {
3172   my $p = shift;
3173
3174   my $conf = new FS::Conf;
3175   my $verification = $conf->config('selfservice-password_reset_verification')
3176     or return { 'error' => 'Password resets disabled' };
3177
3178   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3179     or return { 'error' => "Can't resume session" }; #better error message
3180
3181   my $info = '';
3182
3183   my $svc_acct = '';
3184   if ( $reset_session->{'svcnum'} ) {
3185
3186     my $svcnum = $reset_session->{'svcnum'};
3187
3188     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3189       or return { 'error' => "Service not found" };
3190
3191     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3192     $info ||= skin_info($p);
3193
3194   }
3195
3196   my $contact = '';
3197   if ( $reset_session->{'contactnum'} ) {
3198
3199     my $contactnum = $reset_session->{'contactnum'};
3200
3201     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3202       or return { 'error' => "Contact not found" };
3203
3204     $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3205     $info ||= skin_info($p);
3206
3207   }
3208
3209   return { %$info, 'error' => "New passwords don't match." }
3210     if $p->{'new_password'} ne $p->{'new_password2'};
3211
3212   return { %$info, 'error' => 'Enter new password' }
3213     unless length($p->{'new_password'});
3214
3215   if ( $svc_acct ) {
3216
3217     $svc_acct->set_password($p->{'new_password'});
3218     my $error = $svc_acct->replace();
3219
3220     return { %$info, 'error' => $error } if $error;
3221
3222     #my($label, $value) = $svc_acct->cust_svc->label;
3223     #return { 'error' => $error,
3224     #         #'label' => $label,
3225     #         #'value' => $value,
3226     #       };
3227
3228   }
3229
3230   if ( $contact ) {
3231
3232     my $error = $contact->change_password($p->{'new_password'});
3233
3234     return { %$info, 'error' => $error }; # if $error;
3235
3236   }
3237
3238   #password changed ,so remove session, don't want it reused
3239   _cache->remove($p->{'session_id'});
3240
3241   return { %$info, 'error' => '' };
3242
3243 }
3244
3245 sub list_tickets {
3246   my $p = shift;
3247   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3248   return { 'error' => $session } if $context eq 'error';
3249
3250   my @tickets = ();
3251   if ( $session->{'pkgnum'} ) { 
3252
3253     #tickets for specific service with pkg-balances on
3254     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3255                                           'pkgnum'  => $session->{'pkgnum'} })
3256                      or return { 'error' => 'unknown package' };
3257     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3258       push @tickets, $cust_svc->tickets( $p->{status} );
3259     }
3260
3261   } else {
3262
3263     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3264       or return { 'error' => "unknown custnum $custnum" };
3265
3266     @tickets = $cust_main->tickets( $p->{status} );
3267   }
3268
3269   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3270   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3271     my $conf = new FS::Conf;
3272     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3273     +{ tickets => [ 
3274          sort { 
3275            (
3276              ($a->{'_selfservice_priority'} eq '') <=>
3277              ($b->{'_selfservice_priority'} eq '')
3278            ) ||
3279            ( $dir * 
3280              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3281            )
3282          } @tickets
3283        ]
3284     };
3285   } else {
3286     +{ tickets => \@tickets };
3287   }
3288
3289 }
3290
3291 sub create_ticket {
3292   my $p = shift;
3293   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3294   return { 'error' => $session } if $context eq 'error';
3295
3296   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3297   FS::TicketSystem->init();
3298
3299   my $conf = new FS::Conf;
3300   my $queue = $p->{'queue'}
3301               || $conf->config('ticket_system-selfservice_queueid')
3302               || $conf->config('ticket_system-default_queueid');
3303
3304   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3305   my $err_or_ticket = FS::TicketSystem->create_ticket(
3306     '', #create RT session based on FS CurrentUser (fs_selfservice)
3307     'queue'   => $queue,
3308     'custnum' => $custnum,
3309     'svcnum'  => $session->{'svcnum'},
3310     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3311   );
3312
3313   if ( ref($err_or_ticket) ) {
3314     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3315       if $DEBUG;
3316     return { 'error'     => '',
3317              'ticket_id' => $err_or_ticket->id,
3318            };
3319   } else {
3320     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3321       if $DEBUG;
3322     return { 'error' => $err_or_ticket };
3323   }
3324
3325
3326 }
3327
3328 sub did_report {
3329   my $p = shift;
3330   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3331   return { 'error' => $session } if $context eq 'error';
3332  
3333   return { error => 'requested format not implemented' } 
3334     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3335
3336   my $conf = new FS::Conf;
3337   my $age_threshold = 0;
3338   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3339     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3340
3341   my $search = { 'custnum' => $custnum };
3342   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3343   my $cust_main = qsearchs('cust_main', $search )
3344     or return { 'error' => "unknown custnum $custnum" };
3345
3346 # does it make more sense to just run one sql query for this instead of all the
3347 # insanity below? would increase performance greately for large data sets?
3348   my @svc_phone = ();
3349   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3350         my @part_svc = $cust_pkg->part_svc;
3351         foreach my $part_svc ( @part_svc ) {
3352             if($part_svc->svcdb eq 'svc_phone'){
3353                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3354                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3355                     push @svc_phone, $cust_pkg_svc->svc_x
3356                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3357                 }
3358             }
3359         }
3360   }
3361
3362   my $csv;
3363   my $xls;
3364   my($xls_r,$xls_c) = (0,0);
3365   my $xls_workbook;
3366   my $content = '';
3367   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3368   if($p->{'format'} eq 'csv') {
3369     $csv = new Text::CSV_XS { 'always_quote' => 1,
3370                                  'eol'          => "\n",
3371                                 };
3372     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3373     $content .= $csv->string;
3374   }
3375   elsif($p->{'format'} eq 'xls') {
3376     my $XLS1 = new IO::Scalar \$content;
3377     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3378         or return { 'error' => "Error opening .xls file: $!" };
3379     $xls = $xls_workbook->add_worksheet('DIDs');
3380     foreach ( @fields ) {
3381         $xls->write(0,$xls_c++,$_);
3382     }
3383     $xls_r++;
3384   }
3385
3386   foreach my $svc_phone ( @svc_phone ) {
3387     my @cols = map { $svc_phone->$_ } @fields;
3388     if($p->{'format'} eq 'csv') {
3389         return { 'error' => 'Unable to create CSV' } 
3390             unless $csv->combine(@cols);
3391         $content .= $csv->string;
3392     }
3393     elsif($p->{'format'} eq 'xls') {
3394         $xls_c = 0;
3395         foreach ( @cols ) {
3396             $xls->write($xls_r,$xls_c++,$_);
3397         }
3398         $xls_r++;
3399     }
3400   }
3401
3402   $xls_workbook->close() if $p->{'format'} eq 'xls';
3403   
3404   { content => $content, format => $p->{'format'}, };
3405 }
3406
3407 sub get_ticket {
3408   my $p = shift;
3409   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3410   return { 'error' => $session } if $context eq 'error';
3411
3412 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3413 #  FS::TicketSystem->init();
3414 #  return { 'error' => 'get_ticket configuration error' }
3415 #    if $FS::TicketSystem::system ne 'RT_Internal';
3416
3417   # check existence and ownership as part of this
3418   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3419   my $rt_session = FS::TicketSystem->session('');
3420   my $Ticket = FS::TicketSystem->get_ticket_object(
3421     $rt_session, 
3422     ticket_id => $p->{'ticket_id'},
3423     custnum => $custnum
3424   );
3425   return { 'error' => 'ticket not found' } if !$Ticket;
3426
3427   if ( length( $p->{'subject'} || '' ) ) {
3428     # subject change
3429     if ( $p->{'subject'} ne $Ticket->Subject ) {
3430       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3431       return { 'error' => "unable to set subject: $msg" } if !$val;
3432     }
3433   }
3434
3435   if(length($p->{'reply'})) {
3436     my @err_or_res = FS::TicketSystem->correspond_ticket(
3437       $rt_session,
3438       'ticket_id' => $p->{'ticket_id'},
3439       'content' => $p->{'reply'},
3440     );
3441
3442     return { 'error' => 'unable to reply to ticket' } 
3443     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3444   }
3445
3446   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3447   my $err_or_ticket = FS::TicketSystem->get_ticket(
3448     $rt_session,
3449     'ticket_id' => $p->{'ticket_id'},
3450   );
3451
3452   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3453     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3454       if $DEBUG;
3455     return { 'error' => $err_or_ticket };
3456   }
3457
3458   my @custs = @{$err_or_ticket->{'custs'}};
3459   my @txns = @{$err_or_ticket->{'txns'}};
3460   my @filtered_txns;
3461
3462   # superseded by check in get_ticket_object
3463   #return { 'error' => 'invalid ticket requested' } 
3464   #unless grep($_ eq $custnum, @custs);
3465
3466   foreach my $txn ( @txns ) {
3467     push @filtered_txns, $txn 
3468     if ($txn->{'type'} eq 'EmailRecord' 
3469       || $txn->{'type'} eq 'Correspond'
3470       || $txn->{'type'} eq 'Create');
3471   }
3472
3473   warn "$me get_ticket: successful: \n"
3474   if $DEBUG;
3475   return { 'error'     => '',
3476     'transactions' => \@filtered_txns,
3477     'ticket_fields' => $err_or_ticket->{'fields'},
3478     'ticket_id' => $p->{'ticket_id'},
3479   };
3480 }
3481
3482 sub adjust_ticket_priority {
3483   my $p = shift;
3484   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3485   return { 'error' => $session } if $context eq 'error';
3486
3487 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3488 #  FS::TicketSystem->init;
3489   my $ss_priority = FS::TicketSystem->selfservice_priority;
3490
3491   return { 'error' => 'adjust_ticket_priority configuration error' }
3492     if $FS::TicketSystem::system ne 'RT_Internal'
3493       or !$ss_priority;
3494
3495   my $values = $p->{'values'}; #hashref, id => priority value
3496   my %ticket_error;
3497
3498   foreach my $id (keys %$values) {
3499     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3500     my $Ticket = FS::TicketSystem->get_ticket_object('',
3501       'ticket_id' => $id,
3502       'custnum'   => $custnum,
3503     );
3504     if ( !$Ticket ) {
3505       $ticket_error{$id} = 'ticket not found';
3506       next;
3507     }
3508     
3509   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3510   # We're not going to implement it for RT_External.
3511     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3512     my $new_value = $values->{$id};
3513     next if $old_value eq $new_value;
3514
3515     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3516
3517     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3518     # a single-valued custom field, which it should be.  If it's not, you're 
3519     # doing something wrong.
3520     my ($val, $msg);
3521     if ( length($new_value) ) {
3522       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3523         Field => $ss_priority,
3524         Value => $new_value,
3525       );
3526     }
3527     else {
3528       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3529         Field => $ss_priority,
3530         Value => $old_value,
3531       );
3532     }
3533
3534     $ticket_error{$id} = $msg if !$val;
3535     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3536   }
3537   return { 'error' => '',
3538            'ticket_error' => \%ticket_error,
3539            %{ customer_info($p) } # send updated customer info back
3540          }
3541 }
3542
3543 #--
3544
3545 sub _custoragent_session_custnum {
3546   my $p = shift;
3547
3548   my($context, $session, $custnum);
3549   if ( $p->{'session_id'} ) {
3550
3551     $context = 'customer';
3552     $session = _cache->get($p->{'session_id'})
3553       or return ( 'error' => "Can't resume session" ); #better error message
3554     $custnum = $session->{'custnum'};
3555
3556   } elsif ( $p->{'agent_session_id'} ) {
3557
3558     $context = 'agent';
3559     my $agent_cache = new FS::ClientAPI_SessionCache( {
3560       'namespace' => 'FS::ClientAPI::Agent',
3561     } );
3562     $session = $agent_cache->get($p->{'agent_session_id'})
3563       or return ( 'error' => "Can't resume session" ); #better error message
3564     $custnum = $p->{'custnum'};
3565
3566   } else {
3567     $context = 'error';
3568     return ( 'error' => "Can't resume session" ); #better error message
3569   }
3570
3571   ($context, $session, $custnum);
3572
3573 }
3574
3575 1;
3576