-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheckoutByBarcode.js
More file actions
263 lines (248 loc) · 8.23 KB
/
Copy pathcheckoutByBarcode.js
File metadata and controls
263 lines (248 loc) · 8.23 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
const fs = require('fs');
const superagent = require('superagent');
const path = require('path');
const { getAuthToken } = require('./lib/login');
const readline = require('readline');
const tout = 60000;
const fn = process.argv[2];
let checkIn = process.argv[3];
let errs = { checkouts: [] };
const wait = (ms) => {
console.log(`(Waiting ${ms}ms...)`);
return new Promise((resolve) => setTimeout(resolve, ms));
};
let config;
const post_put = async (authToken, url, checkout, r, username) => {
r = (r) ? r : 0;
try {
if (url.match(/.{8}-.{4}-.{4}-.{4}-.{12}$/)) {
await superagent
.put(url)
.timeout(tout)
.set('User-Agent', config.agent)
.set('cookie', config.cookie)
.set('x-okapi-tenant', config.tenant)
.set('x-okapi-token', config.token)
.set('content-type', 'application/json')
.send(checkout);
return;
} else {
let res = await superagent
.post(url)
.timeout(tout)
.set('User-Agent', config.agent)
.set('cookie', config.cookie)
.set('x-okapi-tenant', config.tenant)
.set('x-okapi-token', config.token)
.set('accept', 'application/json', 'text/plain')
.set('content-type', 'application/json')
.send(checkout);
return res.body;
}
} catch (e) {
if (process.env.DEBUG) console.log(e);
if (e.code) {
console.log(` Connection timed out! Retrying (${r})...`);
r++;
if (r < 10) {
let loanObj = await post_put(authToken, url, checkout, r);
return loanObj;
} else {
throw new Error(`Too many retries (${r})!`);
}
} else {
let text = (e.response) ? e.response.text : JSON.stringify(e);
if (text.match(/overridableBlock/) && !r) {
let err = JSON.parse(text);
let block = {};
err.errors.forEach(er => {
if (er.message.match(/not loanable|blocked|maximum /)) {
block = er.overridableBlock;
}
});
let name = block.name;
checkout.overrideBlocks = {
comment: 'Migration override',
[name]: { dueDate: new Date().toISOString() },
}
if (name !== 'patronBlock') {
checkout.overrideBlocks.patronBlock = {};
}
console.log(`WARN we've encountered a ${name} block, retrying with override...`);
let body = await post_put(authToken, url, checkout, 1);
return body;
} else if (text.match(/USER_BARCODE_NOT_FOUND/) && username) {
console.log(` WARN user barcode ${checkout.userBarcode} does not exist-- looking up by username: ${username}...`);
try {
let res = await superagent
.get(`${config.okapi}/users?query=username==${username}`)
.set('User-Agent', config.agent)
.set('cookie', config.cookie)
.set('x-okapi-tenant', config.tenant)
.set('x-okapi-token', config.token)
let u = res.body.users[0];
if (u.barcode) {
checkout.userBarcode = u.barcode;
let body = await post_put(authToken, url, checkout, 1);
return body;
} else {
throw(` ERROR no barcode found for username: ${username}`)
}
} catch (e) {
throw(e);
}
} else {
throw(text);
}
}
}
}
(async () => {
let added = 0;
let errors = 0;
let claimed = 0;
let claimedErrs = 0;
try {
if (!fn) {
throw new Error('Usage: node checkoutByBarcode.js <checkouts_jsonl> [checkin]');
}
const dir = path.dirname(fn);
const fname = path.basename(fn, '.jsonl');
const saveFile = `${dir}/${fname}_done.jsonl`;
if (fs.existsSync(saveFile)) {
fs.unlinkSync(saveFile);
}
const errPath = `${dir}/${fname}_errors.jsonl`;
if (fs.existsSync(errPath)) {
fs.unlinkSync(errPath);
}
config = await getAuthToken(superagent);
let url = `${config.okapi}/circulation/check-out-by-barcode`;
let today;
if (checkIn === 'checkin') {
url = `${config.okapi}/circulation/check-in-by-barcode`;
today = new Date().toISOString();
}
const fileStream = fs.createReadStream(fn);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let d = 0;
for await (let line of rl) {
d++;
let lDate = new Date();
if (config.expiry && config.expiry <= lDate.valueOf()) {
config = await getAuthToken(superagent);
}
let data = JSON.parse(line);
delete data.errorMessage;
let errData = JSON.parse(line);
delete data.__;
let errMsg;
let dueDate;
let claimedReturnedDate = '';
let renewalCount = 0;
let username = '';
let held = data.held;
delete data.held;
if (checkIn === 'checkin') {
delete data.loanDate;
delete data.userBarcode;
delete data.expirationDate;
delete data.renewalCount;
data.checkInDate = today;
} else {
dueDate = data.dueDate;
delete data.dueDate;
delete data.expirationDate;
if (data.claimedReturnedDate) {
claimedReturnedDate = data.claimedReturnedDate;
delete data.claimedReturnedDate;
}
if (data.renewalCount) {
renewalCount = data.renewalCount;
delete data.renewalCount;
}
if (data.username) {
username = data.username;
delete data.username;
}
}
try {
let uc = '';
if (data.userBarcode) uc = ` --> ${data.userBarcode}`
let postData = Object.assign({}, data);
console.log(`[${d}] POST ${url} (${data.itemBarcode}${uc})`);
let loanObj = await post_put(config.token, url, postData, 0, username, config);
if (checkIn === 'checkin') {
added++;
} else if (held) {
let url = `${config.okapi}/circulation/hold-by-barcode-for-use-at-location`;
console.log(`[${d}] POST ${url} (${data.itemBarcode})`);
await post_put(config.token, url, data);
} else if (loanObj && dueDate) {
let loanStr = JSON.stringify(loanObj) + '\n';
fs.writeFileSync(saveFile, loanStr, { flag: 'a' });
try {
loanObj.dueDate = dueDate;
loanObj.loanDate = data.loanDate;
loanObj.action = 'dueDateChanged';
loanObj.renewalCount = renewalCount;
delete loanObj.dueDateChangedByNearExpireUser;
if (process.env.DEBUG) console.log(loanObj);
let lurl = `${config.okapi}/circulation/loans/${loanObj.id}`;
console.log(`[${d}] PUT ${lurl} (${data.itemBarcode})`);
await post_put(config.token, lurl, loanObj);
added++
if (claimedReturnedDate) {
try {
let claimedObj = {};
claimedObj.itemClaimedReturnedDateTime = claimedReturnedDate;
claimedObj.comment = "Migrated action";
let lurl = `${config.okapi}/circulation/loans/${loanObj.id}/claim-item-returned`;
console.log(`[${d}] POST ${lurl} (${data.itemBarcode})`);
await post_put(config.token, lurl, claimedObj);
claimed++;
} catch (e) {
console.log(e);
claimedErrs++;
}
}
} catch (e) {
let m;
if (e.response) {
m = e.response.text
} else {
m = e;
}
console.log(m);
errors++;
}
} else if (loanObj && !dueDate) {
added++;
}
} catch (e) {
let m;
if (e.response) {
m = e.response.text
} else {
m = e;
}
console.log(m);
errMsg = m;
if (errMsg) errData.errorMessage = errMsg;
errors++;
if (!checkIn) fs.writeFileSync(errPath, JSON.stringify(errData) + '\n', { flag: 'a' });
}
if (config.delay) await wait(config.delay);
console.log('----------------------');
}
console.log('Added:', added);
console.log('Claimed:', claimed);
console.log('Errors:', errors);
console.log('Claimed errors:', claimedErrs);
} catch (e) {
console.error(e.message);
}
})();