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