-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
1646 lines (1414 loc) · 59.8 KB
/
index.js
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const moment = require('moment-timezone')
const path = require('path')
const activeCollab = require('./MyActiveCollabClient')
const toggl = require('./MyTogglClient')
const schedule = require('node-schedule')
const AsyncSingleInstance = require('./AsyncSingleInstance')
const config = require('./MyConfig')
const argv = require('./MyCommandLineArguments')
const eventEmitter = require('./MyEventEmitter')
var TimeEntriesRetrieveDuration = moment.duration(
config.TimeEntriesRetrieveDuration || { weeks: 2 }
)
var TimeEntiresAfter = null
if (config.TimeEntiresAfter) {
TimeEntiresAfter = moment(config.TimeEntiresAfter, 'YYYY/MM/DD')
}
const { timeMappings, clientMappings, projectMappings } = require('./MyMappings')
const NodeCache = require('node-cache')
const projectTasksCache = new NodeCache({
useClones: false,
deleteOnExpire: true,
stdTTL: config.projectTasksCacheTTLSeconds || 300 // 5 Minutes retention TTL is in seconds.
})
Main()
.then(result => {
console.log(result)
})
.catch(err => {
console.error(err, err.stack)
})
/* Application Specific methods/tasks. */
// Ensure these operations do not execute whilst they are already operating.
const singleInstanceSyncCompanies = new AsyncSingleInstance(SyncCompanies)
const singleInstanceSyncProjects = new AsyncSingleInstance(SyncProjects)
const singleInstanceSyncTimeEntries = new AsyncSingleInstance(SyncTimeEntries)
// Run our initial start up checks and initial syncs.
// The sequental calling and order of these operations is intended.
async function Main () {
await ConfigCheck()
var activeCollabToken = activeCollab.getToken()
if (activeCollabToken === '') {
try {
await activeCollab.issueToken()
var token = activeCollab.getToken()
if (token === undefined || token === '') {
console.error('Active Collab Token is not set!')
}
console.log(`Active Collab Token is: ${token} you may set this in your config file as key apiToken on the ActiveCollab object to persist it.`)
} catch (e) {
console.error('Unable to issue a token from Active Collab.')
throw e
}
}
await LoadPlugins()
await LoadMappings()
await eventEmitter.emit('startup')
await singleInstanceSyncCompanies.run()
await singleInstanceSyncProjects.run()
await singleInstanceSyncTimeEntries.run()
await InitScheduledTasks()
}
const plugins = []
async function LoadPlugins () {
if (config.plugins) {
Object.entries(config.plugins).sort((a, b) => {
return (a[1].pluginOrder || 0) - (b[1].pluginOrder || 0)
}).forEach(
([pluginName, pluginConfig]) => {
var scriptName = pluginName
pluginConfig.name = pluginName
// Allow for multiple plugin config entries to exist.
if (pluginConfig.scriptName) {
scriptName = pluginConfig.scriptName
}
if (pluginConfig.enabled) {
console.log(`Loading Plugin: ${pluginName}`)
var plugin = require('./plugins/' + scriptName)
if (plugin.init instanceof Function) {
plugin.init(pluginConfig)
}
plugins.push(plugin)
}
}
)
}
}
async function ConfigCheck () {
if (config.verbose) {
argv.verbose = config.verbose
}
if (argv.verbose) {
console.log(`Config Check`)
}
// We require the workspaceId in toggl to be set.
if (!config.Toggl.workspaceId) {
// If workspace name is given in the config we can attempt to look up the id.
if (config.Toggl.workspace) {
console.log(
`Attempting to find Toggl workspace id for '${config.Toggl.workspace}'.`
)
// Get the Toggl work spaces and find workspace id.
let workspaces = await toggl.getWorkspacesAsync()
// Get the workspaceId based on workspace name.
for (let index = 0; index < workspaces.length; ++index) {
let workspace = workspaces[index]
if (workspace.name === config.Toggl.workspace) {
config.Toggl.workspaceId = workspace.id
console.log(
`Toggl workspace id found '${
config.Toggl.workspace
}' you should set Toggl.workspaceId in your config to ${
workspace.id
}.`
)
break
}
}
if (!config.Toggl.workspaceId) {
throw new Error(
'Expecting config.Toggl.workspaceId to be set. Please get the id from the URL on the appropriate Toggl workspace page.'
)
}
} else {
throw new Error(
'Expecting config.Toggl.workspaceId to be set. Please get the id from the URL on the appropriate Toggl workspace page.'
)
}
}
// We also require other settings.
if (
!config.togglToActiveCollabUserMapping ||
Object.keys(config.togglToActiveCollabUserMapping).length === 0
) {
// Be helpful, list out the Toggl workspace users.
var togglWorkspaceUsers = await toggl.getWorkspaceUsersAsync(
config.Toggl.workspaceId,
true
)
togglWorkspaceUsers.forEach(user => {
console.log(`ID: ${user.id} Name: ${user.fullname} Email: ${user.email}`)
})
// Note: We could get users from active collab, and guess mapping to toggl ones by name match?
// We would need to know the Company name or id however.
// people/PeopleId/users
throw new Error(
"Expecting config.togglToActiveCollabUserMapping to map the Toggl User ID's to Active Collab User ID's.\nExample: { \"2108110\": 925 }"
)
}
if ( !config.ActiveCollab ) {
throw new Error("Expecting config.ActiveCollab to be set.")
}
if ( !config.ActiveCollab.apiToken ) {
console.info("Active Collab API token is not set.")
}
// TODO: Check other settings such as Self Hosted, Account ID, URL etc etc, although these are checked in the MyActiveCollabClient.js as well so may not need to check them here?
if (config.redirectFilters !== undefined) {
if (Array.isArray(config.redirectFilters) === false) {
throw new Error('Expecting config.redirectFilters if set to be an array.')
}
config.redirectFilters.forEach(filter => {
if (filter.targetIssueNumber === undefined) {
if (filter.skipTimeEntryIfMatched) {
// It's okay.
} else {
throw new Error('Expecting redirect filter to have a targetIssueNumber set.')
}
}
})
}
}
/**
* Load historical record mappings for comparison.
*/
async function LoadMappings () {
await clientMappings.load()
await projectMappings.load()
await timeMappings.load()
}
/**
* Copy the companies from Active Collab as Toggl Clients.
*/
async function SyncCompanies () {
try {
var response = await activeCollab.get('companies')
if (response.statusText !== 'OK') {
throw new Error('Getting companies did not return OK.')
}
var activeCollabCompanies = response.data
} catch (e) {
console.error('Unable to get companies from Active Collab')
throw e
}
for (const company of activeCollabCompanies) {
// TODO: A way to skip specific records?
// TODO: Exclude specific companies.
// Both of these can be done with a plugin if emitted here.
// TODO: Ignore trashed and archived?
// if (company.is_trashed) {
// continue;
// }
try {
let clientMapping = await TogglTryCreateClient(company)
await clientMappings.store(clientMapping.togglId, clientMapping)
} catch (e) {
console.error('Unable to save company as a client in Toggl.')
throw e;
}
}
}
/**
* Copy the projects from Active Collab as Toggl Projects.
*/
async function SyncProjects () {
try {
var response = await activeCollab.get('projects')
if (response.statusText !== 'OK') {
throw new Error('Getting projects did not return OK.')
}
var activeCollabProjects = response.data
} catch (e) {
console.error('Unable to get projects from Active Collab')
throw e
}
// TODO: Resolve an issue where projects for archived clients are attempted to map.
for (const project of activeCollabProjects) {
// TODO: A way to skip specific records?
// TODO: Exclude projects for specific companies.
// TOOD: Ignore trashed and archived?
// if (project.is_trashed || project.is_archived) {
// continue
// }
let projectMapping = await TogglTryCreateProject(project)
if (projectMapping) {
await projectMappings.store(projectMapping.togglId, projectMapping)
}
}
}
async function processTimeEntrySyncResults (results) {
console.log('Sync finished with results.', new Date())
}
async function processTimeEntrySyncError (error) {
console.error('Error syncing time entries: ', error)
}
async function processSyncCompaniesAndProjectsError (error) {
console.error('Error syncing companies/projects: ', error)
}
async function InitScheduledTasks () {
// Sync Companies and Projects.
schedule.scheduleJob(
config.Schedule.CompaniesAndProjects || '0 * * * *',
function SyncCompaniesAndProjectsScheduledJob () {
singleInstanceSyncCompanies.run()
.then(singleInstanceSyncProjects.run())
.catch(processSyncCompaniesAndProjectsError)
}
)
// Sync Time Entries.
schedule.scheduleJob(
config.Schedule.TimeEntries || '*/5 * * * *',
function SyncTimeEntriesScheduledJob () {
singleInstanceSyncTimeEntries.run()
.then(processTimeEntrySyncResults)
.catch(processTimeEntrySyncError)
}
)
}
/* Misc utility functions. */
/**
* Used to prevent null or undefined showing up when dealing with optional values.
* @param {*} value
*/
function toEmptyStringOrValue (value) {
if (value === null || value === undefined) {
return ''
}
return value
}
/* Helper Methods to sync to Toggl from Active Collab. */
/**
* Attempt to create a Client in Toggl.
* If a previous mapping record is found then it will be used.
* Otherwise create the Client and store a mapping record.
* @param {*} clientInfo
*/
async function TogglTryCreateClient (clientInfo) {
// Get from mapping if already there we can just return if unmodified.
var previousMapping = clientMappings.find(function (mappedClientRecord) {
return mappedClientRecord.activeCollabId === clientInfo.id
})
// Check if record would be same as what we already mapped.
// If so we can return doing nothing.
if (
previousMapping &&
previousMapping.activeCollabName === clientInfo.name &&
previousMapping.activeCollabId === clientInfo.id
) {
// Note: We are assuming Toggl client has not changed.
return previousMapping
} else if (previousMapping && previousMapping.activeCollabName !== clientInfo.name && previousMapping.activeCollabId === clientInfo.id) {
// If the previous mapping exists, and the id matches but the name does not.
// Then Update the cilent in Toggl and store the updated mapping.
// If unable to update because name already exists then delete the previous mapping and attempt to create it again as another syncing may have already done this.
try {
let result = await toggl.updateClientAsync(previousMapping.togglId, {
id: previousMapping.togglId,
name: clientInfo.name, // Name required and should be unique per workspace.
wid: config.Toggl.workspaceId, // The workspace ID is required.
notes: toEmptyStringOrValue(clientInfo.note)
})
var activeCollabTimestamp = clientInfo.updated_on
? clientInfo.updated_on
: clientInfo.created_on
previousMapping.activeCollabLastUpdated = new Date(activeCollabTimestamp * 1000 ).toISOString()
previousMapping.togglName = clientInfo.name
previousMapping.togglLastUpdated = new Date().toISOString()
return previousMapping
} catch (e) {
if (
e.code === 400 &&
(e.data.startsWith('Name has already been taken') || err.data.startsWith('Missing or invalid client ID'))
) {
if (argv.verbose > 5) {
console.log(`Client Name ${clientInfo.name} already exists in Toggl getting it's information and removing old mapping.`)
}
// Delete the previous mapping.
await clientMappings.delete(previousMapping.togglId)
// Continue on to create or get existing client in/from Toggl.
} else {
console.error(`Error updating toggl client.`, e)
throw e
}
}
}
let clientMapping = await TogglCreateClient(clientInfo)
await clientMappings.store(clientMapping.togglId, clientMapping)
return clientMapping
}
var tempCache = {}
/**
* Create a Client in Toggl.
* Returns the Client Mapping.
* @param {*} clientInfo
*/
async function TogglCreateClient (clientInfo) {
// Relevant documentation:
// http://7eggs.github.io/node-toggl-api/TogglClient.html#createClient
// https://github.com/toggl/toggl_api_docs/blob/master/chapters/clients.md
// https://developers.activecollab.com/api-documentation/v1/people/companies/companies.html
try {
var result = await toggl.createClientAsync({
name: clientInfo.name, // Name required and should be unique per workspace.
wid: config.Toggl.workspaceId, // The workspace ID is required.
notes: toEmptyStringOrValue(clientInfo.note)
})
if (argv.verbose > 5) {
console.log(
`Toggl Client created: ${clientInfo.name}, ${clientInfo.id} => ${
result.id
}.`
)
}
var activeCollabTimestamp = clientInfo.updated_on
? clientInfo.updated_on
: clientInfo.created_on
var mapping = {
sync: true,
activeCollabName: clientInfo.name,
activeCollabId: clientInfo.id,
activeCollabLastUpdated: new Date(
activeCollabTimestamp * 1000
).toISOString(),
togglName: result.name,
togglId: result.id,
togglLastUpdated: new Date().toISOString() // Not as reliable, toggl does not seem to give us back the date last updated/created for the Client records.
}
return mapping
} catch (err) {
// Special handling if name already taken, get the existing one and map to it.
if (
err.code === 400 &&
err.data.startsWith('Name has already been taken')
) {
if (argv.verbose > 5) {
console.log(`Client Name ${clientInfo.name} already taken getting it's information.`)
}
if (tempCache.clients === undefined) {
clearTimeout(tempCache.clearClientsTimeout)
tempCache.clearClientsTimeout = setTimeout(() => {
delete tempCache.clients
}, 300000) // Keep this for 5 minutes.
tempCache.clients = await toggl.getClientsAsync()
}
for (let index = 0; index < tempCache.clients.length; index++) {
var togglClient = tempCache.clients[index]
if (
togglClient.name === clientInfo.name &&
togglClient.wid === config.Toggl.workspaceId
) {
activeCollabTimestamp = clientInfo.updated_on
? clientInfo.updated_on
: clientInfo.created_on
return {
sync: true,
activeCollabName: clientInfo.name,
activeCollabId: clientInfo.id,
activeCollabLastUpdated: new Date(
activeCollabTimestamp * 1000
).toISOString(),
togglName: togglClient.name,
togglId: togglClient.id,
togglLastUpdated: new Date().toISOString()
}
}
}
}
console.error(
`Toggl Client create failed: ${clientInfo.name} ${err.code} ${err.data}.`
)
throw err
}
}
/**
* Attempt to create a Project in Toggl.
* If a previous mapping record is found then it will be used.
* Otherwise create the Project and store a mapping record.
* @param {*} projectInfo
*/
async function TogglTryCreateProject (projectInfo) {
// Get from mapping if already there we can just return the previous mapping if no updates are required.
var previousMapping = projectMappings.find(function (mappedProjectRecord) {
return mappedProjectRecord.activeCollabProjectId === projectInfo.id
})
// Check if record would be same as what we already mapped.
// If so we can return doing nothing. Note: Does not check billable status!
if (
previousMapping &&
previousMapping.activeCollabName === projectInfo.name &&
previousMapping.activeCollabCompanyId === projectInfo.company_id &&
previousMapping.activeCollabProjectId === projectInfo.id
) {
// Note: We are assuming the Toggl project has not changed.
return previousMapping
} else if (
previousMapping &&
previousMapping.activeCollabName !== projectInfo.name &&
previousMapping.activeCollabProjectId === projectInfo.id
) {
// If the previous mapping exists, and the id matches but the name or client do not.
// Then Update the project in Toggl and store the updated mapping.
// If unable to update because name already exists then delete the previous mapping and attempt to create it again as another syncing may have already done this.
// Find mapping for the company id.
//
var clientMapping = clientMappings.find(function (mappedClientRecord) {
return mappedClientRecord.activeCollabId === projectInfo.company_id
})
if (!clientMapping) {
throw new Error(`Unable to find client mapping for active collab project ${projectInfo.name}`)
}
try {
let result = await toggl.updateProjectAsync(previousMapping.togglId, {
id: previousMapping.togglId,
cid: clientMapping.togglId,
name: projectInfo.name, // Name required and should be unique per workspace.
wid: config.Toggl.workspaceId, // The workspace ID is required.
})
var activeCollabTimestamp = projectInfo.updated_on
? projectInfo.updated_on
: projectInfo.created_on
previousMapping.activeCollabLastUpdated = new Date(activeCollabTimestamp * 1000 ).toISOString()
previousMapping.togglName = projectInfo.name
previousMapping.togglLastUpdated = new Date().toISOString()
return previousMapping
} catch (e) {
if (
e.code === 400 &&
(e.data.startsWith('Name has already been taken') || err.data.startsWith('Missing or invalid project ID'))
) {
if (argv.verbose > 5) {
console.log(`Project Name ${projectInfo.name} already exists in Toggl getting it's information and removing old mapping.`)
}
// Delete the previous mapping.
await projectMappings.delete(previousMapping.togglId)
// Continue on to create or get existing project in/from Toggl.
} else {
console.error(`Error updating toggl project.`, e)
throw e
}
}
}
return TogglCreateProject(projectInfo)
}
/**
* Create the project in Toggl and return the mapping.
* @param {*} projectInfo
*/
async function TogglCreateProject (projectInfo) {
// TODO: Decide if we want to ignore is_completed: 1 or by project state?
var togglClientMapping = clientMappings.find(function (mappedClientRecord) {
return mappedClientRecord.activeCollabId === projectInfo.company_id
})
if (!togglClientMapping) {
console.error(
`Toggl Client mapping not found for Active Collab Project ${
projectInfo.name
} ${projectInfo.company_id}.`
)
return null
}
try {
var result = await toggl.createProjectAsync({
name: projectInfo.name, // Note: Name should be unique for client and workspace (Not really a concern for my usage.)
wid: config.Toggl.workspaceId,
cid: togglClientMapping.togglId,
active: true,
is_private: false,
billable: projectInfo.is_billable, // Note: Might not work in free version of Toggl?
color: Math.floor(Math.random() * 15) // 15 colors. Taste the rainbow.
// rate: 9001, // We don't use Rate.
})
if (argv.verbose > 5) {
console.log(
`Toggl Project created: ${projectInfo.name}, ${projectInfo.id} => ${
result.id
}.`
)
}
var activeCollabTimestamp = projectInfo.updated_on
? projectInfo.updated_on
: projectInfo.created_on
var mapping = {
sync: true,
activeCollabName: projectInfo.name,
activeCollabCompanyId: projectInfo.company_id,
activeCollabProjectId: projectInfo.id,
activeCollabLastUpdated: new Date(
activeCollabTimestamp * 1000
).toISOString(),
togglName: result.name,
togglId: result.id,
togglClientId: togglClientMapping.togglId,
togglLastUpdated: result.at,
togglColor: result.color,
togglColorHex: result.hex_color
}
return mapping
} catch (err) {
// Special handling if name already taken, get the existing one and map to it.
if (
err.code === 400 &&
err.data.startsWith('Name has already been taken')
) {
if (argv.verbose > 5) {
console.log(`Project Name ${projectInfo.name} already taken getting it's information.`)
}
let clientsProjects = await toggl.getClientProjectsAsync(
togglClientMapping.togglId,
'both'
)
for (let index = 0; index < clientsProjects.length; index++) {
var togglProject = clientsProjects[index]
if (
togglProject.name === projectInfo.name &&
togglProject.wid === config.Toggl.workspaceId
) {
activeCollabTimestamp = projectInfo.updated_on
? projectInfo.updated_on
: projectInfo.created_on
return {
sync: true,
activeCollabName: projectInfo.name,
activeCollabCompanyId: projectInfo.company_id,
activeCollabProjectId: projectInfo.id,
activeCollabLastUpdated: new Date(
activeCollabTimestamp * 1000
).toISOString(),
togglName: togglProject.name,
togglId: togglProject.id,
togglClientId: togglClientMapping.togglId,
togglLastUpdated: togglProject.at,
togglColor: togglProject.color,
togglColorHex: togglProject.hex_color
}
}
}
}
console.error(
`Toggl Project create failed: ${projectInfo.name} ${err.code} ${
err.data
}.`
)
throw err
}
}
/**
* Return the tasks on an Active Collab project.
* @param {*} activeCollabProjectId
*/
async function getActiveCollabProjectTasks (activeCollabProjectId) {
var projectTasks = projectTasksCache.get(activeCollabProjectId)
// If the Project Tasks were not found in the cache then get them from Active Collab and store them in the cache.
if (projectTasks === undefined) {
try {
var result = await activeCollab.get(`projects/${activeCollabProjectId}/tasks`)
if (result.statusText !== 'OK') {
throw new Error(`Getting Active Collabs tasks for project ${activeCollabProjectId} returned a non OK status.`)
}
var activeCollabTasks = result.data.tasks || null
// Additionally get any "Archived" (e.g. completed) tasks.
var archivedResult = await activeCollab.get(`projects/${activeCollabProjectId}/tasks/archive`)
if (result.statusText !== 'OK') {
console.warn(`Getting Active Collabs Archived tasks for project ${activeCollabProjectId} returned a non OK status.`)
} else {
if (Array.isArray(archivedResult.data)) {
if (activeCollabTasks === null) {
activeCollabTasks = archivedResult.data
} else {
activeCollabTasks = activeCollabTasks.concat(archivedResult.data)
}
}
}
} catch (e) {
console.error('Unable to get Active Collab tasks.')
throw e
}
if (activeCollabTasks === null) {
console.log(`No tasks found for Project ID: ${activeCollabProjectId}`);
return [];
}
// TODO: Remove trashed tasks from the tasks array as to not add time to them?
// Reduce the array of objects down to key on task number.
projectTasks = activeCollabTasks.reduce(function (obj, item) {
obj[item.task_number] = item
return obj
}, {})
projectTasksCache.set(activeCollabProjectId, projectTasks)
}
return projectTasks
}
// TODO: A way to sync over project active status if marked inactive in activeCollab.
// TODO: A way to deactivate clients and projects should they be deactivated in activeCollab.
/* Helper Methods to sync to Active Collab from Toggl. */
async function applyRedirectFilter (timeEntry, previousTimeEntry) {
if (config.redirectFilters) {
// if (Array.isArray(timeEntry.tags) && timeEntry.tags.includes('DEBUG')) {
// debugger
// }
config.redirectFilters.some(filter => {
// Pattern.
if (filter.pattern && timeEntry.description.match(filter.pattern) === null) {
return false
}
// TogglProjectId wild card or exact match.
if (filter.togglProjectId && !(filter.toggglProjectId === '*' || timeEntry.pid === filter.togglProjectId)) {
return false
}
// ProjectID wild card or exact match.
if (filter.activeCollabProjectId && !(filter.activeCollabProjectId === '*' || timeEntry.activeCollabProjectId === filter.activeCollabProjectId)) {
return false
}
// Project ID in array.
if (filter.projects && Array.isArray(filter.projects) && filter.projects.includes(timeEntry.activeCollabProjectId) === false) {
return false
}
if (filter.issueNumber !== undefined) {
if (filter.issueNumber === null) {
if (timeEntry.issueNumber !== null && timeEntry.issueNumber !== undefined) {
return false
}
} else if (timeEntry.issueNumber !== filter.issueNumber) {
return false
}
}
// Includes tag from
if (filter.tags) {
if (Array.isArray(timeEntry.tags) === false) {
return false
} else if (Array.isArray(filter.tags)) {
if (filter.tags.reduce((accumulator, tag) => {
return (timeEntry.tags.indexOf(tag) > -1) ? accumulator + 1 : accumulator
}, 0) !== filter.tags.length) {
return false
}
} else if (timeEntry.tags.includes(filter.tags) === false) {
return false
}
}
if (filter.excludeTags && timeEntry.tags) {
if (Array.isArray(filter.excludeTags) && filter.excludeTags.some(tag => {
return timeEntry.tags.includes(tag)
}) === true) {
return false
}
}
if (filter.skipTimeEntryIfMatched) {
timeEntry.skip = true
}
// Fail if error on billable is set to true and timeEntry is marked as billable.
if (filter.errorOnBillable === true && timeEntry.billable === true) {
// Fail as billable would have been met by this filter.
throw new Error('Filter error on billable. ' + timeEntry.date + ' ' + timeEntry.description)
}
// Over-ride values with the target values.
if (filter.targetProjectId) {
timeEntry.activeCollabProjectId = filter.targetProjectId
}
timeEntry.issueNumber = filter.targetIssueNumber
timeEntry.redirectFilterApplied = true
// Exit this loop as a filter is applied.
return true
})
}
}
async function fireTagEvents (timeEntryMapping, previousTimeEntryMapping) {
// Get new and previous tags if set.
var newTags = timeEntryMapping.tags
var previousTags = previousTimeEntryMapping ? previousTimeEntryMapping.tags : []
// Work around tags not being set, if no tags set Toggl's tags key is not present.
if (newTags === undefined) {
newTags = []
}
if (previousTags === undefined) {
previousTags = []
}
// Fire an event of tagAdded if a tag in newTags is not present in previousTags.
// Fire an event of tagRemoved if a tag in previousTags is not present in newTags.
newTags = newTags.reduce((obj, tag) => {
obj[tag] = true
return obj
}, {})
previousTags = previousTags.reduce((obj, tag) => {
obj[tag] = true
return obj
}, {})
for (let tag in previousTags) {
if (newTags[tag] === undefined) {
try {
await eventEmitter.emit('tagRemoved', { tag: tag, mapping: timeEntryMapping, previousMapping: previousTimeEntryMapping })
} catch (error) {
console.error(`Error executing tagRemoved event: `, error)
}
}
}
for (let tag in newTags) {
if (previousTags[tag] === undefined) {
try {
await eventEmitter.emit('tagAdded', { tag: tag, mapping: timeEntryMapping, previousMapping: previousTimeEntryMapping })
} catch (error) {
console.error(`Error executing tagadded event: `, error)
}
}
}
}
// duration = (duration / 3600).toFixed(2); // toFixed rounds we might want to ceiling if there is a preference to not loose time but that charging more rounding up to a minute is ok?
// Note: The precision in Active Collab only allows for (2 decimal places) the minimum value we can have is 0.01 so 36 seconds.
// Duration is in seconds.
// We need it in decimal hours for Active Collab. Eg 1.5 is 1 hour 30 minutes it appears to have a 36 second minimum precision.
function durationSecondsToHours(seconds) {
return Math.max((Math.round(seconds / 36) * 36) / 3600, 0.01).toFixed(
2
)
}
// Note: The TogglAPI may impose a rate limit I saw the following in their documentation.
// I have not actually encountered a limit however.
// TogglAPI: For rate limiting we have implemented a Leaky bucket.
// When a limit has been hit the request will get a HTTP 429 response and it's the task of the client to sleep/wait until bucket is empty.
// Limits will and can change during time, but a safe window will be 1 request per second.
// Limiting is applied per api token per IP, meaning two users from the same IP will get their rate allocated separately.
async function SyncTimeEntries () {
//console.time('SyncTimeEntries')
var syncResults = {
// Time entries we have ignored from syncing, although we still track their received id to omit those records from deletion if they were previously processed.
// TODO: Consider if we want to delete time tracking records if they would be ignored but had previously been processed? I think we would.
ignored: [],
// Time entries we successfully synced. (TODO: Consider if we want to have added and updated as different?)
synced: [],
// Any time entrys we failed to process for many reasons.
failed: [],
// To contain mapping info of previous time entries that we deleted from activeCollab because they were no longer received by toggl in a recent query.
deleted: [],
togglIdsReceived: [],
// To contain tasks we reopened.
tasksReopened: [],
}
var startMoment = moment()
try {
let fromMoment = startMoment
.clone()
.subtract(TimeEntriesRetrieveDuration)
// If set in config, clamp the start date to this.
if (TimeEntiresAfter !== null) {
fromMoment = moment.max(fromMoment, TimeEntiresAfter)
}
if (argv.verbose) {
console.log(
`Getting time entries from ${fromMoment.toISOString()}`
)
}
// TODO: Batch this into weeks to handle multiple users in same workspace better?
syncResults.fromMoment = fromMoment
syncResults.toMoment = startMoment
var timeEntries = await toggl.getTimeEntriesAsync(
fromMoment.toISOString(),
startMoment.toISOString()
)
} catch (error) {
//console.timeEnd('SyncTimeEntries')
syncResults.error = error
console.error('Failed to get time entries.', error)
await eventEmitter.emit('timeEntrySyncResults', syncResults)
return syncResults
}
// Apply some cleanups and initial values we want to parse out on all time entries.
for (let index = 0; index < timeEntries.length; ++index) {
let timeEntry = timeEntries[index]
timeEntry.dataType = 'TimeEntry'
if (timeEntry.tags === undefined) {
timeEntry.tags = []
}
// No description. Get outa here, we need a description to get the Ticket ID.
if (!timeEntry.description) {
timeEntry.description = ''
}
// Get the Issue # out of the time entry description.
var match = timeEntry.description.match(/#(\d+)/)
if (match !== null) {
timeEntry.issueNumber = match[1] * 1
}
// Insist that billable be true or false.
if (timeEntry.billable === undefined) {
timeEntry.billable = false
}
// A work around to allow for billable time for this proof of concept. // TODO: Make this a plugin?
if (timeEntry.billable === false && timeEntry.description.startsWith('$')) {
timeEntry.billable = true
}
// Parse the start date from Toggl as UTC then change timezone to configured for storing in Active Collab.
let date = moment(timeEntry.start).tz(config.timezone || 'Pacific/Auckland')
timeEntry.date = date.format('YYYY/MM/DD')
// Allow for modifying a time entry before it is processed.
await eventEmitter.emit('preProcessTimeEntry', { timeEntry: timeEntry, syncResults: syncResults })
}
// Allow for interacting with received time entries prior to processing them.
await eventEmitter.emit('receivedTimeEntries', { timeEntries: timeEntries, syncResults: syncResults })
for (let index = 0; index < timeEntries.length; ++index) {
let timeEntry = timeEntries[index]
if (timeEntry.wid !== config.Toggl.workspaceId) {
// TODO: Fix error Cannot access 'deletePreviousTimeEntryMapping' before initialization
//await deletePreviousTimeEntryMapping()
syncResults.ignored.push({
summary: 'Not in configured workspace.',
timeEntry: timeEntry
})
continue
}
// If the time entry was collated we don't want to process the collated ones as the first one found will have the sum of duration & tags.
if (timeEntry.collated) {
continue
}
// Map the toggl uid to an active collab user id.
var activeCollabUserId =
config.togglToActiveCollabUserMapping[timeEntry.uid]
if (activeCollabUserId === undefined) {
// TODO: Fix error Cannot access 'deletePreviousTimeEntryMapping' before initialization