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