-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
327 lines (281 loc) · 11.9 KB
/
script.js
File metadata and controls
327 lines (281 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
document.addEventListener('DOMContentLoaded', () => {
const orgURL = document.querySelector("#orgURL");
const tagsContainer = document.getElementById('tags');
const inputTag = document.getElementById('input-tag');
const themeToggle = document.getElementById('theme-toggle');
const body = document.body;
let entities = new Set();
// Removed currentContextEntity as we can derive it from the DOM element
// Initialize
(async function init() {
// Theme Init
const savedTheme = localStorage.getItem('theme') || 'light';
body.setAttribute('data-theme', savedTheme);
updateThemeIcon(savedTheme);
// Restore from LocalStorage
if (localStorage.getItem("orgURL") !== null) {
orgURL.value = localStorage.getItem("orgURL");
}
if (localStorage.getItem("counterEntities") !== null) {
// Restore from storage
const storedEntities = JSON.parse(localStorage.getItem("counterEntities"));
entities = new Set(storedEntities);
renderTags();
} else {
// Load from tables.json
try {
const response = await fetch('tables.json');
const data = await response.json();
// Flatten all arrays from the json into one set
Object.values(data).forEach(categoryList => {
categoryList.forEach(e => entities.add(e));
});
updateStorage();
renderTags();
} catch (err) {
console.error("Failed to load tables.json", err);
// Fallback hardcoded list
[
"account", "contact", "email", "annotation", "team",
"systemuser", "opportunity", "lead", "incident"
].forEach(e => entities.add(e));
renderTags();
}
}
})();
// Event Listeners
inputTag.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
const tagContent = inputTag.value.trim();
inputTag.value = '';
if (tagContent !== '') {
addEntity(tagContent);
}
}
});
tagsContainer.addEventListener('click', function (event) {
const target = event.target;
// Handle Delete
if (target.classList.contains('delete-button')) {
const entityName = target.dataset.entity;
deleteEntity(entityName);
return;
}
// Handle Snapshot
if (target.classList.contains('snapshot-icon')) {
const button = target.closest('.button-tag');
if (button) {
runSnapshotCount(button.dataset.name);
}
return;
}
// Handle Peacock (Expand)
if (target.classList.contains('peacock-icon')) {
event.stopPropagation(); // Prevent main button click
const tagItem = target.closest('.tag-item');
if (tagItem) {
// Close others
document.querySelectorAll('.tag-item.active').forEach(item => {
if (item !== tagItem) item.classList.remove('active');
});
// Toggle current
tagItem.classList.toggle('active');
}
return;
}
// Handle Option Click
if (target.classList.contains('option-item')) {
event.stopPropagation();
const action = target.dataset.action;
const entity = target.dataset.entity;
runExtendedQuery(entity, action);
// Close after click
target.closest('.tag-item').classList.remove('active');
return;
}
// Handle Main Button Click (Run Count)
const button = target.closest('.button-tag');
if (button) {
runCount(button.dataset.name);
}
});
// Theme Toggle
themeToggle.addEventListener('click', () => {
const currentTheme = body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
body.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeIcon(newTheme);
});
function updateThemeIcon(theme) {
themeToggle.textContent = theme === 'dark' ? '☀️' : '🌙';
}
// Close options on outside click
document.addEventListener('click', (event) => {
if (!event.target.closest('.tag-item')) {
document.querySelectorAll('.tag-item.active').forEach(item => item.classList.remove('active'));
}
});
// Removed context menu event listener as logic is now delegated above
const validationMsg = document.getElementById('url-validation-msg');
function showValidation(msg) {
validationMsg.textContent = msg;
validationMsg.classList.add('show');
orgURL.classList.add('error'); // Assuming we add .error style to input
}
function clearValidation() {
validationMsg.classList.remove('show');
orgURL.classList.remove('error');
}
orgURL.addEventListener('input', clearValidation);
orgURL.addEventListener('change', function () {
if (orgURL.value.length === 0) return;
if (isValidURL(orgURL.value)) {
try {
const url = new URL(orgURL.value);
orgURL.value = url.origin;
localStorage.setItem("orgURL", orgURL.value);
clearValidation();
} catch (e) {
localStorage.setItem("orgURL", orgURL.value);
}
} else {
showValidation("Please enter a valid organization URL.");
}
});
// --- Core Functions ---
function renderTags() {
tagsContainer.innerHTML = '';
entities.forEach(entity => {
const tag = createTagElement(entity);
tagsContainer.appendChild(tag);
});
}
function createTagElement(entityName) {
const li = document.createElement('li');
li.className = 'tag-item';
// Note: Added options-panel inside the list item
li.innerHTML = `
<button class="button-tag" data-name="${entityName}">
<span class="delete-button" data-entity="${entityName}" title="Remove">✖</span>
${entityName}
<span class="snapshot-icon" title="Snapshot Count (for 50k+ rows)" aria-label="Snapshot Count">📷</span>
<span class="peacock-icon" title="More Options">🦚</span>
</button>
<div class="options-panel">
<div class="option-item" data-action="active" data-entity="${entityName}">Active</div>
<div class="option-item" data-action="inactive" data-entity="${entityName}">Inactive</div>
<div class="option-item" data-action="today" data-entity="${entityName}">Today</div>
<div class="option-item" data-action="last7" data-entity="${entityName}">Last 7 Days</div>
<div class="option-item" data-action="last30" data-entity="${entityName}">Last 30 Days</div>
</div>
`;
return li;
}
function addEntity(entityName) {
if (!entities.has(entityName)) {
entities.add(entityName);
updateStorage();
// Append single instead of re-render all for performance/animation
const tag = createTagElement(entityName);
tagsContainer.appendChild(tag);
}
}
function deleteEntity(entityName) {
if (entities.has(entityName)) {
entities.delete(entityName);
updateStorage();
renderTags(); // Re-render to ensure order/clean state or just remove element
}
}
function updateStorage() {
localStorage.setItem("counterEntities", JSON.stringify(Array.from(entities)));
}
function isValidURL(str) {
const regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
return regexp.test(str);
}
function getPlural(entityName) {
if (entityName.endsWith("s") || entityName.endsWith("x")) {
return entityName + "es";
} else if (entityName.endsWith("y")) {
return entityName.slice(0, -1) + "ies";
} else {
return entityName + "s";
}
}
function getSubdomain(url) {
let domain = url;
if (url.includes("://")) {
domain = url.split('://')[1];
}
let subdomain = domain.split('.')[0];
return subdomain.replaceAll('-', '_');
}
function getCountColumn(entityName) {
if (["email", "letter", "fax", "phonecall", "appointment"].includes(entityName))
return "createdon";
return entityName + "id";
}
function runCount(entityName) {
if (!orgURL.value || !isValidURL(orgURL.value)) {
showValidation("Please enter a valid organization URL then retry.");
return;
}
let pluralName = getPlural(entityName);
let countColumn = getCountColumn(entityName);
let orgName = getSubdomain(orgURL.value);
let query = `/api/data/v9.2/${pluralName}?fetchXml=<fetch mapping="logical" distinct="false" aggregate="true"><entity name="${entityName}"><attribute name="${countColumn}" alias="${pluralName}_count_in_${orgName}_instance" aggregate="count"/></entity></fetch>`;
window.open(orgURL.value + query, '_blank');
}
function runSnapshotCount(entityName) {
if (!orgURL.value || !isValidURL(orgURL.value)) {
showValidation("Please enter a valid organization URL then retry.");
return;
}
let query = `/api/data/v9.2//RetrieveTotalRecordCount(EntityNames=['${entityName}'])`;
window.open(orgURL.value + query, '_blank');
}
// Removed showContextMenu function
function runExtendedQuery(entityName, action) {
if (!orgURL.value || !isValidURL(orgURL.value)) {
showValidation("Please enter a valid organization URL.");
return;
}
let pluralName = getPlural(entityName);
let countColumn = getCountColumn(entityName);
let orgName = getSubdomain(orgURL.value);
let filter = "";
let filterName = action;
switch (action) {
case "active":
filter = `<attribute name="statecode" operator="eq" value="0" />`;
break;
case "inactive":
filter = `<attribute name="statecode" operator="eq" value="1" />`;
break;
case "today":
filter = `<attribute name="createdon" operator="today" />`;
break;
case "last7":
filter = `<attribute name="createdon" operator="last-x-days" value="7" />`;
break;
case "last30":
filter = `<attribute name="createdon" operator="last-x-days" value="30" />`;
break;
}
// Simplified fetchXML construction
let xml = `
<fetch mapping="logical" distinct="false" aggregate="true">
<entity name="${entityName}">
<attribute name="${countColumn}" alias="${pluralName}_${filterName}_count" aggregate="count"/>
<filter>
${filter}
</filter>
</entity>
</fetch>`;
let query = `/api/data/v9.2/${pluralName}?fetchXml=${encodeURIComponent(xml.replace(/\s+/g, ' ').trim())}`;
window.open(orgURL.value + query, '_blank');
}
});