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