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