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