53863e63e97695e101d3eacaf5b5c352cb864231
[odoo/odoo.git] / addons / web / static / src / js / formats.js
1
2 openerp.web.formats = function(openerp) {
3 var _t = openerp.web._t;
4
5 /**
6  * Intersperses ``separator`` in ``str`` at the positions indicated by
7  * ``indices``.
8  *
9  * ``indices`` is an array of relative offsets (from the previous insertion
10  * position, starting from the end of the string) at which to insert
11  * ``separator``.
12  *
13  * There are two special values:
14  *
15  * ``-1``
16  *   indicates the insertion should end now
17  * ``0``
18  *   indicates that the previous section pattern should be repeated (until all
19  *   of ``str`` is consumed)
20  *
21  * @param {String} str
22  * @param {Array<Number>} indices
23  * @param {String} separator
24  * @returns {String}
25  */
26 openerp.web.intersperse = function (str, indices, separator) {
27     separator = separator || '';
28     var result = [], last = str.length;
29
30     for(var i=0; i<indices.length; ++i) {
31         var section = indices[i];
32         if (section === -1 || last <= 0) {
33             // Done with string, or -1 (stops formatting string)
34             break;
35         } else if(section === 0 && i === 0) {
36             // repeats previous section, which there is none => stop
37             break;
38         } else if (section === 0) {
39             // repeat previous section forever
40             //noinspection AssignmentToForLoopParameterJS
41             section = indices[--i];
42         }
43         result.push(str.substring(last-section, last));
44         last -= section;
45     }
46
47     var s = str.substring(0, last);
48     if (s) { result.push(s); }
49     return result.reverse().join(separator);
50 };
51 /**
52  * Insert "thousands" separators in the provided number (which is actually
53  * a string)
54  *
55  * @param {String} num
56  * @returns {String}
57  */
58 openerp.web.insert_thousand_seps = function (num) {
59     var negative = num[0] === '-';
60     num = (negative ? num.slice(1) : num);
61     return (negative ? '-' : '') + openerp.web.intersperse(
62         num, _t.database.parameters.grouping, _t.database.parameters.thousands_sep);
63 };
64
65 /**
66  * removes literal (non-format) text from a date or time pattern, as datejs can
67  * not deal with literal text in format strings (whatever the format), whereas
68  * strftime allows for literal characters
69  *
70  * @param {String} value original format
71  */
72 openerp.web.strip_raw_chars = function (value) {
73     var isletter = /[a-zA-Z]/, output = [];
74     for(var index=0; index < value.length; ++index) {
75         var character = value[index];
76         if(isletter.test(character) && (index === 0 || value[index-1] !== '%')) {
77             continue;
78         }
79         output.push(character);
80     }
81     return output.join('');
82 };
83 var normalize_format = function (format) {
84     return Date.normalizeFormat(openerp.web.strip_raw_chars(format));
85 };
86 /**
87  * Formats a single atomic value based on a field descriptor
88  *
89  * @param {Object} value read from OpenERP
90  * @param {Object} descriptor union of orm field and view field
91  * @param {Object} [descriptor.widget] widget to use to display the value
92  * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
93  * @param {Object} [descriptor.digits] used for the formatting of floats
94  * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
95  */
96 openerp.web.format_value = function (value, descriptor, value_if_empty) {
97     // If NaN value, display as with a `false` (empty cell)
98     if (typeof value === 'number' && isNaN(value)) {
99         value = false;
100     }
101     //noinspection FallthroughInSwitchStatementJS
102     switch (value) {
103         case '':
104             if (descriptor.type === 'char') {
105                 return '';
106             }
107             console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
108         case false:
109         case Infinity:
110         case -Infinity:
111             return value_if_empty === undefined ?  '' : value_if_empty;
112     }
113     var l10n = _t.database.parameters;
114     switch (descriptor.widget || descriptor.type) {
115         case 'id':
116             return value.toString();
117         case 'integer':
118             return openerp.web.insert_thousand_seps(
119                 _.str.sprintf('%d', value));
120         case 'float':
121             var precision = descriptor.digits ? descriptor.digits[1] : 2;
122             var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
123             formatted[0] = openerp.web.insert_thousand_seps(formatted[0]);
124             return formatted.join(l10n.decimal_point);
125         case 'float_time':
126             var pattern = '%02d:%02d';
127             if (value < 0) {
128                 value = Math.abs(value);
129                 pattern = '-' + pattern;
130             }
131             return _.str.sprintf(pattern,
132                     Math.floor(value),
133                     Math.round((value % 1) * 60));
134         case 'many2one':
135             // name_get value format
136             return value[1];
137         case 'datetime':
138             if (typeof(value) == "string")
139                 value = openerp.web.auto_str_to_date(value);
140
141             return value.toString(normalize_format(l10n.date_format)
142                         + ' ' + normalize_format(l10n.time_format));
143         case 'date':
144             if (typeof(value) == "string")
145                 value = openerp.web.auto_str_to_date(value);
146             return value.toString(normalize_format(l10n.date_format));
147         case 'time':
148             if (typeof(value) == "string")
149                 value = openerp.web.auto_str_to_date(value);
150             return value.toString(normalize_format(l10n.time_format));
151         case 'selection': case 'statusbar':
152             // Each choice is [value, label]
153             if(_.isArray(value)) {
154                  value = value[0]
155             }
156             var result = _(descriptor.selection).detect(function (choice) {
157                 return choice[0] === value;
158             });
159             if (result) { return result[1]; }
160             return;
161         default:
162             return value;
163     }
164 };
165
166 openerp.web.parse_value = function (value, descriptor, value_if_empty) {
167     var date_pattern = normalize_format(_t.database.parameters.date_format),
168         time_pattern = normalize_format(_t.database.parameters.time_format);
169     switch (value) {
170         case false:
171         case "":
172             return value_if_empty === undefined ?  false : value_if_empty;
173     }
174     switch (descriptor.widget || descriptor.type) {
175         case 'integer':
176             var tmp;
177             do {
178                 tmp = value;
179                 value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
180             } while(tmp !== value);
181             tmp = Number(value);
182             if (isNaN(tmp))
183                 throw new Error(value + " is not a correct integer");
184             return tmp;
185         case 'float':
186             var tmp = Number(value);
187             if (!isNaN(tmp))
188                 return tmp;
189
190             var tmp2 = value;
191             do {
192                 tmp = tmp2;
193                 tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
194             } while(tmp !== tmp2);
195             var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
196             var parsed = Number(reformatted_value);
197             if (isNaN(parsed))
198                 throw new Error(value + " is not a correct float");
199             return parsed;
200         case 'float_time':
201             var factor = 1;
202             if (value[0] === '-') {
203                 value = value.slice(1);
204                 factor = -1;
205             }
206             var float_time_pair = value.split(":");
207             if (float_time_pair.length != 2)
208                 return factor * openerp.web.parse_value(value, {type: "float"});
209             var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
210             var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
211             return factor * (hours + (minutes / 60));
212         case 'progressbar':
213             return openerp.web.parse_value(value, {type: "float"});
214         case 'datetime':
215             var datetime = Date.parseExact(
216                     value, (date_pattern + ' ' + time_pattern));
217             if (datetime !== null)
218                 return openerp.web.datetime_to_str(datetime);
219             datetime = Date.parse(value);
220             if (datetime !== null)
221                 return openerp.web.datetime_to_str(datetime);
222             throw new Error(value + " is not a valid datetime");
223         case 'date':
224             var date = Date.parseExact(value, date_pattern);
225             if (date !== null)
226                 return openerp.web.date_to_str(date);
227             date = Date.parse(value);
228             if (date !== null)
229                 return openerp.web.date_to_str(date);
230             throw new Error(value + " is not a valid date");
231         case 'time':
232             var time = Date.parseExact(value, time_pattern);
233             if (time !== null)
234                 return openerp.web.time_to_str(time);
235             time = Date.parse(value);
236             if (time !== null)
237                 return openerp.web.time_to_str(time);
238             throw new Error(value + " is not a valid time");
239     }
240     return value;
241 };
242
243 openerp.web.auto_str_to_date = function(value, type) {
244     try {
245         return openerp.web.str_to_datetime(value);
246     } catch(e) {}
247     try {
248         return openerp.web.str_to_date(value);
249     } catch(e) {}
250     try {
251         return openerp.web.str_to_time(value);
252     } catch(e) {}
253     throw new Error("'" + value + "' is not a valid date, datetime nor time");
254 };
255
256 openerp.web.auto_date_to_str = function(value, type) {
257     switch(type) {
258         case 'datetime':
259             return openerp.web.datetime_to_str(value);
260         case 'date':
261             return openerp.web.date_to_str(value);
262         case 'time':
263             return openerp.web.time_to_str(value);
264         default:
265             throw new Error(type + " is not convertible to date, datetime nor time");
266     }
267 };
268
269 /**
270  * Formats a provided cell based on its field type. Most of the field types
271  * return a correctly formatted value, but some tags and fields are
272  * special-cased in their handling:
273  *
274  * * buttons will return an actual ``<button>`` tag with a bunch of error handling
275  *
276  * * boolean fields will return a checkbox input, potentially disabled
277  *
278  * * binary fields will return a link to download the binary data as a file
279  *
280  * @param {Object} row_data record whose values should be displayed in the cell
281  * @param {Object} column column descriptor
282  * @param {"button"|"field"} column.tag base control type
283  * @param {String} column.type widget type for a field control
284  * @param {String} [column.string] button label
285  * @param {String} [column.icon] button icon
286  * @param {Object} [options]
287  * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
288  * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
289  * @param {String} [options.model] current record's model
290  * @param {Number} [options.id] current record's id
291  *
292  */
293 openerp.web.format_cell = function (row_data, column, options) {
294     options = options || {};
295     var attrs = {};
296     if (options.process_modifiers !== false) {
297         attrs = column.modifiers_for(row_data);
298     }
299     if (attrs.invisible) { return ''; }
300
301     if (column.tag === 'button') {
302         return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
303             '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
304             '</button>', {
305                 title: column.string || '',
306                 additional_attributes: isNaN(row_data["id"].value) && openerp.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
307                     'disabled="disabled" class="oe-listview-button-disabled"' : '',
308                 prefix: openerp.connection.prefix,
309                 icon: column.icon,
310                 alt: column.string || ''
311             });
312     }
313     if (!row_data[column.id]) {
314         return options.value_if_empty === undefined ? '' : options.value_if_empty;
315     }
316
317     switch (column.widget || column.type) {
318     case "boolean":
319         return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
320                  row_data[column.id].value ? 'checked="checked"' : '');
321     case "binary":
322         var text = _t("Download"),
323             download_url = _.str.sprintf('/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d', openerp.connection.session_id, options.model, column.id, options.id);
324         if (column.filename) {
325             download_url += '&filename_field=' + column.filename;
326             if (row_data[column.filename]) {
327                 text = _.str.sprintf(_t("Download \"%s\""), openerp.web.format_value(
328                         row_data[column.filename].value, {type: 'char'}));
329             }
330         }
331         return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
332             text: text,
333             href: download_url,
334             size: row_data[column.id].value
335         });
336     case 'progressbar':
337         return _.template(
338             '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
339                 value: _.str.sprintf("%.0f", row_data[column.id].value || 0)
340             });
341     }
342
343     return _.escape(openerp.web.format_value(
344             row_data[column.id].value, column, options.value_if_empty));
345 }
346
347 };