lavkach3

Форк
0
107 строк · 5.5 Кб
1
import uuid
2
from typing import Any, Optional, List
3

4
from fastapi.exceptions import HTTPException
5
from sqlalchemy.ext.asyncio import AsyncSession
6
from starlette.requests import Request
7
from app.inventory.order.enums.exceptions_suggest_enums import SuggestErrors
8
from app.inventory.order.enums.order_enum import SuggestStatus, SuggestType, MoveStatus
9
from app.inventory.order.models.order_models import Suggest
10
from app.inventory.order.schemas.suggest_schemas import SuggestCreateScheme, SuggestUpdateScheme, SuggestFilter
11
from core.exceptions.module import ModuleException
12
from core.permissions import permit
13
from core.service.base import BaseService, UpdateSchemaType, ModelType, FilterSchemaType, CreateSchemaType
14
from core.helpers.broker.tkq import list_brocker
15

16
class SuggestService(BaseService[Suggest, SuggestCreateScheme, SuggestUpdateScheme, SuggestFilter]):
17
    def __init__(self, request: Request):
18
        super(SuggestService, self).__init__(request, Suggest, SuggestCreateScheme, SuggestUpdateScheme)
19

20
    @permit('suggest_edit')
21
    async def update(self, id: Any, obj: UpdateSchemaType, commit=False) -> Optional[ModelType]:
22
        return await super(SuggestService, self).update(id, obj, commit=commit)
23

24
    @permit('suggest_list')
25
    async def list(self, _filter: FilterSchemaType | dict, size: int):
26
        return await super(SuggestService, self).list(_filter, size)
27

28
    @permit('suggest_create')
29
    async def create(self, obj: CreateSchemaType, commit=False) -> ModelType:
30
        return await super(SuggestService, self).create(obj, commit)
31

32
    @permit('suggest_delete')
33
    async def delete(self, id: Any) -> None:
34
        return await super(SuggestService, self).delete(id)
35

36
    @permit('suggest_confirm')
37
    async def suggest_confirm(self, suggest_ids: List[uuid.UUID], value: Any, commit: bool = True) -> Optional[ModelType]:
38
        suggest_entities = await self.list({'id__in': suggest_ids}, 999)
39
        for suggest_entity in suggest_entities:
40
            is_last = True
41
            if suggest_entity.status == SuggestStatus.DONE:
42
                raise ModuleException(
43
                    status_code=406,
44
                    enum=SuggestErrors.SUGGEST_ALREADY_DONE
45
                )
46
            elif suggest_entity.type == SuggestType.IN_QUANTITY:
47
                try:
48
                    val_in_cleaned = float(value)
49
                except ValueError as e:
50
                    raise ModuleException(
51
                        status_code=406,
52
                        enum=SuggestErrors.SUGGEST_INVALID_VALUE,
53
                        message=str(e)
54
                    )
55
                #TODO: Здесь нужно вставить проверки на overdelivery, ZERO CONDITION и т.д.
56
                suggest_entity.result_value = str(val_in_cleaned) # Перекладываем в str тк поле универсальное str
57
                suggest_entity.status = SuggestStatus.DONE
58
            elif suggest_entity.type == SuggestType.IN_PRODUCT:
59
                product_obj = await self.env['product'].adapter.product_by_barcode(value)
60
                if product_obj:
61
                    suggest_entity.result_value = value
62
                    suggest_entity.status = SuggestStatus.DONE
63
            elif suggest_entity.type == SuggestType.IN_LOCATION:
64
                try:
65
                    val_in_cleaned = uuid.UUID(value)  # type: ignore
66
                except ValueError as e:
67
                    raise ModuleException(
68
                        status_code=406,
69
                        enum=SuggestErrors.SUGGEST_INVALID_VALUE,
70
                        message=str(e)
71
                    )
72
                location_entity = await self.env['location'].service.list(_filter={'id__in': [val_in_cleaned]})
73
                if location_entity:
74
                    #TODO: Здесь нужно вставить проверки на проверку подходящего места назначения
75
                    suggest_entity.result_value = value
76
                    suggest_entity.status = SuggestStatus.DONE
77
            else:
78
                raise ModuleException(
79
                    status_code=500,
80
                    enum=SuggestErrors.SUGGEST_TYPE_NOT_FOUND,
81
                )
82
            suggest_entity.user_id = self.user.user_id
83
        # КОСТЫЛЬ: Проверяем не последний ли это саджест, если последний окаем Мув
84
            move = await self.env['move'].service.get(suggest_entity.move_id)
85
            for suggest in move.suggest_list_rel:
86
                if suggest.id != suggest_entity.id and suggest.status != SuggestStatus.DONE:
87
                    is_last = False
88
            if is_last:
89
                move.status = MoveStatus.DONE
90
                #await self.env['move'].service.set_done.kiq(move_id=move.id)
91
                task__set_done = list_brocker.register_task(self.env['move'].service.set_done)
92
                task = await task__set_done.kiq(move_id=move.id)
93
                task_result = await task.wait_result()
94
                a=1
95
        if commit:
96
            try:
97
                await self.session.commit()
98
                for suggest_entity in suggest_entities:
99
                    await self.session.refresh(suggest_entity)
100
                    await suggest_entity.notify('update')
101
            except Exception as e:
102
                await self.session.rollback()
103
                raise HTTPException(status_code=500, detail=f"Some Error entity {str(e)}")
104
        else:
105
            await self.session.flush(suggest_entities)
106

107
        return suggest_entities
108

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.