forked from folio-org/ui-requests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestForm.js
489 lines (455 loc) · 17.4 KB
/
RequestForm.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
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { Field } from 'redux-form';
import Button from '@folio/stripes-components/lib/Button';
import Datepicker from '@folio/stripes-components/lib/Datepicker';
import KeyValue from '@folio/stripes-components/lib/KeyValue';
import Pane from '@folio/stripes-components/lib/Pane';
import Paneset from '@folio/stripes-components/lib/Paneset';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import Pluggable from '@folio/stripes-components/lib/Pluggable';
import Select from '@folio/stripes-components/lib/Select';
import TextField from '@folio/stripes-components/lib/TextField';
import { Row, Col } from '@folio/stripes-components/lib/LayoutGrid';
import stripesForm from '@folio/stripes-form';
import UserDetail from './UserDetail';
import ItemDetail from './ItemDetail';
import { toUserAddress } from './constants';
function asyncValidate(values, dispatch, props, blurredField) {
if (blurredField === 'item.barcode') {
return new Promise((resolve, reject) => {
const uv = props.uniquenessValidator.itemUniquenessValidator;
const query = `(barcode="${values.item.barcode}")`;
uv.reset();
uv.GET({ params: { query } }).then((items) => {
if (items.length < 1) {
reject({ item: { barcode: 'Item with this barcode does not exist' } });
} else if (values.requestType === 'Recall' &&
items[0].status.name !== 'Checked out' &&
items[0].status.name !== 'Checked out - Held' &&
items[0].status.name !== 'Checked out - Recalled') {
reject({ item: { barcode: 'Only checked out items can be recalled' } });
} else {
resolve();
}
});
});
} else if (blurredField === 'requester.barcode') {
return new Promise((resolve, reject) => {
const uv = props.uniquenessValidator.userUniquenessValidator;
const query = `(barcode="${values.requester.barcode}")`;
uv.reset();
uv.GET({ params: { query } }).then((users) => {
if (users.length < 1) {
reject({ requester: { barcode: 'User with this barcode does not exist' } });
} else {
resolve();
}
});
});
}
return new Promise(resolve => resolve());
}
class RequestForm extends React.Component {
static propTypes = {
change: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
findUser: PropTypes.func,
findItem: PropTypes.func,
findLoan: PropTypes.func,
findRequestsForItem: PropTypes.func,
initialValues: PropTypes.object,
onCancel: PropTypes.func.isRequired,
pristine: PropTypes.bool,
submitting: PropTypes.bool,
// okapi: PropTypes.object,
optionLists: PropTypes.shape({
addressTypes: PropTypes.arrayOf(PropTypes.object),
requestTypes: PropTypes.arrayOf(PropTypes.object),
fulfilmentTypes: PropTypes.arrayOf(PropTypes.object),
}),
patronGroups: PropTypes.shape({
hasLoaded: PropTypes.bool.isRequired,
isPending: PropTypes.bool.isPending,
other: PropTypes.shape({
totalRecords: PropTypes.number,
}),
}).isRequired,
dateFormatter: PropTypes.func.isRequired,
};
static defaultProps = {
findUser: () => {},
findItem: () => {},
findLoan: () => {},
findRequestsForItem: () => {},
initialValues: {},
optionLists: {},
pristine: true,
submitting: false,
};
constructor(props) {
super(props);
const { requester, item, loan, fulfilmentPreference, deliveryAddressTypeId } = props.initialValues;
this.state = {
selectedDelivery: fulfilmentPreference === 'Delivery',
selectedAddressTypeId: deliveryAddressTypeId,
selectedItem: item ? {
itemRecord: item,
borrowerRecord: loan.userDetail,
loanRecord: loan,
} : null,
selectedUser: requester ? {
patronGroup: requester.patronGroup,
personal: requester,
} : null,
selectedItemBarcode: null,
selectedUserBarcode: null,
itemSelectionError: null,
userSelectionError: null,
};
this.onChangeAddress = this.onChangeAddress.bind(this);
this.onChangeFulfilment = this.onChangeFulfilment.bind(this);
this.onChangeItem = this.onChangeItem.bind(this);
this.onChangeUser = this.onChangeUser.bind(this);
this.onItemClick = this.onItemClick.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.onSelectUser = this.onSelectUser.bind(this);
this.onUserClick = this.onUserClick.bind(this);
}
componentDidUpdate(prevProps) {
const initials = this.props.initialValues;
const oldInitials = prevProps.initialValues;
if (initials && initials.requester &&
oldInitials && !oldInitials.requester) {
initials.item.location = { name: initials.location };
/* eslint react/no-did-update-set-state: 0 */
this.setState({
selectedAddressTypeId: initials.deliveryAddressTypeId,
selectedDelivery: initials.fulfilmentPreference === 'Delivery',
selectedItem: {
itemRecord: initials.item,
borrowerRecord: initials.loan.userDetail,
loanRecord: initials.loan,
},
selectedUser: {
patronGroup: initials.requester.patronGroup,
personal: initials.requester,
},
});
}
}
onChangeFulfilment(e) {
this.setState({
selectedDelivery: e.target.value === 'Delivery',
});
}
onChangeAddress(e) {
this.setState({
selectedAddressTypeId: e.target.value,
});
}
onChangeUser(e) {
this.setState({
selectedUserBarcode: e.target.value,
});
}
// This function is called from the "search and select user" widget when
// a user has been selected from the list
onSelectUser(user) {
if (user) {
this.setState({
selectedUserBarcode: user.barcode,
});
// Set the new value in the redux-form barcode field
this.props.change('requester.barcode', user.barcode);
setTimeout(() => this.onUserClick());
}
}
onChangeItem(e) {
this.setState({
selectedItemBarcode: e.target.value,
});
}
onUserClick() {
this.props.findUser(this.state.selectedUserBarcode, 'barcode').then((result) => {
if (result.totalRecords > 0) {
this.setState({
selectedUser: result.users[0],
userSelectionError: null,
});
this.props.change('requesterId', result.users[0].id);
}
});
}
onItemClick() {
const { findItem, findLoan, findUser, findRequestsForItem } = this.props;
findItem(this.state.selectedItemBarcode, 'barcode').then((result) => {
if (result.totalRecords > 0) {
const item = result.items[0];
this.props.change('itemId', item.id);
return Promise.all(
[
findLoan(item.id),
findRequestsForItem(item.id),
],
).then((resultArray) => {
const loan = resultArray[0].loans[0];
const requestCount = resultArray[1].requests.length;
if (loan) {
return findUser(loan.userId).then((result2) => {
const borrower = result2.users[0];
this.setState({
selectedItem: {
itemRecord: item,
loanRecord: loan,
borrowerRecord: borrower,
requestCount,
},
});
});
}
// If no loan is found, just set the item record and rq count
this.setState({
selectedItem: {
itemRecord: item,
requestCount,
},
});
return result;
});
}
return result;
});
}
// This function only exists to enable 'do lookup on enter' for item and
// user search
onKeyDown(e, element) {
if (e.key === 'Enter' && e.shiftKey === false) {
e.preventDefault();
if (element === 'item') {
this.onItemClick();
} else {
this.onUserClick();
}
}
}
requireItem = value => (value ? undefined : 'Please select an item');
requireUser = value => (value ? undefined : 'Please select a requester');
render() {
const {
handleSubmit,
initialValues,
onCancel,
optionLists,
patronGroups,
pristine,
submitting,
} = this.props;
const { selectedUser } = this.state;
const isEditForm = (initialValues && initialValues.itemId);
const addRequestFirstMenu = <PaneMenu><Button onClick={onCancel} title="close" aria-label="Close New Request Dialog"><span style={{ fontSize: '30px', color: '#999', lineHeight: '18px' }} >×</span></Button></PaneMenu>;
const addRequestLastMenu = <PaneMenu><Button id="clickable-create-request" type="button" title="Create New Request" disabled={pristine || submitting} onClick={handleSubmit}>Create Request</Button></PaneMenu>;
const editRequestLastMenu = <PaneMenu><Button id="clickable-update-request" type="button" title="Update Request" disabled={pristine || submitting} onClick={handleSubmit}>Update Request</Button></PaneMenu>;
const requestTypeOptions = _.sortBy(optionLists.requestTypes || [], ['label']).map(t => ({ label: t.label, value: t.id, selected: initialValues.requestType === t.id }));
const fulfilmentTypeOptions = _.sortBy(optionLists.fulfilmentTypes || [], ['label']).map(t => ({ label: t.label, value: t.id, selected: t.id === initialValues.fulfilmentPreference }));
const labelAsterisk = isEditForm ? '' : '*';
const disableRecordCreation = true;
let deliveryLocations;
let deliveryLocationsDetail = [];
let addressDetail;
if (selectedUser && selectedUser.personal && selectedUser.personal.addresses) {
deliveryLocations = selectedUser.personal.addresses.map((a) => {
const typeName = _.find(optionLists.addressTypes, { id: a.addressTypeId }).addressType;
return { label: typeName, value: a.addressTypeId };
});
deliveryLocations = _.sortBy(deliveryLocations, ['label']);
deliveryLocationsDetail = _.keyBy(selectedUser.personal.addresses, a => a.addressTypeId);
}
if (this.state.selectedAddressTypeId) {
addressDetail = toUserAddress(deliveryLocationsDetail[this.state.selectedAddressTypeId]);
}
return (
<form id="form-requests" style={{ height: '100%', overflow: 'auto' }}>
<Paneset isRoot>
<Pane defaultWidth="100%" height="100%" firstMenu={addRequestFirstMenu} lastMenu={isEditForm ? editRequestLastMenu : addRequestLastMenu} paneTitle={isEditForm ? 'Edit request' : 'New request'}>
<Row>
<Col sm={5} smOffset={1}>
<h2>Request record</h2>
{ !isEditForm &&
<Field
label={`Request Type ${labelAsterisk}`}
name="requestType"
component={Select}
fullWidth
dataOptions={requestTypeOptions}
disabled={isEditForm}
/>
}
{ isEditForm &&
<KeyValue label="Request Type" value={initialValues.requestType} />
}
<fieldset id="section-item-info">
<legend>{`Item info ${labelAsterisk}`}</legend>
{!isEditForm &&
<Row>
<Col xs={9}>
<Field
name="item.barcode"
placeholder="Scan or enter item barcode"
aria-label="Item barcode"
fullWidth
component={TextField}
onInput={this.onChangeItem}
onKeyDown={e => this.onKeyDown(e, 'item')}
validate={[this.requireItem]}
/>
</Col>
<Col xs={3}>
<Button
id="clickable-select-item"
buttonStyle="primary noRadius"
fullWidth
onClick={this.onItemClick}
disabled={submitting}
>Enter
</Button>
</Col>
</Row>
}
{ (this.state.selectedItem || this.state.itemSelectionError) &&
<ItemDetail
item={this.state.selectedItem}
error={this.state.itemSelectionError}
patronGroups={patronGroups}
dateFormatter={this.props.dateFormatter}
/>
}
</fieldset>
<br />
<fieldset id="section-requester-info">
<legend>{`Requester info ${labelAsterisk}`}</legend>
{!isEditForm &&
<Row>
<Col xs={9}>
<Field
name="requester.barcode"
placeholder="Scan or enter requester barcode"
aria-label="Requester barcode"
fullWidth
component={TextField}
onInput={this.onChangeUser}
onKeyDown={e => this.onKeyDown(e, 'requester')}
validate={this.requireUser}
/>
<Pluggable
aria-haspopup="true"
type="find-user"
searchLabel="Requester look-up"
marginTop0
searchButtonStyle="link"
{...this.props}
dataKey="users"
selectUser={this.onSelectUser}
disableRecordCreation={disableRecordCreation}
visibleColumns={['Name', 'Patron Group', 'Username', 'Barcode']}
/>
</Col>
<Col xs={3}>
<Button
id="clickable-select-requester"
buttonStyle="primary noRadius"
fullWidth
onClick={this.onUserClick}
disabled={submitting}
>Enter
</Button>
</Col>
</Row>
}
{ (this.state.selectedUser || this.state.userSelectionError) &&
<UserDetail
user={this.state.selectedUser}
error={this.state.userSelectionError}
patronGroups={patronGroups}
/>
}
{ this.state.selectedUser &&
<Row>
<Col xs={6}>
<Field
name="fulfilmentPreference"
label="Fulfilment preference"
component={Select}
fullWidth
dataOptions={fulfilmentTypeOptions}
onChange={this.onChangeFulfilment}
/>
</Col>
{ this.state.selectedDelivery && deliveryLocations &&
<Col>
<Field
name="deliveryAddressTypeId"
label="Delivery Address"
component={Select}
fullWidth
dataOptions={[{ label: 'Select address type', value: '' }, ...deliveryLocations]}
onChange={this.onChangeAddress}
/>
</Col>
}
</Row>
}
{ this.state.selectedDelivery && this.state.selectedAddressTypeId &&
<Row>
<Col xsOffset={6} xs={6}>
{addressDetail}
</Col>
</Row>
}
</fieldset>
<fieldset>
<legend>Request details</legend>
<Field
name="requestExpirationDate"
label="Request expiration date"
aria-label="Request expiration date"
backendDateStandard="YYYY-MM-DD"
component={Datepicker}
/>
<Field
name="holdShelfExpirationDate"
label="Hold shelf expiration date"
aria-label="Hold shelf expiration date"
backendDateStandard="YYYY-MM-DD"
component={Datepicker}
/>
</fieldset>
</Col>
</Row>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</Pane>
</Paneset>
</form>
);
}
}
export default stripesForm({
form: 'requestForm',
asyncValidate,
asyncBlurFields: ['item.barcode', 'requester.barcode'],
navigationCheck: true,
enableReinitialize: true,
keepDirtyOnReinitialize: true,
})(RequestForm);