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