Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/adding migrate changing service order #109

Merged
merged 5 commits into from
Jul 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/models/ordem_servico_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class Item(db.EmbeddedDocument):
codigo = db.StringField(required=False)
nome = db.StringField(required=False)
unidade_medida = db.StringField(required=False)
quantidade = db.IntField(required=False)
descricao = db.StringField(required=False)
quantidade = db.IntField(required=False)


class Diagnostico(db.EmbeddedDocument):
Expand Down
11 changes: 7 additions & 4 deletions api/services/ordem_servico_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ def get_ordem_servico_equipamento_pipeline():
}
]


def listar_ordem_servico():
def fetch_ordem_servico():
pipeline = [
{
"$lookup": {
Expand All @@ -34,10 +33,14 @@ def listar_ordem_servico():

docs = []
for ordem in ordem_servico_model.OrdemServico.objects(
status__ne='tmp').aggregate(pipeline):
status__ne='tmp').aggregate(pipeline):
docs.append(ordem)

return dumps(docs)
return docs


def listar_ordem_servico():
return dumps(fetch_ordem_servico())


def gera_query_adaptada(current_key, currnet_value):
Expand Down
131 changes: 131 additions & 0 deletions api/v2/controllers/items_merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
from flask_restful import Resource
from flask import make_response, jsonify, request
from ..helpers.helper_response import error_response, get_response, post_response
from ..helpers.helper_update import pop_id
from ..services.item_service import ItemService
from ..validation.schemas.item_schema import ItemSchema
from ..validation.validation_request import (
validate_request,
validate_post,
invalid_deleted_parameter,
validate_request_dict_id,
validate_request_id,
validate_is_list,
)
import json


class ItemsManyController(Resource):
def get(self):
args_deleted = request.args.get("deleted")
if invalid_deleted_parameter(args_deleted):
return error_response("Parameter deleted is not equal true.", 400)

content = ItemService().fetch_items_list(args_deleted)

return get_response(content, args_deleted)

def post(self):
body = request.get_json()

validate, message = validate_request(body)
if not validate:
return error_response(message)

errors = []
for index, item in enumerate(body["content"]):
validate, message = validate_post(item)
if not validate:
errors.append({index: message})
continue

erro_schema = ItemSchema().validate(item)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Talvez seja uma boa ideia mover as validações de esquema desta classe para validators/validation_request

if erro_schema:
errors.append({index: erro_schema})

if errors:
return error_response(errors)

content = []
for item in body["content"]:
content.append(ItemService().register_item(item))

return post_response(content)

def put(self):
body = request.get_json()
validate, message = validate_request(body)
if not validate:
return error_response(message)

errors = []
for index, item in enumerate(body['content']):
validate, message = validate_request_dict_id(item)
if not validate:
errors.append({index: message})
continue

erro_schema = ItemSchema().validate(item)
if erro_schema:
errors.append({index: erro_schema})

if errors:
return error_response(errors)

for index, item in enumerate(body['content']):
id = pop_id(item)
ItemService().replace_fields(id, item)

return '', 200

def patch(self):
body = request.get_json()
validate, message = validate_request(body)
if not validate:
return error_response(message)

errors = []
for index, item in enumerate(body["content"]):
validate, message = validate_request_dict_id(item)
if not validate:
errors.append({index: message})
continue

erro_schema = ItemSchema().validate_updates(item, index)
if erro_schema:
errors.append({index: erro_schema})

if errors:
return error_response(errors)

for index, item in enumerate(body["content"]):
id = pop_id(item)
ItemService().update_item_only_fields(data=item, id=id)

return "", 200

def delete(self):
body = request.get_json()
validate, message = validate_request(body)
if not validate:
return error_response(message)

validate, message = validate_is_list(body['content'])
if not validate:
return error_response(message)

errors = []
for index, _id in enumerate(body['content']):
validate, message = validate_request_id(_id)

if not validate:
errors.append({index: message})

if errors:
return error_response(errors)


for _id in body['content']:
ItemService().delete_item(_id)

return "", 200
5 changes: 5 additions & 0 deletions api/v2/migrations/items_from_diagnostico_service_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@ def fetch_items_from_diagnostico(self):
if 'diagnostico' in service_order.keys():
if 'itens' in service_order['diagnostico']:
for item in service_order['diagnostico']['itens']:
if "item_id" in item:
continue

reference_key = self.generate_reference_key(item)
if not reference_key in items:
item['reference_key'] = reference_key
items[reference_key] = item
continue
items[reference_key]['quantidade'] += item['quantidade']

return items

def generate_reference_key(self, item):
Expand All @@ -28,6 +32,7 @@ def generate_item(self, items):
new_items = []

for key, item in items.items():
item['tipo'] = 'pecas'
new_items.append(item)

return new_items
Expand Down
15 changes: 10 additions & 5 deletions api/v2/migrations/items_from_triagem_service_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,28 @@ def fetch_items_from_triagem(self):
if 'triagem' in service_order:
if 'acessorios' in service_order['triagem']:
for acessorio in service_order['triagem']['acessorios']:
if "item_id" in acessorio:
continue

reference_key = self.generate_reference_key(acessorio)
acessorio['reference_key'] = reference_key
if not reference_key in items:
acessorio['reference_key'] = reference_key
items[reference_key] = acessorio
continue
items[reference_key]['quantidade'] += acessorio['quantidade']

items[reference_key]['quantidade'] += acessorio[
'quantidade']
return items

def generate_reference_key(self, acessorio):
reference_key = slugify(acessorio['descricao'], separator='')
return reference_key
return slugify(acessorio['descricao'], separator='')

def generate_item(self, items):
new_items = []

for key, item in items.items():
aux = {}
aux['tipo'] = 'acessorio'
aux['nome'] = item['descricao']
aux['quantidade'] = item['quantidade']
aux['unidade_medida'] = 'und'
Expand All @@ -42,5 +47,5 @@ def generate_item(self, items):
def get_items(self):
items_from_collection = self.fetch_items_from_triagem()
items = self.generate_item(items_from_collection)

return items
80 changes: 75 additions & 5 deletions api/v2/migrations/items_migration_base.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,86 @@
from flask_restful import Resource
from flask import make_response, jsonify
from flask import make_response, jsonify, request
from .items_from_triagem_service_order import ItemsTriagemMigration
from .items_from_diagnostico_service_order import ItemsDiagnosticoMigration
from api.v2.services.item_service import ItemService
from ..models import service_order_model
from ...services.ordem_servico_service import fetch_ordem_servico


def has_accessories_service_order(service_order):
return "triagem" in service_order \
and "acessorios" in service_order["triagem"]


def has_items_service_order(service_order):
return "diagnostico" in service_order \
and "itens" in service_order["diagnostico"]


def get_item_by_reference_key(items):
doc = {}
for item in items:
doc[ItemsDiagnosticoMigration().generate_reference_key(item)] = item
return doc


def define_service_order_screening(service_order, items):
if has_accessories_service_order(service_order):
for i in range(len(service_order["triagem"]["acessorios"])):
acessorio = service_order["triagem"]["acessorios"][i]
acessorio["item_id"] = items[ItemsTriagemMigration()
.generate_reference_key(acessorio)]['_id']
del acessorio['descricao']
service_order["triagem"]["acessorios"][i] = acessorio

return service_order


def define_service_order_diagnosis(service_order, items):
if has_items_service_order(service_order):
for i in range(len(service_order["diagnostico"]["itens"])):
item = {}
item["item_id"] = items[ItemsDiagnosticoMigration()
.generate_reference_key(
service_order["diagnostico"]["itens"][i]
)]['_id']
item['quantidade'] = service_order["diagnostico"]["itens"][i][
'quantidade']
service_order["diagnostico"]["itens"][i] = item

return service_order


def update_service_order_migrated(service_order):
id = service_order['_id']
del service_order['_id']
del service_order['equipamento']
service_order_model.OrdemServico.objects.get(id=id).update(**service_order)


class ItemsMigrationBase(Resource):
def get(self):
self.register_items('triagem')
self.register_items('diagnostico')
def handle_migrate_service_order(self):
self.migrate_service_order(
get_item_by_reference_key(ItemService().fetch_items_list()),
fetch_ordem_servico()
)

return make_response(jsonify('Items migrated.'), 200)
def migrate_service_order(self, items, service_orders):
for service_order in service_orders:
update_service_order_migrated(
define_service_order_diagnosis(
define_service_order_screening(service_order, items),
items
)
)

def check_reference_key_in_collection(self, obj):
items_from_collection = ItemService().fetch_items_list()

for item in items_from_collection:
if obj['reference_key'] in item.values():
return False

return True

def register_items(self, key):
Expand All @@ -33,3 +96,10 @@ def register_items(self, key):
validate = self.check_reference_key_in_collection(item)
if validate:
ItemService().register_item(item)

def get(self):
self.register_items('triagem')
self.register_items('diagnostico')
self.handle_migrate_service_order()

return make_response(jsonify('Items migrated.'), 200)
7 changes: 7 additions & 0 deletions api/v2/models/service_order_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class Acessorio(db.EmbeddedDocument):
acompanha = db.BooleanField(required=True)
quantidade = db.IntField(required=True)
estado_de_conservacao = db.StringField(required=False)
descricao = db.StringField(required=False)


class Triagem(db.EmbeddedDocument):
Expand All @@ -21,6 +22,12 @@ class Triagem(db.EmbeddedDocument):
class ItemDiagnostico(db.EmbeddedDocument):
item_id = db.ReferenceField(Item, required=True)
quantidade = db.IntField(required=True)
tipo = db.StringField(required=False)
fabricante = db.StringField(required=False)
codigo = db.StringField(required=False)
nome = db.StringField(required=False)
unidade_medida = db.StringField(required=False)
descricao = db.StringField(required=False)


class Diagnostico(db.EmbeddedDocument):
Expand Down
1 change: 1 addition & 0 deletions tests/items_many/test_items_base_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ def test_reference_key_in_collection(self):
item_triagem = self.get_mock("item", "objeto_item")
response = ItemsMigrationBase().\
check_reference_key_in_collection(item_triagem)

self.assertEqual(response, False)
1 change: 1 addition & 0 deletions tests/items_many/test_items_triagem_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def test_item_should_generate_reference_key(self):
def test_object_is_valid_item(self):
item_triagem = self.get_mock("item", "triagem_formatado")
generated_item = ItemsTriagemMigration().generate_item(item_triagem)
self.assertIn('tipo', generated_item[0])
self.assertIn('nome', generated_item[0])
self.assertIn('quantidade', generated_item[0])
self.assertIn('unidade_medida', generated_item[0])
Expand Down
Loading