2021-05-19 07:47:14 +00:00
|
|
|
import os
|
2021-05-19 11:59:59 +00:00
|
|
|
import time
|
2021-05-19 07:47:14 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from flask import current_app as app, request, g, Response
|
2021-05-13 11:35:46 +00:00
|
|
|
from teal.resource import View
|
|
|
|
|
|
|
|
from ereuse_devicehub.db import db
|
2021-05-14 10:58:56 +00:00
|
|
|
from ereuse_devicehub.resources.tradedocument.models import TradeDocument
|
2021-05-19 07:47:14 +00:00
|
|
|
from ereuse_devicehub.resources.hash_reports import insert_hash
|
|
|
|
|
|
|
|
|
|
|
|
def save_doc(data, user):
|
|
|
|
"""
|
|
|
|
This function allow save a snapshot in json format un a TMP_SNAPSHOTS directory
|
|
|
|
The file need to be saved with one name format with the stamptime and uuid joins
|
|
|
|
"""
|
|
|
|
filename = data['file_name']
|
|
|
|
lot = data['lot']
|
|
|
|
now = datetime.now()
|
|
|
|
year = now.year
|
|
|
|
month = now.month
|
|
|
|
day = now.day
|
|
|
|
hour = now.hour
|
|
|
|
minutes = now.minute
|
2021-05-19 11:59:59 +00:00
|
|
|
created = time.time()
|
2021-05-19 07:47:14 +00:00
|
|
|
|
2021-05-19 11:59:59 +00:00
|
|
|
name_file = f"{year}-{month}-{day}-{hour}-{minutes}_{created}_{user}_{filename}"
|
2021-05-19 07:47:14 +00:00
|
|
|
path_dir_base = os.path.join(app.config['PATH_DOCUMENTS_STORAGE'] , user)
|
|
|
|
path = os.path.join(path_dir_base, str(lot.id))
|
|
|
|
path_name = os.path.join(path, name_file)
|
|
|
|
|
|
|
|
os.system(f'mkdir -p {path}')
|
|
|
|
|
|
|
|
with open(path_name, 'wb') as doc_file:
|
|
|
|
doc_file.write(data['file'])
|
|
|
|
|
|
|
|
return path_name
|
|
|
|
|
2021-05-13 11:35:46 +00:00
|
|
|
|
2021-05-14 10:58:56 +00:00
|
|
|
class TradeDocumentView(View):
|
2021-05-13 11:35:46 +00:00
|
|
|
|
|
|
|
def one(self, id: str):
|
2021-05-14 10:58:56 +00:00
|
|
|
doc = TradeDocument.query.filter_by(id=id, owner=g.user).one()
|
|
|
|
return self.schema.jsonify(doc)
|
2021-05-13 11:35:46 +00:00
|
|
|
|
|
|
|
def post(self):
|
2021-05-14 10:58:56 +00:00
|
|
|
"""Add one document."""
|
2021-05-19 07:47:14 +00:00
|
|
|
|
2021-05-14 10:58:56 +00:00
|
|
|
data = request.get_json(validate=True)
|
2021-05-19 07:47:14 +00:00
|
|
|
data['path_name'] = save_doc(data, g.user.email)
|
|
|
|
bfile = data.pop('file')
|
|
|
|
insert_hash(bfile)
|
|
|
|
|
2021-05-14 10:58:56 +00:00
|
|
|
doc = TradeDocument(**data)
|
|
|
|
db.session.add(doc)
|
2021-05-13 11:35:46 +00:00
|
|
|
db.session().final_flush()
|
2021-05-14 10:58:56 +00:00
|
|
|
ret = self.schema.jsonify(doc)
|
2021-05-13 11:35:46 +00:00
|
|
|
ret.status_code = 201
|
|
|
|
db.session.commit()
|
|
|
|
return ret
|
2021-05-14 10:58:56 +00:00
|
|
|
|
|
|
|
def delete(self, id):
|
|
|
|
doc = TradeDocument.query.filter_by(id=id, owner=g.user).one()
|
|
|
|
db.session.delete(doc)
|
|
|
|
db.session.commit()
|
|
|
|
return Response(status=204)
|