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