WebshopApi: ShopOrder Presenter
[kivitendo-erp.git] / SL / Presenter.pm
1 package SL::Presenter;
2
3 use strict;
4
5 use parent qw(Rose::Object);
6
7 use Carp;
8 use Template;
9
10 use SL::Presenter::Chart;
11 use SL::Presenter::CustomerVendor;
12 use SL::Presenter::DeliveryOrder;
13 use SL::Presenter::EscapedText;
14 use SL::Presenter::Invoice;
15 use SL::Presenter::GL;
16 use SL::Presenter::Letter;
17 use SL::Presenter::Order;
18 use SL::Presenter::Part;
19 use SL::Presenter::Project;
20 use SL::Presenter::Record;
21 use SL::Presenter::RequirementSpec;
22 use SL::Presenter::RequirementSpecItem;
23 use SL::Presenter::RequirementSpecTextBlock;
24 use SL::Presenter::SepaExport;
25 use SL::Presenter::ShopOrder;
26 use SL::Presenter::Text;
27 use SL::Presenter::Tag;
28 use SL::Presenter::BankAccount;
29
30 use Rose::Object::MakeMethods::Generic (
31   scalar => [ qw(need_reinit_widgets) ],
32 );
33
34 sub get {
35   return $::request->presenter;
36 }
37
38 sub render {
39   my $self               = shift;
40   my $template           = shift;
41   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
42
43   # Set defaults for all available options.
44   my %defaults = (
45     type       => 'html',
46     process    => 1,
47   );
48   $options->{$_} //= $defaults{$_} for keys %defaults;
49   $options->{type} = lc $options->{type};
50
51   # Check supplied options for validity.
52   foreach (keys %{ $options }) {
53     croak "Unsupported option: $_" unless $defaults{$_};
54   }
55
56   # Only certain types are supported.
57   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json|text)$/;
58
59   # The "template" argument must be a string or a reference to one.
60   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
61   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
62
63   # Look for the file given by $template if $template is not a reference.
64   my $source;
65   if (!ref $template) {
66     my $ext = $options->{type} eq 'text' ? 'txt' : $options->{type};
67     $source = "templates/webpages/${template}.${ext}";
68     croak "Template file ${source} not found" unless -f $source;
69
70   } elsif (ref($template) eq 'SCALAR') {
71     # Normal scalar reference: hand over to Template
72     $source = $template;
73
74   } else {
75     # Instance of SL::Presenter::EscapedText. Get reference to its content.
76     $source = \$template->{text};
77   }
78
79   # If no processing is requested then return the content.
80   if (!$options->{process}) {
81     # If $template is a reference then don't try to read a file.
82     my $ref = ref $template;
83     return $template                                                                if $ref eq 'SL::Presenter::EscapedText';
84     return SL::Presenter::EscapedText->new(text => ${ $template }, is_escaped => 1) if $ref eq 'SCALAR';
85
86     # Otherwise return the file's content.
87     my $file    = IO::File->new($source, "r") || croak("Template file ${source} could not be read");
88     my $content = do { local $/ = ''; <$file> };
89     $file->close;
90
91     return SL::Presenter::EscapedText->new(text => $content, is_escaped => 1);
92   }
93
94   # Processing was requested. Set up all variables.
95   my %params = ( %locals,
96                  AUTH          => $::auth,
97                  FLASH         => $::form->{FLASH},
98                  FORM          => $::form,
99                  INSTANCE_CONF => $::instance_conf,
100                  LOCALE        => $::locale,
101                  LXCONFIG      => \%::lx_office_conf,
102                  LXDEBUG       => $::lxdebug,
103                  MYCONFIG      => \%::myconfig,
104                  PRESENTER     => $self,
105                );
106
107   my $output;
108   my $parser = $self->get_template;
109   $parser->process($source, \%params, \$output) || croak $parser->error;
110
111   return SL::Presenter::EscapedText->new(text => $output, is_escaped => 1);
112 }
113
114 sub get_template {
115   my ($self) = @_;
116
117   # Make locales.pl parse generic/exception.html, too:
118   # $::form->parse_html_template("generic/exception")
119   $self->{template} ||=
120     Template->new({ INTERPOLATE  => 0,
121                     EVAL_PERL    => 0,
122                     ABSOLUTE     => 1,
123                     CACHE_SIZE   => 0,
124                     PLUGIN_BASE  => 'SL::Template::Plugin',
125                     INCLUDE_PATH => '.:templates/webpages',
126                     COMPILE_EXT  => '.tcc',
127                     COMPILE_DIR  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
128                     ERROR        => 'templates/webpages/generic/exception.html',
129                     ENCODING     => 'utf8',
130                   }) || croak;
131
132   return $self->{template};
133 }
134
135 sub escape {
136   my ($self, $text) = @_;
137
138   return SL::Presenter::EscapedText->new(text => $text);
139 }
140
141 sub escaped_text {
142   my ($self, $text) = @_;
143
144   return SL::Presenter::EscapedText->new(text => $text, is_escaped => 1);
145 }
146
147 sub escape_js {
148   my ($self, $text) = @_;
149
150   $text =~ s|\\|\\\\|g;
151   $text =~ s|\"|\\\"|g;
152   $text =~ s|\n|\\n|g;
153
154   return SL::Presenter::EscapedText->new(text => $text, is_escaped => 1);
155 }
156
157 1;
158
159 __END__
160
161 =head1 NAME
162
163 SL::Presenter - presentation layer class
164
165 =head1 SYNOPSIS
166
167   use SL::Presenter;
168   my $presenter = SL::Presenter->get;
169
170   # Lower-level template parsing:
171   my $html = $presenter->render(
172     'presenter/dir/template.html',
173     var1 => 'value',
174   );
175
176   # Higher-level rendering of certain objects:
177   use SL::DB::Customer;
178
179   my $linked_customer_name = $presenter->customer($customer, display => 'table-cell');
180
181   # Render a list of links to sales/purchase records:
182   use SL::DB::Order;
183
184   my $quotation = SL::DB::Manager::Order->get_first(where => { quotation => 1 });
185   my $records   = $quotation->linked_records(direction => 'to');
186   my $html      = $presenter->grouped_record_list($records);
187
188 =head1 CLASS FUNCTIONS
189
190 =over 4
191
192 =item C<get>
193
194 Returns the global presenter object and creates it if it doesn't exist
195 already.
196
197 =back
198
199 =head1 INSTANCE FUNCTIONS
200
201 =over 4
202
203 =item C<render $template, [ $options, ] %locals>
204
205 Renders the template C<$template>. Provides other variables than
206 C<Form::parse_html_template> does.
207
208 C<$options>, if present, must be a hash reference. All remaining
209 parameters are slurped into C<%locals>.
210
211 This is the backend function that L<SL::Controller::Base/render>
212 calls. The big difference is that the presenter's L<render> function
213 always returns the input and never sends anything to the browser while
214 the controller's function usually sends the result to the
215 controller. Therefore the presenter's L<render> function does not use
216 all of the parameters for controlling the output that the controller's
217 function does.
218
219 What is rendered and how C<$template> is interpreted is determined
220 both by C<$template>'s reference type and by the supplied options.
221
222 If C<$template> is a normal scalar (not a reference) then it is meant
223 to be a template file name relative to the C<templates/webpages>
224 directory. The file name to use is determined by the C<type> option.
225
226 If C<$template> is a reference to a scalar then the referenced
227 scalar's content is used as the content to process. The C<type> option
228 is not considered in this case.
229
230 C<$template> can also be an instance of L<SL::Presenter::EscapedText>
231 or a reference to such an instance. Both of these cases are handled
232 the same way as if C<$template> were a reference to a scalar: its
233 content is processed, and C<type> is not considered.
234
235 Other reference types, unknown options and unknown arguments to the
236 C<type> option cause the function to L<croak>.
237
238 The following options are available:
239
240 =over 2
241
242 =item C<type>
243
244 The template type. Can be C<html> (the default), C<js> for JavaScript,
245 C<json> for JSON and C<text> for plain text content. Affects only the
246 extension that's added to the file name given with a non-reference
247 C<$template> argument.
248
249 =item C<process>
250
251 If trueish (which is also the default) it causes the template/content
252 to be processed by the Template toolkit. Otherwise the
253 template/content is returned as-is.
254
255 =back
256
257 If template processing is requested then the template has access to
258 the following variables:
259
260 =over 2
261
262 =item * C<AUTH> -- C<$::auth>
263
264 =item * C<FLASH> -- the flash instance (C<$::form-E<gt>{FLASH}>)
265
266 =item * C<FORM> -- C<$::form>
267
268 =item * C<INSTANCE_CONF> -- C<$::instance_conf>
269
270 =item * C<LOCALE> -- C<$::locale>
271
272 =item * C<LXCONFIG> -- all parameters from C<config/kivitendo.conf>
273 with the same name they appear in the file (first level is the
274 section, second the actual variable, e.g. C<system.language>,
275 C<features.webdav> etc)
276
277 =item * C<LXDEBUG> -- C<$::lxdebug>
278
279 =item * C<MYCONFIG> -- C<%::myconfig>
280
281 =item * C<SELF> -- the controller instance
282
283 =item * C<PRESENTER> -- the presenter instance the template is
284 rendered with
285
286 =item * All items from C<%locals>
287
288 =back
289
290 The function will always return the output and never send anything to
291 the browser.
292
293 Example: Render a HTML template with a certain title and a few locals
294
295   $presenter->render('todo/list',
296                      title      => 'List TODO items',
297                      TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
298
299 Example: Render a string and return its content for further processing
300 by the calling function.
301
302   my $content = $presenter->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]');
303
304 Example: Return the content of a JSON template file without processing
305 it at all:
306
307   my $template_content = $presenter->render(
308     'customer/contact',
309     { type => 'json', process => 0 }
310   );
311
312 =item C<escape $text>
313
314 Returns an HTML-escaped version of C<$text>. Instead of a string an
315 instance of the thin proxy-object L<SL::Presenter::EscapedText> is
316 returned.
317
318 It is safe to call C<escape> on an instance of
319 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
320 be returned).
321
322 =item C<escaped_text $text>
323
324 Returns an instance of L<SL::Presenter::EscapedText>. C<$text> is
325 assumed to be a string that has already been HTML-escaped.
326
327 It is safe to call C<escaped_text> on an instance of
328 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
329 be returned).
330
331 =item C<escape_js $text>
332
333 Returns a JavaScript-escaped version of C<$text>. Instead of a string
334 an instance of the thin proxy-object L<SL::Presenter::EscapedText> is
335 returned.
336
337 It is safe to call C<escape> on an instance of
338 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
339 be returned).
340
341 =item C<get_template>
342
343 Returns the global instance of L<Template> and creates it if it
344 doesn't exist already.
345
346 =back
347
348 =head1 AUTHOR
349
350 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
351
352 =cut