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

Add service orders patch #104

Merged
merged 6 commits into from
Jul 2, 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
Empty file.
13 changes: 13 additions & 0 deletions api/v2/controllers/dtos/service_order_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class ServiceOrderRequest:
def __init__(self, data):
self.tipo = data["tipo"]
self.data = data

def get(self):
return self.data

def valid(self):
return True

def errors(self):
return [{}]
6 changes: 6 additions & 0 deletions api/v2/controllers/dtos/service_orders_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class ServiceOrdersRequest():
Copy link

Choose a reason for hiding this comment

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

Essa classe está sendo utilizada na aplicação? Se sim, o método errors é realmente necessário? Aparentemente ele só está chamando o pass.

Copy link

@Adrilene Adrilene Jul 2, 2020

Choose a reason for hiding this comment

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

Toda a pasta dtos foi feita pela @sarahraqueld , mas não sei onde nem mesmo se é usada. Então queria deixar nas mãos dela a deleção ou não.

def __init__(self, data):
self.data = data

def errors(self):
pass
46 changes: 41 additions & 5 deletions api/v2/controllers/service_orders_many_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
from flask_restful import Resource
from ..helpers.helper_response import get_response
from ..validation.validation_request import invalid_deleted_parameter
from api.v2.controllers.validators.validation_request import validate_request
from api.v2.controllers.validators.validation_request import (
validate_request,
validate_request_id,
validate_request_dict_id,
)
from api.v2.services.service_order_service import ServiceOrderService
from api.v2.models.schemas.service_order_schema import ServiceOrderSchema
from api.v2.utils.util_response import error_response, post_response
from .validators.validation_request import validate_request_id
from ..utils.util_update import pop_id


class ServiceOrdersManyController(Resource):
Expand All @@ -24,6 +28,34 @@ def get(self):

return get_response(service_orders, deleted_included)

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

errors = []
for index, service_order in enumerate(body["content"]):
validate, message = ServiceOrderSchema().validate_updates(
service_order, index
)

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

validate, message = validate_request_dict_id("service_order", service_order)
if not validate:
errors.append({index: message})

if errors:
return error_response(errors)

for index, service_order in enumerate(body["content"]):
id = pop_id(service_order)
ServiceOrderService().update(id, service_order)

return "", 200

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

Expand Down Expand Up @@ -56,12 +88,16 @@ def post(self):
if not validate:
errors.append({index: message})

