-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
632 lines (564 loc) · 19 KB
/
main.js
File metadata and controls
632 lines (564 loc) · 19 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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// main.js
// Electron main process
const { app, BrowserWindow, ipcMain, shell, Tray, Menu, nativeImage } = require('electron');
const path = require('path');
const db = require('./database/db');
const { exec } = require('child_process');
const os = require('os');
// Helper function to get local date in YYYY-MM-DD format
function getLocalDate() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
}
let mainWindow;
let tray = null;
let isQuiting = false;
/**
* Create the main application window
*/
function createWindow() {
const isMac = process.platform === 'darwin';
mainWindow = new BrowserWindow({
width: 430,
height: isMac ? 800 : 932,
resizable: true,
frame: false, // Frameless window for modern look
autoHideMenuBar: true,
backgroundColor: '#101c22',
title: 'Workflow',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('https:') || url.startsWith('http:')) {
// WSL kontrolü: Linux ise ve kernel isminde 'microsoft' geçiyorsa
if (process.platform === 'linux' && os.release().toLowerCase().includes('microsoft')) {
// Windows komut satırı üzerinden URL'i aç
exec(`cmd.exe /c start "" "${url}"`, (error) => {
if (error) {
console.error('Link açılamadı:', error);
}
});
} else {
// Normal Windows veya Mac/Linux davranışı
shell.openExternal(url);
}
}
return { action: 'deny' };
});
// Load index.html from new location
mainWindow.loadFile('src/pages/index.html');
// Open DevTools in development (disabled for production)
// mainWindow.webContents.openDevTools();
mainWindow.webContents.closeDevTools();
// Prevent default close to allow hiding to tray instead
mainWindow.on('close', function (event) {
if (!isQuiting) {
event.preventDefault();
mainWindow.hide();
}
return false;
});
}
/**
* Initialize database and create window when app is ready
*/
app.whenReady().then(() => {
db.initDatabase();
createWindow();
// System Tray Setup
const iconPath = path.join(__dirname, 'assets', 'workflow-timer.png');
// Resize icon specifically for tray to avoid large image issues on Windows
const trayIcon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 });
tray = new Tray(trayIcon);
const contextMenu = Menu.buildFromTemplate([
{
label: 'Göster',
click: () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
}
}
},
{
label: 'Çıkış',
click: () => {
isQuiting = true;
app.quit();
}
}
]);
tray.setToolTip('Workflow');
tray.setContextMenu(contextMenu);
// Toggle window visibility on click
tray.on('click', () => {
if (mainWindow) {
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
mainWindow.show();
mainWindow.focus();
}
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
/**
* Quit when all windows are closed (except on macOS)
*/
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// ============================================
// IPC Handlers for Database Operations
// ============================================
/**
* Save a work session
*/
ipcMain.handle('save-session', async (event, { name, duration, date, companyId, note }) => {
try {
const id = db.saveSession(name, duration, date, companyId, note);
return { success: true, id };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get all sessions
*/
ipcMain.handle('get-sessions', async () => {
try {
const sessions = db.getSessions();
return { success: true, sessions };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get sessions by date range
*/
ipcMain.handle('get-sessions-by-date', async (event, { startDate, endDate }) => {
try {
const sessions = db.getSessionsByDateRange(startDate, endDate);
return { success: true, sessions };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Update a session
*/
ipcMain.handle('update-session', async (event, { id, name, duration, date, companyId, note }) => {
try {
const success = db.updateSession(id, name, duration, date, companyId, note);
return { success };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Delete a session
*/
ipcMain.handle('delete-session', async (event, { id }) => {
try {
const success = db.deleteSession(id);
return { success };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Delete all sessions
*/
ipcMain.handle('delete-all-sessions', async () => {
try {
const count = db.deleteAllSessions();
return { success: true, count };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Create a company
*/
ipcMain.handle('create-company', async (event, { name, noteRequired }) => {
try {
const id = db.createCompany(name, noteRequired);
return { success: true, id };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get all companies
*/
ipcMain.handle('get-companies', async () => {
try {
const companies = db.getCompanies();
return { success: true, companies };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get a single company
*/
ipcMain.handle('get-company', async (event, { id }) => {
try {
const company = db.getCompany(id);
return { success: true, company };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Update a company
*/
ipcMain.handle('update-company', async (event, { id, name, excelColumn, noteColumn, noteRequired }) => {
try {
const success = db.updateCompany(id, name, excelColumn, noteColumn, noteRequired);
return { success };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Update company Excel configuration
*/
ipcMain.handle('update-company-excel-config', async (event, { id, excelColumn, noteColumn }) => {
try {
const success = db.updateCompanyExcelConfig(id, excelColumn, noteColumn);
return { success };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Delete a company
*/
ipcMain.handle('delete-company', async (event, { id }) => {
try {
const success = db.deleteCompany(id);
return { success };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get sessions grouped by date and company
*/
ipcMain.handle('get-sessions-grouped', async () => {
try {
const groups = db.getSessionsGroupedByDateAndCompany();
return { success: true, groups };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get detailed sessions for a specific date and company
*/
ipcMain.handle('get-sessions-by-date-company', async (event, { date, companyId }) => {
try {
const sessions = db.getSessionsByDateAndCompany(date, companyId);
return { success: true, sessions };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get a setting
*/
ipcMain.handle('get-setting', async (event, { key }) => {
try {
const value = db.getSetting(key);
return { success: true, value };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Set a setting
*/
ipcMain.handle('set-setting', async (event, { key, value }) => {
try {
db.setSetting(key, value);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get this week's total
*/
ipcMain.handle('get-week-total', async () => {
try {
const thisWeek = db.getThisWeekTotal();
const lastWeek = db.getLastWeekTotal();
return { success: true, thisWeek, lastWeek };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get current streak
*/
ipcMain.handle('get-current-streak', async () => {
try {
const streak = db.calculateCurrentStreak();
return { success: true, streak };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get today's sessions
*/
ipcMain.handle('get-today-sessions', async () => {
try {
const sessions = db.getTodaySessions();
return { success: true, sessions };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Get today's sessions summary for export
*/
ipcMain.handle('get-todays-sessions-summary', async () => {
try {
const summary = db.getTodaysSessionsSummary();
return { success: true, summary };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Export day end - sends data to Google Sheets via Apps Script
*/
/**
* Helper: Prepare export data
*/
function prepareExportData(date = null) {
// Use provided date or default to today
const targetDate = date || getLocalDate();
const summary = db.getSessionsSummaryByDate(targetDate);
const halfHourPrecision = db.getSetting('export_half_hour_precision') === 'true';
// Format duration as decimal hours
const formatDecimalHours = (seconds) => {
if (!seconds) return 0;
const hours = seconds / 3600;
if (halfHourPrecision) {
return Math.round(hours * 2) / 2;
}
return Math.round(hours * 100) / 100;
};
// Format duration for display
const formatDuration = (seconds) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return `${hours}:${minutes.toString().padStart(2, '0')}`;
};
// Prepare export data
return summary.map(item => ({
companyName: item.company_name,
excelColumn: item.excel_column,
noteColumn: item.note_column,
duration: formatDuration(item.total_duration || 0),
durationHours: formatDecimalHours(item.total_duration || 0),
durationSeconds: item.total_duration || 0,
notes: item.combined_notes || ''
}));
}
/**
* Preview day end data
*/
ipcMain.handle('preview-day-end', async (event, { date } = {}) => {
try {
const targetDate = date || getLocalDate();
const exportData = prepareExportData(targetDate);
return {
success: true,
exportData,
date: targetDate
};
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Export day end - sends data to Google Sheets via Apps Script
*/
ipcMain.handle('export-day-end', async (event, { date } = {}) => {
try {
const targetDate = date || getLocalDate();
const exportData = prepareExportData(targetDate);
// Get script URL from settings
const scriptUrl = db.getSetting('script_url');
// Prepare entries for Google Sheets
const entries = [];
// Helper to aggregate notes by column
const notesByColumn = {};
exportData.forEach(item => {
// Add hours entry (keep separate per company)
if (item.excelColumn) {
entries.push({
column: item.excelColumn.toUpperCase().replace(/[0-9]/g, ''), // Remove any numbers, keep only letters
value: item.durationHours,
type: 'hours',
company: item.companyName
});
}
// Collect notes for aggregation
if (item.noteColumn && item.notes) {
const col = item.noteColumn.toUpperCase().replace(/[0-9]/g, '');
if (!notesByColumn[col]) {
notesByColumn[col] = [];
}
// Optional: You could prefix with company name here if desired, e.g. `${item.companyName}: ${item.notes}`
// For now, adhering to user request of simple joining
notesByColumn[col].push(item.notes);
}
});
// Add aggregated notes entries
Object.keys(notesByColumn).forEach(col => {
entries.push({
column: col,
value: notesByColumn[col].join(' | '), // Join with separator
type: 'note',
company: 'Combined' // Indicating this is a combined entry
});
});
const now = new Date(targetDate + 'T00:00:00');
if (scriptUrl && entries.length > 0) {
const https = require('https');
// const url = require('url'); // Unused
// Calculate row based on local date (Day of month + 1)
const row = now.getDate() + 1;
const postData = JSON.stringify({ entries, row });
const makeRequest = (requestUrl, redirectCount = 0) => {
return new Promise((resolve, reject) => {
if (redirectCount > 5) {
reject(new Error('Too many redirects'));
return;
}
const parsedUrl = new URL(requestUrl);
const options = {
hostname: parsedUrl.hostname,
port: 443,
path: parsedUrl.pathname + parsedUrl.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, (res) => {
let data = '';
// Handle redirects
if (res.statusCode === 302 || res.statusCode === 301) {
const redirectUrl = res.headers.location;
// For GET redirects after POST
const getRequest = (getUrl) => {
return new Promise((getResolve, getReject) => {
https.get(getUrl, (getRes) => {
let getData = '';
getRes.on('data', chunk => getData += chunk);
getRes.on('end', () => {
try {
getResolve(JSON.parse(getData));
} catch {
// If not JSON, still consider it success
getResolve({ success: true, message: 'Request completed' });
}
});
}).on('error', getReject);
});
};
getRequest(redirectUrl)
.then(resolve)
.catch(reject);
return;
}
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch {
resolve({ success: true, message: 'Request completed', raw: data });
}
});
});
req.on('error', (error) => {
console.error('Request error:', error);
reject(error);
});
req.write(postData);
req.end();
});
};
try {
const result = await makeRequest(scriptUrl);
return {
success: true,
exportData,
date: targetDate,
row,
googleSheets: result
};
} catch (error) {
return {
success: true,
exportData,
date: targetDate,
row,
googleSheets: { success: false, error: error.message }
};
}
}
return {
success: true,
exportData,
date: targetDate,
googleSheets: scriptUrl ? null : { success: false, error: 'Script URL not configured' }
};
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Navigate to a different page
*/
ipcMain.handle('navigate', async (event, { page }) => {
try {
// Add src/pages/ prefix if not already present
const pagePath = page.startsWith('src/') ? page : `src/pages/${page}`;
mainWindow.loadFile(pagePath);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
/**
* Window control handlers
*/
ipcMain.on('minimize-window', () => {
if (mainWindow) {
mainWindow.hide(); // Hide completely from taskbar
}
});
ipcMain.on('close-window', () => {
if (mainWindow) {
mainWindow.hide(); // Hide completely from taskbar instead of closing
}
});