Skip to content

Commit

Permalink
Merge pull request #53 from PsyCity/bank-sensor-install-way
Browse files Browse the repository at this point in the history
Bank sensor install way
  • Loading branch information
darloof authored Feb 11, 2024
2 parents 6767217 + 280381f commit d4fe149
Show file tree
Hide file tree
Showing 6 changed files with 395 additions and 213 deletions.
32 changes: 28 additions & 4 deletions psycity/core/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from collections.abc import Iterable
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils.translation import gettext_lazy as _
Expand All @@ -15,6 +16,7 @@ class Meta:


class WarehouseBox(BaseModel):

BOX_STATUS = (
(0, "Lock"),
(1, "Robbed"),
Expand Down Expand Up @@ -61,14 +63,15 @@ def is_lock(self):
def worth(self):
return self.box_question.price + self.money


class BankDepositBox(BaseModel):
SENSOR_STATE_CHOICE = [
(0, 'Not Installed'),
(1, 'Installed'),
]

money = models.PositiveIntegerField(default=0)
password = models.IntegerField(default=randint(1000,9999))
password = models.IntegerField()
robbery_state = models.BooleanField(default=False)
reported = models.BooleanField(default=False)
rubbery_team = models.ForeignKey("Team",
Expand All @@ -90,6 +93,10 @@ class BankDepositBox(BaseModel):
is_copy = models.BooleanField(default=False)
parent_box = models.ForeignKey('self', on_delete=models.CASCADE, related_name="bankdispositbox_parent_box", null=True, blank=True)

def save(self, *args, **kwargs) -> None:
if self.password is None:
self.password = randint(1000, 9999)
return super().save(*args, **kwargs)


class ConstantConfig(BaseModel):
Expand Down Expand Up @@ -410,13 +417,30 @@ class WarehouseQuestions(BaseModel):

class BankSensorInstall(BaseModel):

STATE_CHOICE=[
(1, "Created"),
(2, "Used"),
(3, "Solved"),
(4, "Failed")
]

state = models.IntegerField(choices=STATE_CHOICE ,default=1)
contract = models.ForeignKey("Contract", on_delete=models.DO_NOTHING)
citizen = models.ForeignKey("Team", on_delete=models.DO_NOTHING)
police = models.ForeignKey("Team",
on_delete=models.DO_NOTHING,
related_name="bank_sensor_police"
)
citizen = models.ForeignKey("Team",
on_delete=models.DO_NOTHING,
related_name="bank_sensor_citizen",
)
room = models.ForeignKey("EscapeRoom",
verbose_name=_("selected room for citizen"),
on_delete=models.CASCADE,
null=True)

null=True
)
opening_time = models.DateTimeField(blank=True, null=True)

class Meta:
verbose_name = _("bank sensor install request")
verbose_name_plural = _("bank sensor install requests")
140 changes: 106 additions & 34 deletions psycity/team_api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
WarehouseBox,
BankSensorInstall,
)
from team_api.utils import cost_validation
from team_api.utils import cost_validation, ModelSerializerAndABCMetaClass
from datetime import timedelta
from abc import ABC, abstractmethod
from abc import ABC, abstractmethod, ABCMeta

class TeamMemberSerializer(serializers.Serializer):
Expand Down Expand Up @@ -454,7 +455,8 @@ def validate_mafia_max_escape_room(self, mafia:Team):

if not profile.mafia_reserved_escape_room < conf.team_escape_room_max:
raise exceptions.NotAcceptable("team_escape_room limit")



class BankRobberyListSerializer(serializers.ModelSerializer):

citizen_id = serializers.IntegerField(source="citizen.id")
Expand All @@ -463,6 +465,7 @@ class BankRobberyListSerializer(serializers.ModelSerializer):
mafia_name = serializers.CharField(source="mafia.name")
robbery_id = serializers.IntegerField(source="id")


class Meta:
model = BankRobbery
fields = [
Expand All @@ -476,61 +479,60 @@ class Meta:
]


class BankRobberyOpenSerializer(serializers.ModelSerializer):
class BankPenetrationOpenSerializer(serializers.ModelSerializer):

class Meta:
model = BankRobbery
fields = []
obj_name = ""

def validate(self, attrs):
if self.instance.state != 1:
raise exceptions.NotAcceptable(f"BankRobbery is on state {self.instance.state}")
raise exceptions.NotAcceptable(f"{self.obj_name} is on state {self.instance.state}")
return super().validate(attrs)

class BankRobberyOpenDepositBoxSerializer(serializers.ModelSerializer):
deposit_box = serializers.IntegerField()
password = serializers.IntegerField()


class BankRobberyOpenSerializer(BankPenetrationOpenSerializer):
obj_name = "BankRobbery"
class Meta:
model = BankRobbery
fields = [
"deposit_box",
"password"
]

fields = []


class BankPenetrationOpenDepositBoxSerializer(
ABC,
serializers.ModelSerializer,
metaclass=ModelSerializerAndABCMetaClass
):
deposit_box = serializers.IntegerField()


def validate_deposit_box(self, pk):
try:
box = BankDepositBox.objects.get(pk=pk)
except:
raise exceptions.NotFound("Box not found.")
return box


def check_deposit_box(self, box:BankDepositBox):

