Skip to content
Open
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
32 changes: 32 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Тесты (shop/tests)

on:
push:
branches: [ main, master ]
pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Установка Python
uses: actions/setup-python@v5
with:
python-version: '3.11'

- name: Установка Django
run: |
python -m pip install --upgrade pip
pip install Django coverage

- name: Запуск только тестов из shop/tests/
run: |
python manage.py test shop.tests --verbosity=2 --keepdb

- name: Покрытие кода
run: |
coverage run --source=shop manage.py test shop.tests
coverage report -m
99 changes: 99 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,102 @@

__pycache__/
*.py[cod]
*$py.class
*.pyo
*.pyd
.Python
env/
venv/
.venv
ENV/
env.bak/
venv.bak/
pip-log.txt
pip-delete-me.txt

.venv*/
env*/
venv*/
ENV*/
env*/

# Django stuff
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
media/
staticfiles/
*.sqlite3

.idea/
.vscode/
*.sublime-project
*.sublime-workspace
*.suo
*.sdf
*.opensdf
*.sln
*.user
*.userosscache
*.sln.docstates

.vscode/

.DS_Store
.DS_Store
.AppleDouble
.LSOverride

._*

.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/

node_modules/
npm-debug.log
yarn-debug.log*
yarn-error.log*

htmlcov/
.coverage
.coverage.*
cache/
nosetests.xml
coverage.xml
*.cover
.pytest_cache/

celerybeat-schedule
celerybeat.pid

docs/_build/

.ipynb_checkpoints

.mypy_cache/
.dmypy.json
dmypy.json

.pyre/

*.env
.env
.env.local
.env.*.local
secret_key.txt

*.orig
*.rej
*.bak
*.backup
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Константин Захаров

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
32 changes: 29 additions & 3 deletions shop/fixtures/products.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,41 @@
- model: shop.product
pk: 1
fields:
name: Стол
name: Стол письменный
price: 2000
quantity: 8

- model: shop.product
pk: 2
fields:
name: Стул
name: Стул офисный
price: 1000
quantity: 25

- model: shop.product
pk: 3
fields:
name: Табурет
name: Табурет кухонный
price: 500
quantity: 0

- model: shop.product
pk: 4
fields:
name: Шкаф двухстворчатый
price: 7500
quantity: 3

- model: shop.product
pk: 5
fields:
name: Кровать односпальная
price: 12000
quantity: 5

- model: shop.product
pk: 6
fields:
name: Диван угловой
price: 35000
quantity: 1
28 changes: 26 additions & 2 deletions shop/models.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
from django.db import models
from django.core.exceptions import ValidationError
from django.db import models, transaction

# Create your models here.
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.PositiveIntegerField()
quantity = models.PositiveIntegerField(default=0)

def can_buy(self, count=1):
return self.quantity >= count

def buy(self, count=1):
if not self.can_buy(count):
raise ValidationError(f"Недостаточно товара {self.name} на складе")
self.quantity -= count
self.save(update_fields=['quantity'])

def clean(self):
if self.quantity < 0:
raise ValidationError("количество не может быть отрицательным")


class Purchase(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
person = models.CharField(max_length=200)
address = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
date = models.DateTimeField(auto_now_add=True)

def save(self, *args, **kwargs):
if self.pk is None: # только при создании новой покупки
# Что бы откатиться если ошибки
with transaction.atomic():
product = Product.objects.select_for_update().get(pk=self.product_id)
product.buy() # уменьшаем на 1 штуку
super().save(*args, **kwargs)
44 changes: 25 additions & 19 deletions shop/templates/shop/index.html
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta charset="utf-8">
<title>Товары</title>
</head>
<body>
<div>
<h3>Список</h3>
<table>
<tr>
<td><p>Наименование</p></td>
<td><p>Цена</p></td>
<td></td>
</tr>
{% for p in products %}
<tr>
<td><p>{{ p.name }}</p></td>
<td><p>{{ p.price }}</p></td>
<td><p><a href="/buy/{{ p.id }}">Купить</a></p></td>
</tr>
{% endfor %}
</table>
</div>
<h2>Товары в магазине</h2>
<table border="1">
<tr>
<th>Наименование</th>
<th>Цена</th>
<th>Остаток</th>
<th>Действие</th>
</tr>
{% for p in products %}
<tr>
<td>{{ p.name }}</td>
<td>{{ p.price }} ₽</td>
<td>{{ p.quantity }} шт.</td>
<td>
{% if p.quantity > 0 %}
<a href="{% url 'buy' p.id %}">Купить</a>
{% else %}
Нет в наличии
{% endif %}
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
</html>
32 changes: 10 additions & 22 deletions shop/templates/shop/purchase_form.html
Original file line number Diff line number Diff line change
@@ -1,28 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Покупка</title>
<meta charset="utf-8">
<title>Оформление покупки {{ product.name }}</title>
</head>
<body>
<div>
<h3>Покупка</h3>
<form method="post">{% csrf_token %}
<input type="hidden" value="{{ view.kwargs.product_id }}" name="product" />
<table>
<tr>
<td><p>Введите свое имя </p></td>
<td><input type="text" name="person" /> </td>
</tr>
<tr>
<td><p>Введите адрес доставки:</p></td>
<td>
<input type="text" name="address" />
</td>
</tr>
<tr><td><input type="submit" value="Отправить" /> </td><td></td></tr>
</table>
</form>
</div>
<h3>Покупка товара: {{ product.name }} (цена {{ product.price }} )</h3>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Оформить покупку</button>
</form>
<a href="{% url 'index' %}">← Назад к списку</a>
</body>
</html>
</html>
Loading