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