1 (function(angular
, $, _
) {
5 angular
.module('crmSearchDisplay', CRM
.angRequires('crmSearchDisplay'))
7 .factory('searchDisplayUtils', function() {
8 function getUrl(link
, row
) {
9 var url
= replaceTokens(link
, row
);
10 if (url
.slice(0, 1) !== '/' && url
.slice(0, 4) !== 'http') {
16 function replaceTokens(str
, data
) {
17 _
.each(data
, function(value
, key
) {
18 str
= str
.replace('[' + key
+ ']', value
);
23 function formatSearchValue(row
, col
, value
) {
24 var type
= col
.dataType
,
26 if (_
.isArray(value
)) {
27 return _
.map(value
, function(val
) {
28 return formatSearchValue(row
, col
, val
);
31 if (value
&& (type
=== 'Date' || type
=== 'Timestamp') && /^\d{4}-\d{2}-\d{2}/.test(value
)) {
32 result
= CRM
.utils
.formatDate(value
, null, type
=== 'Timestamp');
34 else if (type
=== 'Boolean' && typeof value
=== 'boolean') {
35 result
= value
? ts('Yes') : ts('No');
37 else if (type
=== 'Money' && typeof value
=== 'number') {
38 result
= CRM
.formatMoney(value
);
40 result
= _
.escape(result
);
42 result
= '<a href="' + getUrl(col
.link
, row
) + '">' + result
+ '</a>';
47 function canAggregate(fieldName
, prefix
, apiParams
) {
48 // If the query does not use grouping, never
49 if (!apiParams
.groupBy
.length
) {
52 // If the column is used for a groupBy, no
53 if (apiParams
.groupBy
.indexOf(prefix
+ fieldName
) > -1) {
56 // If the entity this column belongs to is being grouped by id, then also no
57 return apiParams
.groupBy
.indexOf(prefix
+ 'id') < 0;
60 function prepareColumns(columns
, apiParams
) {
61 columns
= _
.cloneDeep(columns
);
62 _
.each(columns
, function(col
, num
) {
63 var index
= apiParams
.select
.indexOf(col
.expr
);
64 if (_
.includes(col
.expr
, '(') && !_
.includes(col
.expr
, ' AS ')) {
65 col
.expr
+= ' AS column_' + num
;
66 apiParams
.select
[index
] += ' AS column_' + num
;
68 col
.key
= _
.last(col
.expr
.split(' AS '));
73 function prepareParams(apiParams
, filters
, page
) {
74 var params
= _
.cloneDeep(apiParams
);
75 if (_
.isEmpty(params
.where
)) {
78 // Select the ids of joined entities (helps with displaying links)
79 _
.each(params
.join
, function(join
) {
80 var joinEntity
= join
[0].split(' AS ')[1],
81 idField
= joinEntity
+ '.id';
82 if (!_
.includes(params
.select
, idField
) && !canAggregate('id', joinEntity
+ '.', params
)) {
83 params
.select
.push(idField
);
86 _
.each(filters
, function(value
, key
) {
88 params
.where
.push([key
, 'CONTAINS', value
]);
92 params
.offset
= (page
- 1) * apiParams
.limit
;
93 params
.select
.push('row_count');
99 formatSearchValue
: formatSearchValue
,
100 canAggregate
: canAggregate
,
101 prepareColumns
: prepareColumns
,
102 prepareParams
: prepareParams
106 })(angular
, CRM
.$, CRM
._
);