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