-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
359 lines (295 loc) · 13.3 KB
/
Copy pathapp.js
File metadata and controls
359 lines (295 loc) · 13.3 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* MobileAPI Trade-In Estimator
*
* Demonstrates combining MobileAPI device data with custom business logic
* to estimate trade-in values. Users search for a device, see its specs,
* select condition, and get an instant value estimate.
*
* The pricing algorithm is illustrative -- real trade-in platforms would
* use market data, supply/demand signals, and more sophisticated models.
*
* Get a free API key: https://mobileapi.dev/signup/
* API docs: https://mobileapi.dev/docs/
*/
(function () {
"use strict";
const API_BASE = "https://api.mobileapi.dev";
// -----------------------------------------------------------------------
// State
// -----------------------------------------------------------------------
const state = {
device: null,
specs: {},
condition: null,
};
// -----------------------------------------------------------------------
// DOM
// -----------------------------------------------------------------------
const apiKeyInput = document.getElementById("api-key-input");
const searchInput = document.getElementById("search-input");
const dropdown = document.getElementById("dropdown");
const deviceCard = document.getElementById("device-card");
const deviceHeader = document.getElementById("device-header");
const specGrid = document.getElementById("spec-grid");
const conditionOptions = document.getElementById("condition-options");
const estimateResult = document.getElementById("estimate-result");
const estimateValue = document.getElementById("estimate-value");
const estimateRange = document.getElementById("estimate-range");
const estimateBreakdown = document.getElementById("estimate-breakdown");
const errorBanner = document.getElementById("error-banner");
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
function debounce(fn, ms) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}
function escapeHtml(s) {
const d = document.createElement("div");
d.textContent = s;
return d.innerHTML;
}
function showError(msg) {
errorBanner.textContent = msg;
errorBanner.classList.add("visible");
setTimeout(() => errorBanner.classList.remove("visible"), 6000);
}
function getApiKey() {
const key = apiKeyInput.value.trim();
if (!key) {
showError("Please enter your MobileAPI key above.");
return null;
}
return key;
}
async function apiGet(path, params = {}) {
const key = getApiKey();
if (!key) return null;
const url = new URL(`${API_BASE}${path}`);
for (const [k, v] of Object.entries(params)) {
if (v != null) url.searchParams.set(k, String(v));
}
const resp = await fetch(url.toString(), {
headers: { "Authorization": `Bearer ${key}`, "Accept": "application/json" },
});
if (!resp.ok) {
if (resp.status === 401) showError("Invalid API key.");
else if (resp.status === 429) showError("Rate limit exceeded. Please wait.");
else showError(`API error: ${resp.status}`);
return null;
}
return resp.json();
}
// -----------------------------------------------------------------------
// Autocomplete
// -----------------------------------------------------------------------
let acItems = [];
const doAutocomplete = debounce(async function (query) {
if (query.length < 2) { dropdown.classList.remove("visible"); return; }
const data = await apiGet("/devices/autocomplete/", { name: query, limit: 8 });
if (!data) return;
acItems = data.results || [];
if (acItems.length === 0) { dropdown.classList.remove("visible"); return; }
dropdown.innerHTML = acItems.map((d, i) => {
const img = d.main_image_b64
? `<img src="data:image/png;base64,${d.main_image_b64}" alt="">`
: `<div class="img-placeholder"></div>`;
return `<div class="autocomplete-item" data-index="${i}">
${img}
<div><div class="item-name">${escapeHtml(d.name)}</div></div>
</div>`;
}).join("");
dropdown.classList.add("visible");
}, 250);
searchInput.addEventListener("input", () => doAutocomplete(searchInput.value.trim()));
searchInput.addEventListener("keydown", (e) => {
if (e.key === "Escape") dropdown.classList.remove("visible");
});
dropdown.addEventListener("click", (e) => {
const item = e.target.closest(".autocomplete-item");
if (!item) return;
const idx = parseInt(item.dataset.index);
selectDevice(acItems[idx]);
dropdown.classList.remove("visible");
});
document.addEventListener("click", (e) => {
if (!e.target.closest("#search-section")) dropdown.classList.remove("visible");
});
// -----------------------------------------------------------------------
// Device selection
// -----------------------------------------------------------------------
async function selectDevice(summary) {
searchInput.value = summary.name;
deviceCard.classList.add("visible");
deviceHeader.innerHTML = `<div class="loading-spinner"></div>
<div><h2>Loading...</h2></div>`;
specGrid.innerHTML = "";
estimateResult.classList.remove("visible");
state.condition = null;
resetConditionButtons();
// Fetch device details
const device = await apiGet(`/devices/${summary.id}/`);
if (!device) return;
state.device = device;
state.specs = {};
renderDeviceHeader();
// Fetch key specs in parallel
const specKeys = ["display", "memory", "battery", "platform"];
const promises = specKeys.map(async (key) => {
const data = await apiGet(`/devices/${device.id}/${key}/`);
if (data) state.specs[key] = data;
});
await Promise.all(promises);
renderSpecGrid();
}
function renderDeviceHeader() {
const d = state.device;
const img = d.main_image_b64
? `<img src="data:image/png;base64,${d.main_image_b64}" alt="${escapeHtml(d.name)}">`
: "";
deviceHeader.innerHTML = `
${img}
<div>
<h2>${escapeHtml(d.name)}</h2>
</div>`;
}
function renderSpecGrid() {
const items = [];
const display = state.specs.display || {};
if (display.size) items.push({ label: "Display", value: display.size });
if (display.resolution) items.push({ label: "Resolution", value: display.resolution });
const memory = state.specs.memory || {};
if (memory.internal) items.push({ label: "Storage", value: memory.internal });
const battery = state.specs.battery || {};
if (battery.capacity || battery.type) {
items.push({ label: "Battery", value: battery.capacity || battery.type });
}
const platform = state.specs.platform || {};
if (platform.chipset) items.push({ label: "Chipset", value: platform.chipset });
if (platform.os) items.push({ label: "OS", value: platform.os });
specGrid.innerHTML = items.map(i =>
`<div class="spec-item">
<div class="spec-label">${escapeHtml(i.label)}</div>
<div class="spec-value">${escapeHtml(String(i.value))}</div>
</div>`
).join("");
}
// -----------------------------------------------------------------------
// Condition selection
// -----------------------------------------------------------------------
function resetConditionButtons() {
conditionOptions.querySelectorAll(".condition-btn").forEach(b => b.classList.remove("selected"));
}
conditionOptions.addEventListener("click", (e) => {
const btn = e.target.closest(".condition-btn");
if (!btn || !state.device) return;
resetConditionButtons();
btn.classList.add("selected");
state.condition = btn.dataset.condition;
calculateEstimate();
});
// -----------------------------------------------------------------------
// Trade-in pricing algorithm
// -----------------------------------------------------------------------
/**
* Estimate trade-in value based on device specs and condition.
*
* This is a simplified demonstration algorithm. Real trade-in platforms
* use market data, historical pricing, supply/demand, and more.
*
* Factors used:
* 1. Base value from device type (phone, tablet, etc.)
* 2. Age depreciation based on release year
* 3. Storage tier bonus
* 4. Condition multiplier
*/
function calculateEstimate() {
if (!state.device || !state.condition) return;
const device = state.device;
const memory = state.specs.memory || {};
const platform = state.specs.platform || {};
// --- 1. Base value by approximate device tier ---
let baseValue = 200; // Default base
// Attempt to detect premium vs budget from chipset or name
const name = (device.name || "").toLowerCase();
const chipset = (platform.chipset || "").toLowerCase();
if (name.includes("ultra") || name.includes("pro max") || name.includes("fold") || name.includes("flip")) {
baseValue = 550;
} else if (name.includes("pro") || name.includes("plus") || name.includes("+")) {
baseValue = 400;
} else if (chipset.includes("snapdragon 8") || chipset.includes("a17") || chipset.includes("a18") ||
chipset.includes("dimensity 9") || chipset.includes("exynos 2")) {
baseValue = 350;
} else if (name.includes("lite") || name.includes("fe") || name.includes("budget")) {
baseValue = 120;
}
// --- 2. Age depreciation ---
// Try to extract release year from device data
let releaseYear = null;
const currentYear = new Date().getFullYear();
// Check common places for year info
const yearMatch = (device.released || device.year || "").toString().match(/20\d{2}/);
if (yearMatch) {
releaseYear = parseInt(yearMatch[0]);
}
let ageFactor = 1.0;
if (releaseYear) {
const age = currentYear - releaseYear;
if (age <= 0) ageFactor = 1.0; // Brand new / unreleased
else if (age === 1) ageFactor = 0.75;
else if (age === 2) ageFactor = 0.55;
else if (age === 3) ageFactor = 0.35;
else if (age === 4) ageFactor = 0.20;
else ageFactor = 0.10;
} else {
ageFactor = 0.50; // Unknown age, assume mid-life
}
// --- 3. Storage bonus ---
let storageBonus = 0;
const internalStr = (memory.internal || "").toLowerCase();
const storageMatch = internalStr.match(/(\d+)\s*(gb|tb)/);
if (storageMatch) {
const size = parseInt(storageMatch[1]);
const unit = storageMatch[2];
const sizeGB = unit === "tb" ? size * 1024 : size;
if (sizeGB >= 1024) storageBonus = 80;
else if (sizeGB >= 512) storageBonus = 50;
else if (sizeGB >= 256) storageBonus = 25;
else if (sizeGB >= 128) storageBonus = 10;
}
// --- 4. Condition multiplier ---
const conditionMultipliers = {
excellent: 1.0,
good: 0.80,
fair: 0.60,
poor: 0.35,
};
const conditionMult = conditionMultipliers[state.condition] || 0.5;
// --- Calculate final estimate ---
const rawValue = (baseValue * ageFactor + storageBonus) * conditionMult;
const estimate = Math.round(rawValue / 5) * 5; // Round to nearest $5
const low = Math.max(0, Math.round((estimate * 0.85) / 5) * 5);
const high = Math.round((estimate * 1.15) / 5) * 5;
// --- Render ---
estimateValue.textContent = `$${estimate}`;
estimateRange.textContent = `Range: $${low} - $${high}`;
const ageYears = releaseYear ? `${currentYear - releaseYear} year(s)` : "Unknown";
estimateBreakdown.innerHTML = `
<div><span>Base value (device tier)</span><span>$${baseValue}</span></div>
<div><span>Age depreciation (${ageYears})</span><span>${Math.round(ageFactor * 100)}%</span></div>
<div><span>Storage bonus</span><span>+$${storageBonus}</span></div>
<div><span>Condition (${state.condition})</span><span>${Math.round(conditionMult * 100)}%</span></div>
`;
estimateResult.classList.add("visible");
}
// -----------------------------------------------------------------------
// API key persistence
// -----------------------------------------------------------------------
const savedKey = localStorage.getItem("mobileapi_key");
if (savedKey) apiKeyInput.value = savedKey;
apiKeyInput.addEventListener("change", function () {
const key = this.value.trim();
if (key) localStorage.setItem("mobileapi_key", key);
else localStorage.removeItem("mobileapi_key");
});
})();