Skip to content

Commit

Permalink
Add price change by new API. Required new api key.
Browse files Browse the repository at this point in the history
  • Loading branch information
matacoder committed Apr 19, 2022
1 parent 200160a commit 0b917f4
Show file tree
Hide file tree
Showing 11 changed files with 142 additions and 17 deletions.
10 changes: 5 additions & 5 deletions templates/api.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
{% block content %}
<div class="box">
{% load bulma_tags %}
<h2 class="title">Укажите ваш ключ API (x64)</h2>
<h2 class="title">Укажите ваш ключ API</h2>
<div class="block"><a href="https://seller.wb.ru/supplier-settings/access-to-api" target="_blank">Ссылка на
раздел ВБ с ключом</a></div>
{% if api %}
<div class="block">Указан ключ: <strong>{{ api }}</strong></div>
{% endif %}
раздел ВБ с x64 ключом</a></div>
<div class="block"><a href="https://seller.wb.ru/supplier-settings/access-to-new-api" target="_blank">Ссылка на
раздел ВБ с новым JWT ключом</a></div>

<form method="post">
{% csrf_token %}
{{ form|bulma }}
Expand Down
22 changes: 21 additions & 1 deletion templates/includes/card.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,28 @@
<progress class="progress is-primary" value="{{ item.days_on_site }}"
max="999"></progress>
Остаток: {{ item.stock }} шт.<br/>
Цена: <span class="tag is-light">{{ item.price }}</span> руб<br/>
Цена старая: {{ item.full_price }} рублей <br/>
Цена на сайте: <span class="tag is-danger">{{ item.price }}</span> руб<br/>
Скидка: {{ item.discount }}%<br/>
<span class="box">
<form hx-get="/update_discount/"
hx-target="#discount_update_result">
<input type="hidden" id="wb_id" name="wb_id" value="{{ item.nm_id }}">
<input type="hidden" id="full_price" name="full_price" value="{{ item.full_price }}">
<div class="field is-grouped">
<p class="is-small">Цена:&nbsp;</p>
<p class="control is-expanded">
<input class="input is-small" type="text"
value="{{ item.price }}" id="new_price"
name="new_price">
</p>
</div>
<p class="control">
<button class="button is-info is-small" type="submit" id="discount_update_result"
value="">Установить через %</button>
</p>
</form>
</span>
</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion templates/includes/revenue.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


<a class="button is-warning is-light" href="{% url "summary" %}">
Недельная выплата:&nbsp<strong>{{ payment }}</strong>&nbsp₽ (без расходов на логистику)
Недельная выплата:&nbsp<strong>{{ payment }}</strong>&nbsp₽ (без вычета расходов на логистику)
</a>


Expand Down
1 change: 1 addition & 0 deletions wb/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ class Meta:
model = ApiKey
fields = [
"api",
"new_api",
]
23 changes: 23 additions & 0 deletions wb/migrations/0004_auto_20220419_0958.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 3.2.8 on 2022-04-19 06:58

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('wb', '0003_alter_apikey_user'),
]

operations = [
migrations.AddField(
model_name='apikey',
name='new_api',
field=models.CharField(default='', max_length=400),
),
migrations.AlterField(
model_name='apikey',
name='api',
field=models.CharField(max_length=200),
),
]
23 changes: 23 additions & 0 deletions wb/migrations/0005_auto_20220419_1012.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 3.2.8 on 2022-04-19 07:12

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('wb', '0004_auto_20220419_0958'),
]

operations = [
migrations.AlterField(
model_name='apikey',
name='api',
field=models.CharField(max_length=200, verbose_name='Ключ API (x64)'),
),
migrations.AlterField(
model_name='apikey',
name='new_api',
field=models.CharField(default='', max_length=400, verbose_name='Ключ нового API (JWT)'),
),
]
4 changes: 3 additions & 1 deletion wb/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@


