-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinventory.py
More file actions
640 lines (506 loc) · 20.1 KB
/
inventory.py
File metadata and controls
640 lines (506 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
from sqlmodel import SQLModel, Field, Session, create_engine, select
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
#import os
#db_path = "inventory.db"
#if os.path.exists(db_path):
# os.remove(db_path)
engine = create_engine("sqlite:///inventory.db")
app = FastAPI(title="Inventory Management API")
class Player(SQLModel, table=True):
ID_Player: int = Field(primary_key = True)
Name: str
Status: str
First_Join: datetime
Last_Visit: datetime
class Character(SQLModel, table=True):
ID_Character: int = Field(primary_key = True)
ID_Player: int = Field(foreign_key = "player.ID_Player")
Name: str
Description: Optional[str] = None
Faction: str
Model_Path: str
class Inventory(SQLModel, table=True):
ID_Character: int = Field(primary_key = True, foreign_key = "character.ID_Character")
ID_Player: int = Field(foreign_key = "player.ID_Player")
Volume: int
class Item(SQLModel, table=True):
ID_Item: int = Field(primary_key = True)
Type: str
Name: str
Description: Optional[str] = None
Model_Path: str
class Slot(SQLModel, table=True):
ID_Slot: int = Field(primary_key = True)
ID_Character: int = Field(foreign_key = "character.ID_Character")
ID_Item: Optional[int] = Field(default=None, foreign_key = "item.ID_Item")
Amount: Optional[int] = None
Quality: Optional[str] = None
SQLModel.metadata.create_all(engine)
class PlayerCreate(BaseModel):
Name: str
Status: str
First_Join: datetime
Last_Visit: datetime
class PlayerUpdate(BaseModel):
Name: Optional[str] = None
Status: Optional[str] = None
Last_Visit: Optional[datetime] = None
class CharacterCreate(BaseModel):
ID_Player: int
Name: str
Description: Optional[str] = None
Faction: str = "Citizen"
Model_Path: str = "player/holloway_citizen/citizen.mdl"
class CharacterUpdate(BaseModel):
Name: Optional[str] = None
Description: Optional[str] = None
Faction: Optional[str] = None
Model_Path: Optional[str] = None
class InventoryCreate(BaseModel):
ID_Character: int
ID_Player: int
Volume: int
class InventoryUpdate(BaseModel):
Volume: Optional[int] = None
class ItemCreate(BaseModel):
Type: str
Name: str
Description: Optional[str] = None
Model_Path: str
class ItemUpdate(BaseModel):
Type: Optional[str] = None
Name: Optional[str] = None
Description: Optional[str] = None
Model_Path: Optional[str] = None
class SlotCreate(BaseModel):
ID_Character: int
class SlotUpdate(BaseModel):
ID_Item: Optional[int] = None
Amount: Optional[int] = None
Quality: Optional[str] = None
class MoveItemRequest(BaseModel):
from_slot_id: int
to_slot_id: int
def get_session():
with Session(engine) as session:
yield session
#-------------------------------------------------------------------------------------
@app.post("/players/", response_model=Player)
def create_player(player: PlayerCreate, session: Session = Depends(get_session)):
new_player = Player(**player.model_dump())
session.add(new_player)
session.commit()
session.refresh(new_player)
return new_player
@app.get("/players/{player_id}", response_model=Player)
def get_player(player_id: int, session: Session = Depends(get_session)):
player = session.get(Player, player_id)
if not player:
raise HTTPException(status_code=404, detail=f"Player {player_id} not found")
return player
@app.put("/players/{player_id}", response_model=Player)
def update_player(player_id: int, player_update: PlayerUpdate, session: Session = Depends(get_session)):
player = session.get(Player, player_id)
if not player:
raise HTTPException(status_code=404, detail=f"Player {player_id} not found")
update_data = player_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(player, field, value)
session.add(player)
session.commit()
session.refresh(player)
return player
@app.post("/characters/", response_model=Character)
def create_character(
character_data: CharacterCreate,
session: Session = Depends(get_session)
) -> Character:
if not character_data.Name:
raise HTTPException(status_code=400, detail="Character name cannot be empty")
player = session.get(Player, character_data.ID_Player)
if not player:
raise HTTPException(status_code=404, detail=f"Player {character_data.ID_Player} does not exist")
new_character = Character(**character_data.model_dump())
session.add(new_character)
session.commit()
session.refresh(new_character)
return new_character
@app.get("/characters/{character_id}", response_model=Character)
def get_character(character_id: int, session: Session = Depends(get_session)):
character = session.get(Character, character_id)
if not character:
raise HTTPException(status_code=404, detail=f"Character {character_id} not found")
return character
@app.put("/characters/{character_id}", response_model=Character)
def update_character(character_id: int, character_update: CharacterUpdate, session: Session = Depends(get_session)):
character = session.get(Character, character_id)
if not character:
raise HTTPException(status_code=404, detail=f"Character {character_id} not found")
update_data = character_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(character, field, value)
session.add(character)
session.commit()
session.refresh(character)
return character
@app.post("/inventories", response_model=Inventory)
def create_inventory(
inventory_data: InventoryCreate,
session: Session = Depends(get_session)
) -> Inventory:
player = session.get(Player, inventory_data.ID_Player)
if not player:
raise HTTPException(status_code=404, detail=f"Player {inventory_data.ID_Player} does not exist")
character = session.get(Character, inventory_data.ID_Character)
if not character:
raise HTTPException(status_code=404, detail=f"Character {inventory_data.ID_Character} does not exist")
if character.ID_Player != inventory_data.ID_Player:
raise HTTPException(status_code=400,
detail=f"Player {inventory_data.ID_Player} does not own Character {inventory_data.ID_Character}")
existing_inventory = session.exec(
select(Inventory).where(Inventory.ID_Character == inventory_data.ID_Character)
).first()
if existing_inventory:
raise HTTPException(status_code=400, detail=f"Character {inventory_data.ID_Character} already has an inventory")
# Validate volume
if inventory_data.Volume <= 0:
raise HTTPException(status_code=400, detail="Volume must be greater than 0")
# Calculate maximum volume based on player status
max_volume = 10 # Default for Player status
if player.Status == "VIP":
max_volume = 15
elif player.Status == "Admin":
max_volume = 20
if inventory_data.Volume > max_volume:
raise HTTPException(
status_code=400,
detail=f"Maximum volume for {player.Status} status is {max_volume}"
)
new_inventory = Inventory(**inventory_data.model_dump())
session.add(new_inventory)
for slot_number in range(1, inventory_data.Volume + 1):
new_slot = Slot(
ID_Character=inventory_data.ID_Character,
ID_Item=None,
Amount=None,
Quality=None
)
session.add(new_slot)
session.commit()
session.refresh(new_inventory)
return new_inventory
@app.get("/inventories", response_model=list[Slot])
def get_character_inventory(character_id: int, session: Session = Depends(get_session)):
slots = session.exec(
select(Slot).where(Slot.ID_Character == character_id)
).all()
return slots
@app.put("/inventories/update_volume/")
def update_volume(
character_id: int,
player_id: int,
session: Session = Depends(get_session)
) -> dict:
player = session.get(Player, player_id)
if not player:
raise HTTPException(status_code=404, detail=f"Player {player_id} does not exist")
if player.Status == "Player":
new_volume = 10
elif player.Status == "VIP":
new_volume = 15
elif player.Status == "Admin":
new_volume = 20
else:
raise HTTPException(status_code=400, detail=f"Player {player_id} has wrong status")
character = session.get(Character, character_id)
if not character:
raise HTTPException(status_code=404, detail=f"Character {character_id} does not exist")
if character.ID_Player != player_id:
raise HTTPException(status_code=400, detail=f"Player {player_id} does not own Character {character_id}")
inventory = session.exec(
select(Inventory).where(Inventory.ID_Character == character_id)
).first()
if not inventory:
raise HTTPException(status_code=404, detail=f"Character {character_id} does not have an inventory")
old_volume = inventory.Volume
if old_volume == new_volume:
raise HTTPException(status_code=400, detail="New volume equals old volume")
elif old_volume < new_volume:
slots_to_add = new_volume - old_volume
added_slots = 0
while added_slots < slots_to_add:
character_check = session.get(Character, character_id)
if not character_check:
raise HTTPException(status_code=404, detail=f"Character {character_id} does not exist")
inventory_check = session.exec(
select(Inventory).where(Inventory.ID_Character == character_id)
).first()
if not inventory_check:
raise HTTPException(status_code=404, detail=f"Character {character_id} does not have an inventory")
new_slot = Slot(
ID_Character=character_id,
ID_Item=None,
Amount=None,
Quality=None
)
session.add(new_slot)
added_slots += 1
session.commit()
inventory.Volume = new_volume
else:
existing_slots = session.exec(
select(Slot).where(Slot.ID_Character == character_id)
).all()
empty_slots = [slot for slot in existing_slots if slot.ID_Item is None]
empty_slot_count = len(empty_slots)
slots_to_delete = old_volume - new_volume
if empty_slot_count < slots_to_delete:
raise HTTPException(status_code=400, detail="Not enough empty slots")
deleted_slots = 0
for slot in empty_slots:
if deleted_slots >= slots_to_delete:
break
session.delete(slot)
deleted_slots += 1
inventory.Volume = new_volume
session.commit()
session.refresh(inventory)
return {"message": f"Inventory volume updated from {old_volume} to {new_volume}"}
@app.post("/slots/", response_model=Slot)
def create_slot(
slot_data: SlotCreate,
session: Session = Depends(get_session)
) -> Slot:
character = session.get(Character, slot_data.ID_Character)
if not character:
raise HTTPException(status_code=404, detail=f"Character {slot_data.ID_Character} does not exist")
inventory = session.exec(
select(Inventory).where(Inventory.ID_Character == slot_data.ID_Character)
).first()
if not inventory:
raise HTTPException(status_code=404, detail=f"Character {slot_data.ID_Character} does not have an inventory")
new_slot = Slot(
ID_Character=slot_data.ID_Character,
ID_Item=None,
Amount=None,
Quality=None
)
session.add(new_slot)
session.commit()
session.refresh(new_slot)
return new_slot
@app.get("/slots/{slot_id}", response_model=Slot)
def get_slot(
slot_id: int,
session: Session = Depends(get_session)
):
"""Get basic slot information"""
slot = session.get(Slot, slot_id)
if not slot:
raise HTTPException(status_code=404, detail=f"Slot {slot_id} not found")
return slot
@app.delete("/slots/{slot_id}")
def delete_slot(
slot_id: int,
force_remove: bool = False,
session: Session = Depends(get_session)
) -> dict:
slot = session.get(Slot, slot_id)
if not slot:
raise HTTPException(status_code=404, detail=f"Slot {slot_id} does not exist")
if slot.ID_Item is not None and not force_remove:
raise HTTPException(status_code=400, detail=f"Slot {slot_id} contains an item. Use force_remove=True to delete")
session.delete(slot)
session.commit()
return {"message": f"Slot {slot_id} deleted successfully"}
@app.put("/slots/{slot_id}", response_model=Slot)
def update_slot(
slot_id: int,
slot_update: SlotUpdate,
session: Session = Depends(get_session)
):
slot = session.get(Slot, slot_id)
if not slot:
raise HTTPException(status_code=404, detail=f"Slot {slot_id} not found")
update_data = slot_update.model_dump(exclude_unset=True)
if 'Quality' in update_data and update_data['Quality'] is not None:
if 'Amount' in update_data and update_data['Amount'] and update_data['Amount'] > 1:
raise HTTPException(
status_code=400,
detail="Items can't both be numerous and have quality"
)
if 'Amount' in update_data and update_data['Amount'] is not None:
if update_data['Amount'] <= 0:
raise HTTPException(
status_code=400,
detail="Amount must be positive"
)
for field, value in update_data.items():
setattr(slot, field, value)
if 'ID_Item' in update_data and update_data['ID_Item'] is None:
slot.Amount = None
slot.Quality = None
session.add(slot)
session.commit()
session.refresh(slot)
return slot
@app.post("/slots/{slot_id}/add_item/")
def add_item_to_slot(
slot_id: int,
item_id: int,
amount: Optional[int] = 1,
quality: Optional[str] = None,
session: Session = Depends(get_session)
) -> dict:
if amount <= 0:
raise HTTPException(status_code=400, detail="Amount must be positive")
if quality is not None and amount != 1:
raise HTTPException(status_code=400, detail="Items can't both be numerous and of quality")
slot = session.get(Slot, slot_id)
if not slot:
raise HTTPException(status_code=404, detail=f"Slot {slot_id} does not exist")
item = session.get(Item, item_id)
if not item:
raise HTTPException(status_code=404, detail=f"Item {item_id} does not exist")
if slot.ID_Item is not None:
raise HTTPException(status_code=400, detail=f"Slot {slot_id} is already occupied by item {slot.ID_Item}")
slot.ID_Item = item_id
slot.Amount = amount
slot.Quality = quality
session.commit()
session.refresh(slot)
return {"message": f"Item {item_id} added to slot {slot_id}"}
@app.delete("/slots/{slot_id}/remove_item/")
def remove_item_from_slot(
slot_id: int,
remove_amount: Optional[int] = None,
session: Session = Depends(get_session)
) -> dict:
slot = session.get(Slot, slot_id)
if not slot:
raise HTTPException(status_code=404, detail=f"Slot {slot_id} does not exist")
if remove_amount is None:
slot.ID_Item = None
slot.Amount = None
slot.Quality = None
else:
if remove_amount <= 0:
raise HTTPException(status_code=400, detail="Remove amount must be positive")
current_amount = slot.Amount or 0
if remove_amount > current_amount:
raise HTTPException(status_code=400,
detail=f"Cannot remove {remove_amount} items. Slot only has {current_amount}")
new_amount = current_amount - remove_amount
if new_amount > 0:
slot.Amount = new_amount
else:
slot.ID_Item = None
slot.Amount = None
slot.Quality = None
session.commit()
session.refresh(slot)
return {"message": f"Item removed from slot {slot_id}"}
@app.post("/slots/move_item/")
def move_item(
move_request: MoveItemRequest,
session: Session = Depends(get_session)
) -> dict:
if move_request.from_slot_id == move_request.to_slot_id:
raise HTTPException(status_code=400, detail="Cannot move item to the same slot")
from_slot = session.get(Slot, move_request.from_slot_id)
if not from_slot:
raise HTTPException(status_code=404, detail=f"Source slot {move_request.from_slot_id} does not exist")
to_slot = session.get(Slot, move_request.to_slot_id)
if not to_slot:
raise HTTPException(status_code=404, detail=f"Destination slot {move_request.to_slot_id} does not exist")
if from_slot.ID_Item is None:
raise HTTPException(status_code=400, detail=f"Source slot {move_request.from_slot_id} is empty")
if to_slot.ID_Item is not None:
if to_slot.ID_Item != from_slot.ID_Item:
raise HTTPException(status_code=400,
detail=f"Destination slot {move_request.to_slot_id} contains different item")
if to_slot.Quality != from_slot.Quality:
raise HTTPException(status_code=400, detail="Cannot stack items with different quality")
current_amount = from_slot.Amount or 0
from_slot.ID_Item = None
from_slot.Amount = None
from_slot.Quality = None
if to_slot.ID_Item is not None and to_slot.ID_Item == from_slot.ID_Item:
existing_amount = to_slot.Amount or 0
new_amount = existing_amount + current_amount
to_slot.Amount = new_amount
else:
to_slot.ID_Item = from_slot.ID_Item
to_slot.Amount = current_amount
to_slot.Quality = from_slot.Quality
session.commit()
return {"message": f"Item moved from slot {move_request.from_slot_id} to slot {move_request.to_slot_id}"}
@app.post("/items/", response_model=Item)
def create_item(
item_data: ItemCreate,
session: Session = Depends(get_session)
) -> Item:
new_item = Item(**item_data.model_dump())
session.add(new_item)
session.commit()
session.refresh(new_item)
return new_item
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int, session: Session = Depends(get_session)):
item = session.get(Item, item_id)
if not item:
raise HTTPException(status_code=404, detail=f"Item {item_id} not found")
return item
@app.put("/items/{item_id}", response_model=Item)
def update_item(
item_id: int,
item_update: ItemUpdate,
session: Session = Depends(get_session)
):
item = session.get(Item, item_id)
if not item:
raise HTTPException(status_code=404, detail=f"Item {item_id} not found")
update_data = item_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(item, field, value)
session.add(item)
session.commit()
session.refresh(item)
return item
@app.delete("/characters/{character_id}")
def delete_character(
character_id: int,
player_id: int,
session: Session = Depends(get_session)
) -> dict:
character = session.get(Character, character_id)
if not character:
raise HTTPException(status_code=404, detail=f"Character {character_id} does not exist")
if character.ID_Player != player_id:
raise HTTPException(status_code=400, detail=f"Character {character_id} does not belong to player {player_id}")
slots = session.exec(
select(Slot).where(Slot.ID_Character == character_id)
).all()
slots_deleted = 0
for slot in slots:
try:
session.delete(slot)
slots_deleted += 1
except:
session.delete(slot)
slots_deleted += 1
inventory = session.exec(
select(Inventory).where(Inventory.ID_Character == character_id)
).first()
if inventory:
session.delete(inventory)
session.delete(character)
session.commit()
return {"message": f"Character {character_id} deleted successfully"}
#-------------------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)