def check_deposit_box(self, box:BankDepositBox):
if box.robbery_state:
raise exceptions.NotAcceptable("Money has been stolen from the box.")
if box.money == 0 :
raise exceptions.NotAcceptable("Empty box. try another one.")



def check_password(self, password):
if password != self.validated_data["deposit_box"].password:
raise exceptions.NotAcceptable("Password Not match")



def deadline_check(self):
solve_time = self.instance.escape_room.solve_time
def __deadline_check(self):
room = self.query()
solve_time = room.solve_time
if timezone.now() > (self.instance.opening_time + timedelta(minutes=solve_time)):
self.save(state=4)
raise exceptions.NotAcceptable("Expired escape room.")
return True

@abstractmethod
def query(self):
...

def check_password(self):
...

def is_acceptable(self):
self.deadline_check()
self.__deadline_check()
self.check_deposit_box(self.validated_data["deposit_box"])
self.check_password(self.validated_data["password"])

Expand Down Expand Up @@ -596,6 +598,48 @@ def validate_team(self, pk):
return team



class BankRobberyOpenDepositBoxSerializer(
BankPenetrationOpenDepositBoxSerializer
):
password = serializers.IntegerField()

class Meta:
model = BankRobbery
fields = [
"deposit_box",
"password"
]


def check_deposit_box(self, box: BankDepositBox):
super().check_deposit_box(box)
if box.money == 0 :
raise exceptions.NotAcceptable("Empty box. try another one.")

def check_password(self, password):
if password != self.validated_data["deposit_box"].password:
raise exceptions.NotAcceptable("Password Not match")

def query(self) -> EscapeRoom:
return self.instance.escape_room


class BankSensorInstallOpenDepositBox(
BankPenetrationOpenDepositBoxSerializer
):
class Meta:
model = BankSensorInstall
fields = "deposit_box",

def check_deposit_box(self, box: BankDepositBox):
super().check_deposit_box(box)
if box.sensor_state == 1:
raise exceptions.NotAcceptable("Sensor is already installed. Try another one")

def query(self):
return self.instance.room

class BankSensorInstallWaySerializer(
serializers.ModelSerializer
):
Expand All @@ -613,7 +657,6 @@ def validate_contract(self, contract):
raise exceptions.ValidationError("Not a valid type contract")
if BankSensorInstall.objects.filter(contract=contract).last():
raise exceptions.NotAcceptable("Contract used")

return contract

def validate_team(self, team) ->Team:
Expand All @@ -634,11 +677,9 @@ def check_contract_and_team(self):

def check_room_usage_of_team(self):
citizen : Team= self.validated_data["team"]

profile = citizen.team_feature.first()
if not profile:
profile = TeamFeature.objects.create(team=citizen)

conf = ConstantConfig.objects.last()

if not profile.citizen_opened_night_escape_rooms < conf.team_escape_room_max:
Expand All @@ -649,9 +690,40 @@ def save(self, **kwargs):

kwargs["citizen"] = self.validated_data["team"]
kwargs["contract"] = self.validated_data["contract"]
assert self.validated_data["contract"].first_party_team.team_role == "Police"
kwargs["police"] = self.validated_data["contract"].first_party_team
self.instance = self.create(kwargs)
assert self.instance is not None, (
'`create()` did not return an object instance.'
)
return self.instance


class BankSensorInstallationListSerializer(serializers.ModelSerializer):

citizen_id = serializers.IntegerField(source="citizen.id")
citizen_name = serializers.CharField(source="citizen.name")
police_id = serializers.IntegerField(source="police.id")
police_name = serializers.CharField(source="police.name")
request_id = serializers.IntegerField(source="id")

class Meta:
model = BankSensorInstall
fields = [
"request_id",
"state",
"citizen_id",
"citizen_name",
"police_id",
"police_name",
"room"
]

class BankSensorInstallationOpenSerializer(
BankPenetrationOpenSerializer
):
obj_name = "Installation request"
class Meta:
model = BankSensorInstall
fields = []

1 change: 1 addition & 0 deletions psycity/team_api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
action_router.register("discover_bank_robber", action.DiscoverBankRobber)
action_router.register("bank_robbery_way", action.BankRobberyWayViewSet, "bank_robbery_way")
action_router.register("bank_robbery", action.BankRobberyViewSet, "bank_robbery")
action_router.register("bank_sensor_installation", action.BankSensorInstallViewSet, "bank_sensor_installation")
action_router.register("warehouse", action.WarehouseDepositBoxRobberyViewSet, "warehouse_robbery")
action_router.register("bank-sensor-install-way", action.BankSensorInstallWay, "Bank_sensor_install")
action_router.register("depositbox-robbery", action.WarehouseDepositBoxRobberyViewSet, "warehouse_robbery")
Expand Down
10 changes: 9 additions & 1 deletion psycity/team_api/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from django.http import Http404
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework import exceptions, status
from psycity.settings import DEBUG
from core.models import Team, BankDepositBox
from drf_yasg import openapi
from functools import wraps
from abc import ABCMeta


class ResponseStructure:
Expand Down Expand Up @@ -156,4 +158,10 @@ def find_boxes(box: BankDepositBox) -> set:
else:
boxes = [box]

return set(boxes)
return set(boxes)


class ModelSerializerAndABCMetaClass(
type(serializers.ModelSerializer),
ABCMeta
): ...
Loading

0 comments on commit d4fe149

Please sign in to comment.