-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscratch
364 lines (339 loc) · 10.2 KB
/
scratch
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
// Handle form submission
const handleSubmit = async (e) => {
e.preventDefault();
// Validate the form and set errors if validation fails
const formErrors = validateForm();
if (Object.values(formErrors).length > 0) {
setErrors(formErrors);
return;
}
setErrors({});
// Create a new product object
const new_product = {
title,
description,
inventory: Number(inventory),
price: Number(price),
category_id: Number(categoryId),
seller_id: user.id,
};
// Dispatch addProduct action to add the new product
const result = await dispatch(addProduct(new_product));
if (result.errors) setErrors(result.errors);
const productId = result.id;
// Prepare an array of images to upload
let imageArray = [
{
product_id: productId,
url: previewImageUrl,
preview: true,
},
];
// Add additional images if provided
if (image1Url)
imageArray.push({
product_id: productId,
url: image1Url,
preview: false,
});
if (image2Url)
imageArray.push({
product_id: productId,
url: image2Url,
preview: false,
});
if (image3Url)
imageArray.push({
product_id: productId,
url: image3Url,
preview: false,
});
if (image4Url)
imageArray.push({
product_id: productId,
url: image4Url,
preview: false,
});
if (image5Url)
imageArray.push({
product_id: productId,
url: image5Url,
preview: false,
});
setImagesLoading(true)
try {
await Promise.all(
imageArray.map((image) => {
const formData = new FormData();
formData.append('product_id', image.product_id);
formData.append('url', image.url);
formData.append('preview', image.preview);
// console.log("formData", formData)
dispatch(addProductImage(formData, user.id))
})
);
} catch (e) {
console.log(e)
setErrors(e.errors)
}
setImagesLoading(false)
// dispatch(productByUserId());
// Handle errors or navigate to the new product page
if (!errors) {
navigate(`/products/${productId}`);
}
};
// Helper function to format the price input as a decimal
const formatDecimal = (input) => {
let value = parseFloat(input.value);
if (!isNaN(value)) {
input.value = value.toFixed(2);
}
return input.value;
};
return (
<main>
<form method="POST" onSubmit={handleSubmit} className="product_form" encType="multipart/form-data">
<div>
<label>
<h3>Title</h3>
</label>
<p>Include keywords that buyers would use to search for this item.</p>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
{errors.title && <p className="error">{errors.title}</p>}
</div>
<div>
<label>
<h3>Description</h3>
</label>
<p>
Tell the world all about your item and why they’ll love it. Buyers
will only see the first few lines unless they expand the
description.
</p>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
></textarea>
{errors.description && <p className="error">{errors.description}</p>}
</div>
<div>
<label>
<h3>Inventory</h3>
</label>
<p>
Keep your product availability up-to-date to ensure customers know
when your item is in stock.
</p>
<input
type="number"
min="1"
step="1"
value={inventory}
onChange={(e) => setInventory(e.target.value)}
onBlur={(e) => {
const formatted = parseInt(e.target.value);
setInventory(formatted);
}}
/>
{errors.inventory && <p className="error">{errors.inventory}</p>}
</div>
<div>
<label>
<h3>Price</h3>
</label>
<p>
Competitive pricing can help your listing stand out and rank higher
in search results.
</p>
<input
type="number"
value={price}
onChange={(e) => {
setPrice(e.target.value);
}}
step="0.01"
onBlur={(e) => {
const formatted = formatDecimal(e.target);
setPrice(formatted);
}}
/>
{errors.price && <p className="error">{errors.price}</p>}
</div>
<div>
<label>
<h3>Category</h3>
</label>
<p>
Categorize your product accurately to help customers find it more
easily.
</p>
<div className="select-container">
<select
name="category_id"
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
>
<option value="0">Select a category</option>
<option value="1">Home & Living</option>
<option value="2">Accessories</option>
<option value="3">Crafting</option>
<option value="4">Jewelry</option>
<option value="5">Clothing</option>
</select>
</div>
{errors.categoryId && <p className="error">{errors.categoryId}</p>}
</div>
<div>
<label>
<h3>Preview Image URL</h3>
</label>
<p>Submit at least one photo to publish your product.</p>
<input
type="file"
onChange={(e) => setPreviewImageUrl(e.target.files[0])}
accept="image/*, video/*"
name="url"
/>
{previewImageUrl && previewImageUrl.type.match(/image\/\w*/) ? (
<img
className="previewImagesize"
src={URL.createObjectURL(previewImageUrl)}
alt="Preview if Image is valid"
/>
) : null}
{errors.previewImageUrl && (
<p className="error">{errors.previewImageUrl}</p>
)}
</div>
<div>
<label>Image URL:</label>
<input
type="file"
onChange={(e) => setImage1Url(e.target.files[0])}
accept="image/*, video/*"
/>
{image1Url ? (
<img
className="previewImagesize"
src={image1Url}
alt="Preview if Image is valid"
/>
) : null}
</div>
<div>
<label>Image URL:</label>
<input
type="file"
onChange={(e) => setImage2Url(e.target.files[0])}
accept="image/*, video/*"
/>
{image2Url ? (
<img
className="previewImagesize"
src={image2Url}
alt="Preview if Image is valid"
/>
) : null}
</div>
<div>
<label>Image URL:</label>
<input
type="file"
onChange={(e) => setImage3Url(e.target.files[0])}
accept="image/*, video/*"
/>
{image3Url ? (
<img
className="previewImagesize"
src={image3Url}
alt="Preview if Image is valid"
/>
) : null}
</div>
<div>
<label>Image URL:</label>
<input
type="file"
onChange={(e) => setImage4Url(e.target.files[0])}
accept="image/*, video/*"
/>
{image4Url ? (
<img
className="previewImagesize"
src={image4Url}
alt="Preview if Image is valid"
/>
) : null}
</div>
<div>
<label>Image URL:</label>
<input
type="file"
onChange={(e) => setImage5Url(e.target.files[0])}
accept="image/*, video/*"
/>
{image5Url ? (
<img
className="previewImagesize"
src={image5Url}
alt="Preview if Image is valid"
/>
) : null}
</div>
<button type="submit">{imagesLoading? "Loading" : "Publish Your Product"}</button>
</form>
</main>
);
}
// Add Image Thunk
export const addProductImage = (image, userId) => async (dispatch) => {
console.log('add image', image)
const response = await fetch("/api/products/images/new", {
method: "POST",
// headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify(image),
});
if (response.ok) {
const newImage = await response.json();
dispatch(createImage(newImage, userId));
return newImage;
} else {
const error = await response.json();
return error;
}
};
@products_routes.route("/images/new", methods=["POST"])
@login_required
def create_images():
form = ProductImageForm()
form["csrf_token"].data = request.cookies["csrf_token"]
print("FORMMMMMM", form.data)
if form.validate_on_submit():
image = form.data["image"]
image.filename = get_unique_filename(image["filename"])
print("~~~~~~~~~~~~~~~~~", image)
upload = upload_file_to_s3(image)
print(upload)
if "url" not in upload:
# if the dictionary doesn't have a url key
# it means that there was an error when you tried to upload
# so you send back that error message (and you printed it above)
return {"errors": upload}, 400
url = upload["url"]
new_image = ProductImage(
product_id=form.data["product_id"],
url=url,
preview=form.data["preview"],
)
print('HEERRERERERE', new_image)
db.session.add(new_image)
db.session.commit()
return new_image.to_dict(), 201
else:
print("Form errors:", form.errors)
return form.errors, 400