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