service_order["numero_ordem_servico"] = ServiceOrderService().format_service_order_number(
service_order[
"numero_ordem_servico"
] = ServiceOrderService().format_service_order_number(
service_order["numero_ordem_servico"]
)

if ServiceOrderService().check_duplicates_service_order_number(service_order["numero_ordem_servico"]):
errors.append({index: 'Service Order number already exists'})
if ServiceOrderService().check_duplicates_service_order_number(
service_order["numero_ordem_servico"]
):
errors.append({index: "Service Order number already exists"})

if errors:
return error_response(errors)
Expand Down
18 changes: 12 additions & 6 deletions api/v2/controllers/validators/validation_request.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from bson import ObjectId
from api.v2.services.item_service import ItemService
from api.services.equipamento_service import listar_equipamento_by_id
from ...services.service_order_service import ServiceOrderService


def invalid_deleted_parameter(param):
Expand Down Expand Up @@ -31,6 +32,7 @@ def validate_request(body):

if not len(body["content"]):
return (False, "Empty list. Nothing to do.")

for item in body["content"]:
if not item:
return (False, "Some entry has no data.")
Expand Down Expand Up @@ -61,28 +63,32 @@ def validate_id_exists(entity, _id):
if not listar_equipamento_by_id(_id):
return (False, "Nonexistent equipamento ID")

if entity == "service_order":
if not ServiceOrderService().fetch_service_order_by_id(_id):
return (False, "Nonexistent service order ID")

return (True, "OK")


def validate_request_dict_id(entity):
def validate_request_dict_id(name_entity: str, entity: dict):
validate, message = validate_id_included(entity)
if not validate:
return (validate, message)

validate, message = validate_request_id(entity["_id"])
validate, message = validate_request_id(name_entity, entity["_id"])
if not validate:
return (validate, message)

return (True, "OK")


def validate_request_id(entity, _id):
def validate_request_id(name_entity: str, _id: str):
validate, message = validate_id_objectID(_id)
if not validate:
return (validate, message)
return validate, message

validate, message = validate_id_exists(entity, _id)
validate, message = validate_id_exists(name_entity, _id)
if not validate:
return (validate, message)
return validate, message

return (True, "OK")
10 changes: 9 additions & 1 deletion api/v2/models/schemas/schema_base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from marshmallow import ValidationError
from marshmallow import Schema


class SchemaBase:
class SchemaBase(Schema):
def validate_save(self, body):
if "_id" in body:
return False, "Id must not be sent"
Expand All @@ -18,3 +19,10 @@ def validate_save(self, body):
return False, err.messages

return True, "OK"

def validate_updates(self, entity: dict, index: int, fields: tuple):
try:
self.load(entity, partial=fields)
return True, "OK"
except ValidationError as err:
return False, err.messages
6 changes: 5 additions & 1 deletion api/v2/models/schemas/service_order_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class Meta:
status = fields.String(required=False)


class ServiceOrderSchema(Schema, SchemaBase):
class ServiceOrderSchema(SchemaBase):
class Meta:
model = service_order_model.OrdemServico
fields = ("_id",
Expand All @@ -90,3 +90,7 @@ class Meta:
calibragem = fields.Nested(CalibrationSchema, required=True)
status = fields.String(validate=validate.OneOf(["triagem", "diagnostico"]),
required=True)

def validate_updates(self, service_order: dict, index: int):
fields = ('numero_ordem_servico', 'calibragem', 'status')
return super().validate_updates(service_order, index, fields)
Empty file added api/v2/routes.py
Empty file.
18 changes: 17 additions & 1 deletion api/v2/services/service_order_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .service_base import ServiceBase
from ..models.service_order_model import OrdemServico

from ..utils.util_update import update_only_fields

class ServiceOrderService(ServiceBase):
def fetch_active(self):
Expand All @@ -11,6 +11,22 @@ def fetch_active(self):
def fetch_all(self):
return self.parser_mongo_response_to_list(OrdemServico.objects())

def fetch_service_order_by_id(self, _id):
return OrdemServico.objects(id=_id).first()

def update(self, id, service_order):
update_only_fields(_id=id, data=service_order, model=OrdemServico)

def insert_or_update(self, service_order):
if "_id" in service_order.keys():
self.update(service_order)
else:
self.insert(service_order)

def insert(self, service_order):
pass
return self.parser_mongo_response_to_list(OrdemServico.objects())

def save_service_order(self, service_order):
service_order = OrdemServico(**service_order).save()
return str(service_order.id)
Expand Down
39 changes: 39 additions & 0 deletions api/v2/utils/util_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
def pop_id(data):
id = data['_id']
try:
del data['_id']
except Exception:
return Exception

return id


def define_updated_fields(current_key, current_value):
"""
current_key: String
current_value: Any Primitive type
"""
query = {}
if type(current_value) == dict:
for k, v in current_value.items():
query.update(define_updated_fields(
current_key + "__{}".format(k), v))

else:
query[current_key] = current_value

return query


def update_only_fields(_id, data, model):
"""
_id: ObjectId
data: Dict
model: Mongoengine.Document
"""
query = {}
root_key = "set"
root_value = data
query.update(define_updated_fields(root_key, root_value))

model.objects(id=_id).update(**query)
78 changes: 37 additions & 41 deletions config/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,63 +8,59 @@
movimentacao_view,
log_view,
calibragem_view,
diagnostico_view, utils_view
diagnostico_view,
utils_view,
)

from api.v2.migrations import items_migration_base
from api.v2.controllers import (
from api.v2.controllers import (
items_many_controller,
service_orders_many_controller,
service_order_image_controller
service_order_image_controller,
)


def initialize_routes(api):
api.add_resource(equipamento_view.EquipamentoList,
'/api/equipamentos')
api.add_resource(equipamento_view.EquipamentoBulk,
'/api/equipamentos/bulk')
api.add_resource(equipamento_view.EquipamentoDetail,
'/api/equipamento/<_id>')
api.add_resource(equipamento_view.EquipamentoList, "/api/equipamentos")
api.add_resource(equipamento_view.EquipamentoBulk, "/api/equipamentos/bulk")
api.add_resource(equipamento_view.EquipamentoDetail, "/api/equipamento/<_id>")

api.add_resource(ordem_servico_view.OrdemServicoList,
'/api/ordem_servicos')
api.add_resource(ordem_servico_view.OrdemServicoDetail,
'/api/ordem_servico/<_id>')
api.add_resource(ordem_servico_view.OrdemServicoQuery,
'/api/ordem_servico/find')
api.add_resource(ordem_servico_view.OrdemServicoList, "/api/ordem_servicos")
api.add_resource(ordem_servico_view.OrdemServicoDetail, "/api/ordem_servico/<_id>")
api.add_resource(ordem_servico_view.OrdemServicoQuery, "/api/ordem_servico/find")

api.add_resource(
importador_view.TriagemImportacao, '/api/importar/triagem')
api.add_resource(importador_view.DiagnosticoImportacao,
'/api/importar/diagnostico')
api.add_resource(foto_view.TriagemImagem, '/api/importar/imagem')
api.add_resource(importador_view.TriagemImportacao, "/api/importar/triagem")
api.add_resource(importador_view.DiagnosticoImportacao, "/api/importar/diagnostico")
api.add_resource(foto_view.TriagemImagem, "/api/importar/imagem")

api.add_resource(fabricante_view.FabricanteList, '/api/fabricantes')
api.add_resource(fabricante_view.FabricanteDetail,
'/api/fabricante/<fabricante_nome>')
api.add_resource(fabricante_view.FabricanteList, "/api/fabricantes")
api.add_resource(
fabricante_view.FabricanteDetail, "/api/fabricante/<fabricante_nome>"
)

api.add_resource(ordem_compra_view.OrdemCompraList, '/api/ordem_compra')
api.add_resource(ordem_compra_view.OrdemCompraDetail,
'/api/ordem_compra/<_id>')
api.add_resource(ordem_compra_view.OrdemCompraQuery,
'/api/ordem_compra/find')
api.add_resource(ordem_compra_view.OrdemCompraList, "/api/ordem_compra")
api.add_resource(ordem_compra_view.OrdemCompraDetail, "/api/ordem_compra/<_id>")
api.add_resource(ordem_compra_view.OrdemCompraQuery, "/api/ordem_compra/find")

api.add_resource(movimentacao_view.MovimentacaoList, '/api/movimentacao')
api.add_resource(movimentacao_view.MovimentacaoDetail,
'/api/movimentacao/<_id>')
api.add_resource(movimentacao_view.MovimentacaoQuery,
'/api/movimentacao/')
api.add_resource(movimentacao_view.MovimentacaoList, "/api/movimentacao")
api.add_resource(movimentacao_view.MovimentacaoDetail, "/api/movimentacao/<_id>")
api.add_resource(movimentacao_view.MovimentacaoQuery, "/api/movimentacao/")

api.add_resource(log_view.LogQuery, '/api/logs/find')
api.add_resource(log_view.LogQuery, "/api/logs/find")

api.add_resource(calibragem_view.CalibragemCrud, '/api/calibragem')
api.add_resource(diagnostico_view.DiagnosticoCrud, '/api/diagnosticos')
api.add_resource(utils_view.VersaoView, '/api/')
api.add_resource(calibragem_view.CalibragemCrud, "/api/calibragem")
api.add_resource(diagnostico_view.DiagnosticoCrud, "/api/diagnosticos")
api.add_resource(utils_view.VersaoView, "/api/")

# Routes V2

api.add_resource(items_many_controller.ItemsManyController, '/v2/items')
api.add_resource(items_migration_base.ItemsMigrationBase, '/v2/items/migrate')
api.add_resource(service_orders_many_controller.ServiceOrdersManyController, '/v2/service_orders')
api.add_resource(service_order_image_controller.ServiceOrderImageController, '/v2/service_order/<id>/<img>')
api.add_resource(items_many_controller.ItemsManyController, "/v2/items")
api.add_resource(items_migration_base.ItemsMigrationBase, "/v2/items/migrate")
api.add_resource(
service_orders_many_controller.ServiceOrdersManyController, "/v2/service_orders"
)
api.add_resource(
service_order_image_controller.ServiceOrderImageController,
"/v2/service_order/<id>/<img>",
)

Empty file.
4 changes: 4 additions & 0 deletions tests/v2/controllers/fixtures/service_orders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def valid_service_order():
return {
"content": { "id": "1", "tipo": "Tipo 1"}
}
Loading