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