This commit was generated by cvs2svn to compensate for changes in r9232,
[freeside.git] / FS / FS / UI / Web.pm
1 package FS::UI::Web;
2
3 use strict;
4 use vars qw($DEBUG @ISA @EXPORT_OK $me);
5 use Exporter;
6 use FS::Conf;
7 use FS::Misc::DateTime qw( parse_datetime );
8 use FS::Record qw(dbdef);
9 use FS::cust_main;  # are sql_balance and sql_date_balance in the right module?
10
11 #use vars qw(@ISA);
12 #use FS::UI
13 #@ISA = qw( FS::UI );
14 @ISA = qw( Exporter );
15
16 @EXPORT_OK = qw( svc_url );
17
18 $DEBUG = 0;
19 $me = '[FS::UID::Web]';
20
21 ###
22 # date parsing
23 ###
24
25 use Date::Parse;
26 sub parse_beginning_ending {
27   my($cgi, $prefix) = @_;
28   $prefix .= '_' if $prefix;
29
30   my $beginning = 0;
31   if ( $cgi->param($prefix.'begin') =~ /^(\d+)$/ ) {
32     $beginning = $1;
33   } elsif ( $cgi->param($prefix.'beginning') =~ /^([ 0-9\-\/]{1,64})$/ ) {
34     $beginning = parse_datetime($1) || 0;
35   }
36
37   my $ending = 4294967295; #2^32-1
38   if ( $cgi->param($prefix.'end') =~ /^(\d+)$/ ) {
39     $ending = $1 - 1;
40   } elsif ( $cgi->param($prefix.'ending') =~ /^([ 0-9\-\/]{1,64})$/ ) {
41     #probably need an option to turn off the + 86399
42     $ending = parse_datetime($1) + 86399;
43   }
44
45   ( $beginning, $ending );
46 }
47
48 =item svc_url
49
50 Returns a service URL, first checking to see if there is a service-specific
51 page to link to, otherwise to a generic service handling page.  Options are
52 passed as a list of name-value pairs, and include:
53
54 =over 4
55
56 =item * m - Mason request object ($m)
57
58 =item * action - The action for which to construct "edit", "view", or "search"
59
60 =item ** part_svc - Service definition (see L<FS::part_svc>)
61
62 =item ** svcdb - Service table
63
64 =item *** query - Query string
65
66 =item *** svc   - FS::cust_svc or FS::svc_* object
67
68 =item ahref - Optional flag, if set true returns <A HREF="$url"> instead of just the URL.
69
70 =back 
71
72 * Required fields
73
74 ** part_svc OR svcdb is required
75
76 *** query OR svc is required
77
78 =cut
79
80   # ##
81   # #required
82   # ##
83   #  'm'        => $m, #mason request object
84   #  'action'   => 'edit', #or 'view'
85   #
86   #  'part_svc' => $part_svc, #usual
87   #   #OR
88   #  'svcdb'    => 'svc_table',
89   #
90   #  'query'    => #optional query string
91   #                # (pass a blank string if you want a "raw" URL to add your
92   #                #  own svcnum to)
93   #   #OR
94   #  'svc'      => $svc_x, #or $cust_svc, it just needs a svcnum
95   #
96   # ##
97   # #optional
98   # ##
99   #  'ahref'    => 1, # if set true, returns <A HREF="$url">
100
101 use FS::CGI qw(rooturl);
102 sub svc_url {
103   my %opt = @_;
104
105   #? return '' unless ref($opt{part_svc});
106
107   my $svcdb = $opt{svcdb} || $opt{part_svc}->svcdb;
108   my $query = exists($opt{query}) ? $opt{query} : $opt{svc}->svcnum;
109   my $url;
110   warn "$me [svc_url] checking for /$opt{action}/$svcdb.cgi component"
111     if $DEBUG;
112   if ( $opt{m}->interp->comp_exists("/$opt{action}/$svcdb.cgi") ) {
113     $url = "$svcdb.cgi?";
114   } else {
115
116     my $generic = $opt{action} eq 'search' ? 'cust_svc' : 'svc_Common';
117
118     $url = "$generic.html?svcdb=$svcdb;";
119     $url .= 'svcnum=' if $query =~ /^\d+(;|$)/ or $query eq '';
120   }
121
122   import FS::CGI 'rooturl'; #WTF!  why is this necessary
123   my $return = rooturl(). "$opt{action}/$url$query";
124
125   $return = qq!<A HREF="$return">! if $opt{ahref};
126
127   $return;
128 }
129
130 sub svc_link {
131   my($m, $part_svc, $cust_svc) = @_ or return '';
132   svc_X_link( $part_svc->svc, @_ );
133 }
134
135 sub svc_label_link {
136   my($m, $part_svc, $cust_svc) = @_ or return '';
137   svc_X_link( ($cust_svc->label)[1], @_ );
138 }
139
140 sub svc_X_link {
141   my ($x, $m, $part_svc, $cust_svc) = @_ or return '';
142
143   return $x
144    unless $FS::CurrentUser::CurrentUser->access_right('View customer services');
145
146   my $ahref = svc_url(
147     'ahref'    => 1,
148     'm'        => $m,
149     'action'   => 'view',
150     'part_svc' => $part_svc,
151     'svc'      => $cust_svc,
152   );
153
154   "$ahref$x</A>";
155 }
156
157 #this probably needs an ACL too...
158 sub svc_export_links {
159   my ($m, $part_svc, $cust_svc) = @_ or return '';
160
161   my $ahref = $cust_svc->export_links;
162
163   join('', @$ahref);
164 }
165
166 sub parse_lt_gt {
167   my($cgi, $field) = @_;
168
169   my @search = ();
170
171   my %op = ( 
172     'lt' => '<',
173     'gt' => '>',
174   );
175
176   foreach my $op (keys %op) {
177
178     warn "checking for ${field}_$op field\n"
179       if $DEBUG;
180
181     if ( $cgi->param($field."_$op") =~ /^\s*\$?\s*(-?[\d\,\s]+(\.\d\d)?)\s*$/ ) {
182
183       my $num = $1;
184       $num =~ s/[\,\s]+//g;
185       my $search = "$field $op{$op} $num";
186       push @search, $search;
187
188       warn "found ${field}_$op field; adding search element $search\n"
189         if $DEBUG;
190     }
191
192   }
193
194   @search;
195
196 }
197
198 ###
199 # cust_main report subroutines
200 ###
201
202
203 =item cust_header [ CUST_FIELDS_VALUE ]
204
205 Returns an array of customer information headers according to the supplied
206 customer fields value, or if no value is supplied, the B<cust-fields>
207 configuration value.
208
209 =cut
210
211 use vars qw( @cust_fields @cust_colors @cust_styles @cust_aligns );
212
213 sub cust_header {
214
215   warn "FS::UI:Web::cust_header called"
216     if $DEBUG;
217
218   my $conf = new FS::Conf;
219
220   my %header2method = (
221     'Customer'                 => 'name',
222     'Cust. Status'             => 'ucfirst_cust_status',
223     'Cust#'                    => 'custnum',
224     'Name'                     => 'contact',
225     'Company'                  => 'company',
226     '(bill) Customer'          => 'name',
227     '(service) Customer'       => 'ship_name',
228     '(bill) Name'              => 'contact',
229     '(service) Name'           => 'ship_contact',
230     '(bill) Company'           => 'company',
231     '(service) Company'        => 'ship_company',
232     'Address 1'                => 'address1',
233     'Address 2'                => 'address2',
234     'City'                     => 'city',
235     'State'                    => 'state',
236     'Zip'                      => 'zip',
237     'Country'                  => 'country_full',
238     'Day phone'                => 'daytime', # XXX should use msgcat, but how?
239     'Night phone'              => 'night',   # XXX should use msgcat, but how?
240     'Fax number'               => 'fax',
241     '(bill) Address 1'         => 'address1',
242     '(bill) Address 2'         => 'address2',
243     '(bill) City'              => 'city',
244     '(bill) State'             => 'state',
245     '(bill) Zip'               => 'zip',
246     '(bill) Country'           => 'country_full',
247     '(bill) Day phone'         => 'daytime', # XXX should use msgcat, but how?
248     '(bill) Night phone'       => 'night',   # XXX should use msgcat, but how?
249     '(bill) Fax number'        => 'fax',
250     '(service) Address 1'      => 'ship_address1',
251     '(service) Address 2'      => 'ship_address2',
252     '(service) City'           => 'ship_city',
253     '(service) State'          => 'ship_state',
254     '(service) Zip'            => 'ship_zip',
255     '(service) Country'        => 'ship_country_full',
256     '(service) Day phone'      => 'ship_daytime', # XXX should use msgcat, how?
257     '(service) Night phone'    => 'ship_night',   # XXX should use msgcat, how?
258     '(service) Fax number'     => 'ship_fax',
259     'Invoicing email(s)'       => 'invoicing_list_emailonly_scalar',
260     'Payment Type'             => 'payby',
261     'Current Balance'          => 'current_balance',
262   );
263   $header2method{'Cust#'} = 'display_custnum'
264     if $conf->exists('cust_main-default_agent_custid');
265
266   my %header2colormethod = (
267     'Cust. Status' => 'cust_statuscolor',
268   );
269   my %header2style = (
270     'Cust. Status' => 'b',
271   );
272   my %header2align = (
273     'Cust. Status' => 'c',
274     'Cust#'        => 'r',
275   );
276
277   my $cust_fields;
278   my @cust_header;
279   if ( @_ && $_[0] ) {
280
281     warn "  using supplied cust-fields override".
282           " (ignoring cust-fields config file)"
283       if $DEBUG;
284     $cust_fields = shift;
285
286   } else {
287
288     if (    $conf->exists('cust-fields')
289          && $conf->config('cust-fields') =~ /^([\w\. \|\#\(\)]+):?/
290        )
291     {
292       warn "  found cust-fields configuration value"
293         if $DEBUG;
294       $cust_fields = $1;
295     } else { 
296       warn "  no cust-fields configuration value found; using default 'Cust. Status | Customer'"
297         if $DEBUG;
298       $cust_fields = 'Cust. Status | Customer';
299     }
300   
301   }
302
303   @cust_header = split(/ \| /, $cust_fields);
304   @cust_fields = map { $header2method{$_} || $_ } @cust_header;
305   @cust_colors = map { exists $header2colormethod{$_}
306                          ? $header2colormethod{$_}
307                          : ''
308                      }
309                      @cust_header;
310   @cust_styles = map { exists $header2style{$_} ? $header2style{$_} : '' }
311                      @cust_header;
312   @cust_aligns = map { exists $header2align{$_} ? $header2align{$_} : 'l' }
313                      @cust_header;
314
315   #my $svc_x = shift;
316   @cust_header;
317 }
318
319 =item cust_sql_fields [ CUST_FIELDS_VALUE ]
320
321 Returns a list of fields for the SELECT portion of an SQL query.
322
323 As with L<the cust_header subroutine|/cust_header>, the fields returned are
324 defined by the supplied customer fields setting, or if no customer fields
325 setting is supplied, the <B>cust-fields</B> configuration value. 
326
327 =cut
328
329 sub cust_sql_fields {
330
331   my @fields = qw( last first company );
332   push @fields, map "ship_$_", @fields;
333   push @fields, 'country';
334
335   cust_header(@_);
336   #inefficientish, but tiny lists and only run once per page
337
338   my @add_fields = qw( address1 address2 city state zip daytime night fax );
339   push @fields,
340     grep { my $field = $_; grep { $_ eq $field } @cust_fields }
341          ( @add_fields, ( map "ship_$_", @add_fields ), 'payby' );
342
343   push @fields, 'agent_custid';
344
345   my @extra_fields = ();
346   if (grep { $_ eq 'current_balance' } @cust_fields) {
347     push @extra_fields, FS::cust_main->balance_sql . " AS current_balance";
348   }
349
350   map("cust_main.$_", @fields), @extra_fields;
351 }
352
353 =item cust_fields OBJECT [ CUST_FIELDS_VALUE ]
354
355 Given an object that contains fields from cust_main (say, from a
356 JOINed search.  See httemplate/search/svc_* for examples), returns an array
357 of customer information, or "(unlinked)" if this service is not linked to a
358 customer.
359
360 As with L<the cust_header subroutine|/cust_header>, the fields returned are
361 defined by the supplied customer fields setting, or if no customer fields
362 setting is supplied, the <B>cust-fields</B> configuration value. 
363
364 =cut
365
366
367 sub cust_fields {
368   my $record = shift;
369   warn "FS::UI::Web::cust_fields called for $record ".
370        "(cust_fields: @cust_fields)"
371     if $DEBUG > 1;
372
373   #cust_header(@_) unless @cust_fields; #now need to cache to keep cust_fields
374   #                                     #override incase we were passed as a sub
375   
376   my $seen_unlinked = 0;
377
378   map { 
379     if ( $record->custnum ) {
380       warn "  $record -> $_" if $DEBUG > 1;
381       $record->$_(@_);
382     } else {
383       warn "  ($record unlinked)" if $DEBUG > 1;
384       $seen_unlinked++ ? '' : '(unlinked)';
385     }
386   } @cust_fields;
387 }
388
389 =item cust_fields_subs
390
391 Returns an array of subroutine references for returning customer field values.
392 This is similar to cust_fields, but returns each field's sub as a distinct 
393 element.
394
395 =cut
396
397 sub cust_fields_subs {
398   my $unlinked_warn = 0;
399   return map { 
400     my $f = $_;
401     if( $unlinked_warn++ ) {
402       sub {
403         my $record = shift;
404         if( $record->custnum ) {
405           $record->$f(@_);
406         }
407         else {
408           '(unlinked)'
409         };
410       }
411     } 
412     else {
413       sub {
414         my $record = shift;
415         $record->$f(@_) if $record->custnum;
416       }
417     }
418   } @cust_fields;
419 }
420
421 =item cust_colors
422
423 Returns an array of subroutine references (or empty strings) for returning
424 customer information colors.
425
426 As with L<the cust_header subroutine|/cust_header>, the fields returned are
427 defined by the supplied customer fields setting, or if no customer fields
428 setting is supplied, the <B>cust-fields</B> configuration value. 
429
430 =cut
431
432 sub cust_colors {
433   map { 
434     my $method = $_;
435     if ( $method ) {
436       sub { shift->$method(@_) };
437     } else {
438       '';
439     }
440   } @cust_colors;
441 }
442
443 =item cust_styles
444
445 Returns an array of customer information styles.
446
447 As with L<the cust_header subroutine|/cust_header>, the fields returned are
448 defined by the supplied customer fields setting, or if no customer fields
449 setting is supplied, the <B>cust-fields</B> configuration value. 
450
451 =cut
452
453 sub cust_styles {
454   map { 
455     if ( $_ ) {
456       $_;
457     } else {
458       '';
459     }
460   } @cust_styles;
461 }
462
463 =item cust_aligns
464
465 Returns an array or scalar (depending on context) of customer information
466 alignments.
467
468 As with L<the cust_header subroutine|/cust_header>, the fields returned are
469 defined by the supplied customer fields setting, or if no customer fields
470 setting is supplied, the <B>cust-fields</B> configuration value. 
471
472 =cut
473
474 sub cust_aligns {
475   if ( wantarray ) {
476     @cust_aligns;
477   } else {
478     join('', @cust_aligns);
479   }
480 }
481
482 ###
483 # begin JSRPC code...
484 ###
485
486 package FS::UI::Web::JSRPC;
487
488 use strict;
489 use vars qw($DEBUG);
490 use Carp;
491 use Storable qw(nfreeze);
492 use MIME::Base64;
493 use JSON;
494 use FS::UID qw(getotaker);
495 use FS::Record qw(qsearchs);
496 use FS::queue;
497
498 $DEBUG = 0;
499
500 sub new {
501         my $class = shift;
502         my $self  = {
503                 env => {},
504                 job => shift,
505                 cgi => shift,
506         };
507
508         bless $self, $class;
509
510         croak "CGI object required as second argument" unless $self->{'cgi'};
511
512         return $self;
513 }
514
515 sub process {
516
517   my $self = shift;
518
519   my $cgi = $self->{'cgi'};
520
521   # XXX this should parse JSON foo and build a proper data structure
522   my @args = $cgi->param('arg');
523
524   #work around konqueror bug!
525   @args = map { s/\x00$//; $_; } @args;
526
527   my $sub = $cgi->param('sub'); #????
528
529   warn "FS::UI::Web::JSRPC::process:\n".
530        "  cgi=$cgi\n".
531        "  sub=$sub\n".
532        "  args=".join(', ',@args)."\n"
533     if $DEBUG;
534
535   if ( $sub eq 'start_job' ) {
536
537     $self->start_job(@args);
538
539   } elsif ( $sub eq 'job_status' ) {
540
541     $self->job_status(@args);
542
543   } else {
544
545     die "unknown sub $sub";
546
547   }
548
549 }
550
551 sub start_job {
552   my $self = shift;
553
554   warn "FS::UI::Web::start_job: ". join(', ', @_) if $DEBUG;
555 #  my %param = @_;
556   my %param = ();
557   while ( @_ ) {
558     my( $field, $value ) = splice(@_, 0, 2);
559     unless ( exists( $param{$field} ) ) {
560       $param{$field} = $value;
561     } elsif ( ! ref($param{$field}) ) {
562       $param{$field} = [ $param{$field}, $value ];
563     } else {
564       push @{$param{$field}}, $value;
565     }
566   }
567   $param{CurrentUser} = getotaker();
568   warn "FS::UI::Web::start_job\n".
569        join('', map {
570                       if ( ref($param{$_}) ) {
571                         "  $_ => [ ". join(', ', @{$param{$_}}). " ]\n";
572                       } else {
573                         "  $_ => $param{$_}\n";
574                       }
575                     } keys %param )
576     if $DEBUG;
577
578   #first get the CGI params shipped off to a job ASAP so an id can be returned
579   #to the caller
580   
581   my $job = new FS::queue { 'job' => $self->{'job'} };
582   
583   #too slow to insert all the cgi params as individual args..,?
584   #my $error = $queue->insert('_JOB', $cgi->Vars);
585   
586   #warn 'froze string of size '. length(nfreeze(\%param)). " for job args\n"
587   #  if $DEBUG;
588
589   my $error = $job->insert( '_JOB', encode_base64(nfreeze(\%param)) );
590
591   if ( $error ) {
592
593     warn "job not inserted: $error\n"
594       if $DEBUG;
595
596     $error;  #this doesn't seem to be handled well,
597              # will trigger "illegal jobnum" below?
598              # (should never be an error inserting the job, though, only thing
599              #  would be Pg f%*kage)
600   } else {
601
602     warn "job inserted successfully with jobnum ". $job->jobnum. "\n"
603       if $DEBUG;
604
605     $job->jobnum;
606   }
607   
608 }
609
610 sub job_status {
611   my( $self, $jobnum ) = @_; #$url ???
612
613   sleep 1; # XXX could use something better...
614
615   my $job;
616   if ( $jobnum =~ /^(\d+)$/ ) {
617     $job = qsearchs('queue', { 'jobnum' => $jobnum } );
618   } else {
619     die "FS::UI::Web::job_status: illegal jobnum $jobnum\n";
620   }
621
622   my @return;
623   if ( $job && $job->status ne 'failed' ) {
624     my ($progress, $action) = split ',', $job->statustext, 2; 
625     $action ||= 'Server processing job';
626     @return = ( 'progress', $progress, $action );
627   } elsif ( !$job ) { #handle job gone case : job successful
628                       # so close popup, redirect parent window...
629     @return = ( 'complete' );
630   } else {
631     @return = ( 'error', $job ? $job->statustext : $jobnum );
632   }
633
634   #to_json(\@return);  #waiting on deb 5.0 for new JSON.pm?
635   objToJson(\@return);
636
637 }
638
639 1;
640