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