class ApiKey(models.Model):
api = models.CharField(max_length=200)
api = models.CharField(max_length=200, verbose_name="Ключ API (x64)")
new_api = models.CharField(max_length=400, default="", verbose_name="Ключ нового API (JWT)")
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)

def __str__(self):
Expand All @@ -19,6 +20,7 @@ class Product:
"""WB product."""
nm_id: int # nmId (Wildberries sku number)
supplier_article: str = ""
full_price: int = 0 # Price without discount
price: float = 0 # Price
discount: float = 0 # Discount
sizes: dict = field(default_factory=dict)
Expand Down
30 changes: 30 additions & 0 deletions wb/services/new_api_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import json

import requests
from loguru import logger


class NewApiClient:
def __init__(self, new_api_key: str):
self.token = new_api_key
self.base = "https://suppliers-api.wildberries.ru/public/api/v1/"

def update_discount(self, wb_id, new_discount):
url = self.base + "updateDiscounts"
data = [
{
"discount": int(new_discount),
"nm": int(wb_id)
}
]
headers = {
"Authorization": self.token,
"accept": "application/json",
"Content-Type": "application/json"
}
response = requests.post(url, data=json.dumps(data), headers=headers)
logger.info(f"{response.status_code}, message: {response.json()}")
if response.status_code == 200:
return True

return False
1 change: 1 addition & 0 deletions wb/services/warehouse.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def get_stock_objects(token):

# Update product
product.price = int(item["Price"] * ((100 - item["Discount"]) / 100))
product.full_price = int(item["Price"])
product.discount = item["Discount"]
product.in_way_to_client = item.get("inWayToClient", 0)
product.in_way_from_client = item.get("inWayFromClient", 0)
Expand Down
1 change: 1 addition & 0 deletions wb/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
path("summary/", views.weekly_orders_summary, name="summary"),
path("add/", views.add_to_cart, name="add"),
path("cart/", views.cart, name="cart"),
path("update_discount/", views.update_discount, name="update_discount"),
]
42 changes: 33 additions & 9 deletions wb/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from loguru import logger

from _settings.settings import redis_client
from wb.forms import ApiForm
from wb.models import ApiKey
from wb.services.new_api_client import NewApiClient
from wb.services.services import (
api_key_required,
get_bought_products,
Expand All @@ -25,13 +25,36 @@


def index(request):
big_data = {"key": "value"}
redis_client.set("foo", json.dumps(big_data))
logger.info(redis_client.get("foo"))
# https://images.wbstatic.net/portal/education/Kak_rabotat'_s_servisom_statistiki.pdf
# https://suppliers-api.wildberries.ru/swagger/index.html
return render(request, "index.html", {})


# https://images.wbstatic.net/portal/education/Kak_rabotat'_s_servisom_statistiki.pdf
@login_required
@api_key_required
def update_discount(request):
key = ApiKey.objects.get(user=request.user).new_api

if not key:
redirect("api")

new_client = NewApiClient(key)
wb_id = request.GET.get("wb_id")

new_price = int(request.GET.get("new_price"))
if new_price:
full_price = int(request.GET.get("full_price"))
new_discount = int(100 - new_price / full_price * 100)
logger.info(f"Посчитана скидка в {new_discount}%")
else:
new_discount = int(request.GET.get("new_discount"))
if new_discount is not None:
if new_client.update_discount(wb_id, new_discount):
return HttpResponse(f"Установлена {new_discount}% скидка")
return HttpResponse("Не удалось обновить :(")





@login_required
Expand Down Expand Up @@ -150,11 +173,12 @@ def bought(request):
@login_required
def api(request):
logger.info("Api page requested...")
form = ApiForm(request.POST or None)

if ApiKey.objects.filter(user=request.user.id).exists():
api = ApiKey.objects.get(user=request.user.id)
else:
api = False
api = None
form = ApiForm(request.POST or None, instance=api)
if form.is_valid():
form.instance.user = request.user
form.save()
Expand Down

0 comments on commit 0b917f4

Please sign in to comment.