2 openerp.web.formats = function(openerp) {
3 var _t = openerp.web._t;
6 * Intersperses ``separator`` in ``str`` at the positions indicated by
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
13 * There are two special values:
16 * indicates the insertion should end now
18 * indicates that the previous section pattern should be repeated (until all
19 * of ``str`` is consumed)
22 * @param {Array<Number>} indices
23 * @param {String} separator
26 openerp.web.intersperse = function (str, indices, separator) {
27 separator = separator || '';
28 var result = [], last = str.length;
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)
35 } else if(section === 0 && i === 0) {
36 // repeats previous section, which there is none => stop
38 } else if (section === 0) {
39 // repeat previous section forever
40 //noinspection AssignmentToForLoopParameterJS
41 section = indices[--i];
43 result.push(str.substring(last-section, last));
47 var s = str.substring(0, last);
48 if (s) { result.push(s); }
49 return result.reverse().join(separator);
52 * Insert "thousands" separators in the provided number (which is actually
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);
65 * Formats a single atomic value based on a field descriptor
67 * @param {Object} value read from OpenERP
68 * @param {Object} descriptor union of orm field and view field
69 * @param {Object} [descriptor.widget] widget to use to display the value
70 * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
71 * @param {Object} [descriptor.digits] used for the formatting of floats
72 * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
74 openerp.web.format_value = function (value, descriptor, value_if_empty) {
75 // If NaN value, display as with a `false` (empty cell)
76 if (typeof value === 'number' && isNaN(value)) {
79 //noinspection FallthroughInSwitchStatementJS
82 if (descriptor.type === 'char') {
85 console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
89 return value_if_empty === undefined ? '' : value_if_empty;
91 var l10n = _t.database.parameters;
92 switch (descriptor.widget || descriptor.type) {
94 return openerp.web.insert_thousand_seps(
95 _.str.sprintf('%d', value));
97 var precision = descriptor.digits ? descriptor.digits[1] : 2;
98 var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
99 formatted[0] = openerp.web.insert_thousand_seps(formatted[0]);
100 return formatted.join(l10n.decimal_point);
102 return _.str.sprintf("%02d:%02d",
104 Math.round((value % 1) * 60));
106 // name_get value format
109 if (typeof(value) == "string")
110 value = openerp.web.auto_str_to_date(value);
112 return value.format(l10n.date_format
113 + ' ' + l10n.time_format);
115 if (typeof(value) == "string")
116 value = openerp.web.auto_str_to_date(value);
117 return value.format(l10n.date_format);
119 if (typeof(value) == "string")
120 value = openerp.web.auto_str_to_date(value);
121 return value.format(l10n.time_format);
123 // Each choice is [value, label]
124 if(_.isArray(value)) {
127 var result = _(descriptor.selection).detect(function (choice) {
128 return choice[0] === value;
130 if (result) { return result[1]; }
137 openerp.web.parse_value = function (value, descriptor, value_if_empty) {
138 var date_pattern = Date.normalizeFormat(_t.database.parameters.date_format),
139 time_pattern = Date.normalizeFormat(_t.database.parameters.time_format);
143 return value_if_empty === undefined ? false : value_if_empty;
145 switch (descriptor.widget || descriptor.type) {
150 value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
151 } while(tmp !== value);
154 throw new Error(value + " is not a correct integer");
157 var tmp = Number(value);
164 tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
165 } while(tmp !== tmp2);
166 var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
167 var parsed = Number(reformatted_value);
169 throw new Error(value + " is not a correct float");
172 var float_time_pair = value.split(":");
173 if (float_time_pair.length != 2)
174 return openerp.web.parse_value(value, {type: "float"});
175 var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
176 var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
177 return hours + (minutes / 60);
179 return openerp.web.parse_value(value, {type: "float"});
181 var datetime = Date.parseExact(
182 value, (date_pattern + ' ' + time_pattern));
183 if (datetime !== null)
184 return openerp.web.datetime_to_str(datetime);
185 datetime = Date.parse(value);
186 if (datetime !== null)
187 return openerp.web.datetime_to_str(datetime);
188 throw new Error(value + " is not a valid datetime");
190 var date = Date.parseExact(value, date_pattern);
192 return openerp.web.date_to_str(date);
193 date = Date.parse(value);
195 return openerp.web.date_to_str(date);
196 throw new Error(value + " is not a valid date");
198 var time = Date.parseExact(value, time_pattern);
200 return openerp.web.time_to_str(time);
201 time = Date.parse(value);
203 return openerp.web.time_to_str(time);
204 throw new Error(value + " is not a valid time");
209 openerp.web.auto_str_to_date = function(value, type) {
211 return openerp.web.str_to_datetime(value);
214 return openerp.web.str_to_date(value);
217 return openerp.web.str_to_time(value);
219 throw new Error("'" + value + "' is not a valid date, datetime nor time");
222 openerp.web.auto_date_to_str = function(value, type) {
225 return openerp.web.datetime_to_str(value);
227 return openerp.web.date_to_str(value);
229 return openerp.web.time_to_str(value);
231 throw new Error(type + " is not convertible to date, datetime nor time");
236 * Formats a provided cell based on its field type. Most of the field types
237 * return a correctly formatted value, but some tags and fields are
238 * special-cased in their handling:
240 * * buttons will return an actual ``<button>`` tag with a bunch of error handling
242 * * boolean fields will return a checkbox input, potentially disabled
244 * * binary fields will return a link to download the binary data as a file
246 * @param {Object} row_data record whose values should be displayed in the cell
247 * @param {Object} column column descriptor
248 * @param {"button"|"field"} column.tag base control type
249 * @param {String} column.type widget type for a field control
250 * @param {String} [column.string] button label
251 * @param {String} [column.icon] button icon
252 * @param {Object} [options]
253 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
254 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
255 * @param {String} [options.model] current record's model
256 * @param {Number} [options.id] current record's id
259 openerp.web.format_cell = function (row_data, column, options) {
260 options = options || {};
262 if (options.process_modifiers !== false) {
263 attrs = column.modifiers_for(row_data);
265 if (attrs.invisible) { return ''; }
267 if (column.tag === 'button') {
268 return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
269 '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
271 title: column.string || '',
272 additional_attributes: isNaN(row_data["id"].value) && openerp.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
273 'disabled="disabled" class="oe-listview-button-disabled"' : '',
274 prefix: openerp.connection.prefix,
276 alt: column.string || ''
279 if (!row_data[column.id]) {
280 return options.value_if_empty === undefined ? '' : options.value_if_empty;
283 switch (column.widget || column.type) {
285 return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
286 row_data[column.id].value ? 'checked="checked"' : '');
288 var text = _t("Download"),
289 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);
290 if (column.filename) {
291 download_url += '&filename_field=' + column.filename;
292 if (row_data[column.filename]) {
293 text = _.str.sprintf(_t("Download \"%s\""), openerp.web.format_value(
294 row_data[column.filename].value, {type: 'char'}));
297 return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
300 size: row_data[column.id].value
304 '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
305 value: row_data[column.id].value
309 return _.escape(openerp.web.format_value(
310 row_data[column.id].value, column, options.value_if_empty));