view svc_pbx usage in selfservice, #34836
[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 use FS::cust_location;
50
51 use FS::ClientAPI::MyAccount::quotation; # just for code organization
52
53 $DEBUG = 0;
54 $me = '[FS::ClientAPI::MyAccount]';
55
56 use vars qw( @cust_main_editable_fields @location_editable_fields );
57 @cust_main_editable_fields = qw(
58   first last company daytime night fax mobile
59   locale
60   payby payinfo payname paystart_month paystart_year payissue payip
61   ss paytype paystate stateid stateid_state
62 );
63 @location_editable_fields = qw(
64   address1 address2 city county state zip country
65 );
66
67
68 BEGIN { #preload to reduce time customer_info takes
69   if ( $FS::TicketSystem::system ) {
70     warn "$me: initializing ticket system\n" if $DEBUG;
71     FS::TicketSystem->init();
72   }
73 }
74
75 sub _cache {
76   $cache ||= new FS::ClientAPI_SessionCache( {
77                'namespace' => 'FS::ClientAPI::MyAccount',
78              } );
79 }
80
81 sub skin_info {
82   my $p = shift;
83
84   my($context, $session, $custnum) = _custoragent_session_custnum($p);
85   #return { 'error' => $session } if $context eq 'error';
86
87   my $agentnum = '';
88   if ( $context eq 'customer' ) {
89
90     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
91       or die dbh->errstr;
92
93     $sth->execute($custnum) or die $sth->errstr;
94
95     $agentnum = $sth->fetchrow_arrayref->[0]
96       or die "no agentnum for custnum $custnum";
97
98   #} elsif ( $context eq 'agent' ) {
99   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
100     $agentnum = $1;
101   }
102   $p->{'agentnum'} = $agentnum;
103
104   my $conf = new FS::Conf;
105
106   #false laziness w/Signup.pm
107
108   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
109
110   if ( $skin_info_cache_agent ) {
111
112     warn "$me loading cached skin info for agentnum $agentnum\n"
113       if $DEBUG > 1;
114
115   } else {
116
117     warn "$me populating skin info cache for agentnum $agentnum\n"
118       if $DEBUG > 1;
119
120     $skin_info_cache_agent = {
121       'agentnum' => $agentnum,
122       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
123         qw( company_name date_format ) ),
124       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
125         qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
126             text_color link_color vlink_color hlink_color alink_color
127             font title_color title_align title_size menu_bgcolor menu_fontsize
128           )
129       ),
130       'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
131       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
132         qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
133       ),
134       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
135         qw( title_left_image title_right_image
136             menu_top_image menu_body_image menu_bottom_image
137           )
138       ),
139       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
140       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
141         qw( head body_header body_footer company_address ) ),
142       'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
143                 'main.php Home
144
145                  services.php Services
146                  services.php My Services
147                  services_new.php Order a new service
148
149                  personal.php Profile
150                  personal.php Personal Information
151                  password.php Change Password
152
153                  payment.php Payments
154                  payment_cc.php Credit Card Payment
155                  payment_ach.php Electronic Check Payment
156                  payment_paypal.php PayPal Payment
157                  payment_webpay.php Webpay Payments
158
159                  usage.php Usage
160                  usage_data.php Data usage
161                  usage_cdr.php Call usage
162
163                  tickets.php Help Desk
164                  tickets.php Open Tickets
165                  tickets_resolved.php Resolved Tickets
166                  ticket_create.php Create a new ticket
167
168                  docs.php FAQs
169
170                  logout.php Logout
171                 ',
172     };
173
174     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
175
176   }
177
178   #{ %$skin_info_cache_agent };
179   $skin_info_cache_agent;
180
181 }
182
183 sub login_info {
184   my $p = shift;
185
186   my $conf = new FS::Conf;
187
188   my %info = (
189     %{ skin_info($p) },
190     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
191     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
192     'banner_url'       => scalar($conf->config('selfservice-login_banner_url')),
193     'banner_image_md5' => 
194       md5_hex($conf->config_binary('selfservice-login_banner_image')),
195   );
196
197   return \%info;
198
199 }
200
201 sub login_banner_image {
202   my $p = shift;
203   my $conf = new FS::Conf;
204   my $image = $conf->config_binary('selfservice-login_banner_image');
205   return { 
206     'md5'   => md5_hex($image),
207     'image' => $image,
208   };
209 }
210
211 #false laziness w/FS::ClientAPI::passwd::passwd
212 sub login {
213   my $p = shift;
214
215   my $conf = new FS::Conf;
216
217   my $svc_x = '';
218   my $session = {};
219   if ( $p->{'domain'} eq 'svc_phone'
220        && $conf->exists('selfservice_server-phone_login') ) { 
221
222     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
223     return { error => 'Number not found.' } unless $svc_phone;
224
225     #XXX?
226     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
227     #return { error => 'Only primary user may log in.' } 
228     #  if $conf->exists('selfservice_server-primary_only')
229     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
230
231     return { error => 'Incorrect PIN.' }
232       unless $svc_phone->check_pin($p->{'password'});
233
234     $svc_x = $svc_phone;
235
236   } elsif ( $p->{email}
237               && (my $contact = FS::contact->by_selfservice_email($p->{email}))
238           )
239   {
240     return { error => 'Incorrect contact password.' }
241       unless $contact->authenticate_password($p->{'password'});
242
243     $session->{'custnum'} = $contact->custnum;
244
245   } else {
246
247     ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
248
249     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
250       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
251
252     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
253                                            'domsvc'    => $svc_domain->svcnum, }
254                            );
255     return { error => 'User not found.' } unless $svc_acct;
256
257     if($conf->exists('selfservice_server-login_svcpart')) {
258         my @svcpart = $conf->config('selfservice_server-login_svcpart');
259         my $svcpart = $svc_acct->cust_svc->svcpart;
260         return { error => 'Invalid user.' } 
261             unless grep($_ eq $svcpart, @svcpart);
262     }
263
264     return { error => 'Incorrect password.' }
265       unless $svc_acct->check_password($p->{'password'});
266
267     $svc_x = $svc_acct;
268
269   }
270
271   if ( $svc_x ) {
272
273     $session->{'svcnum'} = $svc_x->svcnum;
274
275     my $cust_svc = $svc_x->cust_svc;
276     my $cust_pkg = $cust_svc->cust_pkg;
277     if ( $cust_pkg ) {
278       my $cust_main = $cust_pkg->cust_main;
279       $session->{'custnum'} = $cust_main->custnum;
280       if ( $conf->exists('pkg-balances') ) {
281         my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
282                             $cust_main->ncancelled_pkgs;
283         $session->{'pkgnum'} = $cust_pkg->pkgnum
284           if scalar(@cust_pkg) > 1;
285       }
286     }
287
288     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
289     #return { error => 'Only primary user may log in.' } 
290     #  if $conf->exists('selfservice_server-primary_only')
291     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
292     my $part_pkg = $cust_pkg->part_pkg;
293     return { error => 'Only primary user may log in.' }
294       if $conf->exists('selfservice_server-primary_only')
295          && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
296
297   }
298
299   my $session_id;
300   do {
301     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
302   } until ( ! defined _cache->get($session_id) ); #just in case
303
304   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
305   _cache->set( $session_id, $session, $timeout );
306
307   return { 'error'      => '',
308            'session_id' => $session_id,
309          };
310 }
311
312 sub logout {
313   my $p = shift;
314   my $skin_info = skin_info($p);
315   if ( $p->{'session_id'} ) {
316     _cache->remove($p->{'session_id'});
317     return { %$skin_info, 'error' => '' };
318   } else {
319     return { %$skin_info, 'error' => "Can't resume session" }; #better error message
320   }
321 }
322
323 sub switch_acct {
324   my $p = shift;
325
326   my($context, $session, $custnum) = _custoragent_session_custnum($p);
327   return { 'error' => $session } if $context eq 'error';
328
329   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
330     or return { 'error' => "Service not found" };
331
332   $session->{'svcnum'} = $svc_acct->svcnum;
333
334   my $conf = new FS::Conf;
335   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
336   _cache->set( $p->{'session_id'}, $session, $timeout );
337
338   return { 'error' => '' };
339
340 }
341
342 sub payment_gateway {
343   # internal use only
344   # takes a cust_main and a cust_payby entry, returns the payment_gateway
345   my $conf = new FS::Conf;
346   my $cust_main = shift;
347   my $cust_payby = shift;
348   my $gatewaynum = $conf->config('selfservice-payment_gateway');
349   if ( $gatewaynum ) {
350     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
351     die "configured gatewaynum $gatewaynum not found!" if !$pg;
352     return $pg;
353   }
354   else {
355     return '' if ! FS::payby->realtime($cust_payby);
356     my $pg = $cust_main->agent->payment_gateway(
357       'method'  => FS::payby->payby2bop($cust_payby),
358       'nofatal' => 1
359     );
360     return $pg;
361   }
362 }
363
364 sub access_info {
365   my $p = shift;
366
367   my $conf = new FS::Conf;
368
369   my $info = skin_info($p);
370
371   use vars qw( $cust_paybys ); #cache for performance
372   unless ( $cust_paybys ) {
373
374     my %cust_paybys = map { $_ => 1 }
375                       map { FS::payby->payby2payment($_) }
376                           $conf->config('signup_server-payby');
377
378     $cust_paybys = [ keys %cust_paybys ];
379
380   }
381   $info->{'cust_paybys'} = $cust_paybys;
382
383   my($context, $session, $custnum) = _custoragent_session_custnum($p);
384   return { 'error' => $session } if $context eq 'error';
385
386   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
387     or return { 'error' => "unknown custnum $custnum" };
388
389   $info->{'hide_payment_fields'} = [ 
390     map { 
391       my $pg = payment_gateway($cust_main, $_);
392       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
393     } @{ $info->{cust_paybys} }
394   ];
395
396   $info->{'self_suspend_reason'} = 
397       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
398
399   $info->{'edit_ticket_subject'} =
400       $conf->exists('ticket_system-selfservice_edit_subject') && 
401       $cust_main->edit_subject;
402
403   $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
404
405   $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
406
407   return { %$info,
408            'custnum'       => $custnum,
409            'access_pkgnum' => $session->{'pkgnum'},
410            'access_svcnum' => $session->{'svcnum'},
411          };
412 }
413
414 sub customer_info {
415   my $p = shift;
416
417   my($context, $session, $custnum) = _custoragent_session_custnum($p);
418   return { 'error' => $session } if $context eq 'error';
419
420   my %return;
421
422   my $conf = new FS::Conf;
423   $return{'require_address2'} = $conf->exists('cust_main-require_address2');
424
425 #  if ( $FS::TicketSystem::system ) {
426 #    warn "$me customer_info: initializing ticket system\n" if $DEBUG;
427 #    FS::TicketSystem->init();
428 #  }
429  
430   if ( $custnum ) { #customer record
431
432     %return = ( %return, %{ customer_info_short($p) } );
433
434     #redundant with customer_info_short, but we need it for several things below
435     my $search = { 'custnum' => $custnum };
436     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
437     my $cust_main = qsearchs('cust_main', $search )
438       or return { 'error' => "unknown custnum $custnum" };
439
440     my $list_tickets = list_tickets($p);
441     $return{'tickets'} = $list_tickets->{'tickets'};
442
443     if ( $session->{'pkgnum'} ) {
444       #XXX open invoices in the pkg-balances case
445     } else {
446       my @open = map {
447                        {
448                          invnum => $_->invnum,
449                          date   => time2str("%b %o, %Y", $_->_date),
450                          owed   => $_->owed,
451                        };
452                      } $cust_main->open_cust_bill;
453       $return{open_invoices} = \@open;
454
455       my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
456       my $sth = dbh->prepare($sql) or die  dbh->errstr;
457       $sth->execute($custnum)      or die $sth->errstr;
458       $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
459       $return{'last_invoice_date_pretty'} =
460         time2str('%m/%d/%Y', $return{'last_invoice_date'} );
461     }
462
463     #customer_info_short always has nobalance on..
464     $return{small_custview} =
465       small_custview( $cust_main,
466                       $return{countrydefault},
467                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
468                     );
469
470     $return{has_ship_address} = $cust_main->has_ship_address;
471     $return{status} = $cust_main->status;
472     $return{statuscolor} = $cust_main->statuscolor;
473
474     # compatibility: some places in selfservice use this to determine
475     # if there's a ship address
476     if ( $return{has_ship_address} ) {
477       $return{ship_last}  = $cust_main->last;
478       $return{ship_first} = $cust_main->first;
479     }
480
481     if (scalar($conf->config('support_packages'))) {
482       my @support_services = ();
483       foreach ($cust_main->support_services) {
484         my $seconds = $_->svc_x->seconds || 0;
485         my $time_remaining = (($seconds < 0) ? '-' : '' ).
486                              int(abs($seconds)/3600)."h".
487                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
488         my $cust_pkg = $_->cust_pkg;
489         my $pkgnum = '';
490         my $pkg = '';
491         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
492         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
493         push @support_services, { svcnum => $_->svcnum,
494                                   time => $time_remaining,
495                                   pkgnum => $pkgnum,
496                                   pkg => $pkg,
497                                 };
498       }
499       $return{support_services} = \@support_services;
500     }
501
502     if ( $conf->config('prepayment_discounts-credit_type') ) {
503       #need to eval?
504       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
505     }
506
507   } elsif ( $session->{'svcnum'} ) { #no customer record
508
509     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
510       or die "unknown svcnum";
511     $return{name} = $svc_acct->email;
512
513   } else {
514
515     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
516
517   }
518
519   return { 'error'   => '',
520            'custnum' => $custnum,
521            %return,
522          };
523
524 }
525
526 sub customer_info_short {
527   my $p = shift;
528
529   my($context, $session, $custnum) = _custoragent_session_custnum($p);
530   return { 'error' => $session } if $context eq 'error';
531
532   my %return;
533
534   my $conf = new FS::Conf;
535
536   if ( $custnum ) { #customer record
537
538     my $search = { 'custnum' => $custnum };
539     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
540     my $cust_main = qsearchs('cust_main', $search )
541       or return { 'error' => "unknown custnum $custnum" };
542
543     $return{display_custnum} = $cust_main->display_custnum;
544
545     if ( $session->{'pkgnum'} ) { 
546       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
547       #next_bill_date from cust_pkg?
548     } else {
549       $return{balance} = $cust_main->balance;
550       $return{next_bill_date} = $cust_main->next_bill_date;
551       $return{next_bill_date_pretty} =
552         $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
553                                 : '(none)';
554     }
555
556     $return{countrydefault} = scalar($conf->config('countrydefault'));
557
558     $return{small_custview} =
559       small_custview( $cust_main,
560                       $return{countrydefault},
561                       1, ##nobalance
562                     );
563
564     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
565
566     $return{payby} = $cust_main->payby;
567
568     #none of these are terribly expensive if we want 'em...
569     for (@cust_main_editable_fields) {
570       $return{$_} = $cust_main->get($_);
571     }
572     #maybe a little more expensive, but it should be cached by now
573     for (@location_editable_fields) {
574       $return{$_} = $cust_main->bill_location->get($_);
575       $return{'ship_'.$_} = $cust_main->ship_location->get($_);
576     }
577  
578     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
579       $return{payinfo} = $cust_main->paymask;
580       @return{'month', 'year'} = $cust_main->paydate_monthyear;
581     }
582     
583     my @invoicing_list = $cust_main->invoicing_list;
584     $return{'invoicing_list'} =
585       join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
586     $return{'postal_invoicing'} =
587       0 < ( grep { $_ eq 'POST' } @invoicing_list );
588
589     if ( $session->{'svcnum'} ) {
590       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
591       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
592       $return{'svcnum'} = $session->{'svcnum'};
593     }
594
595   } elsif ( $session->{'svcnum'} ) { #no customer record
596
597     #uuh, not supproted yet... die?
598     return { 'error' => 'customer_info_short not yet supported as agent' };
599
600   } else {
601
602     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
603
604   }
605
606   return { 'error'          => '',
607            'custnum'        => $custnum,
608            %return,
609          };
610 }
611
612 sub billing_history {
613   my $p = shift;
614
615   my($context, $session, $custnum) = _custoragent_session_custnum($p);
616   return { 'error' => $session } if $context eq 'error';
617
618   return { 'error' => 'No customer' } unless $custnum;
619
620   my $search = { 'custnum' => $custnum };
621   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
622   my $cust_main = qsearchs('cust_main', $search )
623     or return { 'error' => "unknown custnum $custnum" };
624
625   my %return = ();
626
627   if ( $session->{'pkgnum'} ) { 
628     #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
629     #next_bill_date from cust_pkg?
630     return { 'error' => 'No history for package' };
631   }
632
633   $return{balance} = $cust_main->balance;
634   $return{next_bill_date} = $cust_main->next_bill_date;
635   $return{next_bill_date_pretty} =
636     $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
637                             : '(none)';
638
639   my @history = ();
640
641   my $conf = new FS::Conf;
642
643   if ( $conf->exists('selfservice-billing_history-line_items') ) {
644
645     foreach my $cust_bill ( $cust_main->cust_bill ) {
646
647       push @history, {
648         'type'        => 'Line item',
649         'description' => $_->desc( $cust_main->locale ).
650                            ( $_->sdate && $_->edate
651                                ? ' '. time2str('%d-%b-%Y', $_->sdate).
652                                  ' To '. time2str('%d-%b-%Y', $_->edate)
653                                : ''
654                            ),
655         'amount'      => sprintf('%.2f', $_->setup + $_->recur ),
656         'date'        => $cust_bill->_date,
657         'date_pretty' =>  time2str('%m/%d/%Y', $cust_bill->_date ),
658       }
659         foreach $cust_bill->cust_bill_pkg;
660
661     }
662
663   } else {
664
665     push @history, {
666                      'type'        => 'Invoice',
667                      'description' => 'Invoice #'. $_->display_invnum,
668                      'amount'      => sprintf('%.2f', $_->charged ),
669                      'date'        => $_->_date,
670                      'date_pretty' =>  time2str('%m/%d/%Y', $_->_date ),
671                    }
672       foreach $cust_main->cust_bill;
673
674   }
675
676   push @history, {
677                    'type'        => 'Payment',
678                    'description' => 'Payment', #XXX type
679                    'amount'      => sprintf('%.2f', 0 - $_->paid ),
680                    'date'        => $_->_date,
681                    'date_pretty' =>  time2str('%m/%d/%Y', $_->_date ),
682                  }
683     foreach $cust_main->cust_pay;
684
685   push @history, {
686                    'type'        => 'Credit',
687                    'description' => 'Credit', #more info?
688                    'amount'      => sprintf('%.2f', 0 -$_->amount ),
689                    'date'        => $_->_date,
690                    'date_pretty' =>  time2str('%m/%d/%Y', $_->_date ),
691                  }
692     foreach $cust_main->cust_credit;
693
694   push @history, {
695                    'type'        => 'Refund',
696                    'description' => 'Refund', #more info?  type, like payment?
697                    'amount'      => $_->refund,
698                    'date'        => $_->_date,
699                    'date_pretty' =>  time2str('%m/%d/%Y', $_->_date ),
700                  }
701     foreach $cust_main->cust_refund;
702
703   @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
704
705   $return{'history'} = \@history;
706
707   return \%return;
708
709 }
710
711 sub edit_info {
712   my $p = shift;
713   my $session = _cache->get($p->{'session_id'})
714     or return { 'error' => "Can't resume session" }; #better error message
715
716   my $custnum = $session->{'custnum'}
717     or return { 'error' => "no customer record" };
718
719   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
720     or return { 'error' => "unknown custnum $custnum" };
721
722   my $new = new FS::cust_main { $cust_main->hash };
723
724   $new->set( $_ => $p->{$_} )
725     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
726
727   if ( exists($p->{address1}) ) {
728     my $bill_location = FS::cust_location->new({
729         map { $_ => $p->{$_} } @location_editable_fields
730     });
731     # if this is unchanged from before, cust_main::replace will ignore it
732     $new->set('bill_location' => $bill_location);
733   }
734
735   if ( exists($p->{ship_address1}) ) {
736     my $ship_location = FS::cust_location->new({
737         map { $_ => $p->{"ship_$_"} } @location_editable_fields
738     });
739     if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
740       # Selfservice unfortunately tries to indicate "same as billing 
741       # address" by sending all fields empty.  Did this ever work?
742       $ship_location = $cust_main->bill_location;
743     }
744     $new->set('ship_location' => $ship_location);
745   }
746   # but if it hasn't been passed in at all, leave ship_location alone--
747   # DON'T change it to match bill_location.
748
749   my $payby = '';
750   if (exists($p->{'payby'})) {
751     $p->{'payby'} =~ /^([A-Z]{4})$/
752       or return { 'error' => "illegal_payby " . $p->{'payby'} };
753     $payby = $1;
754   }
755
756   my $conf = new FS::Conf;
757
758   if ( $payby =~ /^(CARD|DCRD)$/ ) {
759
760     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
761
762     if ( $new->payinfo eq $cust_main->paymask ) {
763       $new->payinfo($cust_main->payinfo);
764     } else {
765       $new->payinfo($p->{'payinfo'});
766     }
767
768     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
769
770     if ( $conf->exists('selfservice-onfile_require_cvv') ){
771       return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
772     }
773
774   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
775
776     my $payinfo;
777     $p->{'payinfo1'} =~ /^([\dx]+)$/
778       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
779     my $payinfo1 = $1;
780      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
781       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
782     my $payinfo2 = $1;
783     $payinfo = $payinfo1. '@'. $payinfo2;
784
785     $new->payinfo( ($payinfo eq $cust_main->paymask)
786                      ? $cust_main->payinfo
787                      : $payinfo
788                  );
789
790     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
791
792   } elsif ( $payby =~ /^(BILL)$/ ) {
793     #no-op
794   } elsif ( $payby ) {  #notyet ready
795     return { 'error' => "unknown payby $payby" };
796   }
797
798   my @invoicing_list;
799   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
800     #false laziness with httemplate/edit/process/cust_main.cgi
801     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
802     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
803   } else {
804     @invoicing_list = $cust_main->invoicing_list;
805   }
806
807   my $error = $new->replace($cust_main, \@invoicing_list);
808   return { 'error' => $error } if $error;
809   #$cust_main = $new;
810   
811   return { 'error' => '' };
812 }
813
814 sub payment_info {
815   my $p = shift;
816   my $session = _cache->get($p->{'session_id'})
817     or return { 'error' => "Can't resume session" }; #better error message
818
819   ##
820   #generic
821   ##
822
823   my $conf = new FS::Conf;
824   use vars qw($payment_info); #cache for performance
825   unless ( $payment_info ) {
826
827     my %states = map { $_->state => 1 }
828                    qsearch('cust_main_county', {
829                      'country' => $conf->config('countrydefault') || 'US'
830                    } );
831
832     my %cust_paybys = map { $_ => 1 }
833                       map { FS::payby->payby2payment($_) }
834                           $conf->config('signup_server-payby');
835
836     my @cust_paybys = keys %cust_paybys;
837
838     $payment_info = {
839
840       #list all counties/states/countries
841       'cust_main_county' => 
842         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
843
844       #shortcut for one-country folks
845       'states' =>
846         [ sort { $a cmp $b } keys %states ],
847
848       'card_types' => card_types(),
849
850       'withcvv'            => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
851       'require_cvv'        => $conf->exists('selfservice-require_cvv'),
852       'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
853
854       'paytypes' => [ @FS::cust_main::paytypes ],
855
856       'paybys' => [ $conf->config('signup_server-payby') ],
857       'cust_paybys' => \@cust_paybys,
858
859       'stateid_label' => FS::Msgcat::_gettext('stateid'),
860       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
861
862       'show_ss'  => $conf->exists('show_ss'),
863       'show_stateid' => $conf->exists('show_stateid'),
864       'show_paystate' => $conf->exists('show_bankstate'),
865
866       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
867
868       'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
869     };
870
871   }
872
873   ##
874   #customer-specific
875   ##
876
877   my %return = %$payment_info;
878
879   my $custnum = $session->{'custnum'};
880
881   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
882     or return { 'error' => "unknown custnum $custnum" };
883
884   $return{'hide_payment_fields'} = [
885     map { 
886       my $pg = payment_gateway($cust_main, $_);
887       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
888     } @{ $return{cust_paybys} }
889   ];
890
891   $return{balance} = $cust_main->balance; #XXX pkg-balances?
892
893   $return{payname} = $cust_main->payname
894                      || ( $cust_main->first. ' '. $cust_main->get('last') );
895
896   $return{$_} = $cust_main->bill_location->get($_) 
897     for qw(address1 address2 city state zip);
898
899   $return{payby} = $cust_main->payby;
900   $return{stateid_state} = $cust_main->stateid_state;
901
902   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
903     $return{card_type} = cardtype($cust_main->payinfo);
904     $return{payinfo} = $cust_main->paymask;
905
906     @return{'month', 'year'} = $cust_main->paydate_monthyear;
907
908   }
909
910   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
911     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
912     $return{payinfo1} = $payinfo1;
913     $return{payinfo2} = $payinfo2;
914     $return{paytype}  = $cust_main->paytype;
915     $return{paystate} = $cust_main->paystate;
916     $return{payname}  = $cust_main->payname;    # override 'first/last name' default from above, if any.  Is instution-name here.  (#15819)
917   }
918
919   if ( $conf->config('prepayment_discounts-credit_type') ) {
920     #need to eval?
921     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
922   }
923
924   #doubleclick protection
925   my $_date = time;
926   $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
927   $return{paybatch} = $return{payunique};  #back compat
928
929   return { 'error' => '',
930            %return,
931          };
932
933 }
934
935 #some false laziness with httemplate/process/payment.cgi - look there for
936 #ACH and CVV support stuff
937
938 sub validate_payment {
939   my $p = shift;
940
941   my $session = _cache->get($p->{'session_id'})
942     or return { 'error' => "Can't resume session" }; #better error message
943
944   my $custnum = $session->{'custnum'};
945
946   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
947     or return { 'error' => "unknown custnum $custnum" };
948
949   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
950     or return { 'error' => gettext('illegal_amount') };
951   my $amount = $1;
952   return { error => 'Amount must be greater than 0' } unless $amount > 0;
953
954   #false laziness w/tr-amount_fee.html, but we don't want selfservice users
955   #changing the hidden form values
956   my $conf = new FS::Conf;
957   my $fee_display = $conf->config('selfservice_process-display') || 'add';
958   my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
959   my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
960   if ( $fee_display eq 'add'
961          and $fee_pkgpart
962          and ! $fee_skip_first || scalar($cust_main->cust_pay)
963      )
964   {
965     my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
966     $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
967   }
968
969   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
970     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
971   my $discount_term = $1;
972
973   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
974     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
975   my $payname = $1;
976
977   $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
978     or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
979   my $payunique = $1;
980
981   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
982     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
983   my $paybatch = $1;
984
985   $payunique = $paybatch if ! length($payunique) && length($paybatch);
986
987   $p->{'payby'} ||= 'CARD';
988   $p->{'payby'} =~ /^([A-Z]{4})$/
989     or return { 'error' => "illegal_payby " . $p->{'payby'} };
990   my $payby = $1;
991
992   #false laziness w/process/payment.cgi
993   my $payinfo;
994   my $paycvv = '';
995   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
996   
997     $p->{'payinfo1'} =~ /^([\dx]+)$/
998       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
999     my $payinfo1 = $1;
1000      $p->{'payinfo2'} =~ /^([\dx]+)$/
1001       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1002     my $payinfo2 = $1;
1003     $payinfo = $payinfo1. '@'. $payinfo2;
1004
1005     $payinfo = $cust_main->payinfo
1006       if $cust_main->paymask eq $payinfo;
1007    
1008   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1009    
1010     $payinfo = $p->{'payinfo'};
1011
1012     my $onfile = 0;
1013
1014     #more intelligent matching will be needed here if you change
1015     #card_masking_method and don't remove existing paymasks
1016     if ( $cust_main->paymask eq $payinfo ) {
1017       $payinfo = $cust_main->payinfo;
1018       $onfile = 1;
1019     }
1020
1021     $payinfo =~ s/\D//g;
1022     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1023       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1024     $payinfo = $1;
1025
1026     validate($payinfo)
1027       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1028     return { 'error' => gettext('unknown_card_type') }
1029       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1030
1031     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1032       if ( cardtype($payinfo) eq 'American Express card' ) {
1033         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1034           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1035         $paycvv = $1;
1036       } else {
1037         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1038           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1039         $paycvv = $1;
1040       }
1041     } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1042       return { 'error' => 'CVV2 is required' };
1043     } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1044       return { 'error' => 'CVV2 is required' };
1045     }
1046   
1047   } else {
1048     die "unknown payby $payby";
1049   }
1050
1051   my %payby2fields = (
1052     'CARD' => [ qw( paystart_month paystart_year payissue payip
1053                     address1 address2 city state zip country    ) ],
1054     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1055   );
1056
1057   my $card_type = '';
1058   $card_type = cardtype($payinfo) if $payby eq 'CARD';
1059
1060   { 
1061     'cust_main'      => $cust_main, #XXX or just custnum??
1062     'amount'         => sprintf('%.2f', $amount),
1063     'payby'          => $payby,
1064     'payinfo'        => $payinfo,
1065     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
1066     'card_type'      => $card_type,
1067     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
1068     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1069     'month'          => $p->{'month'},
1070     'year'           => $p->{'year'},
1071     'payname'        => $payname,
1072     'payunique'      => $payunique,
1073     'paybatch'       => $paybatch,
1074     'paycvv'         => $paycvv,
1075     'payname'        => $payname,
1076     'discount_term'  => $discount_term,
1077     'pkgnum'         => $session->{'pkgnum'},
1078     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1079                              qw( save auto ),
1080                            )
1081   };
1082
1083 }
1084
1085 sub store_payment {
1086   my $p = shift;
1087
1088   my $validate = validate_payment($p);
1089   return $validate if $validate->{'error'};
1090
1091   my $conf = new FS::Conf;
1092   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1093   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1094
1095   +{ map { $_=>$validate->{$_} }
1096       qw( card_type paymask payname paydate_pretty month year amount
1097           address1 address2 city state zip country
1098         )
1099   };
1100
1101 }
1102
1103 sub process_stored_payment {
1104   my $p = shift;
1105
1106   my $session_id = $p->{'session_id'};
1107
1108   my $payment_info = _cache->get( "payment_$session_id" )
1109     or return { 'error' => "Can't resume session" }; #better error message
1110
1111   do_process_payment($payment_info);
1112
1113 }
1114
1115 sub process_payment {
1116   my $p = shift;
1117
1118   my $payment_info = validate_payment($p);
1119   return $payment_info if $payment_info->{'error'};
1120
1121   do_process_payment($payment_info);
1122
1123 }
1124
1125 sub do_process_payment {
1126   my $validate = shift;
1127
1128   my $cust_main = $validate->{'cust_main'};
1129
1130   my $amount = delete $validate->{'amount'};
1131   my $paynum = '';
1132
1133   my $payby = delete $validate->{'payby'};
1134
1135   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1136     'quiet'       => 1,
1137     'manual'      => 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' or $svcdb eq 'svc_pbx' ) {
1827       if (!$hide_usage) {
1828         # could potentially show lots of things...
1829         $hash{'outbound'} = 1;
1830         $hash{'inbound'}  = 0;
1831         if ( $svcdb eq 'svc_phone' ) {
1832           if ( $part_pkg->plan eq 'voip_inbound' ) {
1833             $hash{'outbound'} = 0;
1834             $hash{'inbound'}  = 1;
1835           } elsif ( $part_pkg->option('selfservice_inbound_format')
1836                 or  $conf->config('selfservice-default_inbound_cdr_format')
1837           ) {
1838             $hash{'inbound'}  = 1;
1839           }
1840         }
1841         foreach (qw(inbound outbound)) {
1842           # hmm...we can't filter by status here, because there might
1843           # not be cdr_terminations at all.  have to go by date.
1844           # find all since the last bill date.
1845           # XXX cdr types?  we are going to need them.
1846           if ( $hash{$_} ) {
1847             my $sum_cdr = $svc_x->sum_cdrs(
1848               'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1849               'begin'   => ($cust_pkg->last_bill || 0),
1850               'nonzero' => 1,
1851               'disable_charged_party' => 1,
1852             );
1853             $hash{$_} = $sum_cdr->hashref;
1854           }
1855         }
1856       } # not hiding usage
1857     } # svcdb
1858
1859     push @svcs, \%hash;
1860   } # foreach $cust_svc
1861
1862   return { 
1863     'svcnum'   => $session->{'svcnum'},
1864     'custnum'  => $custnum,
1865     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1866     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1867     'svcs'     => \@svcs,
1868     'usage_pools' => [
1869       map { $usage_pools{$_} }
1870       sort { $a cmp $b }
1871       keys %usage_pools
1872     ],
1873     'hide_usage' => $hide_usage,
1874   };
1875
1876 }
1877
1878 sub _customer_svc_x {
1879   my($custnum, $svcnum, $table) = (shift, shift, shift);
1880   my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1881
1882   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1883   my $search = " AND custnum = $1";
1884   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1885
1886   qsearchs( {
1887     'table'     => ($table || 'svc_acct'),
1888     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1889                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1890                    #'LEFT JOIN cust_main USING ( custnum ) ',
1891     'hashref'   => $hashref,
1892     'extra_sql' => $search, #important
1893   } );
1894
1895 }
1896
1897 sub svc_status_html {
1898   my $p = shift;
1899
1900   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1901   return { 'error' => $session } if $context eq 'error';
1902
1903   #XXX only svc_dsl for now
1904   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1905     or return { 'error' => "Service not found" };
1906
1907   my $html = $svc_x->getstatus_html;
1908
1909   return { 'html' => $html };
1910
1911 }
1912
1913 sub svc_status_hash {
1914   my $p = shift;
1915
1916   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1917   return { 'error' => $session } if $context eq 'error';
1918
1919   #XXX only svc_acct for now
1920   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1921     or return { 'error' => "Service not found" };
1922
1923   my ( $html, $hashref ) = $svc_x->export_getstatus;
1924   return $hashref;
1925
1926 }
1927
1928 sub set_svc_status_hash    { _svc_method_X(shift, 'export_setstatus') }
1929 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1930 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1931 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1932 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1933
1934 sub _svc_method_X {
1935   my( $p, $method ) = @_;
1936
1937   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1938   return { 'error' => $session } if $context eq 'error';
1939
1940   #XXX only svc_acct for now
1941   my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1942     or return { 'error' => "Service not found" };
1943
1944   warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1945     if $DEBUG;
1946   my $error = $svc_x->$method($p); #$p? returns error?
1947   return { 'error' => $error } if $error;
1948
1949   return {}; #? { 'error' => '' }
1950
1951 }
1952
1953 sub acct_forward_info {
1954   my $p = shift;
1955
1956   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1957   return { 'error' => $session } if $context eq 'error';
1958
1959   my $svc_forward = _customer_svc_x( $custnum,
1960                                      { 'srcsvc' => $p->{'svcnum'} },
1961                                      'svc_forward',
1962                                    )
1963     or return { 'error' => '',
1964                 'dst'   => '',
1965               };
1966
1967   return { 'error' => '',
1968            'dst'   => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1969          };
1970
1971 }
1972
1973 sub process_acct_forward {
1974   my $p = shift;
1975   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1976   return { 'error' => $session } if $context eq 'error';
1977
1978   my $old = _customer_svc_x( $custnum,
1979                              { 'srcsvc' => $p->{'svcnum'} },
1980                              'svc_forward',
1981                            );
1982
1983   if ( $p->{'dst'} eq '' ) {
1984     if ( $old ) {
1985       my $error = $old->delete;
1986       return { 'error' => $error };
1987     }
1988     return { 'error' => '' };
1989   }
1990
1991   my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1992                                   'dst'    => $p->{'dst'},
1993                                 };
1994
1995   my $error;
1996   if ( $old ) {
1997     $new->svcnum($old->svcnum);
1998     my $cust_svc = $old->cust_svc;
1999     $new->svcpart($old->svcpart);
2000     $new->pkgnuym($old->pkgnum);
2001     $error = $new->replace($old);
2002   } else {
2003     my $conf = new FS::Conf;
2004     $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2005
2006     my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2007       or return { 'error' => 'No service' }; #how would we even get here?
2008
2009     $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2010
2011     $error = $new->insert;
2012   }
2013
2014   return { 'error' => $error };
2015
2016 }
2017
2018 sub list_dsl_devices {
2019   my $p = shift;
2020
2021   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2022   return { 'error' => $session } if $context eq 'error';
2023
2024   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2025     or return { 'error' => "Service not found" };
2026
2027   return {
2028     'devices' => [ map {
2029                          +{ 'mac_addr' => $_->mac_addr };
2030                        } $svc_dsl->dsl_device
2031                  ],
2032   };
2033
2034 }
2035
2036 sub add_dsl_device {
2037   my $p = shift;
2038
2039   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2040   return { 'error' => $session } if $context eq 'error';
2041
2042   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2043     or return { 'error' => "Service not found" };
2044
2045   return { 'error' => 'No MAC address supplied' }
2046     unless length($p->{'mac_addr'});
2047
2048   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
2049                                         'mac_addr' => scalar($p->{'mac_addr'}),
2050                                       };
2051   my $error = $dsl_device->insert;
2052   return { 'error' => $error };
2053
2054 }
2055
2056 sub delete_dsl_device {
2057   my $p = shift;
2058
2059   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2060   return { 'error' => $session } if $context eq 'error';
2061
2062   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2063     or return { 'error' => "Service not found" };
2064
2065   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
2066                                             'mac_addr' => scalar($p->{'mac_addr'}),
2067                                           }
2068                            )
2069     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2070
2071   my $error = $dsl_device->delete;
2072   return { 'error' => $error };
2073
2074 }
2075
2076 sub port_graph {
2077   my $p = shift;
2078   _usage_details( \&_port_graph, $p,
2079                   'svcdb' => 'svc_port',
2080                 );
2081 }
2082
2083 sub _port_graph {
2084   my($svc_port, $begin, $end) = @_;
2085   my @usage = ();
2086   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2087   push @usage, { 'png' => $pngOrError };
2088   (@usage);
2089 }
2090
2091 sub _list_svc_usage {
2092   my($svc_acct, $begin, $end) = @_;
2093   my @usage = ();
2094   foreach my $part_export ( 
2095     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2096     qw( sqlradius sqlradius_withdomain )
2097   ) {
2098     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2099   }
2100   (@usage);
2101 }
2102
2103 sub list_svc_usage {
2104   _usage_details(\&_list_svc_usage, @_);
2105 }
2106
2107 sub _list_support_usage {
2108   my($svc_acct, $begin, $end) = @_;
2109   my @usage = ();
2110   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2111             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2112           ) {
2113     push @usage, { 'seconds'  => $_->seconds,
2114                    'support'  => $_->support,
2115                    '_date'    => $_->_date,
2116                    'id'       => $_->transaction_id,
2117                    'creator'  => $_->creator,
2118                    'subject'  => $_->subject,
2119                    'status'   => $_->status,
2120                    'ticketid' => $_->ticketid,
2121                  };
2122   }
2123   (@usage);
2124 }
2125
2126 sub list_support_usage {
2127   _usage_details(\&_list_support_usage, @_);
2128 }
2129
2130 sub _list_cdr_usage {
2131   # XXX CDR type support...
2132   # XXX any way to do a paged search on this?
2133   # we have to return the results all at once...
2134   my($svc_x, $begin, $end, %opt) = @_;
2135   map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2136     $svc_x->get_cdrs(
2137       'begin' => $begin,
2138       'end'   => $end,
2139       'disable_charged_party' => 1,
2140       %opt
2141     );
2142 }
2143
2144 sub list_cdr_usage {
2145   my $p = shift;
2146   _usage_details( \&_list_cdr_usage, $p );
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 $cust_svc = qsearchs( 'cust_svc', $search );
2164   return { 'error' => 'No service selected in list_svc_usage' } 
2165     unless $cust_svc;
2166
2167   my $svc_x = $cust_svc->svc_x;
2168   my $svcdb = $svc_x->table;
2169   my $cust_pkg = $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' or $svcdb eq 'svc_pbx' ) {
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
2275   my %order_pkg_options = ();
2276   if ( $p->{locationnum} > 0 ) {
2277     $order_pkg_options{locationnum} = delete($p->{locationnum});
2278   } elsif ( $p->{address1} ) {
2279     $order_pkg_options{'cust_location'} = new FS::cust_location {
2280       map { $_ => $p->{$_} }
2281         qw( address1 address2 city county state zip country )
2282     };
2283   }
2284
2285   #false laziness w/ClientAPI/Signup.pm
2286
2287   my $cust_pkg = new FS::cust_pkg ( {
2288     'custnum'  => $custnum,
2289     'pkgpart'  => $p->{'pkgpart'},
2290     'quantity' => $p->{'quantity'} || 1,
2291   } );
2292   my $error = $cust_pkg->check;
2293   return { 'error' => $error } if $error;
2294
2295   my @svc = ();
2296   unless ( $p->{'svcpart'} eq 'none' ) {
2297
2298     my $svcdb;
2299     my $svcpart = '';
2300     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2301       $svcpart = $1;
2302       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2303       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2304       $svcdb = $part_svc->svcdb;
2305     } else {
2306       $svcdb = 'svc_acct';
2307     }
2308     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2309
2310     my %fields = (
2311       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
2312       'svc_domain'   => [ qw( domain ) ],
2313       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
2314       'svc_external' => [ qw( id title ) ],
2315       'svc_pbx'      => [ qw( id title ) ],
2316     );
2317   
2318     my $svc_x = "FS::$svcdb"->new( {
2319       'svcpart'   => $svcpart,
2320       map { $_ => $p->{$_} } @{$fields{$svcdb}}
2321     } );
2322     
2323     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2324       my @acct_snarf;
2325       my $snarfnum = 1;
2326       while ( length($p->{"snarf_machine$snarfnum"}) ) {
2327         my $acct_snarf = new FS::acct_snarf ( {
2328           'machine'   => $p->{"snarf_machine$snarfnum"},
2329           'protocol'  => $p->{"snarf_protocol$snarfnum"},
2330           'username'  => $p->{"snarf_username$snarfnum"},
2331           '_password' => $p->{"snarf_password$snarfnum"},
2332         } );
2333         $snarfnum++;
2334         push @acct_snarf, $acct_snarf;
2335       }
2336       $svc_x->child_objects( \@acct_snarf );
2337     }
2338     
2339     my $y = $svc_x->setdefault; # arguably should be in new method
2340     return { 'error' => $y } if $y && !ref($y);
2341   
2342     $error = $svc_x->check;
2343     return { 'error' => $error } if $error;
2344
2345     push @svc, $svc_x;
2346
2347   }
2348
2349   $error = $cust_main->order_pkg(
2350     'cust_pkg' => $cust_pkg,
2351     'svcs'     => \@svc,
2352     'noexport' => 1,
2353     %order_pkg_options,
2354   );
2355   return { 'error' => $error } if $error;
2356
2357   my $conf = new FS::Conf;
2358   if ( $conf->exists('signup_server-realtime') ) {
2359
2360     my $bill_error = _do_bop_realtime( $cust_main, $status );
2361
2362     if ($bill_error) {
2363       $cust_pkg->cancel('quiet'=>1);
2364       return $bill_error;
2365     } else {
2366       $cust_pkg->reexport;
2367     }
2368
2369   } else {
2370     $cust_pkg->reexport;
2371   }
2372
2373   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2374
2375   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2376
2377 }
2378
2379 sub change_pkg {
2380   my $p = shift;
2381
2382   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2383   return { 'error' => $session } if $context eq 'error';
2384
2385   my $conf = new FS::Conf;
2386   my $immutable = $conf->exists('selfservice_immutable-package');
2387   return { 'error' => "Package modification disabled" } if $immutable;
2388
2389   my $search = { 'custnum' => $custnum };
2390   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2391   my $cust_main = qsearchs('cust_main', $search )
2392     or return { 'error' => "unknown custnum $custnum" };
2393
2394   my $status = $cust_main->status;
2395   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2396     or return { 'error' => "unknown package $p->{pkgnum}" };
2397
2398   #if someone does need self-service package change of suspended packages,
2399   # figure out how to be more discriminating
2400   return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2401     if $cust_pkg->status eq 'suspended';
2402
2403   my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart'  => $p->{'pkgpart'},
2404                                            'quantity' => $p->{'quantity'} || 1,
2405                                          );
2406
2407   return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2408     unless ref($err_or_cust_pkg);
2409
2410   if ( $conf->exists('signup_server-realtime') ) {
2411
2412     my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2413
2414     if ($bill_error) {
2415       $err_or_cust_pkg->suspend;
2416       return $bill_error;
2417     } else {
2418       $err_or_cust_pkg->reexport;
2419     }
2420
2421   } else {  
2422     $err_or_cust_pkg->reexport;
2423   }
2424
2425   return { error => '', pkgnum => $cust_pkg->pkgnum };
2426
2427 }
2428
2429 sub order_recharge {
2430   my $p = shift;
2431
2432   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2433   return { 'error' => $session } if $context eq 'error';
2434
2435   my $search = { 'custnum' => $custnum };
2436   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2437   my $cust_main = qsearchs('cust_main', $search )
2438     or return { 'error' => "unknown custnum $custnum" };
2439
2440   my $status = $cust_main->status;
2441   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2442     or return { 'error' => "unknown service " . $p->{'svcnum'} };
2443
2444   my $svc_x = $cust_svc->svc_x;
2445   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2446
2447   my %vhash =
2448     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
2449     qw ( recharge_seconds recharge_upbytes recharge_downbytes
2450          recharge_totalbytes );
2451   my $amount = $part_pkg->option('recharge_amount', 1); 
2452   
2453   my ($l, $v, $d) = $cust_svc->label;  # blah
2454   my $pkg = "Recharge $v"; 
2455
2456   my $bill_error = $cust_main->charge($amount, $pkg,
2457      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
2458      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2459      $part_pkg->taxclass); #meh
2460
2461   my $conf = new FS::Conf;
2462   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2463
2464     $bill_error = _do_bop_realtime( $cust_main, $status );
2465
2466     if ($bill_error) {
2467       return $bill_error;
2468     } else {
2469       my $error = $svc_x->recharge (\%vhash);
2470       return { 'error' => $error } if $error;
2471     }
2472
2473   } else {  
2474     my $error = $bill_error;
2475     $error ||= $svc_x->recharge (\%vhash);
2476     return { 'error' => $error } if $error;
2477   }
2478
2479   return { error => '', svc => $cust_svc->part_svc->svc };
2480
2481 }
2482
2483 sub _do_bop_realtime {
2484   my ($cust_main, $status, %opt) = @_;
2485
2486     my $old_balance = $cust_main->balance;
2487
2488     my $bill_error =    $cust_main->bill
2489                      || $cust_main->apply_payments_and_credits;
2490
2491     $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2492       if $cust_main->payby =~ /^(CARD|CHEK)$/;
2493
2494     if (    $cust_main->balance > $old_balance
2495          && $cust_main->balance > 0
2496          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2497                 || $status eq 'suspended'
2498             )
2499        )
2500     {
2501       unless ( $opt{'no_credit'} ) {
2502         #this makes sense.  credit is "un-doing" the invoice
2503         my $conf = new FS::Conf;
2504         $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2505                             'self-service decline',
2506                             reason_type=>$conf->config('signup_credit_type'),
2507                           );
2508         $cust_main->apply_credits( 'order' => 'newest' );
2509       }
2510
2511       return { 'error' => '_decline', 'bill_error' => $bill_error };
2512     }
2513
2514     '';
2515 }
2516
2517 sub renew_info {
2518   my $p = shift;
2519
2520   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2521   return { 'error' => $session } if $context eq 'error';
2522
2523   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2524     or return { 'error' => "unknown custnum $custnum" };
2525
2526   my @cust_pkg = sort { $a->bill <=> $b->bill }
2527                  grep { $_->part_pkg->freq ne '0' }
2528                  $cust_main->ncancelled_pkgs;
2529
2530   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2531
2532   my $total = $cust_main->balance;
2533
2534   my @array = map {
2535                     my $bill = $_->bill;
2536                     $total += $_->part_pkg->base_recur($_, \$bill);
2537                     my $renew_date = $_->part_pkg->add_freq($_->bill);
2538                     {
2539                       'pkgnum'             => $_->pkgnum,
2540                       'amount'             => sprintf('%.2f', $total),
2541                       'bill_date'          => $_->bill,
2542                       'bill_date_pretty'   => time2str('%x', $_->bill),
2543                       'renew_date'         => $renew_date,
2544                       'renew_date_pretty'  => time2str('%x', $renew_date),
2545                       'expire_date'        => $_->expire,
2546                       'expire_date_pretty' => time2str('%x', $_->expire),
2547                     };
2548                   }
2549                   @cust_pkg;
2550
2551   return { 'dates' => \@array };
2552
2553 }
2554
2555 sub payment_info_renew_info {
2556   my $p = shift;
2557   my $renew_info   = renew_info($p);
2558   my $payment_info = payment_info($p);
2559   return { %$renew_info,
2560            %$payment_info,
2561          };
2562 }
2563
2564 sub order_renew {
2565   my $p = shift;
2566
2567   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2568   return { 'error' => $session } if $context eq 'error';
2569
2570   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2571     or return { 'error' => "unknown custnum $custnum" };
2572
2573   my $date = $p->{'date'};
2574
2575   my $now = time;
2576
2577   #freeside-daily -n -d $date fs_daily $custnum
2578   $cust_main->bill_and_collect( 'time'         => $date,
2579                                 'invoice_time' => $now,
2580                                 'actual_time'  => $now,
2581                                 'check_freq'   => '1d',
2582                               );
2583
2584   return { 'error' => '' };
2585
2586 }
2587
2588 sub suspend_pkg {
2589   my $p = shift;
2590   my $session = _cache->get($p->{'session_id'})
2591     or return { 'error' => "Can't resume session" }; #better error message
2592
2593   my $custnum = $session->{'custnum'};
2594
2595   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2596     or return { 'error' => "unknown custnum $custnum" };
2597
2598   my $conf = new FS::Conf;
2599   my $reasonnum = 
2600     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2601       or return { 'error' => 'Permission denied' };
2602
2603   my $pkgnum = $p->{'pkgnum'};
2604
2605   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2606                                         'pkgnum'  => $pkgnum,   } )
2607     or return { 'error' => "unknown pkgnum $pkgnum" };
2608
2609   my $error = $cust_pkg->suspend(reason => $reasonnum);
2610   return { 'error' => $error };
2611
2612 }
2613
2614 sub cancel_pkg {
2615   my $p = shift;
2616   my $session = _cache->get($p->{'session_id'})
2617     or return { 'error' => "Can't resume session" }; #better error message
2618
2619   my $custnum = $session->{'custnum'};
2620
2621   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2622     or return { 'error' => "unknown custnum $custnum" };
2623
2624   my $pkgnum = $p->{'pkgnum'};
2625
2626   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2627                                         'pkgnum'  => $pkgnum,   } )
2628     or return { 'error' => "unknown pkgnum $pkgnum" };
2629
2630   my $error = $cust_pkg->cancel('quiet' => 1);
2631   return { 'error' => $error };
2632
2633 }
2634
2635 sub provision_phone {
2636   my $p = shift;
2637   my @bulkdid;
2638   @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2639
2640   #editing an existing phone number
2641   if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2642       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2643       return { 'error' => $session } if $context eq 'error';
2644     
2645       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2646       return { 'error' => 'service not found' } unless $svc_phone;
2647       return { 'error' => 'invalid svcnum' } 
2648         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2649
2650       $svc_phone->email($p->{'email'}) 
2651         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2652       $svc_phone->forwarddst($p->{'forwarddst'}) 
2653         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2654             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2655       return { 'error' => $svc_phone->replace };
2656  }
2657
2658   # single DID LNP
2659   unless ( $p->{'lnp'} ) {
2660     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2661     $p->{'lnp_status'} = "portingin";
2662     return _provision( 'FS::svc_phone',
2663                   [qw(lnp_desired_due_date lnp_other_provider 
2664                     lnp_other_provider_account phonenum countrycode lnp_status)],
2665                   [qw(phonenum countrycode)],
2666                   $p,
2667                   @_
2668                 );
2669   }
2670
2671   # single DID order (the usual case)
2672   unless (scalar(@bulkdid)) {
2673     return _provision( 'FS::svc_phone',
2674                   [qw(phonenum countrycode)],
2675                   [qw(phonenum countrycode)],
2676                   $p,
2677                   @_
2678                 );
2679   }
2680
2681   # bulk DID order case
2682   my $error;
2683   foreach my $did ( @bulkdid ) {
2684     $did =~ s/[^0-9]//g;
2685     $error = _provision( 'FS::svc_phone',
2686               [qw(phonenum countrycode)],
2687               [qw(phonenum countrycode)],
2688               {
2689                 'pkgnum' => $p->{'pkgnum'},
2690                 'svcpart' => $p->{'svcpart'},
2691                 'phonenum' => $did,
2692                 'countrycode' => $p->{'countrycode'},
2693                 'session_id' => $p->{'session_id'},
2694               }
2695             );
2696     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2697   }
2698   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2699 }
2700
2701 sub provision_acct {
2702   my $p = shift;
2703   warn "provision_acct called\n"
2704     if $DEBUG;
2705
2706   return { 'error' => gettext('passwords_dont_match') }
2707     if $p->{'_password'} ne $p->{'_password2'};
2708   return { 'error' => gettext('empty_password') }
2709     unless length($p->{'_password'});
2710  
2711   if ($p->{'domsvc'}) {
2712     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2713                                                   qw ( svcpart pkgnum ) );
2714     return { 'error' => gettext('invalid_domain') }
2715       unless ($domains{$p->{'domsvc'}});
2716   }
2717
2718   warn "provision_acct calling _provision\n"
2719     if $DEBUG;
2720   _provision( 'FS::svc_acct',
2721               [qw(username _password domsvc)],
2722               [qw(username _password domsvc)],
2723               $p,
2724               @_
2725             );
2726 }
2727
2728 sub provision_external {
2729   my $p = shift;
2730   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2731   _provision( 'FS::svc_external',
2732               [],
2733               [qw(id title)],
2734               $p,
2735               @_
2736             );
2737 }
2738
2739 sub _provision {
2740   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2741   warn "_provision called for $class\n"
2742     if $DEBUG;
2743
2744   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2745   return { 'error' => $session } if $context eq 'error';
2746
2747   my $search = { 'custnum' => $custnum };
2748   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2749   my $cust_main = qsearchs('cust_main', $search )
2750     or return { 'error' => "unknown custnum $custnum" };
2751
2752   my $pkgnum = $p->{'pkgnum'};
2753
2754   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2755     if $DEBUG;
2756   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2757                                         'pkgnum'  => $pkgnum,
2758                                                                } )
2759     or return { 'error' => "unknown pkgnum $pkgnum" };
2760
2761   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2762     if $DEBUG;
2763   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2764     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2765
2766   warn "creating $class record\n"
2767     if $DEBUG;
2768   my $svc_x = $class->new( {
2769     'pkgnum'  => $p->{'pkgnum'},
2770     'svcpart' => $p->{'svcpart'},
2771     map { $_ => $p->{$_} } @$fields
2772   } );
2773
2774   my %insert_args = ();
2775   #i shouldn't be a special case here (pass an option or something)
2776   if ( $class eq 'FS::svc_phone'
2777          && grep length($p->{$_}), @location_editable_fields
2778      )
2779   {
2780     $insert_args{'cust_location'} = new FS::cust_location {
2781       map { $_ => $p->{$_} } @location_editable_fields
2782     };
2783   }
2784
2785   warn "inserting $class record\n"
2786     if $DEBUG;
2787   my $error = $svc_x->insert(%insert_args);
2788
2789   unless ( $error ) {
2790     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2791       if $DEBUG;
2792     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2793   }
2794
2795   my $return = { 'svc'   => $part_svc->svc,
2796                  'error' => $error,
2797                  map { $_ => $svc_x->get($_) } @$return_fields
2798                };
2799   warn "_provision returning ". Dumper($return). "\n"
2800     if $DEBUG;
2801   return $return;
2802
2803 }
2804
2805 sub part_svc_info {
2806   my $p = shift;
2807
2808   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2809   return { 'error' => $session } if $context eq 'error';
2810
2811   my $search = { 'custnum' => $custnum };
2812   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2813   my $cust_main = qsearchs('cust_main', $search )
2814     or return { 'error' => "unknown custnum $custnum" };
2815
2816   my $pkgnum = $p->{'pkgnum'};
2817
2818   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2819                                         'pkgnum'  => $pkgnum,
2820                                                                } )
2821     or return { 'error' => "unknown pkgnum $pkgnum" };
2822
2823   my $svcpart = $p->{'svcpart'};
2824
2825   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2826                                       'svcpart' => $svcpart,           } )
2827     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2828   my $part_svc = $pkg_svc->part_svc;
2829
2830   my $conf = new FS::Conf;
2831
2832   my $ret = {
2833     'svc'     => $part_svc->svc,
2834     'svcdb'   => $part_svc->svcdb,
2835     'pkgnum'  => $pkgnum,
2836     'svcpart' => $svcpart,
2837     'custnum' => $custnum,
2838
2839     'security_phrase' => 0, #XXX !
2840     'svc_acct_pop'    => [], #XXX !
2841     'popnum'          => '',
2842     'init_popstate'   => '',
2843     'popac'           => '',
2844     'acstate'         => '',
2845
2846     'small_custview' =>
2847       small_custview( $cust_main, $conf->config('countrydefault') ),
2848
2849   };
2850
2851   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2852                      && $ret->{'svcdb'} eq 'svc_phone') {
2853         $ret->{'svcnum'} = $p->{'svcnum'};
2854         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2855         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2856             $ret->{'email'} = $svc_phone->email;
2857             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2858         }
2859   }
2860
2861   $ret;
2862 }
2863
2864 sub unprovision_svc {
2865   my $p = shift;
2866
2867   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2868   return { 'error' => $session } if $context eq 'error';
2869
2870   my $search = { 'custnum' => $custnum };
2871   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2872   my $cust_main = qsearchs('cust_main', $search )
2873     or return { 'error' => "unknown custnum $custnum" };
2874
2875   my $svcnum = $p->{'svcnum'};
2876
2877   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2878     or return { 'error' => "unknown svcnum $svcnum" };
2879
2880   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2881     unless $cust_svc->cust_pkg->custnum == $custnum;
2882
2883   my $conf = new FS::Conf;
2884
2885   return { 'svc'   => $cust_svc->part_svc->svc,
2886            'error' => $cust_svc->cancel,
2887            'small_custview' =>
2888              small_custview( $cust_main, $conf->config('countrydefault') ),
2889          };
2890
2891 }
2892
2893 sub myaccount_passwd {
2894   my $p = shift;
2895   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2896   return { 'error' => $session } if $context eq 'error';
2897
2898   return { 'error' => "New passwords don't match." }
2899     if $p->{'new_password'} ne $p->{'new_password2'};
2900
2901   return { 'error' => 'Enter new password' }
2902     unless length($p->{'new_password'});
2903
2904   #my $search = { 'custnum' => $custnum };
2905   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2906   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2907   my $search = " AND custnum = $1";
2908   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2909
2910   my $svc_acct = qsearchs( {
2911     'table'     => 'svc_acct',
2912     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2913                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2914                    'LEFT JOIN cust_main USING ( custnum ) ',
2915     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2916     'extra_sql' => $search, #important
2917   } )
2918     or return { 'error' => "Service not found" };
2919
2920   my $error = '';
2921
2922   my $conf = new FS::Conf;
2923
2924   return { 'error' => 'Incorrect current password.' }
2925     if  ( exists($p->{'old_password'})
2926           || $conf->exists('selfservice-password_change_oldpass')
2927         )
2928     && ! $svc_acct->check_password($p->{'old_password'});
2929
2930   $error = 'Password too short.'
2931     if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2932   $error = 'Password too long.'
2933     if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2934
2935   $svc_acct->set_password($p->{'new_password'});
2936   $error ||= $svc_acct->replace();
2937
2938   #regular pw change in self-service should change contact pw too, otherwise its
2939   #way too confusing.  hell its confusing they're separate at all, but alas.
2940   #need to support the "ISP provides email that's used as a contact email" case
2941   #as well as we can.
2942   my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2943   if ( $contact && $contact->custnum == $custnum ) {
2944     #svc_acct was successful but this one returns an error?  "shouldn't happen"
2945     $error ||= $contact->change_password($p->{'new_password'});
2946   }
2947
2948   my($label, $value) = $svc_acct->cust_svc->label;
2949
2950   return { 'error' => $error,
2951            'label' => $label,
2952            'value' => $value,
2953          };
2954
2955 }
2956
2957 #  sub contact_passwd {
2958 #    my $p = shift;
2959 #    my($context, $session, $custnum) = _custoragent_session_custnum($p);
2960 #    return { 'error' => $session } if $context eq 'error';
2961 #  
2962 #    return { 'error' => 'Not logged in as a contact.' }
2963 #      unless $session->{'contactnum'};
2964 #  
2965 #    return { 'error' => "New passwords don't match." }
2966 #      if $p->{'new_password'} ne $p->{'new_password2'};
2967 #  
2968 #    return { 'error' => 'Enter new password' }
2969 #      unless length($p->{'new_password'});
2970 #  
2971 #    #my $search = { 'custnum' => $custnum };
2972 #    #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2973 #    $custnum =~ /^(\d+)$/ or die "illegal custnum";
2974 #    my $search = " AND selfservice_access IS NOT NULL ".
2975 #                 " AND selfservice_access = 'Y' ".
2976 #                 " AND ( disabled IS NULL OR disabled = '' )".
2977 #                 " AND custnum IS NOT NULL AND custnum = $1";
2978 #    $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2979 #  
2980 #    my $contact = qsearchs( {
2981 #      'table'     => 'contact',
2982 #      'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2983 #      'hashref'   => { 'contactnum' => $session->{'contactnum'}, },
2984 #      'extra_sql' => $search, #important
2985 #    } )
2986 #      or return { 'error' => "Email not found" }; #?  how did we get logged in?
2987 #                                                  # deleted since then?
2988 #  
2989 #    my $error = '';
2990 #  
2991 #    # use these svc_acct length restrictions??
2992 #    my $conf = new FS::Conf;
2993 #    $error = 'Password too short.'
2994 #      if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2995 #    $error = 'Password too long.'
2996 #      if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2997 #  
2998 #    $error ||= $contact->change_password($p->{'new_password'});
2999 #  
3000 #    return { 'error' => $error, };
3001 #  
3002 #  }
3003
3004 sub reset_passwd {
3005   my $p = shift;
3006
3007   my $info = skin_info($p);
3008
3009   my $conf = new FS::Conf;
3010   my $verification = $conf->config('selfservice-password_reset_verification')
3011     or return { %$info, 'error' => 'Password resets disabled' };
3012
3013   my $contact = '';
3014   my $svc_acct = '';
3015   my $cust_main = '';
3016   if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3017   
3018     $contact = FS::contact->by_selfservice_email($p->{'email'});
3019
3020     $cust_main = $contact->cust_main if $contact;
3021
3022     #also look for an svc_acct, otherwise it would be super confusing
3023
3024     my($username, $domain) = split('@', $p->{'email'});
3025     my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3026     if ( $svc_domain ) {
3027       $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3028                                          'domsvc'   => $svc_domain->svcnum  }
3029                           );
3030       if ( $svc_acct ) {
3031         my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3032         $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3033
3034         #precaution: don't change svc_acct password not part of the same
3035         # customer as contact
3036         $svc_acct = '' if ! $cust_pkg
3037                        || $cust_pkg->custnum != $cust_main->custnum;
3038       }
3039       
3040     }
3041
3042     return { %$info, 'error' => 'Email address not found' }
3043       unless $contact || $svc_acct;
3044
3045   } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3046
3047     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3048       or return { %$info, 'error' => 'Account not found' };
3049
3050     $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3051                                        'domsvc'   => $svc_domain->svcnum  }
3052                         )
3053       or return { %$info, 'error' => 'Account not found' };
3054
3055     my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3056       or return { %$info, 'error' => 'Account not found' };
3057
3058     $cust_main = $cust_pkg->cust_main;
3059
3060   }
3061
3062   my %verify = (
3063     'email'   => sub { 1; },
3064     'paymask' => sub { 
3065       my( $p, $cust_main ) = @_;
3066       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3067         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3068     },
3069     'amount'  => sub {
3070       my( $p, $cust_main ) = @_;
3071       my $cust_pay = qsearchs({
3072         'table' => 'cust_pay',
3073         'hashref' => { 'custnum' => $cust_main->custnum },
3074         'order_by' => 'ORDER BY _date DESC LIMIT 1',
3075       })
3076         or return 0;
3077
3078       $p->{'amount'} == $cust_pay->paid;
3079     },
3080     'zip'     => sub {
3081       my( $p, $cust_main ) = @_;
3082       $p->{'zip'} eq $cust_main->zip
3083         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3084     },
3085   );
3086
3087   foreach my $verify ( split(',', $verification) ) {
3088
3089     &{ $verify{$verify} }( $p, $cust_main )
3090       or return { %$info, 'error' => 'Account not found' };
3091
3092   }
3093
3094   #okay, we're verified
3095
3096   if ( $contact ) {
3097
3098     my $error = $contact->send_reset_email(
3099                             'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3100                           );
3101
3102     if ( $error ) {
3103       return { %$info, 'error' => $error }; #????
3104     }
3105
3106   } elsif ( $svc_acct ) {
3107
3108     #create a unique session
3109
3110     my $reset_session = {
3111       'svcnum'   => $svc_acct->svcnum,
3112       'agentnum' =>
3113     };
3114
3115     my $timeout = '1 hour'; #?
3116
3117     my $reset_session_id;
3118     do {
3119       $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3120     } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3121       #just in case
3122
3123     _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3124
3125     #email it
3126
3127     my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3128                                $cust_main->agentnum);
3129     #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3130     return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3131       unless $msgnum;
3132     my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3133     my $error = $msg_template->send( 'cust_main'     => $cust_main,
3134                                      'object'        => $svc_acct,
3135                                      'substitutions' => {
3136                                        'session_id' => $reset_session_id,
3137                                      }
3138                                    );
3139     if ( $error ) {
3140       return { %$info, 'error' => $error }; #????
3141     }
3142
3143   }
3144
3145   return { %$info, 'error' => '' };
3146 }
3147
3148 sub check_reset_passwd {
3149   my $p = shift;
3150
3151   my $conf = new FS::Conf;
3152   my $verification = $conf->config('selfservice-password_reset_verification')
3153     or return { 'error' => 'Password resets disabled' };
3154
3155   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3156     or return { 'error' => "Can't resume session" }; #better error message
3157
3158   if ( $reset_session->{'svcnum'} ) {
3159
3160     my $svcnum = $reset_session->{'svcnum'};
3161
3162     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3163       or return { 'error' => "Service not found" };
3164
3165     $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3166     my $info = skin_info($p);
3167
3168     return { %$info,
3169              'error'      => '',
3170              'session_id' => $p->{'session_id'},
3171              'username'   => $svc_acct->username,
3172            };
3173
3174   } elsif ( $reset_session->{'contactnum'} ) {
3175
3176     my $contactnum = $reset_session->{'contactnum'};
3177
3178     my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3179       or return { 'error' => "Contact not found" };
3180
3181     my @contact_email = $contact->contact_email;
3182     return { 'error' => 'No contact email' } unless @contact_email;
3183
3184     $p->{'agentnum'} = $contact->cust_main->agentnum;
3185     my $info = skin_info($p);
3186
3187     return { %$info,
3188              'error'      => '',
3189              'session_id' => $p->{'session_id'},
3190              'email'      => $contact_email[0]->email, #the first?
3191            };
3192
3193   } else {
3194
3195     return { 'error' => 'No svcnum or contactnum in session' }; #??
3196
3197   }
3198
3199 }
3200
3201 sub process_reset_passwd {
3202   my $p = shift;
3203
3204   my $conf = new FS::Conf;
3205   my $verification = $conf->config('selfservice-password_reset_verification')
3206     or return { 'error' => 'Password resets disabled' };
3207
3208   my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3209     or return { 'error' => "Can't resume session" }; #better error message
3210
3211   my $info = '';
3212
3213   my $svc_acct = '';
3214   if ( $reset_session->{'svcnum'} ) {
3215
3216     my $svcnum = $reset_session->{'svcnum'};
3217
3218     $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3219       or return { 'error' => "Service not found" };
3220
3221     $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3222     $info ||= skin_info($p);
3223
3224   }
3225
3226   my $contact = '';
3227   if ( $reset_session->{'contactnum'} ) {
3228
3229     my $contactnum = $reset_session->{'contactnum'};
3230
3231     $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3232       or return { 'error' => "Contact not found" };
3233
3234     $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3235     $info ||= skin_info($p);
3236
3237   }
3238
3239   return { %$info, 'error' => "New passwords don't match." }
3240     if $p->{'new_password'} ne $p->{'new_password2'};
3241
3242   return { %$info, 'error' => 'Enter new password' }
3243     unless length($p->{'new_password'});
3244
3245   if ( $svc_acct ) {
3246
3247     $svc_acct->set_password($p->{'new_password'});
3248     my $error = $svc_acct->replace();
3249
3250     return { %$info, 'error' => $error } if $error;
3251
3252     #my($label, $value) = $svc_acct->cust_svc->label;
3253     #return { 'error' => $error,
3254     #         #'label' => $label,
3255     #         #'value' => $value,
3256     #       };
3257
3258   }
3259
3260   if ( $contact ) {
3261
3262     my $error = $contact->change_password($p->{'new_password'});
3263
3264     return { %$info, 'error' => $error }; # if $error;
3265
3266   }
3267
3268   #password changed ,so remove session, don't want it reused
3269   _cache->remove($p->{'session_id'});
3270
3271   return { %$info, 'error' => '' };
3272
3273 }
3274
3275 sub list_tickets {
3276   my $p = shift;
3277   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3278   return { 'error' => $session } if $context eq 'error';
3279
3280   my @tickets = ();
3281   if ( $session->{'pkgnum'} ) { 
3282
3283     #tickets for specific service with pkg-balances on
3284     my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3285                                           'pkgnum'  => $session->{'pkgnum'} })
3286                      or return { 'error' => 'unknown package' };
3287     foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3288       push @tickets, $cust_svc->tickets( $p->{status} );
3289     }
3290
3291   } else {
3292
3293     my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3294       or return { 'error' => "unknown custnum $custnum" };
3295
3296     @tickets = $cust_main->tickets( $p->{status} );
3297   }
3298
3299   # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3300   if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3301     my $conf = new FS::Conf;
3302     my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3303     +{ tickets => [ 
3304          sort { 
3305            (
3306              ($a->{'_selfservice_priority'} eq '') <=>
3307              ($b->{'_selfservice_priority'} eq '')
3308            ) ||
3309            ( $dir * 
3310              ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3311            )
3312          } @tickets
3313        ]
3314     };
3315   } else {
3316     +{ tickets => \@tickets };
3317   }
3318
3319 }
3320
3321 sub create_ticket {
3322   my $p = shift;
3323   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3324   return { 'error' => $session } if $context eq 'error';
3325
3326   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3327   FS::TicketSystem->init();
3328
3329   my $conf = new FS::Conf;
3330   my $queue = $p->{'queue'}
3331               || $conf->config('ticket_system-selfservice_queueid')
3332               || $conf->config('ticket_system-default_queueid');
3333
3334   warn "$me create_ticket: creating ticket\n" if $DEBUG;
3335   my $err_or_ticket = FS::TicketSystem->create_ticket(
3336     '', #create RT session based on FS CurrentUser (fs_selfservice)
3337     'queue'   => $queue,
3338     'custnum' => $custnum,
3339     'svcnum'  => $session->{'svcnum'},
3340     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3341   );
3342
3343   if ( ref($err_or_ticket) ) {
3344     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3345       if $DEBUG;
3346     return { 'error'     => '',
3347              'ticket_id' => $err_or_ticket->id,
3348            };
3349   } else {
3350     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3351       if $DEBUG;
3352     return { 'error' => $err_or_ticket };
3353   }
3354
3355
3356 }
3357
3358 sub did_report {
3359   my $p = shift;
3360   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3361   return { 'error' => $session } if $context eq 'error';
3362  
3363   return { error => 'requested format not implemented' } 
3364     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3365
3366   my $conf = new FS::Conf;
3367   my $age_threshold = 0;
3368   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3369     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3370
3371   my $search = { 'custnum' => $custnum };
3372   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3373   my $cust_main = qsearchs('cust_main', $search )
3374     or return { 'error' => "unknown custnum $custnum" };
3375
3376 # does it make more sense to just run one sql query for this instead of all the
3377 # insanity below? would increase performance greately for large data sets?
3378   my @svc_phone = ();
3379   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3380         my @part_svc = $cust_pkg->part_svc;
3381         foreach my $part_svc ( @part_svc ) {
3382             if($part_svc->svcdb eq 'svc_phone'){
3383                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3384                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3385                     push @svc_phone, $cust_pkg_svc->svc_x
3386                         if $cust_pkg_svc->date_inserted >= $age_threshold;
3387                 }
3388             }
3389         }
3390   }
3391
3392   my $csv;
3393   my $xls;
3394   my($xls_r,$xls_c) = (0,0);
3395   my $xls_workbook;
3396   my $content = '';
3397   my @fields = qw( countrycode phonenum pin sip_password phone_name );
3398   if($p->{'format'} eq 'csv') {
3399     $csv = new Text::CSV_XS { 'always_quote' => 1,
3400                                  'eol'          => "\n",
3401                                 };
3402     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3403     $content .= $csv->string;
3404   }
3405   elsif($p->{'format'} eq 'xls') {
3406     my $XLS1 = new IO::Scalar \$content;
3407     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
3408         or return { 'error' => "Error opening .xls file: $!" };
3409     $xls = $xls_workbook->add_worksheet('DIDs');
3410     foreach ( @fields ) {
3411         $xls->write(0,$xls_c++,$_);
3412     }
3413     $xls_r++;
3414   }
3415
3416   foreach my $svc_phone ( @svc_phone ) {
3417     my @cols = map { $svc_phone->$_ } @fields;
3418     if($p->{'format'} eq 'csv') {
3419         return { 'error' => 'Unable to create CSV' } 
3420             unless $csv->combine(@cols);
3421         $content .= $csv->string;
3422     }
3423     elsif($p->{'format'} eq 'xls') {
3424         $xls_c = 0;
3425         foreach ( @cols ) {
3426             $xls->write($xls_r,$xls_c++,$_);
3427         }
3428         $xls_r++;
3429     }
3430   }
3431
3432   $xls_workbook->close() if $p->{'format'} eq 'xls';
3433   
3434   { content => $content, format => $p->{'format'}, };
3435 }
3436
3437 sub get_ticket {
3438   my $p = shift;
3439   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3440   return { 'error' => $session } if $context eq 'error';
3441
3442 #  warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3443 #  FS::TicketSystem->init();
3444 #  return { 'error' => 'get_ticket configuration error' }
3445 #    if $FS::TicketSystem::system ne 'RT_Internal';
3446
3447   # check existence and ownership as part of this
3448   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3449   my $rt_session = FS::TicketSystem->session('');
3450   my $Ticket = FS::TicketSystem->get_ticket_object(
3451     $rt_session, 
3452     ticket_id => $p->{'ticket_id'},
3453     custnum => $custnum
3454   );
3455   return { 'error' => 'ticket not found' } if !$Ticket;
3456
3457   if ( length( $p->{'subject'} || '' ) ) {
3458     # subject change
3459     if ( $p->{'subject'} ne $Ticket->Subject ) {
3460       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3461       return { 'error' => "unable to set subject: $msg" } if !$val;
3462     }
3463   }
3464
3465   if(length($p->{'reply'})) {
3466     my @err_or_res = FS::TicketSystem->correspond_ticket(
3467       $rt_session,
3468       'ticket_id' => $p->{'ticket_id'},
3469       'content' => $p->{'reply'},
3470     );
3471
3472     return { 'error' => 'unable to reply to ticket' } 
3473     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3474   }
3475
3476   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3477   my $err_or_ticket = FS::TicketSystem->get_ticket(
3478     $rt_session,
3479     'ticket_id' => $p->{'ticket_id'},
3480   );
3481
3482   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3483     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3484       if $DEBUG;
3485     return { 'error' => $err_or_ticket };
3486   }
3487
3488   my @custs = @{$err_or_ticket->{'custs'}};
3489   my @txns = @{$err_or_ticket->{'txns'}};
3490   my @filtered_txns;
3491
3492   # superseded by check in get_ticket_object
3493   #return { 'error' => 'invalid ticket requested' } 
3494   #unless grep($_ eq $custnum, @custs);
3495
3496   foreach my $txn ( @txns ) {
3497     push @filtered_txns, $txn 
3498     if ($txn->{'type'} eq 'EmailRecord' 
3499       || $txn->{'type'} eq 'Correspond'
3500       || $txn->{'type'} eq 'Create');
3501   }
3502
3503   warn "$me get_ticket: successful: \n"
3504   if $DEBUG;
3505   return { 'error'     => '',
3506     'transactions' => \@filtered_txns,
3507     'ticket_fields' => $err_or_ticket->{'fields'},
3508     'ticket_id' => $p->{'ticket_id'},
3509   };
3510 }
3511
3512 sub adjust_ticket_priority {
3513   my $p = shift;
3514   my($context, $session, $custnum) = _custoragent_session_custnum($p);
3515   return { 'error' => $session } if $context eq 'error';
3516
3517 #  warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3518 #  FS::TicketSystem->init;
3519   my $ss_priority = FS::TicketSystem->selfservice_priority;
3520
3521   return { 'error' => 'adjust_ticket_priority configuration error' }
3522     if $FS::TicketSystem::system ne 'RT_Internal'
3523       or !$ss_priority;
3524
3525   my $values = $p->{'values'}; #hashref, id => priority value
3526   my %ticket_error;
3527
3528   foreach my $id (keys %$values) {
3529     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3530     my $Ticket = FS::TicketSystem->get_ticket_object('',
3531       'ticket_id' => $id,
3532       'custnum'   => $custnum,
3533     );
3534     if ( !$Ticket ) {
3535       $ticket_error{$id} = 'ticket not found';
3536       next;
3537     }
3538     
3539   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3540   # We're not going to implement it for RT_External.
3541     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3542     my $new_value = $values->{$id};
3543     next if $old_value eq $new_value;
3544
3545     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3546
3547     # AddCustomFieldValue works fine (replacing any existing value) if it's 
3548     # a single-valued custom field, which it should be.  If it's not, you're 
3549     # doing something wrong.
3550     my ($val, $msg);
3551     if ( length($new_value) ) {
3552       ($val, $msg) = $Ticket->AddCustomFieldValue( 
3553         Field => $ss_priority,
3554         Value => $new_value,
3555       );
3556     }
3557     else {
3558       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3559         Field => $ss_priority,
3560         Value => $old_value,
3561       );
3562     }
3563
3564     $ticket_error{$id} = $msg if !$val;
3565     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3566   }
3567   return { 'error' => '',
3568            'ticket_error' => \%ticket_error,
3569            %{ customer_info($p) } # send updated customer info back
3570          }
3571 }
3572
3573 #--
3574
3575 sub _custoragent_session_custnum {
3576   my $p = shift;
3577
3578   my($context, $session, $custnum);
3579   if ( $p->{'session_id'} ) {
3580
3581     $context = 'customer';
3582     $session = _cache->get($p->{'session_id'})
3583       or return ( 'error' => "Can't resume session" ); #better error message
3584     $custnum = $session->{'custnum'};
3585
3586   } elsif ( $p->{'agent_session_id'} ) {
3587
3588     $context = 'agent';
3589     my $agent_cache = new FS::ClientAPI_SessionCache( {
3590       'namespace' => 'FS::ClientAPI::Agent',
3591     } );
3592     $session = $agent_cache->get($p->{'agent_session_id'})
3593       or return ( 'error' => "Can't resume session" ); #better error message
3594     $custnum = $p->{'custnum'};
3595
3596   } else {
3597     $context = 'error';
3598     return ( 'error' => "Can't resume session" ); #better error message
3599   }
3600
3601   ($context, $session, $custnum);
3602
3603 }
3604
3605 1;
3606