-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubmit.js
124 lines (113 loc) · 3.67 KB
/
submit.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
const submitButton = document.querySelector("#submit")
submitButton.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: post,
})
})
/**
* Post task hours to jobcan.
*
* 1. Build form and encode them into uri component.
* 2. Submit them sequentially.
*/
const post = async () => {
/**
*
* @param {number} raw
* @returns string
*/
const _toMinutes = (raw) => {
const hours = Math.floor(raw)
const min = Math.floor(60 * (raw - hours))
return `${hours}:${min}`
}
/**
* Build form data
*
* @param {string} token
* @param {number} projectId
* @param {number} year
* @param {number} month
* @param {Array<{ date: number, task: number, hours: number }>} taskHours
* @returns {[date: number, encodedForm: string]}
*/
const _createPayload = (token, projectId, year, month, taskHours) => {
const entries = taskHours
.map(({ date, ...props }) => ({ ...props, date: new Date(year, month - 1, date) }))
.filter(({ date }) => date.getDay() !== 0 && date.getDay() !== 6)
.reduce((acc, { date, task, hours }) => {
// common payload
const prev = acc[date] ?? [
['token', token],
['time', date.getTime() / 1000],
]
// payload for each project
const index = prev.filter(([key]) => key === 'index[]').length + 1
acc[date] = [
...prev,
['index[]', index],
['ids[]', 0],
['projects[]', projectId],
['tasks[]', task],
['minutes[]', _toMinutes(hours)],
['hiddenMinutes[]', hours * 60],
]
return acc
}, {})
return Object.entries(entries).map(([date, formEntries]) => [date, formEntries.map(([key, val])=>key+"="+encodeURIComponent(val)).join("&")])
}
/**
*
* @param {number} date
* @param {string} form
* @returns {Promise<Response>}
*/
const _post = (date, form) => {
console.log(`Submit ${date} data.`);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'credentials': 'include',
}
return fetch(
'https://ssl.jobcan.jp/employee/man-hour-manage/save',
{
method: 'POST',
headers,
body: form,
}
)
}
chrome.storage.local.get(null, ({ token, tasks, yearMonth, projectId, dateTaskHours}) => {
console.log({ token, yearMonth, projectId, dateTaskHours });
if (!token, !yearMonth, !projectId, !dateTaskHours) {
throw new Error("Fill all values!")
}
const [year, month] = yearMonth.split("-")
const _dateTaskHours = dateTaskHours
.split("\n")
.filter(Boolean)
.map((row) => {
const items = row.split(",")
if (items.length !== 3) throw new Error("Invalid Date, TaskID, Hours format", items)
const [date, task, hours] = items
.map((item) => item.trim())
.map((item) => {
const _item = Number.parseFloat(item, 10)
if (Number.isNaN(_item)) throw new Error("Any of Date, TaskID or Hours value were not a number", items)
return _item
})
return { date, task, hours }
})
console.log("post these contents", { token, projectId, year, month, _dateTaskHours })
const dateFormTuples = _createPayload(token, projectId, year, month, _dateTaskHours)
dateFormTuples
.reduce(
(acc, [date, form]) => acc.then(() => _post(date, form)),
Promise.resolve()
)
.then(() => console.log("Sumbitted all data."))
.catch(console.error)
});
}