-
Notifications
You must be signed in to change notification settings - Fork 2
/
import.js
277 lines (215 loc) · 6.69 KB
/
import.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
const fs = require('fs');
const CONFIG_FILE = 'config.json';
const ERROR_FILE = 'errors.json';
function readCsv(file) {
const csv = fs.readFileSync(file, 'utf8')
let lines = csv.split('\n');
let columnNamesLine = lines[0];
let columnNames = parse(columnNamesLine);
let dataLines = lines.slice(1);
let data = dataLines.map(parse);
return data;
}
function parse(row) {
let insideQuote = false,
entries = [],
entry = [];
row.split('').forEach(function (character) {
if (character === '"') {
insideQuote = !insideQuote;
} else {
if (character == "," && !insideQuote) {
entries.push(entry.join(''));
entry = [];
} else {
entry.push(character);
}
}
});
entries.push(entry.join(''));
return entries;
}
function Field(id, type, value) {
this.id = id;
this.type = type;
this.value = value;
};
function getValue(field, line) {
let value = ''
if (field.value == null) {
return null
}
if (typeof field.value == "boolean") {
value = field.value
}
else if (field.type == "index") {
if (field.value < line.length)
value = line[field.value]
}
else if(field.type == "int"){
if (field.value < line.length)
value = parseInt(line[field.value])
}
else if (Array.isArray(field.value)) {
let toJoin = [];
for (let i of field.value)
toJoin.push(line[i].trim())
value = toJoin.join(" - ")
}
const formaCalculo = new Map()
formaCalculo.set('S', 201)
formaCalculo.set('N', 202)
if (formaCalculo.has(value)) {
value = formaCalculo.get(value)
}
return value
}
function populate(file) {
// definindo a ordem dos valores conforme a ordem do csv
let fields = [
new Field("titulo", "text", [0, 1]),
new Field("complexidade", "index", 2),
new Field("definicaoComplexidade", "index", 3),
new Field("permiteTrabalhoRemoto", "boolean", true),
new Field("formaCalculoTempoItemCatalogoId", "index", 4),
new Field("tempoExecucaoPresencial", "int", 5),
new Field("tempoExecucaoRemoto", "int", 6),
new Field("entregasEsperadas", "index", 8),
new Field("descricao", "text", ""),
new Field("assuntos", "text", null)
]
let csv = readCsv(file)
let lastLine = csv[0]
let activities = []
for (let line of csv) {
if(line == '')
continue
// preencher colunas [0, 1, 8] vazias com base na última linha
for (let i in line) {
if (![0, 1, 8].includes(parseInt(i)))
continue
if (line[i].trim() === '')
line[i] = lastLine[i]
}
const activity = fill(fields, line)
validate(activity)
activities.push(activity)
// salva a última linha/atividade
lastLine = line
}
return { activities }
}
function fill(fields, line) {
const activity = {}
for (let field of fields)
activity[field.id] = getValue(field, line)
return activity
}
function validate(activity) {
const MAX_TITULO = 250;
const MAX_ENTREGAS = 200;
if (!activity.titulo.trim())
throw new Error(`O campo <titulo> é obrigatório.`)
if (activity.titulo.length > MAX_TITULO)
throw new Error(`O campo <titulo> não pode exceder ${MAX_TITULO} caracteres.`)
if (!activity.entregasEsperadas.trim())
throw new Error(`O campo <entregasEsperadas> é obrigatório.`)
if (activity.entregasEsperadas.length > MAX_ENTREGAS)
throw new Error(`O campo <entregasEsperadas> não pode exceder ${MAX_ENTREGAS} caracteres.`)
if (!activity.definicaoComplexidade.trim())
throw new Error(`O campo <definicaoComplexidade> é obrigatório.`)
if (activity.definicaoComplexidade.length > MAX_ENTREGAS)
throw new Error(`O campo <definicaoComplexidade> não pode exceder ${MAX_ENTREGAS} caracteres.`)
}
async function auth({ hostname, port, auth_path, method }, data) {
const querystring = require('querystring');
const dataString = querystring.stringify(data)
const https = port == '443' ? require('https') : require('http');
const options = {
hostname: hostname,
port: port,
path: auth_path || '/gateway/connect/token',
method: method || 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode > 299)
return reject(new Error(`${res.statusCode} ${res.statusMessage}`))
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => resolve(JSON.parse(Buffer.concat(body).toString())))
})
req.on('error', (err) => reject(err))
req.on('timeout', () => {
req.destroy()
reject(new Error('Request time out'))
})
req.write(dataString)
req.end()
})
}
async function create({ hostname, port, item_path, method, access_token, token_type }, data) {
const dataString = JSON.stringify(data)
const https = port == '443' ? require('https') : require('http');
const options = {
hostname: hostname,
port: port,
path: item_path || '/gateway/itemcatalogo',
method: method || 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `${token_type} ${access_token}`
}
}
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode > 299)
return reject(new Error(`${res.statusCode} ${res.statusMessage}`))
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => resolve(JSON.parse(Buffer.concat(body).toString())))
})
req.on('error', (err) => reject(err))
req.on('timeout', () => {
req.destroy()
reject(new Error('Request time out'))
})
req.write(dataString)
req.end()
})
}
async function add(activity, { hostname, port, item_path, access_token, token_type }) {
console.log(activity);
const res = await create({ hostname, port, item_path, access_token, token_type }, activity);
console.log(`${res.mensagem} => ${JSON.stringify(res)}`);
}
function read(file) {
try {
return JSON.parse(fs.readFileSync(file))
} catch (error) {
console.error(error)
return []
}
}
function log(errors) {
fs.writeFileSync(ERROR_FILE, JSON.stringify(errors))
}
async function main() {
const { file, endpoint, body, paths } = read(CONFIG_FILE)
const access = await auth({ ...endpoint, ...paths }, body)
const { activities } = populate(file)
let errors = []
let indexes = read(ERROR_FILE)
indexes = !indexes.length ? [...activities.keys()] : indexes
for (const i of indexes) {
try {
await add(activities[i], { ...endpoint, ...access, ...paths })
} catch (e) {
console.error(e)
errors.push(i)
}
}
log(errors)
}
main()