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