/
ReportProblem.tsx
280 lines (261 loc) · 9.36 KB
/
ReportProblem.tsx
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
import { Button, Form, Input, Modal, Tooltip, Upload, UploadFile } from "antd";
import TextArea from "antd/lib/input/TextArea";
import { UploadChangeParam } from "antd/lib/upload";
import { RcFile, UploadFileStatus } from "antd/lib/upload/interface";
import { UploadSimple, Warning } from "phosphor-react";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { selectCurrentPage } from "../../app/mainSelectors";
import { PageType } from "../../app/mainSlice.types";
import { DialogWithForm } from "../../common/components/DialogWithForm";
import { HttpEndpoint, request } from "../../services/backend";
import { ValidationErrorType } from "../locators/locatorSlice.types";
import { selectCurrentPageObject } from "../pageObjects/pageObjectSelectors";
import { isAllowedExtension, isImage, toBase64, getFilesSize, MAX_COUNT_FILES, MAX_FILES_SIZE_MB } from "./utils";
const { error } = Modal;
export interface ReportFormProps {
body: string;
from: string;
upload?: UploadFile[];
}
export const ReportProblem = () => {
const [isModalOpen, setIsModalOpen] = useState(false);
const [serverPingInProcess, setServerPingInProcess] = useState(false);
const [form] = Form.useForm<ReportFormProps>();
const pageData = useSelector(selectCurrentPageObject)?.pageData;
const currentPage = useSelector(selectCurrentPage).page;
const [fileList, setFileList] = useState<UploadFile[]>([]);
const filesSize = getFilesSize(fileList);
const areFilesInvalid = fileList.length >= MAX_COUNT_FILES || filesSize >= MAX_FILES_SIZE_MB;
useEffect(() => {
const defaultFileList = async () =>
pageData && currentPage === PageType.LocatorsList
? [
{
uid: "0",
name: "pageData.json",
status: "done" as UploadFileStatus,
url: (await toBase64(new Blob([pageData]) as RcFile)) as string | undefined,
linkProps: { download: "pageData.json" },
},
]
: [];
defaultFileList().then(setFileList);
}, [currentPage, pageData]);
useEffect(() => {
const files = document.querySelector(".ant-upload-list");
if (files) files.scrollTop = files.scrollHeight;
}, [fileList]);
const showExceprionConfirm = () =>
error({
title: "Report is not available",
content: (
<React.Fragment>
Mail server is not accessible from your location and problem report can't be created automatically.
Please send an email{" "}
<a href="mailto:SupportJDI@epam.com" data-turbo-frame="">
SupportJDI@epam.com
</a>{" "}
by yourself.
</React.Fragment>
),
});
const handleOk = () => {
form
.validateFields()
.then((values) => {
// have no idea how make antd validate uploads properly
if (values.upload?.find((file) => file.status === "error")) {
throw new Error("invalid uploads");
}
sendReport(values);
form.resetFields();
setFileList([]);
setIsModalOpen(false);
})
.catch(() => {
const failedUploadFile = document.querySelector(".ant-upload-list-item-error");
failedUploadFile?.scrollIntoView({ behavior: "smooth" });
});
};
const showModal = () => {
setServerPingInProcess(true);
request
.get(HttpEndpoint.PING_SMTP)
.then((response) => {
if (response === 1) {
setServerPingInProcess(false);
setIsModalOpen(true);
} else showExceprionConfirm();
})
.catch(() => showExceprionConfirm())
.finally(() => setServerPingInProcess(false));
};
const sendReport = (values: ReportFormProps) => {
const { upload, ...rest } = values;
const attachments = upload
? upload.map((file: UploadFile) => ({
file_content: file.url?.replace(/data:(image|text|application)\/.+;base64,/, ""),
filename: file.name,
}))
: [];
request.post(HttpEndpoint.REPORT_PROBLEM, {
attachments,
subject: "Report problem",
...rest,
});
};
const handleUploadChange = async (info: UploadChangeParam<UploadFile>) => {
const newFileList = info.fileList.map(async (_file) => {
if (info.file.uid === _file.uid && _file.originFileObj) {
if (_file.size !== 0 && (_file.size || Infinity) / 1024 / 1024 > 2) {
_file.status = "error";
_file.response = "The file cannot weigh more than 2Mb";
_file.error = true;
return _file;
}
if (isImage(_file) || (_file.type && isAllowedExtension(_file.type))) {
_file.url = (await toBase64(_file.originFileObj)) as string;
} else {
_file.status = "error";
_file.response = "Invalid file extension, only image/*, *.zip, *.rar, *.json, *.txt";
_file.error = true;
}
_file.linkProps = { download: _file.name };
}
return _file;
});
Promise.all(newFileList).then(setFileList);
};
const normFile = (e: Record<string, never>) => {
if (Array.isArray(e)) return e;
return e?.fileList;
};
const getTextforUploadButtonTooltip = () => {
switch (true) {
case fileList.length >= MAX_COUNT_FILES && filesSize >= MAX_FILES_SIZE_MB:
return "Please check number of files and their weight";
case fileList.length >= MAX_COUNT_FILES:
return "Only 10 files can be uploaded";
case filesSize >= MAX_FILES_SIZE_MB:
return "The maximum files weight can not exceed 10Mb";
default:
return "Please check number of files or their weight";
}
};
return (
<div className="jdn__reportProblem">
<Tooltip title="Report a problem" placement="bottomRight" align={{ offset: [12, 0] }}>
<Button
onClick={showModal}
type="link"
loading={serverPingInProcess}
className="ant-btn ant-btn-link ant-btn-icon-only"
icon={<Warning size={14} color="#8C8C8C" />}
></Button>
</Tooltip>
{isModalOpen ? (
<DialogWithForm
modalProps={{
okButtonProps: {
disabled:
fileList.length > MAX_COUNT_FILES ||
filesSize > MAX_FILES_SIZE_MB ||
fileList.some((file) => file.status === "error"),
},
title: "Report a problem",
open: isModalOpen,
onOk: handleOk,
setIsModalOpen,
cancelCallback: () => setFileList([]),
className: "jdn__reportProblem_modal",
}}
formProps={{
form,
}}
>
<Form.Item
label="E-mail"
name="from"
rules={[
{
required: true,
message: ValidationErrorType.EmptyValue,
},
{
// eslint-disable-next-line max-len
pattern: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z](?:[a-z]*[a-z])?/,
message: "Please input a valid email",
},
]}
>
<Input placeholder="Your feedback e-mail" maxLength={28} />
</Form.Item>
<Form.Item
label="Text"
name="body"
rules={[
{
required: true,
message: "Please input your problem description",
},
]}
>
<TextArea rows={5} placeholder="Describe your problem" maxLength={2000} showCount />
</Form.Item>
<Form.Item
name="upload"
label="Upload"
valuePropName="upload"
getValueFromEvent={normFile}
rules={[
() => ({
validator(_, value) {
if (value.length <= MAX_COUNT_FILES) {
return Promise.resolve();
}
return Promise.reject(new Error("Only 10 files can be uploaded"));
},
}),
() => ({
validator(_, value) {
const filesSize = getFilesSize(value);
if (filesSize <= MAX_FILES_SIZE_MB) {
return Promise.resolve();
}
return Promise.reject(new Error("The maximum files weight can not exceed 10Mb"));
},
}),
]}
extra={
<React.Fragment>
Extensions: image/*, *.zip, *.rar, *.json, *.txt
<br />
File size maximum 2Mb, 10 files in total, total size maximum 10Mb
</React.Fragment>
}
>
<Upload name="attachments" onChange={handleUploadChange} multiple>
<Tooltip
placement="right"
title={getTextforUploadButtonTooltip()}
trigger={areFilesInvalid ? ["hover", "focus"] : ""}
>
<Button
disabled={areFilesInvalid}
icon={
<span role="img" className="anticon anticon-upload">
<UploadSimple />
</span>
}
>
Upload
</Button>
</Tooltip>
</Upload>
</Form.Item>
</DialogWithForm>
) : null}
</div>
);
};