-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
methods.js
886 lines (882 loc) · 32.7 KB
/
methods.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
import { ValidatedMethod } from 'meteor/mdg:validated-method'
import dayjs from 'dayjs'
import { NodeVM } from 'vm2'
import { fetch } from 'meteor/fetch'
import { check, Match } from 'meteor/check'
import Timecards from '../timecards.js'
import Tasks from '../../tasks/tasks.js'
import Projects from '../../projects/projects.js'
import { t } from '../../../utils/i18n.js'
import { emojify } from '../../../utils/frontend_helpers'
import { timeInUserUnit } from '../../../utils/periodHelpers.js'
import {
authenticationMixin,
transactionLogMixin,
buildTotalHoursForPeriodSelector,
buildDailyHoursSelector,
buildworkingTimeSelector,
workingTimeEntriesMapper,
buildDetailedTimeEntriesForPeriodSelector,
getGlobalSettingAsync,
calculateSimilarity,
} from '../../../utils/server_method_helpers.js'
import { getOpenAIResponse } from '../../../utils/openai/openai_server.js'
/**
* Inserts a new timecard into the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
* @throws {Meteor.Error} If time entry rule throws an error.
* @throws {Meteor.Error} If time entry rule is not a function.
* @throws {Meteor.Error} If time entry rule is not a string.
* @throws {Meteor.Error} If time entry rule is not a valid JavaScript expression.
*/
async function checkTimeEntryRule({
userId, projectId, task, state, date, hours,
}) {
const meteorUser = await Meteor.users.findOneAsync({ _id: userId })
const vm = new NodeVM({
wrapper: 'none',
timeout: 1000,
sandbox: {
user: meteorUser.profile,
project: await Projects.findOneAsync({ _id: projectId }),
dayjs,
timecard: {
projectId,
task,
state,
date,
hours,
},
},
})
try {
if (!vm.run(await getGlobalSettingAsync('timeEntryRule'))) {
throw new Meteor.Error('notifications.time_entry_rule_failed')
}
} catch (error) {
throw new Meteor.Error(error.message)
}
}
/**
* Inserts a new timecard into the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {number} taskRate - The rate of the task for the time card.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
* @throws {Meteor.Error} If time entry rule throws an error.
*/
async function insertTimeCard(projectId, task, date, hours, userId, taskRate, customfields) {
const newTimeCard = {
userId,
projectId,
date,
hours,
task: await emojify(task),
...customfields,
}
if (taskRate) {
newTimeCard.taskRate = taskRate
}
if (!await Tasks.findOneAsync({ $or: [{ userId }, { projectId }], name: await emojify(task) })) {
await Tasks.insertAsync({
userId, lastUsed: new Date(), name: await emojify(task), ...customfields,
})
} else {
await Tasks.updateAsync(
{ $or: [{ userId }, { projectId }], name: await emojify(task) },
{ $set: { lastUsed: new Date(), ...customfields } },
)
}
return Timecards.insertAsync(newTimeCard)
}
/**
* Updates an existing timecard in the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
*/
async function upsertTimecard(projectId, task, date, hours, userId) {
if (!await Tasks.findOneAsync({ userId, name: await emojify(task) })) {
await Tasks.insertAsync({ userId, lastUsed: new Date(), name: await emojify(task) })
} else {
await Tasks.updateAsync(
{ userId, name: await emojify(task) },
{ $set: { lastUsed: new Date() } },
)
}
if (hours === 0) {
await Timecards.removeAsync({
userId,
projectId,
date,
task: await emojify(task),
})
} else if (await Timecards.find({
userId,
projectId,
date,
task: await emojify(task),
}).countAsync() > 1) {
// if there are more time entries with the same task description for one day,
// we remove all of them and create a new entry for the total sum
await Timecards.removeAsync({
userId,
projectId,
date,
task: await emojify(task),
})
}
await Timecards.updateAsync(
{
userId,
projectId,
date,
task: await emojify(task),
},
{
userId,
projectId,
date,
hours,
task: await emojify(task),
},
{ upsert: true },
)
return 'notifications.success'
}
async function checkProjectAdministratorAndUser(projectId, administratorId, userId) {
const targetProject = Projects.findOne({ _id: projectId })
if (!targetProject
|| !(targetProject.userId === administratorId
|| targetProject.admins.indexOf(administratorId) >= 0)) {
throw new Meteor.Error('notifications.only_administrator_can_register_time')
}
const user = await Meteor.users.findOneAsync({ 'profile.name': userId })
if (!user) {
throw new Meteor.Error('notifications.user_not_found')
}
if (targetProject.public !== true
&& targetProject.userId !== user._id
&& targetProject.team.indexOf(user._id) === -1) {
throw new Meteor.Error('notifications.user_not_found_in_project')
}
return user._id
}
/**
* Inserts a new timecard into the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
*/
const insertTimeCardMethod = new ValidatedMethod({
name: 'insertTimeCard',
validate(args) {
check(args.projectId, Match.Maybe(String))
check(args.task, String)
check(args.date, Date)
check(args.hours, Number)
check(args.taskRate, Match.Maybe(Number))
check(args.customfields, Match.Maybe(Object))
check(args.user, String)
},
mixins: [authenticationMixin, transactionLogMixin],
async run({
projectId, task, date, hours, taskRate, customfields, user,
}) {
let { userId } = this
if (user !== userId) {
userId = await checkProjectAdministratorAndUser(projectId, userId, user)
}
const check = await checkTimeEntryRule({
userId, projectId, task, state: 'new', date, hours,
})
await insertTimeCard(projectId, task, date, hours, userId, taskRate, customfields)
},
})
/**
* Updates an existing timecard in the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
* @throws {Meteor.Error} If timecard does not exist.
*/
const upsertWeek = new ValidatedMethod({
name: 'upsertWeek',
validate(args) {
check(args, Array)
},
mixins: [authenticationMixin, transactionLogMixin],
async run(weekArray) {
weekArray.forEach(async (element) => {
check(element.projectId, String)
check(element.task, String)
check(element.date, Date)
check(element.hours, Number)
await checkTimeEntryRule({
userId: this.userId,
projectId: element.projectId,
task: element.task,
state: 'new',
date: element.date,
hours: element.hours,
})
await upsertTimecard(
element.projectId,
element.task,
element.date,
element.hours,
this.userId,
)
})
},
})
/**
* Updates an existing timecard in the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project for the timecard.
* @param {string} args._id - The ID of the timecard.
* @param {string} args.task - The task for the timecard.
* @param {Date} args.date - The date of the timecard.
* @param {number} args.hours - The number of hours for the timecard.
* @param {string} [args.userId] - The ID of the user for the timecard.
* @param {Object} [args.customfields] - The custom fields for the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
* @throws {Meteor.Error} If timecard does not exist.
*/
const updateTimeCard = new ValidatedMethod({
name: 'updateTimeCard',
validate(args) {
check(args.projectId, String)
check(args._id, String)
check(args.task, String)
check(args.date, Date)
check(args.hours, Number)
check(args.taskRate, Match.Maybe(Number))
check(args.customfields, Match.Maybe(Object))
check(args.user, String)
},
mixins: [authenticationMixin, transactionLogMixin],
async run({
projectId, _id, task, date, hours, taskRate, customfields, user,
}) {
let { userId } = this
if (user !== userId) {
userId = await checkProjectAdministratorAndUser(projectId, userId, user)
}
const timecard = await Timecards.findOneAsync({ _id })
await checkTimeEntryRule({
userId, projectId, task, state: timecard.state, date, hours,
})
if (!await Tasks.findOneAsync({ userId, name: await emojify(task) })) {
await Tasks.insertAsync({ userId, name: await emojify(task), ...customfields })
}
const fieldsToSet = {
projectId,
date,
hours,
task: await emojify(task),
...customfields,
}
if (taskRate) {
fieldsToSet.taskRate = taskRate
await Timecards.updateAsync({ _id }, {
$set: fieldsToSet,
})
} else {
await Timecards.updateAsync({ _id }, {
$set: fieldsToSet,
$unset: { taskRate: '' },
})
}
},
})
/**
* Deletes an existing timecard in the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.timecardId - The ID of the timecard.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
* @throws {Meteor.Error} If time entry rule fails.
* @throws {Meteor.Error} If timecard does not exist.
* @throws {Meteor.Error} If timecard is not owned by user.
*/
const deleteTimeCard = new ValidatedMethod({
name: 'deleteTimeCard',
validate(args) {
check(args, {
timecardId: String,
})
},
mixins: [authenticationMixin, transactionLogMixin],
async run({ timecardId }) {
const timecard = await Timecards.findOneAsync({ _id: timecardId })
await checkTimeEntryRule({
userId: this.userId,
projectId: timecard.projectId,
task: timecard.task,
state: timecard.state,
date: timecard.date,
hours: timecard.hours,
})
return Timecards.removeAsync({ userId: this.userId, _id: timecardId })
},
})
/**
* Creates an invoice in Siwapp through the API and
* updates the state of a timecard in the Timecards collection.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project.
* @param {string} args.timePeriod - The time period for the invoice.
* @param {string} [args.userId] - The ID of the user.
* @param {string} [args.customer] - The ID of the customer.
* @param {Object} [args.dates] - The start and end dates for the invoice.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {String} 'notifications.success' if successful
*/
const sendToSiwapp = new ValidatedMethod({
name: 'sendToSiwapp',
validate(args) {
check(args.projectId, Match.OneOf(String, Array))
check(args.timePeriod, String)
check(args.userId, Match.OneOf(String, Array))
check(args.customer, Match.OneOf(String, Array))
check(args.dates, Match.Maybe(Object))
if (args.timePeriod === 'custom') {
check(args.dates, Object)
check(args.dates.startDate, Date)
check(args.dates.endDate, Date)
}
},
mixins: [authenticationMixin, transactionLogMixin],
async run({
projectId, timePeriod, userId, customer, dates,
}) {
const meteorUser = await Meteor.users.findOneAsync({ _id: this.userId })
if (!meteorUser.profile.siwappurl || !meteorUser.profile.siwapptoken) {
throw new Meteor.Error(t('notifications.siwapp_configuration'))
}
const timeEntries = []
const selector = buildDetailedTimeEntriesForPeriodSelector({
projectId,
search: undefined,
customer,
period: timePeriod,
dates,
userId,
limit: undefined,
page: undefined,
sort: undefined,
})
const projectMap = new Map()
for (const timecard of await Timecards.find(selector[0]).fetchAsync()) {
timeEntries.push(timecard._id)
const resource = meteorUser.profile.name
const projectEntry = projectMap.get(timecard.projectId)
if (projectEntry) {
projectEntry.set(
resource,
(projectEntry.get(resource) ? projectEntry.get(resource) : 0) + timecard.hours,
)
} else {
projectMap.set(timecard.projectId, new Map().set(resource, timecard.hours))
}
}
const invoiceJSON = {
data: {
attributes: {
name: 'from titra',
issue_date: dayjs().format('YYYY-MM-DD'),
draft: true,
},
relationships: {
items: {
data: [],
},
},
},
}
for await (const [project, resources] of projectMap.entries()) {
const projectElement = await Projects.findOneAsync({ _id: project })
if (resources.size > 0) {
for (const [resource, hours] of resources) {
invoiceJSON.data.relationships.items.data.push({
attributes: {
description: `${projectElement.name} (${resource})`,
quantity: timeInUserUnit(hours, meteorUser),
unitary_cost: 0,
},
})
}
}
}
try {
const response = await fetch(`${meteorUser.profile.siwappurl}/api/v1/invoices`, {
method: 'POST',
body: JSON.stringify(invoiceJSON),
headers: {
Authorization: `Token token=${meteorUser.profile.siwapptoken}`,
'Content-type': 'application/json',
},
})
if (response.status === 201) {
await Timecards.updateAsync({ _id: { $in: timeEntries } }, { $set: { state: 'billed' } }, { multi: true })
return 'notifications.siwapp_success'
}
return 'notifications.siwapp_configuration'
} catch (error) {
console.error(error)
throw new Meteor.Error(error)
}
},
})
/**
* Gets the daily timecards sum for a given period.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project.
* @param {string} args.userId - The ID of the user.
* @param {string} args.period - The time period for the invoice.
* @param {Object} [args.dates] - The start and end dates for the invoice.
* @param {string} [args.customer] - The ID of the customer.
* @param {number} [args.limit] - The number of timecards to return.
* @param {number} [args.page] - The page number.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {Object} The daily timecards sum for a given period.
*/
const getDailyTimecards = new ValidatedMethod({
name: 'getDailyTimecards',
validate(args) {
check(args.projectId, Match.OneOf(String, Array))
check(args.userId, String)
check(args.period, String)
check(args.customer, String)
check(args.limit, Number)
check(args.dates, Match.Maybe(Object))
check(args.page, Match.Maybe(Number))
if (args.period === 'custom') {
check(args.dates, Object)
check(args.dates.startDate, Date)
check(args.dates.endDate, Date)
}
},
mixins: [authenticationMixin],
async run({
projectId, userId, period, dates, customer, limit, page,
}) {
const aggregationSelector = buildDailyHoursSelector(
projectId,
period,
dates,
userId,
customer,
limit,
page,
)
const dailyHoursObject = {}
const totalTimeCardsRawCollection = await Timecards.rawCollection()
.aggregate(buildDailyHoursSelector(projectId, period, dates, userId, customer, 0))
.toArray()
const totalEntries = totalTimeCardsRawCollection.length
const dailyHours = await Timecards.rawCollection().aggregate(aggregationSelector)
.toArray()
dailyHoursObject.dailyHours = dailyHours
dailyHoursObject.totalEntries = totalEntries
return dailyHoursObject
},
})
/**
* Gets the total hours for a given period.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project.
* @param {string} args.userId - The ID of the user.
* @param {string} args.period - The time period for the invoice.
* @param {Object} [args.dates] - The start and end dates for the invoice.
* @param {string} [args.customer] - The ID of the customer.
* @param {number} [args.limit] - The number of timecards to return.
* @param {number} [args.page] - The page number.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {Object} The total hours for a given period.
*/
const getTotalHoursForPeriod = new ValidatedMethod({
name: 'getTotalHoursForPeriod',
validate(args) {
check(args.projectId, Match.OneOf(String, Array))
check(args.userId, String)
check(args.period, String)
check(args.customer, String)
check(args.limit, Number)
check(args.dates, Match.Maybe(Object))
check(args.page, Match.Maybe(Number))
if (args.period === 'custom') {
check(args.dates, Object)
check(args.dates.startDate, Date)
check(args.dates.endDate, Date)
}
},
mixins: [authenticationMixin],
async run({
projectId, userId, period, dates, customer, limit, page,
}) {
const aggregationSelector = buildTotalHoursForPeriodSelector(
projectId,
period,
dates,
userId,
customer,
limit,
page,
)
const totalHoursObject = {}
const totalEntriesTimecardsRaw = await Timecards.rawCollection()
.aggregate(buildTotalHoursForPeriodSelector(projectId, period, dates, userId, customer, 0))
.toArray()
const totalEntries = totalEntriesTimecardsRaw.length
const totalHours = await Timecards.rawCollection().aggregate(aggregationSelector)
.toArray()
for (const entry of totalHours) {
entry.totalHours = Number(JSON.parse(JSON.stringify(entry)).totalHours.$numberDecimal)
}
totalHoursObject.totalHours = totalHours
totalHoursObject.totalEntries = totalEntries
return totalHoursObject
},
})
/**
* Gets the working hours for a given period.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project.
* @param {string} args.userId - The ID of the user.
* @param {string} args.period - The time period for the invoice.
* @param {Object} [args.dates] - The start and end dates for the invoice.
* @param {number} [args.limit] - The number of timecards to return.
* @param {number} [args.page] - The page number.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {Object} The working hours for a given period.
*/
const getWorkingHoursForPeriod = new ValidatedMethod({
name: 'getWorkingHoursForPeriod',
validate(args) {
check(args.projectId, Match.OneOf(String, Array))
check(args.userId, String)
check(args.period, String)
check(args.limit, Number)
check(args.dates, Match.Maybe(Object))
check(args.page, Match.Maybe(Number))
if (args.period === 'custom') {
check(args.dates, Object)
check(args.dates.startDate, Date)
check(args.dates.endDate, Date)
}
},
mixins: [authenticationMixin],
async run({
projectId, userId, period, dates, limit, page,
}) {
const aggregationSelector = buildworkingTimeSelector(
projectId,
period,
dates,
userId,
limit,
page,
)
const totalEntriesTimecardsRaw = await Timecards.rawCollection()
.aggregate(buildworkingTimeSelector(projectId, period, dates, userId, limit, page)).toArray()
const totalEntries = totalEntriesTimecardsRaw.length
const workingHoursObject = {}
workingHoursObject.totalEntries = totalEntries
const workingHoursTimeCardsRaw = await Timecards.rawCollection().aggregate(aggregationSelector)
.toArray()
const workingHours = await Promise.all(workingHoursTimeCardsRaw.map(workingTimeEntriesMapper))
workingHoursObject.workingHours = workingHours
return workingHoursObject
},
})
/**
* Sets the time entry state for a list of time entries
* @param {Object} args - The arguments object containing the timecard information.
* @param {string[]} args.timeEntries - The IDs of the time entries.
* @param {string} args.state - The state to set the time entries to.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {undefined}
*/
const setTimeEntriesState = new ValidatedMethod({
name: 'setTimeEntriesState',
validate(args) {
check(args, {
timeEntries: Array,
state: String,
})
for (const timeEntryId of args.timeEntries) {
check(timeEntryId, String)
}
},
mixins: [authenticationMixin, transactionLogMixin],
async run({ timeEntries, state }) {
if (state === 'exported') {
await Timecards.updateAsync(
{ _id: { $in: timeEntries } },
{ $set: { state } },
{ multi: true },
)
} else if (state === 'billed') {
await Timecards.updateAsync(
{ _id: { $in: timeEntries } },
{ $set: { state } },
{ multi: true },
)
} else {
await Timecards.updateAsync(
{ _id: { $in: timeEntries } },
{ $set: { state } },
{ multi: true },
)
}
},
})
/**
* Deletes timecards for a given project, task, and date range.
* @param {Object} args - The arguments object containing the timecard information.
* @param {string} args.projectId - The ID of the project.
* @param {string} args.task - The task associated with the timecards.
* @param {Date} args.startDate - The start date of the timecard range.
* @param {Date} args.endDate - The end date of the timecard range.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {undefined}
*/
const deleteTimeCardsForWeek = new ValidatedMethod({
name: 'deleteTimeCardsForWeek',
validate(args) {
check(args, {
projectId: String,
task: String,
startDate: Date,
endDate: Date,
})
},
mixins: [authenticationMixin, transactionLogMixin],
async run({
projectId, task, startDate, endDate,
}) {
await Timecards.removeAsync({
projectId,
task,
date: { $gte: startDate, $lte: endDate },
})
},
})
/**
* Gets the Google Workspace data for a given date range.
* @param {Object} args - The arguments object containing the date range.
* @param {Date} args.startDate - The start date of the date range.
* @param {Date} args.endDate - The end date of the date range.
* @throws {Meteor.Error} If user is not authenticated.
* @returns {Object} The Google Workspace data for the given date range.
*/
const getGoogleWorkspaceData = new ValidatedMethod({
name: 'getGoogleWorkspaceData',
validate(args) {
check(args, {
startDate: Date,
endDate: Date,
})
},
mixins: [authenticationMixin],
async run({ startDate, endDate }) {
const { serviceData } = Meteor.user().services.googleapi
let eventResponse = []
if (serviceData) {
const events = await fetch(`https://www.googleapis.com/calendar/v3/calendars/primary/events?singleEvents=true&timeMax=${encodeURIComponent(endDate.toISOString())}&timeMin=${encodeURIComponent(startDate.toISOString())}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${serviceData.accessToken}`,
Accept: 'application/json',
},
})
const jsonEvents = await events.json()
const fetchedEvents = jsonEvents.items.map((event) => ({
summary: event.summary,
description: event.description?.substring(0, 255),
startTime: event.start?.dateTime,
endTime: event.end?.dateTime,
attendees: event.attendees,
}))
eventResponse = fetchedEvents
if (await getGlobalSettingAsync('openai_apikey') && fetchedEvents.length > 0) {
eventResponse = await Promise.all(fetchedEvents.map(async (eventData) => getOpenAIResponse(`Based on the following JSON representation of a calendar event, respond with a JSON object summarizing the event with as few words as possible. Add the date of the event and the duration in hours and try to identify the customer based on the majority of attendee e-mail addresses. Include the original un-altered summary in the origin field. Use the following schema for the return JSON:
\`Interface event {summary: string, duration:number, customer:string, date:date, origin:string}\`
${JSON.stringify(eventData)}`)))
}
const emails = await fetch(`https://www.googleapis.com/gmail/v1/users/me/messages?q=in:sent%20after:${Date.parse(startDate) / 1000}%20before:${Date.parse(endDate) / 1000}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${serviceData.accessToken}`,
Accept: 'application/json',
},
})
const emailIds = await emails.json()
let fetchedMessages = []
if (emailIds.messages) {
fetchedMessages = await Promise.all(emailIds.messages.map(async (emailId) => {
const message = await fetch(`https://www.googleapis.com/gmail/v1/users/me/messages/${emailId.id}?format=metadata`, {
method: 'GET',
headers: {
Authorization: `Bearer ${serviceData.accessToken}`,
Accept: 'application/json',
},
})
const jsonMessage = await message.json()
const returnMessage = {}
returnMessage.date = dayjs(new Date(Number.parseInt(jsonMessage.internalDate, 10))).format('YYYY-MM-DD')
returnMessage.sizeEstimate = jsonMessage.sizeEstimate
returnMessage.recipients = ''
const headers = jsonMessage.payload && jsonMessage.payload.headers
if (headers) {
for (const header of headers) {
if (header.name === 'Subject') {
returnMessage.subject = header.value
}
if (header.name === 'To') {
returnMessage.recipients += header.value
}
if (header.name === 'CC') {
returnMessage.recipients += header.value
}
}
if (await getGlobalSettingAsync('openai_apikey')) {
return getOpenAIResponse(`Based on the email representation in JSON format, respond with a JSON object with the following schema where you estimate the time it took to write the email in hours based on the snippet and sizeEstimate in bytes where 0.25 hours is the minimum and add it to the duration field, use date format "YYYY-MM-DD" for dates, summarize the content with as few words as possible, do not include the snippet in the summary, guess the customer company name based on the majority of recipient's mail address domain. Include the original un-altered summary in the origin field. Use the following schema for the return JSON:
\`Interface message {summary:string,customer:string,date:date,duration:number,origin:string}\`
${JSON.stringify(jsonMessage)}`)
}
returnMessage.summary = jsonMessage.snippet.substring(0, 50)
returnMessage.duration = 0.25
returnMessage.origin = returnMessage.summary
return returnMessage
}
return returnMessage
}))
}
let returnEvents = eventResponse
if (await getGlobalSettingAsync('openai_apikey')) {
returnEvents = await Promise.all(eventResponse.map(async (event) => {
const projects = await Projects.find({
$and: [
{
$or: [{ userId: this.userId }, { public: true }, { team: this.userId }],
},
{ $or: [{ archived: false }, { archived: { $exists: false } }] },
],
}).fetchAsync()
const filteredProjects = projects.map((entry) => {
const score = calculateSimilarity(entry.name, event.customer)
if (score > 0.3) {
return {
...entry,
score: calculateSimilarity(entry.name, event.customer),
}
}
return undefined
}).filter((entry) => entry !== undefined)
filteredProjects.sort((a, b) => b.score - a.score)
const updatedMessage = {
...event,
projectID: filteredProjects.length > 0 ? filteredProjects[0]._id : null,
}
return updatedMessage
}))
} else {
returnEvents.map((event) => {
event.date = dayjs(event.startTime).format('YYYY-MM-DD')
event.duration = (Date.parse(event.endTime) - Date.parse(event.startTime))
/ 1000 / 60 / 60
return event
})
}
let returnMessages = fetchedMessages
if (await getGlobalSettingAsync('openai_apikey')) {
returnMessages = await Promise.all(fetchedMessages.map(async (message) => {
const projects = await Projects.find({
$and: [
{
$or: [{ userId: this.userId }, { public: true }, { team: this.userId }],
},
{ $or: [{ archived: false }, { archived: { $exists: false } }] },
],
}).fetchAsync()
const filteredProjects = projects.map((entry) => {
const score = calculateSimilarity(entry.name, message.customer)
if (score > 0.3) {
return {
...entry,
score: calculateSimilarity(entry.name, message.customer),
}
}
return undefined
}).filter((entry) => entry !== undefined)
filteredProjects.sort((a, b) => b.score - a.score)
const updatedMessage = {
...message,
projectID: filteredProjects.length > 0 ? filteredProjects[0]._id : null,
}
return updatedMessage
}))
}
return { returnEvents, returnMessages }
}
throw new Meteor.Error('You need to authorize Google API access for titra first.')
},
})
export {
insertTimeCard,
insertTimeCardMethod,
upsertTimecard,
upsertWeek,
updateTimeCard,
deleteTimeCard,
deleteTimeCardsForWeek,
setTimeEntriesState,
getWorkingHoursForPeriod,
getTotalHoursForPeriod,
getDailyTimecards,
sendToSiwapp,
checkProjectAdministratorAndUser,
getGoogleWorkspaceData,
}