index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
24,878,252
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0028_auto_20221103_1135.py
# Generated by Django 4.1.1 on 2022-11-03 11:35 from django.db import migrations PRODUCT_CODE_SEQUENCE_NAME = "lubricentro_myc_producto_codigo_seq" def reset_product_code_auto_increment(apps, schema_editor): with schema_editor.connection.cursor() as cursor: cursor.execute( f"SELECT oid FROM pg_class where relname='{PRODUCT_CODE_SEQUENCE_NAME}'" ) if cursor.fetchone(): cursor.execute( f"ALTER SEQUENCE {PRODUCT_CODE_SEQUENCE_NAME} RESTART WITH 100000" ) class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0027_productpricehistory"), ] operations = [migrations.RunPython(reset_product_code_auto_increment)]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,253
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0012_remito_cliente.py
# Generated by Django 2.2.3 on 2019-08-21 02:43 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0011_auto_20190821_0240"), ] operations = [ migrations.AddField( model_name="remito", name="cliente", field=models.ForeignKey( default="", on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.Cliente", ), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,254
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0029_alter_producto_codigo.py
# Generated by Django 4.1.6 on 2023-03-11 22:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0028_auto_20221103_1135"), ] # This migration is only required when running an empty database. # For older databases coming from the legacy BE, this migration should be skipped. operations = [ migrations.AlterField( model_name="producto", name="codigo", field=models.AutoField(primary_key=True, serialize=False), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,255
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/client.py
from django.db import models from lubricentro_myc.models.invoice import ElementoRemito, Remito class Cliente(models.Model): nombre = models.CharField(max_length=100, unique=True) direccion = models.CharField(max_length=100, blank=True, default="") localidad = models.CharField(max_length=100, blank=True, default="") codigo_postal = models.CharField(max_length=4, blank=True, default="") telefono = models.CharField(max_length=13, blank=True, default="") cuit = models.CharField(max_length=13, blank=True, default="") email = models.CharField(max_length=100, blank=True, default="") def __str__(self): return self.nombre @property def deuda_actual(self): actual_price = 0 for invoice_item in ElementoRemito.objects.filter( remito__cliente_id=self.id, pagado=False ): actual_price += ( invoice_item.producto.precio_venta_cta_cte * invoice_item.cantidad ) return actual_price @property def lista_remitos(self): return Remito.objects.filter(cliente__id=self.id).order_by("-fecha") @property def data(self): return ( self.id, self.nombre, self.direccion, self.localidad, self.codigo_postal, self.telefono, self.cuit, self.email, )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,256
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/utils.py
from functools import wraps from io import BytesIO from unittest import mock from unittest.mock import MagicMock, patch from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type="application/pdf") return None def mock_auth(func): @wraps(func) @patch( "lubricentro_myc.authentication.JWTAuthentication.authenticate", mock.MagicMock(return_value=(MagicMock(), None)), ) def wrapper(*args, **kwd): return func(*args, **kwd) return wrapper
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,257
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/product_cost_history.py
from django.db import models class ProductPriceHistory(models.Model): product = models.ForeignKey("lubricentro_myc.Producto", on_delete=models.CASCADE) old_price = models.FloatField() new_price = models.FloatField() timestamp = models.DateTimeField() @property def data(self): return ( self.id, self.product.codigo, self.old_price, self.new_price, self.timestamp, )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,258
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0004_auto_20190805_2315.py
# Generated by Django 2.2.3 on 2019-08-05 23:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0003_auto_20190803_2337"), ] operations = [ migrations.AlterField( model_name="cliente", name="telefono", field=models.BigIntegerField(blank=True, default=None), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,259
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/__init__.py
from .client import Cliente from .invoice import Remito from .invoice_item import ElementoRemito from .product import Producto from .product_cost_history import ProductPriceHistory from .sale import Venta
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,260
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/user.py
from django.contrib.auth.models import User from lubricentro_myc.authentication import generate_jwt_token from lubricentro_myc.serializers.user import UserSerializer from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from rest_framework.views import APIView from django_project import settings class SignupView(APIView): authentication_classes = [] def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() user = User.objects.get(username=serializer.data.get("username")) lmyc_jwt = generate_jwt_token(user) response = Response() response.set_cookie(key=settings.LMYC_JWT_KEY, value=lmyc_jwt, httponly=True) return response class LoginView(APIView): authentication_classes = [] def post(self, request): username = request.data.get("username", None) password = request.data.get("password", None) user = User.objects.filter(username=username).first() if user is None: raise AuthenticationFailed("User not found") if not user.check_password(password): raise AuthenticationFailed("Incorrect password") lmyc_jwt = generate_jwt_token(user) response = Response() response.set_cookie(key=settings.LMYC_JWT_KEY, value=lmyc_jwt, httponly=True) response.data = {"lmyc_jwt": lmyc_jwt} return response class UserView(APIView): def get(self, request): serializer = UserSerializer(request.user) return Response(serializer.data) class LogoutView(APIView): def post(self, request): response = Response() response.delete_cookie(settings.LMYC_JWT_KEY) return response
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,261
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0010_auto_20190821_0240.py
# Generated by Django 2.2.3 on 2019-08-21 02:40 import django.db.models.deletion import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0009_elementoremito"), ] operations = [ migrations.CreateModel( name="Remito", fields=[ ("codigo", models.AutoField(primary_key=True, serialize=False)), ("fecha", models.DateTimeField(default=django.utils.timezone.now)), ], ), migrations.RemoveField( model_name="elementoremito", name="numero_remito", ), migrations.AddField( model_name="elementoremito", name="remito", field=models.ForeignKey( default="", on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.Remito", ), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,262
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_product.py
import json from django.test import TestCase from lubricentro_myc.models.product import Producto from lubricentro_myc.tests.factories import ProductFactory from lubricentro_myc.utils import mock_auth from rest_framework.test import APIClient class ProductTestCase(TestCase): @classmethod def setUpTestData(cls): cls.api_client = APIClient() cls.client_url = "/lubricentro_myc/productos" cls.product_1 = ProductFactory( codigo=1, codigo_en_pantalla=1, detalle="CORREA GATES 5PK1815-9", categoria="Correas", precio_costo=2025.00, ) cls.product_2 = ProductFactory( codigo=2, codigo_en_pantalla=2, detalle="CABLE BUJIA R-12 81 EN ADEL.( 26253-R)", categoria="Electricidad", precio_costo=133.0, ) cls.product_3 = ProductFactory( codigo=3, codigo_en_pantalla=3, detalle="KIT DISTRIBUCION AMAROK (SKF)", categoria="Correas", precio_costo=25146.0, ) cls.product_4 = ProductFactory( codigo=4, codigo_en_pantalla=4, detalle="CORREA BTS 13X660", categoria="Correas", precio_costo=514.0, ) cls.product_5 = ProductFactory( codigo=5, codigo_en_pantalla=5, detalle="DESTELLADOR ELEC.12V ALTERNATIVO Nº 78", categoria="Electricidad", precio_costo=1157.0, ) cls.product_6 = ProductFactory( codigo=6, codigo_en_pantalla=6, detalle="FICHA 5T.M-BENZ/FORD CARGO", categoria="Electricidad", precio_costo=147.0, ) @mock_auth def test_search_by_detail(self): response = self.client.get(f"{self.client_url}?detalle=correa", follow=True) productos = json.loads(response.content)["results"] self.assertEqual(len(productos), 2) self.assertEqual(productos[0]["codigo"], self.product_1.codigo) self.assertEqual(productos[1]["codigo"], self.product_4.codigo) @mock_auth def test_search_by_category(self): response = self.client.get( f"{self.client_url}?categoria=electricidad", follow=True, ) productos = json.loads(response.content)["results"] self.assertEqual(len(productos), 3) self.assertEqual(productos[0]["codigo"], self.product_2.codigo) self.assertEqual(productos[1]["codigo"], self.product_5.codigo) self.assertEqual(productos[2]["codigo"], self.product_6.codigo) @mock_auth def test_search_by_query(self): product_7 = ProductFactory( codigo=7, codigo_en_pantalla=41, detalle="FILTRO CHATO T.AGUA PERKINS [PB-212)", categoria="Filtros", precio_costo=45.72, ) cases = ( { "case_name": "Should return products with categories matching 'corr'", "query_params": "?query=corr", "expected_result": [ self.product_1.codigo, self.product_3.codigo, self.product_4.codigo, ], }, { "case_name": "Should return products with detail matching 'fi'", "query_params": "?query=fi", "expected_result": [self.product_6.codigo, product_7.codigo], }, { "case_name": "Should return products with code greater or equal than '4'", "query_params": "?query=4", "expected_result": [ self.product_4.codigo, self.product_5.codigo, self.product_6.codigo, product_7.codigo, ], }, ) for case in cases: with self.subTest(msg=case["case_name"]): response = self.client.get( f"{self.client_url}{case['query_params']}", follow=True, ) self.assertEqual( list(map(lambda x: x["codigo"], response.data["results"])), case["expected_result"], ) @mock_auth def test_update_products_cost(self): response = self.client.post( f"{self.client_url}/aumento_masivo_precio_costo/", json.dumps( {"porcentaje_aumento": 25, "productos": [1, 2, 3, 4, 5, 6, 999999]} ), content_type="application/json", follow=True, ) resultado = json.loads(response.content)["resultado"] productos = Producto.objects.all() self.assertEqual(resultado, "6 producto/s actualizado/s satisfactoriamente.") self.assertEqual(productos[0].precio_costo, 2531.25) self.assertEqual(productos[1].precio_costo, 166.25) self.assertEqual(productos[2].precio_costo, 31432.5) self.assertEqual(productos[3].precio_costo, 642.5) self.assertEqual(productos[4].precio_costo, 1446.25) self.assertEqual(productos[5].precio_costo, 183.75) @mock_auth def test_available_codes(self): product_70 = ProductFactory( codigo=70, codigo_en_pantalla=77, detalle="BATERIA CLOREX 12V.75AMP.", categoria="Baterias", precio_costo=12215.50, ) response = self.client.get( f"{self.client_url}/codigos_disponibles?amount=100", follow=True ) available_codes = json.loads(response.content)["available_codes"] self.assertNotIn(self.product_1.codigo_en_pantalla, available_codes) self.assertNotIn(self.product_2.codigo_en_pantalla, available_codes) self.assertNotIn(self.product_3.codigo_en_pantalla, available_codes) self.assertNotIn(self.product_4.codigo_en_pantalla, available_codes) self.assertNotIn(self.product_5.codigo_en_pantalla, available_codes) self.assertNotIn(self.product_6.codigo_en_pantalla, available_codes) self.assertNotIn(product_70.codigo_en_pantalla, available_codes) self.assertIn(7, available_codes) self.assertIn(70, available_codes)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,263
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/invoice.py
from django.db.models import Q from django.http import HttpResponse from lubricentro_myc.models.invoice import ElementoRemito, Remito from lubricentro_myc.serializers.invoice import RemitoSerializer, UpdateRemitoSerializer from lubricentro_myc.views.pagination import CustomPageNumberPagination from rest_framework import viewsets class RemitoViewSet(viewsets.ModelViewSet, CustomPageNumberPagination): queryset = Remito.objects.all().order_by("-fecha") serializer_class = RemitoSerializer pagination_class = CustomPageNumberPagination def list(self, request): nombre = request.GET.get("nombre", None) query = request.GET.get("query", None) if nombre: self.queryset = Remito.objects.filter( cliente__nombre__icontains=nombre ).order_by("-fecha") elif query: self.queryset = Remito.objects.filter( Q(cliente__nombre__icontains=query) | Q(codigo__icontains=query) ).order_by("-fecha") return super().list(request) def perform_create(self, serializer): remito = serializer.save() elementos_remito = self.request.data.get("elementos_remito") for elemento_remito in elementos_remito: ElementoRemito.objects.create( remito=remito, producto_id=elemento_remito.get("producto"), cantidad=elemento_remito.get("cantidad"), ) def update(self, request, *args, **kwargs): serializer = UpdateRemitoSerializer( data=request.data, context={"invoice_id": kwargs["pk"]} ) serializer.is_valid(raise_exception=True) invoice_items_to_update = ElementoRemito.objects.filter( remito_id=kwargs["pk"], id__in=[ invoice_item["id"] for invoice_item in serializer.data.get("elementos_remito") ], ) invoice_items_to_delete = ElementoRemito.objects.filter( Q(remito_id=kwargs["pk"]) & ~Q( id__in=[ invoice_item["id"] for invoice_item in serializer.data.get("elementos_remito") ] ) ) if invoice_items_to_update.count() > 0: new_quantities = { invoice_item["id"]: invoice_item["cantidad"] for invoice_item in serializer.data.get("elementos_remito") } for invoice_item in invoice_items_to_update: invoice_item.cantidad = new_quantities[invoice_item.id] invoice_item.save() invoice_items_to_delete.delete() return HttpResponse(status=200)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,264
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/authentication.py
import datetime import jwt from django.contrib.auth.models import User from rest_framework import authentication from rest_framework.exceptions import AuthenticationFailed from django_project import settings def generate_jwt_token(user: User): payload = { "id": user.id, "username": user.username, "exp": datetime.datetime.utcnow() + datetime.timedelta(days=1), "iat": datetime.datetime.utcnow(), } return jwt.encode(payload, settings.LMYC_JWT_SECRET, algorithm="HS256") class JWTAuthentication(authentication.BaseAuthentication): def authenticate(self, request): lmyc_jwt = request.COOKIES.get(settings.LMYC_JWT_KEY) if not lmyc_jwt: raise AuthenticationFailed("Unauthenticated") try: payload = jwt.decode( lmyc_jwt, settings.LMYC_JWT_SECRET, algorithms=["HS256"] ) except jwt.ExpiredSignatureError: raise AuthenticationFailed("Unauthenticated") try: user = User.objects.get(id=payload["id"]) except User.DoesNotExist: raise AuthenticationFailed("Unauthenticated") return user, None
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,265
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0018_auto_20190828_0054.py
# Generated by Django 2.2.3 on 2019-08-28 00:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0017_venta_fecha"), ] operations = [ migrations.RenameField( model_name="venta", old_name="precio_venta", new_name="precio", ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,266
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0027_productpricehistory.py
# Generated by Django 4.1.1 on 2022-10-25 13:27 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0026_producto_codigo_en_pantalla_alter_producto_codigo"), ] operations = [ migrations.CreateModel( name="ProductPriceHistory", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("old_price", models.FloatField()), ("new_price", models.FloatField()), ("timestamp", models.DateTimeField()), ( "product", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.producto", ), ), ], ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,267
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/factories.py
import factory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = "auth.User" class ClientFactory(factory.django.DjangoModelFactory): class Meta: model = "lubricentro_myc.Cliente" class ProductFactory(factory.django.DjangoModelFactory): class Meta: model = "lubricentro_myc.Producto" class SaleFactory(factory.django.DjangoModelFactory): class Meta: model = "lubricentro_myc.Venta" producto_id = 1 cantidad = 1.0 precio = 1.0 class InvoiceFactory(factory.django.DjangoModelFactory): class Meta: model = "lubricentro_myc.Remito" class InvoiceItemFactory(factory.django.DjangoModelFactory): class Meta: model = "lubricentro_myc.ElementoRemito"
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,268
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/urls.py
from django.urls import include, re_path from lubricentro_myc.views.client import ClienteViewSet from lubricentro_myc.views.db import reset from lubricentro_myc.views.file import generar_remito_pdf, generar_stock_pdf from lubricentro_myc.views.invoice import RemitoViewSet from lubricentro_myc.views.invoice_item import ElementoRemitoViewSet from lubricentro_myc.views.product import ProductoViewSet from lubricentro_myc.views.sale import VentaViewSet from lubricentro_myc.views.user import LoginView, LogoutView, SignupView, UserView from rest_framework.routers import DefaultRouter from django_project.settings import TESTING_MODE router = DefaultRouter() router.register(r"clientes", ClienteViewSet) router.register(r"productos", ProductoViewSet) router.register(r"remitos", RemitoViewSet) router.register(r"elementos_remito", ElementoRemitoViewSet) router.register(r"ventas", VentaViewSet) urlpatterns = [ re_path(r"account/signup/", SignupView.as_view()), re_path(r"account/login/", LoginView.as_view()), re_path(r"account/user/", UserView.as_view()), re_path(r"account/logout/", LogoutView.as_view()), re_path(r"generar_remito_pdf/", generar_remito_pdf, name="generar_remito_pdf"), re_path(r"generar_stock_pdf/", generar_stock_pdf, name="generar_stock_pdf"), re_path("", include(router.urls)), ] if TESTING_MODE == 1: urlpatterns.append(re_path(r"reset", reset, name="reset_db"))
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,269
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0001_initial.py
# Generated by Django 2.2.3 on 2019-07-14 22:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Cliente", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("nombre", models.CharField(max_length=100)), ("direccion", models.CharField(blank=True, default="", max_length=100)), ("localidad", models.CharField(blank=True, default="", max_length=100)), ("codigo_postal", models.IntegerField(blank=True, default=None)), ("telefono", models.IntegerField(blank=True, default=None)), ("cuit", models.CharField(blank=True, default="", max_length=13)), ], ), migrations.CreateModel( name="Producto", fields=[ ("codigo", models.IntegerField(primary_key=True, serialize=False)), ("detalle", models.CharField(max_length=200)), ("stock", models.IntegerField(blank=True, default=0)), ("precio_costo", models.FloatField(blank=True, default=0.0)), ("precio_venta_contado", models.FloatField(blank=True, default=0.0)), ("precio_venta_cta_cte", models.FloatField(blank=True, default=0.0)), ("categoria", models.CharField(max_length=50)), ], ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,270
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/management/commands/import_data_from_csv.py
import csv import logging from django.core.management import BaseCommand from lubricentro_myc.models import ( Cliente, ElementoRemito, Producto, ProductPriceHistory, Remito, Venta, ) logger = logging.getLogger("django") DELIMITER = "|" def get_reader(filename: str, store_data): with open(f"files/{filename}.csv", "r") as file: csv_reader = csv.reader(file, delimiter=DELIMITER) store_data(csv_reader) def store_products(): def store_data(reader): products = [] for row in reader: products.append( Producto( codigo=row[0], codigo_en_pantalla=row[1], detalle=row[2], stock=row[3], precio_costo=row[4], desc1=row[5], desc2=row[6], desc3=row[7], desc4=row[8], flete=row[9], ganancia=row[10], iva=row[11], agregado_cta_cte=row[12], categoria=row[13], ) ) Producto.objects.all().delete() Producto.objects.bulk_create(products) get_reader("products", store_data) def store_product_prices_history(): def store_data(reader): product_prices_history = [] for row in reader: product_prices_history.append( ProductPriceHistory( id=row[0], product=Producto.objects.get(codigo=row[1]), old_price=row[2], new_price=row[3], timestamp=row[4], ) ) ProductPriceHistory.objects.all().delete() ProductPriceHistory.objects.bulk_create(product_prices_history) get_reader("product_prices_history", store_data) def store_clients(): def store_data(reader): clients = [] for row in reader: clients.append( Cliente( id=row[0], nombre=row[1], direccion=row[2], localidad=row[3], codigo_postal=row[4], telefono=row[5], cuit=row[6], email=row[7], ) ) Cliente.objects.all().delete() Cliente.objects.bulk_create(clients) get_reader("clients", store_data) def store_sales(): def store_data(reader): sales = [] for row in reader: sales.append( Venta( id=row[0], producto=Producto.objects.get(codigo=row[1]), cantidad=row[2], precio=row[3], fecha=row[4], ) ) Venta.objects.all().delete() Venta.objects.bulk_create(sales) get_reader("sales", store_data) def store_invoices(): def store_data(reader): invoices = [] for row in reader: invoices.append( Remito( codigo=row[0], cliente=Cliente.objects.get(id=row[1]), fecha=row[2] ) ) Remito.objects.all().delete() Remito.objects.bulk_create(invoices) get_reader("invoices", store_data) def store_invoice_items(): def store_data(reader): invoice_items = [] for row in reader: invoice_items.append( ElementoRemito( id=row[0], remito=Remito.objects.get(codigo=row[1]), producto=Producto.objects.get(codigo=row[2]), cantidad=row[3], pagado=row[4], ) ) ElementoRemito.objects.all().delete() ElementoRemito.objects.bulk_create(invoice_items) get_reader("invoice_items", store_data) class Command(BaseCommand): help = "Imports models data from a CSV file" def handle(self, *args, **kwargs): logger.info("Starting to import models data...") logger.info("Storing products...") store_products() logger.info("Storing product prices history...") store_product_prices_history() logger.info("Storing clients...") store_clients() logger.info("Storing sales...") store_sales() logger.info("Storing invoices...") store_invoices() logger.info("Storing invoice items...") store_invoice_items() logger.info("Finished.")
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,271
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0025_cliente_email.py
# Generated by Django 3.1.3 on 2021-05-23 16:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0024_auto_20210217_1435"), ] operations = [ migrations.AddField( model_name="cliente", name="email", field=models.CharField(blank=True, default="", max_length=100), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,272
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_client.py
import json from django.test import TestCase from lubricentro_myc.tests.factories import ClientFactory from lubricentro_myc.utils import mock_auth from rest_framework.test import APIClient class ClientTestCase(TestCase): @classmethod def setUpTestData(cls): cls.api_client = APIClient() cls.client_url = "/lubricentro_myc/clientes" cls.client_1 = ClientFactory(id=1, nombre="Jose Gomez") cls.client_2 = ClientFactory(id=15, nombre="Juan Perez") cls.client_3 = ClientFactory(id=30, nombre="Maria Fernandez") cls.client_4 = ClientFactory(id=45, nombre="Jose Hernandez") @mock_auth def test_search_client(self): response = self.client.get(f"{self.client_url}?nombre=jose", follow=True) clientes = json.loads(response.content)["results"] self.assertEqual(len(clientes), 2) self.assertEqual(clientes[0]["nombre"], "Jose Gomez") self.assertEqual(clientes[1]["nombre"], "Jose Hernandez") @mock_auth def test_search_client_using_query_param_to_search_by_id(self): response = self.client.get(f"{self.client_url}?query=1", follow=True) clientes = json.loads(response.content)["results"] self.assertEqual(len(clientes), 2) self.assertEqual(clientes[0]["id"], 1) self.assertEqual(clientes[1]["id"], 15) @mock_auth def test_search_client_using_query_param_to_search_by_name(self): response = self.client.get(f"{self.client_url}?query=jose", follow=True) clientes = json.loads(response.content)["results"] self.assertEqual(len(clientes), 2) self.assertEqual(clientes[0]["nombre"], "Jose Gomez") self.assertEqual(clientes[1]["nombre"], "Jose Hernandez")
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,273
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_invoice.py
import json from django.test import TestCase from lubricentro_myc.models.invoice import ElementoRemito, Remito from lubricentro_myc.models.product import Producto from lubricentro_myc.tests.factories import ( ClientFactory, InvoiceFactory, InvoiceItemFactory, ProductFactory, ) from lubricentro_myc.utils import mock_auth from rest_framework.test import APIClient class InvoiceTestCase(TestCase): @classmethod def setUpTestData(cls): cls.api_client = APIClient() cls.client_url = "/lubricentro_myc/remitos" cls.client_1 = ClientFactory(nombre="Juan") cls.client_2 = ClientFactory(nombre="Pedro") cls.client_3 = ClientFactory(nombre="Jose") cls.client_4 = ClientFactory(nombre="Enrique") cls.product_1 = ProductFactory(codigo=1, stock=5.0) cls.product_2 = ProductFactory(codigo=2, stock=11.5) cls.product_3 = ProductFactory(codigo=3, stock=130.65) cls.product_4 = ProductFactory(codigo=4, stock=62) cls.product_5 = ProductFactory(codigo=5, stock=201.5) cls.invoice_1 = InvoiceFactory(codigo=4250, cliente=cls.client_1) cls.invoice_2 = InvoiceFactory(codigo=4230, cliente=cls.client_3) cls.invoice_3 = InvoiceFactory(codigo=35, cliente=cls.client_4) InvoiceItemFactory(remito=cls.invoice_1, producto=cls.product_1, cantidad=1.5) InvoiceItemFactory(remito=cls.invoice_1, producto=cls.product_2, cantidad=7.0) cls.invoice_item_3 = InvoiceItemFactory( remito=cls.invoice_3, producto=cls.product_3, cantidad=1, pagado=False, ) cls.invoice_item_4 = InvoiceItemFactory( remito=cls.invoice_3, producto=cls.product_4, cantidad=1, pagado=False, ) cls.invoice_item_5 = InvoiceItemFactory( remito=cls.invoice_3, producto=cls.product_5, cantidad=1.5, pagado=False, ) @mock_auth def test_list_invoices_by_clients_name(self): response = self.client.get(f"{self.client_url}?nombre=jua", follow=True) invoices = response.data["results"] self.assertEqual(len(invoices), 1) self.assertEqual(invoices[0]["cliente"], "Juan") @mock_auth def test_list_invoices_using_query_param(self): response = self.client.get(f"{self.client_url}?query=jua", follow=True) invoices = response.data["results"] self.assertEqual(len(invoices), 1) self.assertEqual(invoices[0]["cliente"], "Juan") response = self.client.get(f"{self.client_url}?query=425", follow=True) invoices = response.data["results"] self.assertEqual(len(invoices), 1) self.assertEqual(invoices[0]["codigo"], 4250) @mock_auth def test_store_invoice_items(self): self.client.post( f"{self.client_url}/", json.dumps( { "cliente": self.client_2.id, "elementos_remito": [ { "producto": self.product_1.codigo, "cantidad": 3.5, }, { "producto": self.product_2.codigo, "cantidad": 2.0, }, ], } ), content_type="application/json", follow=True, ) invoice = Remito.objects.filter(cliente=self.client_2).first() invoice_items = ElementoRemito.objects.filter(remito_id=invoice.codigo) self.assertEqual(len(invoice_items), 2) self.assertEqual(invoice_items[0].producto.codigo, self.product_1.codigo) self.assertEqual(invoice_items[0].remito.codigo, invoice.codigo) self.assertEqual(invoice_items[0].cantidad, 3.5) self.assertEqual(invoice_items[1].producto.codigo, self.product_2.codigo) self.assertEqual(invoice_items[1].remito.codigo, invoice.codigo) self.assertEqual(invoice_items[1].cantidad, 2.0) @mock_auth def test_update_invoice(self): self.client.patch( f"{self.client_url}/{self.invoice_3.codigo}/", json.dumps( { "elementos_remito": [ { "id": self.invoice_item_4.id, "cantidad": 2, }, { "id": self.invoice_item_5.id, "cantidad": 8, }, ], } ), content_type="application/json", follow=True, ) invoice = Remito.objects.get(codigo=self.invoice_3.codigo) invoice_items = { invoice_item["id"]: invoice_item["cantidad"] for invoice_item in invoice.resumen_elementos } self.assertNotIn(self.invoice_item_3.id, invoice_items) self.assertIn(self.invoice_item_4.id, invoice_items) self.assertIn(self.invoice_item_5.id, invoice_items) self.assertEqual(invoice_items[self.invoice_item_4.id], 2) self.assertEqual(invoice_items[self.invoice_item_5.id], 8) self.assertEqual( Producto.objects.get(codigo=self.product_3.codigo).stock, 130.65 ) self.assertEqual(Producto.objects.get(codigo=self.product_4.codigo).stock, 60) self.assertEqual( Producto.objects.get(codigo=self.product_5.codigo).stock, 193.5 )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,274
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0005_auto_20190805_2321.py
# Generated by Django 2.2.3 on 2019-08-05 23:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0004_auto_20190805_2315"), ] operations = [ migrations.AlterField( model_name="cliente", name="codigo_postal", field=models.IntegerField(blank=True, default=None, null=True), ), migrations.AlterField( model_name="cliente", name="cuit", field=models.CharField(blank=True, default="", max_length=13, null=True), ), migrations.AlterField( model_name="cliente", name="direccion", field=models.CharField(blank=True, default="", max_length=100, null=True), ), migrations.AlterField( model_name="cliente", name="localidad", field=models.CharField(blank=True, default="", max_length=100, null=True), ), migrations.AlterField( model_name="cliente", name="telefono", field=models.BigIntegerField(blank=True, default=None, null=True), ), migrations.AlterField( model_name="producto", name="desc1", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="desc2", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="desc3", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="desc4", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="precio_costo", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="precio_venta_contado", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="precio_venta_cta_cte", field=models.FloatField(default=0.0), ), migrations.AlterField( model_name="producto", name="stock", field=models.IntegerField(default=0), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,275
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0021_elementoremito_pagado.py
# Generated by Django 2.2.7 on 2019-11-22 02:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0020_remove_elementoremito_pagado"), ] operations = [ migrations.AddField( model_name="elementoremito", name="pagado", field=models.BooleanField(default=False), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,276
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/invoice_item.py
import json from django.db.models import Q from django.http import HttpResponse from lubricentro_myc.models import Venta from lubricentro_myc.models.invoice import ElementoRemito from lubricentro_myc.serializers.invoice_item import ( BillingSerializer, ElementoRemitoSerializer, ) from rest_framework import viewsets from rest_framework.decorators import action class ElementoRemitoViewSet(viewsets.ModelViewSet): queryset = ElementoRemito.objects.all().order_by("id") serializer_class = ElementoRemitoSerializer pagination_class = None def list(self, request): codigo_cliente = request.GET.get("codigo_cliente", None) pago = request.GET.get("pago", None) filters = Q() if codigo_cliente: filters &= Q(remito__cliente=codigo_cliente) if pago: filters &= Q(pagado=json.loads(pago)) if filters: self.queryset = ElementoRemito.objects.filter(filters).order_by("id") return super().list(request) def update(self, request, *args, **kwargs): remito = request.data.get("remito", None) producto = request.data.get("producto", None) if remito or producto: return HttpResponse(status=400) return super().update(request, *args, **kwargs) @action(detail=False, methods=["post"]) def bulk(self, request): serializer = BillingSerializer(data=request.data) serializer.is_valid(raise_exception=True) for invoice_item in ElementoRemito.objects.filter( id__in=serializer.data["items"] ): invoice_item.pagado = True invoice_item.save() # save sale without updating stock Venta.objects.create( producto=invoice_item.producto, cantidad=invoice_item.cantidad, precio=( invoice_item.producto.precio_venta_cta_cte * invoice_item.cantidad ), ) return HttpResponse(status=200)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,277
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0022_auto_20200216_2326.py
# Generated by Django 2.2.7 on 2020-02-16 23:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0021_elementoremito_pagado"), ] operations = [ migrations.RemoveField( model_name="producto", name="precio_venta_contado", ), migrations.RemoveField( model_name="producto", name="precio_venta_cta_cte", ), migrations.AddField( model_name="producto", name="agregado_cta_cte", field=models.FloatField(default=0.0), ), migrations.AddField( model_name="producto", name="flete", field=models.FloatField(default=0.0), ), migrations.AddField( model_name="producto", name="ganancia", field=models.FloatField(default=40.0), ), migrations.AddField( model_name="producto", name="iva", field=models.FloatField(default=21.0), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,278
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0016_venta.py
# Generated by Django 2.2.3 on 2019-08-27 23:23 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0015_auto_20190826_2356"), ] operations = [ migrations.CreateModel( name="Venta", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("cantidad", models.FloatField()), ("precio_venta", models.FloatField()), ( "producto", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.Producto", ), ), ], ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,279
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0002_auto_20190714_2243.py
# Generated by Django 2.2.3 on 2019-07-14 22:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0001_initial"), ] operations = [ migrations.AddField( model_name="producto", name="desc1", field=models.FloatField(blank=True, default=0.0), ), migrations.AddField( model_name="producto", name="desc2", field=models.FloatField(blank=True, default=0.0), ), migrations.AddField( model_name="producto", name="desc3", field=models.FloatField(blank=True, default=0.0), ), migrations.AddField( model_name="producto", name="desc4", field=models.FloatField(blank=True, default=0.0), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,280
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_invoice_item.py
import json from django.test import TestCase from lubricentro_myc.models import ElementoRemito, Venta from lubricentro_myc.tests.factories import ( ClientFactory, InvoiceFactory, InvoiceItemFactory, ProductFactory, ) from lubricentro_myc.utils import mock_auth from rest_framework.test import APIClient class InvoiceItemTestCase(TestCase): @classmethod def setUpTestData(cls): cls.api_client = APIClient() cls.client_url = "/lubricentro_myc/elementos_remito" cls.client_1 = ClientFactory(nombre="Juan") cls.client_2 = ClientFactory(nombre="Pedro") cls.client_3 = ClientFactory(nombre="Matias") cls.product_1 = ProductFactory(codigo=1, stock=5.0) cls.product_2 = ProductFactory(codigo=2, stock=7.5) cls.product_3 = ProductFactory(codigo=3, stock=3.0) cls.invoice_1 = InvoiceFactory(cliente=cls.client_1) cls.invoice_2 = InvoiceFactory(cliente=cls.client_2) cls.invoice_3 = InvoiceFactory(cliente=cls.client_2) cls.invoice_4 = InvoiceFactory(cliente=cls.client_3) cls.invoice_item_1 = InvoiceItemFactory( remito=cls.invoice_1, producto_id=cls.product_1.codigo, cantidad=1, pagado=True, ) cls.invoice_item_2 = InvoiceItemFactory( remito=cls.invoice_1, producto_id=cls.product_1.codigo, cantidad=1, pagado=False, ) cls.invoice_item_3 = InvoiceItemFactory( remito=cls.invoice_1, producto_id=cls.product_1.codigo, cantidad=1, pagado=True, ) cls.invoice_item_4 = InvoiceItemFactory( remito=cls.invoice_2, producto_id=cls.product_1.codigo, cantidad=1, pagado=False, ) cls.invoice_item_5 = InvoiceItemFactory( remito=cls.invoice_2, producto_id=cls.product_2.codigo, cantidad=1, pagado=False, ) cls.invoice_item_6 = InvoiceItemFactory( remito=cls.invoice_4, producto_id=cls.product_1.codigo, cantidad=5.0, pagado=False, ) cls.invoice_item_7 = InvoiceItemFactory( remito=cls.invoice_4, producto_id=cls.product_2.codigo, cantidad=2.0, pagado=False, ) cls.invoice_item_8 = InvoiceItemFactory( remito=cls.invoice_4, producto_id=cls.product_3.codigo, cantidad=8.0, pagado=False, ) @mock_auth def test_search_by_client_code(self): response = self.client.get( f"{self.client_url}?codigo_cliente={self.client_1.id}", follow=True, ) invoice_items = response.data self.assertEqual(len(invoice_items), 3) self.assertEqual(invoice_items[0]["id"], self.invoice_item_1.id) self.assertEqual(invoice_items[1]["id"], self.invoice_item_2.id) self.assertEqual(invoice_items[2]["id"], self.invoice_item_3.id) @mock_auth def test_search_by_paid(self): response = self.client.get( f"{self.client_url}?pago=true", follow=True, ) invoice_items = response.data self.assertEqual(len(invoice_items), 2) self.assertEqual(invoice_items[0]["id"], self.invoice_item_1.id) self.assertEqual(invoice_items[1]["id"], self.invoice_item_3.id) @mock_auth def test_update_dont_allow_to_update_invoice(self): response = self.client.patch( f"{self.client_url}/{self.invoice_item_1.id}/", json.dumps({"producto": self.product_2.codigo}), content_type="application/json", follow=True, ) self.assertEqual(response.status_code, 400) @mock_auth def test_update_dont_allow_to_update_product(self): response = self.client.patch( f"{self.client_url}/{self.invoice_item_1.id}/", json.dumps({"remito": self.invoice_2.codigo}), content_type="application/json", follow=True, ) self.assertEqual(response.status_code, 400) @mock_auth def test_billing(self): invoice_item_ids = [ self.invoice_item_6.id, self.invoice_item_7.id, self.invoice_item_8.id, ] response = self.client.post( f"{self.client_url}/bulk/", json.dumps( { "items": invoice_item_ids, } ), content_type="application/json", follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual( ElementoRemito.objects.filter( id__in=invoice_item_ids, pagado=False ).count(), 0, ) self.assertTrue( Venta.objects.filter( producto=self.invoice_item_6.producto, cantidad=self.invoice_item_6.cantidad, ).exists() ) self.assertTrue( Venta.objects.filter( producto=self.invoice_item_7.producto, cantidad=self.invoice_item_7.cantidad, ).exists() ) self.assertTrue( Venta.objects.filter( producto=self.invoice_item_7.producto, cantidad=self.invoice_item_7.cantidad, ).exists() )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,281
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/serializers/invoice.py
from lubricentro_myc.models.invoice import ElementoRemito, Remito from rest_framework import serializers from rest_framework.exceptions import ValidationError class UpdateElementoRemitoSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = ElementoRemito fields = ["id", "cantidad"] class UpdateRemitoSerializer(serializers.Serializer): elementos_remito = serializers.ListField(child=UpdateElementoRemitoSerializer()) def validate(self, data): invoice_id = self.context.get("invoice_id") if ElementoRemito.objects.filter(remito_id=invoice_id, pagado=True).count() > 0: raise ValidationError( "Remito no puede ser actualizado dado que 1 o mas Elementos de Remito ya estan pagos." ) return data class GetElementoRemitoSerializer(serializers.ModelSerializer): class Meta: model = ElementoRemito fields = ["producto", "cantidad"] class RemitoSerializer(serializers.ModelSerializer): elementos_remito = serializers.ListField( child=GetElementoRemitoSerializer(), write_only=True ) class Meta: model = Remito fields = [ "codigo", "cliente", "fecha", "resumen_elementos", "esta_pago", "elementos_remito", ] def to_representation(self, instance): data = super(RemitoSerializer, self).to_representation(instance) data["cliente"] = instance.cliente.nombre return data def create(self, validated_data): validated_data.pop("elementos_remito") return super(RemitoSerializer, self).create(validated_data)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,282
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0014_auto_20190821_1043.py
# Generated by Django 2.2.3 on 2019-08-21 10:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0013_auto_20190821_0243"), ] operations = [ migrations.AlterField( model_name="elementoremito", name="cantidad", field=models.FloatField(), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,283
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0019_elementoremito_pagado.py
# Generated by Django 2.2.7 on 2019-11-21 10:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0018_auto_20190828_0054"), ] operations = [ migrations.AddField( model_name="elementoremito", name="pagado", field=models.BooleanField(default=False), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,284
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/serializers/client.py
from lubricentro_myc.models.client import Cliente from lubricentro_myc.serializers.invoice import RemitoSerializer from rest_framework import serializers class SingleClienteSerializer(serializers.ModelSerializer): lista_remitos = serializers.ListField(child=RemitoSerializer(), read_only=True) class Meta: model = Cliente fields = [ "id", "nombre", "direccion", "localidad", "codigo_postal", "telefono", "cuit", "email", "lista_remitos", "deuda_actual", ] class ClienteSerializer(serializers.ModelSerializer): class Meta: model = Cliente fields = "__all__"
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,285
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/serializers/sale.py
from lubricentro_myc.models.sale import Venta from rest_framework import serializers class VentaSerializer(serializers.ModelSerializer): class Meta: model = Venta fields = "__all__" def to_representation(self, instance): data = super(VentaSerializer, self).to_representation(instance) # TODO: Improve this hacky solution try: producto = instance.producto except AttributeError: producto = instance["producto"] data["producto"] = { "codigo": producto.codigo, # TODO: not sure if it should be codigo or codigo_en_pantalla "detalle": producto.detalle, } return data class VentasSerializer(serializers.Serializer): ventas = serializers.ListField(child=VentaSerializer())
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,286
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_sale.py
import json from django.test import TestCase from lubricentro_myc.models.product import Producto from lubricentro_myc.models.sale import Venta from lubricentro_myc.tests.factories import ProductFactory, SaleFactory from lubricentro_myc.utils import mock_auth from rest_framework.test import APIClient class SaleTestCase(TestCase): @classmethod def setUpTestData(cls): cls.api_client = APIClient() cls.client_url = "/lubricentro_myc/ventas" cls.product_1 = ProductFactory(codigo=1, stock=5) cls.product_2 = ProductFactory(codigo=2, stock=4) cls.sale_1 = { "producto": cls.product_1.codigo, "cantidad": 3, "precio": "700", } cls.sale_2 = { "producto": cls.product_2.codigo, "cantidad": 1, "precio": "1500", } @mock_auth def test_get_sales_by_date(self): sale_1 = SaleFactory(fecha="2020-01-12") sale_2 = SaleFactory(fecha="2020-03-05") sale_3 = SaleFactory(fecha="2021-03-15") sale_4 = SaleFactory(fecha="2021-03-25") cases = ( { "case_name": "Should return sales made in 2020-01-12", "query_params": "?dia=12&mes=01&anio=2020", "expected_result": [sale_1.id], }, { "case_name": "Should return sales made in 2020", "query_params": "?anio=2020", "expected_result": [sale_1.id, sale_2.id], }, { "case_name": "Should return sales made in March 2021", "query_params": "?mes=03&anio=2021", "expected_result": [sale_3.id, sale_4.id], }, ) for case in cases: with self.subTest(msg=case["case_name"]): response = self.client.get( f"{self.client_url}{case['query_params']}", follow=True, ) self.assertEqual( list(map(lambda x: x["id"], response.data["results"])), case["expected_result"], ) @mock_auth def test_new_sale_without_updating_stock(self): self.client.post( f"{self.client_url}/", json.dumps(self.sale_1), content_type="application/json", follow=True, ) self.client.post( f"{self.client_url}/", json.dumps(self.sale_2), content_type="application/json", follow=True, ) sales = Venta.objects.all() producto_1 = Producto.objects.get(codigo=self.product_1.codigo) producto_2 = Producto.objects.get(codigo=self.product_2.codigo) self.assertEqual(len(sales), 2) self.assertEqual(sales[0].producto.codigo, self.product_1.codigo) self.assertEqual(sales[1].producto.codigo, self.product_2.codigo) self.assertEqual(producto_1.stock, 5) self.assertEqual(producto_2.stock, 4) @mock_auth def test_new_sale_updating_stock(self): self.client.post( f"{self.client_url}/?update_stock=true", json.dumps(self.sale_1), content_type="application/json", follow=True, ) self.client.post( f"{self.client_url}/?update_stock=true", json.dumps(self.sale_2), content_type="application/json", follow=True, ) sales = Venta.objects.all() producto_1 = Producto.objects.get(codigo=self.product_1.codigo) producto_2 = Producto.objects.get(codigo=self.product_2.codigo) self.assertEqual(len(sales), 2) self.assertEqual(sales[0].producto.codigo, self.product_1.codigo) self.assertEqual(sales[1].producto.codigo, self.product_2.codigo) self.assertEqual(producto_1.stock, 2) self.assertEqual(producto_2.stock, 3) @mock_auth def test_bulk_sale(self): sales = [self.sale_1, self.sale_2] self.client.post( f"{self.client_url}/bulk/?update_stock=true", json.dumps({"ventas": sales}), content_type="application/json", follow=True, ) sales = Venta.objects.all() self.assertEqual(len(sales), 2) @mock_auth def test_sales_per_year(self): SaleFactory(fecha="2021-03-12", precio=3500) SaleFactory(fecha="2021-05-05", precio=1750) SaleFactory(fecha="2021-04-29", precio=275) SaleFactory(fecha="2021-05-22", precio=1125) SaleFactory(fecha="2021-10-03", precio=2250) response = self.client.get( f"{self.client_url}/ventas_por_anio?year=2021", follow=True ) ventas = json.loads(response.content)["sales_per_year"] self.assertEqual( ventas, [0, 0, 3500.0, 275.0, 2875.0, 0, 0, 0, 0, 2250.0, 0, 0] ) @mock_auth def test_sales_per_month(self): SaleFactory(fecha="2021-05-12", precio=1050) SaleFactory(fecha="2021-05-05", precio=700) SaleFactory(fecha="2021-05-30", precio=2250) SaleFactory(fecha="2021-05-22", precio=1300) SaleFactory(fecha="2021-05-05", precio=2300) response = self.client.get( f"{self.client_url}/ventas_por_mes?month=5&year=2021", follow=True ) ventas = json.loads(response.content)["sales_per_month"] self.assertEqual( ventas, [ 0, 0, 0, 0, 3000.0, 0, 0, 0, 0, 0, 0, 1050.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1300.0, 0, 0, 0, 0, 0, 0, 0, 2250.0, 0, ], )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,287
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/apps.py
from django.apps import AppConfig class LubricentroMycConfig(AppConfig): name = "lubricentro_myc" def ready(self): import lubricentro_myc.signals
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,288
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0011_auto_20190821_0240.py
# Generated by Django 2.2.3 on 2019-08-21 02:40 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0010_auto_20190821_0240"), ] operations = [ migrations.AlterField( model_name="elementoremito", name="remito", field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.Remito" ), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,289
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/product.py
from django.db.models import Q from django.http import HttpResponse, JsonResponse from lubricentro_myc.models import ProductPriceHistory from lubricentro_myc.models.product import Producto from lubricentro_myc.serializers.product import ProductoSerializer from lubricentro_myc.views.pagination import CustomPageNumberPagination from rest_framework import viewsets from rest_framework.decorators import action class ProductoViewSet(viewsets.ModelViewSet, CustomPageNumberPagination): queryset = Producto.objects.all().order_by("codigo_en_pantalla") serializer_class = ProductoSerializer pagination_class = CustomPageNumberPagination def list(self, request): detalle = request.GET.get("detalle", None) categoria = request.GET.get("categoria", None) query = request.GET.get("query", None) if detalle: self.queryset = Producto.objects.filter( detalle__icontains=detalle ).order_by("codigo_en_pantalla") elif categoria: self.queryset = Producto.objects.filter( categoria__iexact=categoria ).order_by("codigo_en_pantalla") elif query: if query.isnumeric(): self.queryset = Producto.objects.filter( codigo_en_pantalla__gte=query ).order_by("codigo_en_pantalla") else: self.queryset = Producto.objects.filter( Q(codigo_en_pantalla__contains=query) | Q(detalle__icontains=query) | Q(categoria__icontains=query) ).order_by("codigo_en_pantalla") return super().list(request) @action(detail=False, methods=["post"]) def aumento_masivo_precio_costo(self, request): producto_ids = request.data.get("productos") porcentaje_aumento = request.data.get("porcentaje_aumento") if not producto_ids or not porcentaje_aumento: return HttpResponse(status=400) aumento = 1 + int(porcentaje_aumento) / 100 updated_products = 0 for producto_id in producto_ids: try: p = Producto.objects.get(codigo=producto_id) p.precio_costo = p.precio_costo * aumento p.save() updated_products += 1 except Producto.DoesNotExist: pass return JsonResponse( data={ "resultado": f"{updated_products} producto/s actualizado/s satisfactoriamente." } ) @action(detail=True, methods=["get"]) def historial_precios(self, request, pk=None): try: Producto.objects.get(codigo=pk) except Producto.DoesNotExist: return HttpResponse(status=404) prices_history = ProductPriceHistory.objects.filter(product__codigo=pk) return JsonResponse( data={ "prices": [ { "old_price": round(price.old_price, 2), "new_price": round(price.new_price, 2), "date": price.timestamp, } for price in prices_history ] } ) @action(detail=False, methods=["get"]) def codigos_disponibles(self, request): start = int(request.GET.get("start", 1)) amount = int(request.GET.get("amount", 10)) codes_in_used = Producto.objects.all().values_list( "codigo_en_pantalla", flat=True ) available_codes = list(set(list(range(start, 100001))) - set(codes_in_used)) closest_code = min(available_codes, key=lambda x: abs(x - start)) closest_code_index = available_codes.index(closest_code) return JsonResponse( data={ "available_codes": available_codes[ closest_code_index : closest_code_index + amount ] } )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,290
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0015_auto_20190826_2356.py
# Generated by Django 2.2.3 on 2019-08-26 23:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0014_auto_20190821_1043"), ] operations = [ migrations.AlterField( model_name="cliente", name="nombre", field=models.CharField(max_length=100, unique=True), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,291
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0003_auto_20190803_2337.py
# Generated by Django 2.2.3 on 2019-08-03 23:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0002_auto_20190714_2243"), ] operations = [ migrations.AlterField( model_name="producto", name="codigo", field=models.AutoField(primary_key=True, serialize=False), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,292
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0009_elementoremito.py
# Generated by Django 2.2.3 on 2019-08-20 02:16 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0008_auto_20190808_0258"), ] operations = [ migrations.CreateModel( name="ElementoRemito", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("numero_remito", models.IntegerField()), ("cantidad", models.IntegerField()), ( "producto", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="lubricentro_myc.Producto", ), ), ], ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,293
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/serializers/product.py
from lubricentro_myc.models.product import Producto from rest_framework import serializers class ProductoSerializer(serializers.ModelSerializer): class Meta: model = Producto fields = [ "codigo", "codigo_en_pantalla", "detalle", "stock", "precio_costo", "desc1", "desc2", "desc3", "desc4", "flete", "ganancia", "iva", "agregado_cta_cte", "categoria", "precio_venta_contado", "precio_venta_cta_cte", ] def create(self, validated_data): instance = self.Meta.model(**validated_data) instance.save() codigo_en_pantalla = validated_data.get("codigo_en_pantalla") if not codigo_en_pantalla: instance.codigo_en_pantalla = instance.codigo instance.save() return instance def to_representation(self, instance): data = super(ProductoSerializer, self).to_representation(instance) data["precio_costo"] = round(instance.precio_costo, 2) return data
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,294
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/invoice.py
from django.db import models from django.utils import timezone from lubricentro_myc.models.invoice_item import ElementoRemito class Remito(models.Model): codigo = models.AutoField(primary_key=True) cliente = models.ForeignKey("lubricentro_myc.Cliente", on_delete=models.CASCADE) fecha = models.DateTimeField(default=timezone.now) def __str__(self): return f"Remito n°{str(self.codigo)}" @property def resumen_elementos(self): return [ { "id": elemento.id, "producto": { "codigo": elemento.producto.codigo_en_pantalla, "detalle": elemento.producto.detalle, }, "cantidad": elemento.cantidad, "pagado": elemento.pagado, } for elemento in ElementoRemito.objects.filter(remito_id=self.codigo) ] @property def esta_pago(self) -> bool: elementos_remito_no_pagos = ElementoRemito.objects.filter( remito_id=self.codigo, pagado=False ) return len(elementos_remito_no_pagos) == 0 @property def data(self): return self.codigo, self.cliente.id, self.fecha
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,295
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0026_producto_codigo_en_pantalla_alter_producto_codigo.py
# Generated by Django 4.0.4 on 2022-05-02 11:27 from django.db import migrations, models def set_display_codes(apps, schema_editor): Producto = apps.get_model("lubricentro_myc", "Producto") for producto in Producto.objects.all(): producto.codigo_en_pantalla = producto.codigo producto.save(update_fields=["codigo_en_pantalla"]) class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0025_cliente_email"), ] operations = [ migrations.AddField( model_name="producto", name="codigo_en_pantalla", field=models.IntegerField(null=True, unique=True), ), migrations.RunPython(set_display_codes, migrations.RunPython.noop), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,296
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/file.py
from django.http import HttpResponse from lubricentro_myc.models.client import Cliente from lubricentro_myc.models.invoice import ElementoRemito, Remito from lubricentro_myc.models.product import Producto from lubricentro_myc.utils import render_to_pdf def generar_stock_pdf(request): categoria = request.GET.get("categoria") if not categoria: return HttpResponse(status=400) productos = Producto.objects.filter(categoria__iexact=categoria) total_precio_costo = 0.0 total_precio_venta = 0.0 for producto in productos: total_precio_costo += producto.precio_costo_con_descuentos * producto.stock total_precio_venta += producto.precio_venta_contado * producto.stock context = { "categoria": categoria, "productos": productos, "total_precio_costo": total_precio_costo, "total_precio_venta": total_precio_venta, } pdf = render_to_pdf("pdf/stock_pdf.html", context) if not pdf: return HttpResponse(status=500) response = HttpResponse(pdf, content_type="application/pdf") filename = f"stock_{categoria}.pdf" content = f"inline; filename='{filename}'" download = request.GET.get("download") if download: content = f"attachment; filename={filename}" response["Content-Disposition"] = content return response def generar_remito_pdf(request): codigo_remito = request.GET.get("cod_remito") if not codigo_remito: return HttpResponse(status=400) try: remito = Remito.objects.get(codigo=codigo_remito) except Remito.DoesNotExist: return HttpResponse(status=404) elementos_remito = [] for elemento in ElementoRemito.objects.filter(remito=remito): producto = Producto.objects.get(codigo=elemento.producto_id) elemento_remito = { "codigo": producto.codigo_en_pantalla, "detalle": producto.detalle, "cantidad": elemento.cantidad, } elementos_remito.append(elemento_remito) context = { "remito": remito, "cliente": Cliente.objects.get(id=remito.cliente_id), "elementos_remito": elementos_remito, } pdf = render_to_pdf("pdf/remito_pdf.html", context) if not pdf: return HttpResponse(status=500) response = HttpResponse(pdf, content_type="application/pdf") filename = f"remito_{codigo_remito}.pdf" content = f"inline; filename='{filename}'" download = request.GET.get("download") if download: content = f"attachment; filename={filename}" response["Content-Disposition"] = content return response
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,297
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/tests/test_signals.py
from django.test import TestCase from lubricentro_myc.models import ProductPriceHistory from lubricentro_myc.models.product import Producto from lubricentro_myc.signals import delete_invoice_item, save_invoice_item, save_product from lubricentro_myc.tests.factories import ( ClientFactory, InvoiceFactory, InvoiceItemFactory, ProductFactory, ) class SignalsTestCase(TestCase): @classmethod def setUpTestData(cls): cls.client_1 = ClientFactory() cls.product_1 = ProductFactory(codigo=1, stock=5.0, precio_costo=25.0) cls.product_2 = ProductFactory(codigo=2, stock=11.5) cls.invoice = InvoiceFactory(cliente=cls.client_1) def test_save_invoice_item_with_new_invoice_item(self): new_invoice_item = InvoiceItemFactory.build( remito=self.invoice, producto=self.product_1, cantidad=4.0 ) save_invoice_item(sender=None, instance=new_invoice_item) product = Producto.objects.get(codigo=self.product_1.codigo) self.assertEqual(product.stock, 1.0) def test_save_invoice_item_updating_invoice_item(self): invoice_item_1 = InvoiceItemFactory( remito=self.invoice, producto=self.product_1, cantidad=0.0 ) new_invoice_item = InvoiceItemFactory.build( id=invoice_item_1.id, remito=self.invoice, producto=self.product_1, cantidad=3.0, ) save_invoice_item(sender=None, instance=new_invoice_item) product = Producto.objects.get(codigo=self.product_1.codigo) self.assertEqual(product.stock, 2.0) def test_delete_invoice_item(self): invoice_item = InvoiceItemFactory.build( remito=self.invoice, producto=self.product_1, cantidad=3.0, ) delete_invoice_item(sender=None, instance=invoice_item) product = Producto.objects.get(codigo=self.product_1.codigo) self.assertEqual(product.stock, 8.0) def test_save_product(self): updated_product = ProductFactory.build( codigo=self.product_1.codigo, precio_costo=35.0 ) save_product(sender=None, instance=updated_product) product_price_history = ProductPriceHistory.objects.filter( product__codigo=self.product_1.codigo ).first() self.assertEqual(product_price_history.old_price, self.product_1.precio_costo) self.assertEqual(product_price_history.new_price, updated_product.precio_costo)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,298
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/product.py
from django.db import models class Producto(models.Model): codigo = models.AutoField(primary_key=True) codigo_en_pantalla = models.IntegerField(null=True, unique=True) detalle = models.CharField(max_length=200) stock = models.FloatField(default=0.0) precio_costo = models.FloatField(default=0.0) # sin iva desc1 = models.FloatField(default=0.0) desc2 = models.FloatField(default=0.0) desc3 = models.FloatField(default=0.0) desc4 = models.FloatField(default=0.0) flete = models.FloatField(default=0.0) ganancia = models.FloatField(default=40.0) iva = models.FloatField(default=21.0) agregado_cta_cte = models.FloatField(default=0.0) categoria = models.CharField(max_length=50) def __str__(self): return self.detalle @property def precio_venta_contado(self) -> float: precio_total_con_descuentos = ( self.precio_costo * ((100 - self.desc1) / 100) * ((100 - self.desc2) / 100) * ((100 - self.desc3) / 100) * ((100 - self.desc4) / 100) ) precio_total_con_ganancias = ( precio_total_con_descuentos * ((100 + self.flete) / 100) * ((100 + self.ganancia) / 100) * ((100 + self.iva) / 100) ) return round(precio_total_con_ganancias, 2) @property def precio_venta_cta_cte(self) -> float: return round( self.precio_venta_contado * ((100 + self.agregado_cta_cte) / 100), 2 ) @property def data(self): return ( self.codigo, self.codigo_en_pantalla, self.detalle, self.stock, self.precio_costo, self.desc1, self.desc2, self.desc3, self.desc4, self.flete, self.ganancia, self.iva, self.agregado_cta_cte, self.categoria, )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,299
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/db.py
from django.http import HttpResponse from lubricentro_myc.models import ( Cliente, ElementoRemito, Producto, ProductPriceHistory, Remito, Venta, ) def reset(request): # This endpoint is intended to clean up the database after running E2E tests. ElementoRemito.objects.all().delete() Remito.objects.all().delete() Venta.objects.all().delete() Cliente.objects.all().delete() ProductPriceHistory.objects.all().delete() Producto.objects.all().delete() return HttpResponse(status=200)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,300
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0023_auto_20201109_0802.py
# Generated by Django 3.1.3 on 2020-11-09 08:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0022_auto_20200216_2326"), ] operations = [ migrations.AlterField( model_name="producto", name="codigo", field=models.IntegerField(primary_key=True, serialize=False), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,301
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/signals.py
import datetime from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from lubricentro_myc.models import ProductPriceHistory from lubricentro_myc.models.invoice import ElementoRemito from lubricentro_myc.models.product import Producto @receiver(pre_save, sender=ElementoRemito) def save_invoice_item(sender, instance, **kwargs): new_quantity = None if instance.id: # an existent invoice item is being updated older_instance = ElementoRemito.objects.get(id=instance.id) if instance.cantidad != older_instance.cantidad: new_quantity = instance.cantidad - older_instance.cantidad else: # a new invoice item is being created new_quantity = instance.cantidad if new_quantity: product = Producto.objects.get(codigo=instance.producto.codigo) product.stock -= new_quantity product.save() @receiver(post_delete, sender=ElementoRemito) def delete_invoice_item(sender, instance, **kwargs): product = Producto.objects.get(codigo=instance.producto.codigo) product.stock += instance.cantidad product.save() @receiver(pre_save, sender=Producto) def save_product(sender, instance, **kwargs): try: product_being_updated = Producto.objects.get(codigo=instance.codigo) except Producto.DoesNotExist: return old_price = round(product_being_updated.precio_costo, 2) new_price = round(instance.precio_costo, 2) if old_price != new_price: ProductPriceHistory.objects.create( product=product_being_updated, old_price=old_price, new_price=new_price, timestamp=datetime.datetime.utcnow(), )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,302
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0024_auto_20210217_1435.py
# Generated by Django 3.1.3 on 2021-02-17 14:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0023_auto_20201109_0802"), ] operations = [ migrations.AlterField( model_name="producto", name="stock", field=models.FloatField(default=0.0), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,303
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0007_auto_20190806_0051.py
# Generated by Django 2.2.3 on 2019-08-06 00:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0006_auto_20190806_0042"), ] operations = [ migrations.AlterField( model_name="cliente", name="codigo_postal", field=models.CharField(default="", max_length=4), ), migrations.AlterField( model_name="cliente", name="cuit", field=models.CharField(default="", max_length=13), ), migrations.AlterField( model_name="cliente", name="direccion", field=models.CharField(default="", max_length=100), ), migrations.AlterField( model_name="cliente", name="localidad", field=models.CharField(default="", max_length=100), ), migrations.AlterField( model_name="cliente", name="telefono", field=models.CharField(default="", max_length=13), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,304
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/invoice_item.py
from django.db import models class ElementoRemito(models.Model): remito = models.ForeignKey("lubricentro_myc.Remito", on_delete=models.CASCADE) producto = models.ForeignKey("lubricentro_myc.Producto", on_delete=models.CASCADE) cantidad = models.FloatField(null=False) pagado = models.BooleanField(default=False) @property def data(self): return ( self.id, self.remito.codigo, self.producto.codigo, self.cantidad, self.pagado, )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,305
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/migrations/0017_venta_fecha.py
# Generated by Django 2.2.3 on 2019-08-28 00:52 import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("lubricentro_myc", "0016_venta"), ] operations = [ migrations.AddField( model_name="venta", name="fecha", field=models.DateTimeField(default=django.utils.timezone.now), ), ]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,306
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/serializers/invoice_item.py
from lubricentro_myc.models.invoice import ElementoRemito from rest_framework import serializers class ElementoRemitoSerializer(serializers.ModelSerializer): class Meta: model = ElementoRemito fields = "__all__" def to_representation(self, instance): data = super(ElementoRemitoSerializer, self).to_representation(instance) data["producto"] = { "codigo": instance.producto.codigo, "detalle": instance.producto.detalle, "precio_venta_cta_cte": instance.producto.precio_venta_cta_cte, } return data class BillingSerializer(serializers.Serializer): items = serializers.PrimaryKeyRelatedField( queryset=ElementoRemito.objects.filter(pagado=False), many=True )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,307
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/management/commands/export_data_in_csv.py
import csv import logging from django.core.management import BaseCommand from lubricentro_myc.models import ( Cliente, ElementoRemito, Producto, ProductPriceHistory, Remito, Venta, ) logger = logging.getLogger("django") DELIMITER = "|" def create_file(filename: str, queryset): f = open(f"files/{filename}.csv", "w") writer = csv.writer(f, delimiter=DELIMITER) for obj in queryset: writer.writerow(obj.data) class Command(BaseCommand): help = "Exports models data in a CSV file" def handle(self, *args, **kwargs): logger.info("Starting to export models data...") logger.info("Saving products...") create_file("products", Producto.objects.all()) logger.info("Saving product prices history...") create_file("product_prices_history", ProductPriceHistory.objects.all()) logger.info("Saving clients...") create_file("clients", Cliente.objects.all()) logger.info("Saving sales...") create_file("sales", Venta.objects.all()) logger.info("Saving invoices...") create_file("invoices", Remito.objects.all()) logger.info("Saving invoice items...") create_file("invoice_items", ElementoRemito.objects.all()) logger.info("Finished.")
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,308
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/sale.py
import calendar from calendar import monthrange from django.db.models import Q, Sum from django.http import HttpResponse, JsonResponse from lubricentro_myc.models.client import Cliente from lubricentro_myc.models.product import Producto from lubricentro_myc.models.sale import Venta from lubricentro_myc.serializers.sale import VentaSerializer, VentasSerializer from lubricentro_myc.views.pagination import CustomPageNumberPagination from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response class VentaViewSet(viewsets.ModelViewSet, CustomPageNumberPagination): queryset = Venta.objects.all().order_by("id") serializer_class = VentaSerializer pagination_class = CustomPageNumberPagination def list(self, request): dia = request.GET.get("dia") mes = request.GET.get("mes") anio = request.GET.get("anio") if dia or mes or anio: filters = Q() if anio: filters &= Q(fecha__year=int(anio)) else: return HttpResponse(status=400) if mes: filters &= Q(fecha__month=int(mes)) elif dia: return HttpResponse(status=400) if dia: filters &= Q(fecha__day=int(dia)) if filters: self.queryset = Venta.objects.filter(filters).order_by("fecha") return super().list(request) def store_sale(self, venta, update_stock): product = Producto.objects.get(codigo=venta["producto"]["codigo"]) Venta.objects.create( producto=product, cantidad=venta["cantidad"], precio=venta["precio"], ) if update_stock: product.stock -= venta["cantidad"] product.save() def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) update_stock = True if request.GET.get("update_stock") == "true" else False self.store_sale(serializer.data, update_stock) return Response(serializer.data, status=status.HTTP_201_CREATED) @action(detail=False, methods=["post"]) def bulk(self, request): serializer = VentasSerializer( data=request.data ) # TODO: change for VentaSerializer with many=True serializer.is_valid(raise_exception=True) update_stock = True if request.GET.get("update_stock") == "true" else False for venta in serializer.data["ventas"]: self.store_sale(venta, update_stock) return Response(serializer.data, status=status.HTTP_201_CREATED) @action(detail=False, methods=["get"]) def ventas_por_anio(self, request): year = request.GET.get("year") if not year: return HttpResponse(status=400) data = [] for i in range(12): ventas = Venta.objects.filter( fecha__month=int(i + 1), fecha__year=int(year) ) suma_ventas = ventas.aggregate(Sum("precio"))["precio__sum"] data.append(round(suma_ventas, 2) if suma_ventas else 0) return JsonResponse(data={"sales_per_year": data}) @action(detail=False, methods=["get"]) def ventas_por_mes(self, request): year = request.GET.get("year") month = request.GET.get("month") if not year or not month: return HttpResponse(status=400) try: days = monthrange(int(year), int(month)) except calendar.IllegalMonthError: return HttpResponse(status=400) data = [] for i in range(days[1]): ventas = Venta.objects.filter( fecha__day=int(i + 1), fecha__month=int(month), fecha__year=int(year), ) suma_ventas = ventas.aggregate(Sum("precio"))["precio__sum"] data.append(round(suma_ventas, 2) if suma_ventas else 0) return JsonResponse(data={"sales_per_month": data}) @action(detail=False, methods=["get"]) def historial_deudores(self, request): total_debt = 0 clients = [] for client in Cliente.objects.all(): client_debt = client.deuda_actual if client_debt > 0: total_debt += client_debt clients.append( { "id": client.id, "nombre": client.nombre, "deuda_actual": client_debt, } ) return JsonResponse( data={ "clientes": sorted( clients, key=lambda d: d["deuda_actual"], reverse=True ), "deuda_total": total_debt, } )
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,309
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/admin.py
from django.contrib import admin from lubricentro_myc.models.client import Cliente from lubricentro_myc.models.invoice import ElementoRemito, Remito from lubricentro_myc.models.product import Producto from lubricentro_myc.models.sale import Venta def download_csv(modeladmin, request, queryset): import csv from io import StringIO from django.http import HttpResponse f = StringIO() writer = csv.writer(f) row = [] for key in queryset.values()[0].keys(): row.append(key) writer.writerow(row) for s in queryset.values(): row = [] for value in s.values(): row.append(value) writer.writerow(row) f.seek(0) response = HttpResponse(f, content_type="text/csv") content_disposition = "attachment; filename=" + queryset.model.__name__ + "s.csv" response["Content-Disposition"] = content_disposition return response @admin.register(Cliente) class ClienteAdmin(admin.ModelAdmin): list_display = [ "id", "nombre", "direccion", "localidad", "codigo_postal", "telefono", "cuit", ] actions = [download_csv] download_csv.short_description = "Download CSV file for selected items" @admin.register(Producto) class ProductoAdmin(admin.ModelAdmin): list_display = [ "codigo", "detalle", "stock", "precio_costo", "desc1", "desc2", "desc3", "desc4", "flete", "ganancia", "iva", "agregado_cta_cte", "categoria", "precio_venta_contado", "precio_venta_cta_cte", ] actions = [download_csv] download_csv.short_description = "Download CSV file for selected items" @admin.register(Remito) class RemitoAdmin(admin.ModelAdmin): list_display = ["codigo", "fecha"] @admin.register(ElementoRemito) class ElementoRemitoAdmin(admin.ModelAdmin): list_display = ["id", "remito", "producto", "cantidad", "pagado"] @admin.register(Venta) class VentaAdmin(admin.ModelAdmin): list_display = ["producto", "cantidad", "precio", "fecha"]
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,310
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/models/sale.py
from django.db import models from django.utils import timezone class Venta(models.Model): producto = models.ForeignKey("lubricentro_myc.Producto", on_delete=models.CASCADE) cantidad = models.FloatField(null=False) precio = models.FloatField(null=False) fecha = models.DateTimeField(default=timezone.now) @property def data(self): return self.id, self.producto.codigo, self.cantidad, self.precio, self.fecha
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,878,311
MatiasAdrian4/lubricentro_myc
refs/heads/develop
/django_project/lubricentro_myc/views/client.py
from django.db.models import Q from lubricentro_myc.models.client import Cliente from lubricentro_myc.serializers.client import ( ClienteSerializer, SingleClienteSerializer, ) from lubricentro_myc.views.pagination import CustomPageNumberPagination from rest_framework import viewsets class ClienteViewSet(viewsets.ModelViewSet, CustomPageNumberPagination): queryset = Cliente.objects.all().order_by("id") serializer_class = ClienteSerializer pagination_class = CustomPageNumberPagination def retrieve(self, request, *args, **kwargs): self.serializer_class = SingleClienteSerializer return super().retrieve(request) def list(self, request): nombre = request.GET.get("nombre") query = request.GET.get("query") if nombre: self.queryset = Cliente.objects.filter(nombre__icontains=nombre).order_by( "id" ) elif query: self.queryset = Cliente.objects.filter( Q(id__contains=query) | Q(nombre__icontains=query) ).order_by("id") return super().list(request)
{"/django_project/lubricentro_myc/views.py": ["/django_project/lubricentro_myc/models.py", "/django_project/lubricentro_myc/serializers.py", "/django_project/lubricentro_myc/utils.py"], "/django_project/lubricentro_myc/serializers.py": ["/django_project/lubricentro_myc/models.py"], "/django_project/lubricentro_myc/models/__init__.py": ["/django_project/lubricentro_myc/models/client.py", "/django_project/lubricentro_myc/models/invoice.py", "/django_project/lubricentro_myc/models/invoice_item.py", "/django_project/lubricentro_myc/models/product.py", "/django_project/lubricentro_myc/models/product_cost_history.py", "/django_project/lubricentro_myc/models/sale.py"]}
24,893,933
ekdms3868/pore
refs/heads/main
/pore/portfolio/models.py
from django.db import models # user 앱에서 CustomUser, Field 모델 import from user.models import CustomUser, Field from django.db.models import fields class Portfolio(models.Model): def __str__(self): return self.pf_title pf_title = models.CharField(max_length=200) pf_content = models.TextField() pf_attach = models.FileField(blank=True, upload_to="images/", null=True) # summernote 쓰면 필요할까? pf_date = models.DateTimeField() user_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='portfolios', null=True) # 글 작성자 f_id = models.ForeignKey(Field, on_delete=models.CASCADE, related_name='portfolios', null=True) # 포트폴리오 분야
{"/portfolio/forms.py": ["/portfolio/models.py", "/user/models.py"], "/portfolio/models.py": ["/user/models.py"], "/user/forms.py": ["/user/models.py"], "/user/views.py": ["/user/models.py", "/portfolio/models.py", "/user/forms.py"], "/portfolio/views.py": ["/user/models.py", "/portfolio/models.py", "/portfolio/forms.py"], "/user/admin.py": ["/user/models.py"], "/pore/portfolio/models.py": ["/user/models.py"], "/pore/portfolio/views.py": ["/pore/portfolio/models.py", "/pore/portfolio/forms.py"], "/pore/portfolio/forms.py": ["/pore/portfolio/models.py"]}
24,893,934
ekdms3868/pore
refs/heads/main
/pore/portfolio/migrations/0002_auto_20210709_1728.py
# Generated by Django 3.0.6 on 2021-07-09 08:28 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('portfolio', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('user', '0001_initial'), ] operations = [ migrations.AddField( model_name='portfolio', name='f_id', field=models.ForeignKey(default=10, on_delete=django.db.models.deletion.CASCADE, related_name='portfolios', to='user.Field'), ), migrations.AddField( model_name='portfolio', name='user_id', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='portfolios', to=settings.AUTH_USER_MODEL), ), ]
{"/portfolio/forms.py": ["/portfolio/models.py", "/user/models.py"], "/portfolio/models.py": ["/user/models.py"], "/user/forms.py": ["/user/models.py"], "/user/views.py": ["/user/models.py", "/portfolio/models.py", "/user/forms.py"], "/portfolio/views.py": ["/user/models.py", "/portfolio/models.py", "/portfolio/forms.py"], "/user/admin.py": ["/user/models.py"], "/pore/portfolio/models.py": ["/user/models.py"], "/pore/portfolio/views.py": ["/pore/portfolio/models.py", "/pore/portfolio/forms.py"], "/pore/portfolio/forms.py": ["/pore/portfolio/models.py"]}
24,893,935
ekdms3868/pore
refs/heads/main
/pore/portfolio/views.py
from django.db.models import fields from django.shortcuts import redirect, render, get_object_or_404 from django.utils import timezone from .models import CustomUser, Portfolio, Field from .forms import PortfolioForm def pfshow(request, field_id): portfolios = Portfolio.objects.all() field = get_object_or_404(Field, pk=field_id) return render(request, 'portfolio/pfshow.html', {'field':field,'portfolios':portfolios}) def mypage(request): # 로그인 상태가 아닐 경우 signin 페이지 이동 if not request.user.is_active: return render(request, 'user/signin.html') portfolios = Portfolio.objects.all() # 현재 로그인한 유저 user = request.user return render(request, 'portfolio/mypage.html', {'portfolios':portfolios}) def guide(request): return render(request, 'portfolio/guide.html') def pfupload(request): if not request.user.is_active: return render(request, 'user/signin.html') if request.method == 'POST': form = PortfolioForm(request.POST, request.FILES) if form.is_valid(): pf = form.save(commit=False) pf.pf_date = timezone.now() pf.user_id = request.user pf.f_id = request.user.field_id pf.save() return redirect('mypage') else: form = PortfolioForm() return render(request, 'portfolio/pfupload.html', {'form':form}) def pfedit(request, id): pf = get_object_or_404(Portfolio, id=id) if request.method == 'POST': form = PortfolioForm(request.POST, instance=pf) if form.is_valid(): pf = form.save(commit=False) pf.pf_date = timezone.now() pf.save() return redirect('pfdetail', id) else: form = PortfolioForm(instance=pf) return render(request, 'portfolio/pfedit.html', {'form':form}) def delete(request, id): pf = get_object_or_404(Portfolio, id=id) pf.delete() return redirect('mypage') def pfdetail(request, id): portfolio = get_object_or_404(Portfolio, id=id) return render(request, 'portfolio/pfdetail.html', {'portfolio':portfolio}) def withdraw(request): return render(request, 'portfolio/withdraw.html') def chat(request): return render(request, 'portfolio/chat.html') def paylist(request): return render(request, 'portfolio/paylist.html')
{"/portfolio/forms.py": ["/portfolio/models.py", "/user/models.py"], "/portfolio/models.py": ["/user/models.py"], "/user/forms.py": ["/user/models.py"], "/user/views.py": ["/user/models.py", "/portfolio/models.py", "/user/forms.py"], "/portfolio/views.py": ["/user/models.py", "/portfolio/models.py", "/portfolio/forms.py"], "/user/admin.py": ["/user/models.py"], "/pore/portfolio/models.py": ["/user/models.py"], "/pore/portfolio/views.py": ["/pore/portfolio/models.py", "/pore/portfolio/forms.py"], "/pore/portfolio/forms.py": ["/pore/portfolio/models.py"]}
24,893,936
ekdms3868/pore
refs/heads/main
/pore/portfolio/urls.py
from django.urls import path,include from portfolio import views urlpatterns = [ path('', views.mypage, name='mypage'), path('guide/', views.guide, name='guide'), path('pfupload/', views.pfupload, name='pfupload'), path('pfdetail/<int:id>/', views.pfdetail, name='pfdetail'), path('pfedit/<int:id>/', views.pfedit, name='pfedit'), path('delete/<int:id>/', views.delete, name='delete'), path('withdraw/', views.withdraw, name='withdraw'), path('chat/', views.chat, name='chat'), path('paylist/', views.paylist, name='paylist'), path('pfshow/<int:field_id>', views.pfshow, name='pfshow'), ]
{"/portfolio/forms.py": ["/portfolio/models.py", "/user/models.py"], "/portfolio/models.py": ["/user/models.py"], "/user/forms.py": ["/user/models.py"], "/user/views.py": ["/user/models.py", "/portfolio/models.py", "/user/forms.py"], "/portfolio/views.py": ["/user/models.py", "/portfolio/models.py", "/portfolio/forms.py"], "/user/admin.py": ["/user/models.py"], "/pore/portfolio/models.py": ["/user/models.py"], "/pore/portfolio/views.py": ["/pore/portfolio/models.py", "/pore/portfolio/forms.py"], "/pore/portfolio/forms.py": ["/pore/portfolio/models.py"]}
24,893,937
ekdms3868/pore
refs/heads/main
/pore/portfolio/forms.py
from django import forms from django.db.models import fields from .models import Portfolio from django_summernote.widgets import SummernoteWidget class PortfolioForm(forms.ModelForm): class Meta: model = Portfolio fields = ['pf_title', 'pf_content', 'pf_attach'] # pf_content의 위젯으로 summernote 사용 widgets = { 'pf_content': SummernoteWidget(), } labels = { 'pf_title': '제목', 'pf_content': '내용', 'pf_attach': '첨부파일', }
{"/portfolio/forms.py": ["/portfolio/models.py", "/user/models.py"], "/portfolio/models.py": ["/user/models.py"], "/user/forms.py": ["/user/models.py"], "/user/views.py": ["/user/models.py", "/portfolio/models.py", "/user/forms.py"], "/portfolio/views.py": ["/user/models.py", "/portfolio/models.py", "/portfolio/forms.py"], "/user/admin.py": ["/user/models.py"], "/pore/portfolio/models.py": ["/user/models.py"], "/pore/portfolio/views.py": ["/pore/portfolio/models.py", "/pore/portfolio/forms.py"], "/pore/portfolio/forms.py": ["/pore/portfolio/models.py"]}
24,934,539
KlNGDOM/qqbot
refs/heads/main
/fn.py
from qqk import jf with open('tem.txt','r') as fo: s = fo.read() s = s.split() ans = 0 k = float(s[0]) while k<float(s[1]): ans+=0.0001*jf(k) k+=0.0001 print(f'{ans:.3f}')
{"/fn.py": ["/qqk.py"]}
24,934,540
KlNGDOM/qqbot
refs/heads/main
/qqk.py
def jf(x):return x*x*x
{"/fn.py": ["/qqk.py"]}
24,934,541
KlNGDOM/qqbot
refs/heads/main
/wjf.py
import os s = input().split() fo = open('qqk.py','w') txt = 'def jf(x):return '+s[0] fo.write(txt) fo.close() fo=open('tem.txt','w') fo.write(s[1]+' '+s[2]) fo.close() os.system('python fn.py')
{"/fn.py": ["/qqk.py"]}
24,966,252
AbrorR/fastapi-belajar
refs/heads/master
/server/models/merchant.py
from typing import Optional from pydantic import BaseModel, EmailStr, Field class MerchantModel(BaseModel): email: EmailStr = Field(...)#(...) Field required name: str = Field(...) class Config: schema_extra = { "example" : { "email": "merchanta@gmail.com", "name": "Merchant A", } } class UpdateMerchantModel(BaseModel): email: Optional[EmailStr] name: Optional[str] class Config: schema_extra = { "example" : { "email": "merchantb@gmail.com", "name": "Merchant B", } } def ResponseModel(data, message): return { "data": [data], "code": 200, "message": message, } def ErrorResponseModel(error, code, message): return { "error": error, "code": code, "message": message }
{"/server/models/user.py": ["/server/models/merchant.py"], "/server/app.py": ["/server/routes/merchant.py", "/server/routes/user.py", "/server/database.py"], "/server/routes/user.py": ["/server/database.py", "/server/models/user.py"], "/server/routes/merchant.py": ["/server/database.py", "/server/models/merchant.py", "/server/models/user.py"]}
24,966,253
AbrorR/fastapi-belajar
refs/heads/master
/server/app.py
from fastapi import FastAPI from server.routes.merchant import router as MerchantRouter app = FastAPI() app.include_router(MerchantRouter, tags=["Merchant"], prefix="/merchant") @app.get("/", tags=["Root"]) async def read_root(): return {"message": "Welcome to this fantastic app!"}
{"/server/models/user.py": ["/server/models/merchant.py"], "/server/app.py": ["/server/routes/merchant.py", "/server/routes/user.py", "/server/database.py"], "/server/routes/user.py": ["/server/database.py", "/server/models/user.py"], "/server/routes/merchant.py": ["/server/database.py", "/server/models/merchant.py", "/server/models/user.py"]}
24,966,254
AbrorR/fastapi-belajar
refs/heads/master
/server/database.py
import motor.motor_asyncio from bson.objectid import ObjectId from decouple import config MONGO_DETAILS = config('MONGO_DETAILS') # read environment variable. client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_DETAILS) database = client.merchants merchant_collection = database.get_collection("merchants_collection") def merchant_helper(merchant) -> dict: return { "id": str(merchant["_id"]), "email": merchant["email"], "name": merchant["name"], } # Retrieve all merchants present in the database async def retrieve_merchants(): merchants = [] async for merchant in merchant_collection.find(): merchants.append(merchant_helper(merchant)) return merchants # Add a new merchant into to the database async def add_merchant(merchant_data: dict) -> dict: merchant = await merchant_collection.insert_one(merchant_data) new_merchant = await merchant_collection.find_one({"_id": merchant.inserted_id}) return merchant_helper(new_merchant) # Retrieve a merchant with a matching ID async def retrieve_merchant(id:str) -> dict: merchant = await merchant_collection.find_one({"_id": ObjectId(id)}) if merchant: return merchant_helper(merchant) # Update a merchant with a matching ID async def update_merchant(id: str, data: dict): # Return false if an empty request body is sent. if len(data) < 1: return False merchant = await merchant_collection.find_one({"_id": ObjectId(id)}) if merchant: updated_merchant = await merchant_collection.update_one( {"_id": ObjectId(id)}, {"$set": data} ) if updated_merchant: return True return False # Delete a merchant from the database async def delete_merchant(id: str): merchant = await merchant_collection.find_one({"_id": ObjectId(id)}) if merchant: await merchant_collection.delete_one({"_id": ObjectId(id)}) return True
{"/server/models/user.py": ["/server/models/merchant.py"], "/server/app.py": ["/server/routes/merchant.py", "/server/routes/user.py", "/server/database.py"], "/server/routes/user.py": ["/server/database.py", "/server/models/user.py"], "/server/routes/merchant.py": ["/server/database.py", "/server/models/merchant.py", "/server/models/user.py"]}
25,176,505
JamesKai/recording_server
refs/heads/main
/recording_tools/lab_stop_record.py
import rpyc def stop_recording(port): conn = None try: conn = rpyc.connect('localhost', port=port) except ConnectionRefusedError: print('Server is not running ') else: # check if it is previously recording if conn.root.status(): # start recording conn.root.stop_all_services() print('was recording, stop recording now') # kill the server after recording is stopped conn.root.set_flag(True) finally: print('it is not recording') if __name__ == '__main__': stop_recording(port=18845)
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,506
JamesKai/recording_server
refs/heads/main
/telegram_tools/telegram_service.py
from typing import List import rpyc from telegram import Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler pt: int = 18861 class TelegramDispatcher: def _rpyc_getattr(self, name): if name.startswith("_"): # disallow special and private attributes raise AttributeError("cannot accept private/special names") # allow all other attributes return getattr(self, name) def __init__(self, tele_bot_token): self.subscribers: List[str] = [] self.tele_bot_token = tele_bot_token def add_subscribers(self, subs_id: str): self.subscribers.append(subs_id) def pop_subscribers(self, subs_id: str): self.subscribers.remove(subs_id) def get_subscribers(self): return self.subscribers def send_telegram_message(self, send_to_id: str, message: str): bot = Bot(token=self.tele_bot_token) bot.send_message(chat_id=send_to_id, text=message) # sending message to all subscribe user def send_all_subs(self, message: str): # send message to each subscribers provided that they are subscribing for sub_id in self.subscribers: self.send_telegram_message(sub_id, message) def connect_recording_service(port): recording_service = rpyc.connect('localhost', port=port) return recording_service.root def start(update: Update, context: CallbackContext): chat_id = update.message.from_user.id context.bot.send_message( chat_id=chat_id, text='Choose the option in main menu:', reply_markup=main_menu_keyboard(), ) def main_menu(update: Update, _context: CallbackContext): update.callback_query.message.edit_text('Choose the option in main menu:', reply_markup=main_menu_keyboard()) def sub_page(update: Update, context: CallbackContext): recording_service = connect_recording_service(port=pt) sub_id = update.effective_chat.id if sub_id not in recording_service.telegram_dispatch.get_subscribers(): recording_service.telegram_dispatch.add_subscribers(sub_id) message = "You are subscribed" else: message = "You are already subscribed" update.callback_query.message.edit_text(message, reply_markup=sub_page_keyboard()) def unsub_page(update: Update, context: CallbackContext): recording_service = connect_recording_service(port=pt) sub_id = update.effective_chat.id if sub_id in recording_service.telegram_dispatch.get_subscribers(): recording_service.telegram_dispatch.pop_subscribers(sub_id) message = "You are not subscribed" else: message = 'You are already unsubscribed' update.callback_query.message.edit_text(message, reply_markup=unsub_page_keyboard()) def finish_time_page(update: Update, context: CallbackContext): recording_service = connect_recording_service(port=pt) message = recording_service.calculator.estimate_finish_time() update.callback_query.message.edit_text(message, reply_markup=finish_time_page_keyboard()) def main_menu_keyboard(): keyboard = [[InlineKeyboardButton('Subscribe', callback_data='sub_page'), InlineKeyboardButton('Unsubscribe', callback_data='unsub_page')], [InlineKeyboardButton('Predict Finish Time', callback_data='finish_time_page')]] return InlineKeyboardMarkup(keyboard) def sub_page_keyboard(): keyboard = [ [InlineKeyboardButton('Back to Menu', callback_data='main')]] return InlineKeyboardMarkup(keyboard) def unsub_page_keyboard(): keyboard = [ [InlineKeyboardButton('Back to Menu', callback_data='main')]] return InlineKeyboardMarkup(keyboard) def finish_time_page_keyboard(): keyboard = [ [InlineKeyboardButton('Back to Menu', callback_data='main')]] return InlineKeyboardMarkup(keyboard) def start_telegram_service(tele_bot_token, port): global pt pt = port updater = Updater(token=tele_bot_token) # dispatcher will automatically be created once updater is set up dispatcher = updater.dispatcher # create handler handlers = [ CommandHandler('start', start), CallbackQueryHandler(main_menu, pattern='main'), CallbackQueryHandler(sub_page, pattern='sub_page'), CallbackQueryHandler(unsub_page, pattern='unsub_page'), CallbackQueryHandler(finish_time_page, pattern='finish_time_page') ] list(map(dispatcher.add_handler, handlers)) # start the bot updater.start_polling(poll_interval=3)
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,507
JamesKai/recording_server
refs/heads/main
/recording_tools/recording_service/lab_record_service.py
import threading import rpyc import cv2 import asyncio import numpy as np import pyautogui as pag from imaging_tools.calculator import Calculator from telegram_tools import telegram_service from imaging_tools.parsing_text import ParsingText from functools import partial from pathlib import Path from datetime import datetime as dt from telegram_tools.telegram_service import TelegramDispatcher class RecordingService(rpyc.Service): def __init__(self, config_obj, ocr_reader): super(RecordingService, self).__init__() self.config_obj = config_obj self.ocr_reader = ocr_reader # declare saving location self.store_path = '' self.status = False self.record_th = None '''declare shutting service flag, this variable will be read by the server's code, every time an incoming connection is finished, server will check this variable. If found out to be true, then the server will shut down itself''' self.shutdown_service_flag: bool = False # telegram related self.telegram_th = None self.exposed_telegram_dispatch = None # parsing text related self.exposed_parsing = ParsingText(config_obj, ocr_reader) # calculator related self.exposed_calculator = Calculator(self.exposed_parsing) def exposed_status(self): return self.status def exposed_get_flag(self): return self.shutdown_service_flag '''setter for shutting down the service''' def exposed_set_flag(self, do_shut_down: bool): self.shutdown_service_flag = do_shut_down def exposed_start_all_services(self, store_path: str, tele_bot_token: str, port: int, fps: float, delay_time: float): self.start_record(store_path, delay_time, fps) self.start_telegram(tele_bot_token, port) def exposed_stop_all_services(self): self.stop_telegram() self.stop_record() def start_record(self, store_path: str, delay_time: float, fps: float): # update the recording status to true self.status = True # configure video storage path and frame rate self.store_path = store_path # spawn up a recording thread to handle all the recording related stuff self.record_th = threading.Thread( target=partial(self.record_process, store_path, fps, delay_time)) # starting running the recording thread self.record_th.start() def start_telegram(self, tele_bot_token: str, port: int): # spawn up a telegram thread to handle all the telegram stuff self.telegram_th = threading.Thread( target=partial(telegram_service.start_telegram_service, tele_bot_token, port)) '''make it a daemon server, a daemon server will automatically close itself once the main program is finished ''' self.telegram_th.daemon = True # starting running the telegram thread self.telegram_th.start() self.exposed_telegram_dispatch = TelegramDispatcher(tele_bot_token) def stop_record(self): # updating the recoding status to false self.status = False # joining recording thread self.record_th.join() def stop_telegram(self): self.exposed_telegram_dispatch.send_all_subs(message='end recording') # joining telegram thread self.telegram_th.join() def record_process(self, store_path: str, fps: float, delay_time: float): # create video writer video_writer = RecordingService.create_video_writer(store_path, fps) # create parsing object capture_count = 0 async def record_task(): # make a screenshot img = pag.screenshot() # convert these pixels to a proper numpy array to work with OpenCV frame = np.array(img) # convert colors from BGR to RGB frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # write the frame video_writer.write(frame) async def delay_task(): await asyncio.sleep(delay_time) async def tasks(): recording_task = asyncio.create_task(record_task()) delaying_task = asyncio.create_task(delay_task()) await recording_task await delaying_task # keep recording until the status is off while self.status: asyncio.run(tasks()) capture_count += 1 # clean up video writer video_writer.release() @staticmethod def create_video_writer(store_path: str, fps: float): pth = Path(store_path, dt.now().strftime('%Y_%m_%d_%H_%M') + '.avi') pth_in_str = str(pth) # display screen resolution, get it from OS settings screen_size = pag.size() # define the codec fourcc = cv2.VideoWriter_fourcc(*"DIVX") # create the video writer object return cv2.VideoWriter(pth_in_str, fourcc, fps, screen_size)
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,508
JamesKai/recording_server
refs/heads/main
/setup.py
from setuptools import setup setup( name='ScreenRecord', version='0.1.2', packages=['recording_tools', 'recording_tools.closable_server', 'recording_tools.recording_service', 'telegram_tools', 'imaging_tools'], url='', license='', author='James Kai', author_email='kai.hsiang.ju@gmail.com', install_requires=[ "setuptools ~= 52.0.0", "rpyc ~= 5.0.1", "pyautogui ~= 0.9.52", "opencv-python ~= 4.2", "numpy", "python-telegram-bot ~= 13.2", "cnocr"] )
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,509
JamesKai/recording_server
refs/heads/main
/imaging_tools/calculator.py
from datetime import datetime as dt from imaging_tools.parsing_text import ParsingText class Calculator: def _rpyc_getattr(self, name): if name.startswith("_"): # disallow special and private attributes raise AttributeError("cannot accept private/special names") # allow all other attributes return getattr(self, name) def __init__(self, parsing: ParsingText): self.parsing = parsing self.start_label = 0 self.start_time = dt.timestamp(dt.now()) self.total_label = None def estimate_finish_time(self) -> str: if self.total_label is None: self.total_label = self.get_total_label() if self.get_total_label() is None: return 'total label count is not detected' current_label = self.get_current_label() if type(current_label) != (int or float): return 'current label count is not detected' current_time = Calculator.get_current_time() diff_in_label = current_label - self.start_label if diff_in_label < 10: return "More info needed, wait a few seconds and try again" diff_in_time = current_time - self.start_time period = diff_in_time / diff_in_label finish_time = (self.total_label - current_label) * period + current_time finish_time_dt = dt.fromtimestamp(finish_time) display_prefix = Calculator.get_display_prefix(finish_time_dt) return f"{display_prefix} {finish_time_dt.strftime('%H:%M %p')}" @staticmethod def get_current_time(): return dt.timestamp(dt.now()) def get_current_label(self) -> str or None: return self.parsing.get_info_of('current_label') def set_total_label(self, label_count): self.total_label = label_count def get_total_label(self): return self.parsing.get_info_of('total_label') @staticmethod def get_display_prefix(dt_obj: dt) -> str: day = dt_obj.strftime('%d') day_int = int(day) now_day = dt.now().day if day_int == now_day: return 'Today' elif (day_int - now_day) == 1: return 'Tomorrow' else: return dt_obj.strftime('%A')
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,510
JamesKai/recording_server
refs/heads/main
/recording_tools/lab_start_record.py
import rpyc import threading from functools import partial from cnocr import CnOcr, NUMBERS from recording_tools.closable_server.lab_closable_server import RecordingServer from typing import Dict def start_recording(store_path: str, delay_time: float, fps: float, port: int, tele_bot_token: str, config: Dict): conn = None print('running...') # declare connection object ,this is not needed, stating it here as pycharm cannot resolve the issues # of pycharm referencing local variable try: conn = rpyc.connect('localhost', port=port) except ConnectionRefusedError: print('Server is not running, start the server now') # load ocr model into memory, only need to load once, run in another thread ocr_reader = CnOcr(cand_alphabet=NUMBERS) threading.Thread(target=partial(start_server, port, config, ocr_reader)).start() _try_connect = True while _try_connect: try: conn = rpyc.connect('localhost', port=port) except ConnectionRefusedError: continue else: _try_connect = False finally: # check if it is currently recording if conn.root.status(): print('it is already recording') return # start recording conn.root.start_all_services(store_path, tele_bot_token, port, fps, delay_time) print('start recording now') # config_obj is for configuring parsing text, as the obj can only be passed via constructor in RPyC, it is placed here def start_server(port, config_obj, ocr_reader): from recording_tools.recording_service.lab_record_service import RecordingService # create server and run the server, passing RecordingService object will invoke singleton pattern server = RecordingServer(RecordingService(config_obj, ocr_reader), port=port) server.start() if __name__ == '__main__': my_config = { 'current_label': { 'matching_image': r"C:\Users\James\Pictures\Screenshots\current_label.png", 'matching_confidence': 0.8, 'x_offset': 8, 'y_offset': 38, 'new_width': 70, 'new_height': 16 }, 'total_label': { 'matching_image': r"C:\Users\James\Pictures\Screenshots\total_label.png", 'matching_confidence': 0.8, 'x_offset': 9, 'y_offset': 38, 'new_width': 70, 'new_height': 18 }, } start_recording(r"C:\Users\James\Desktop\Video", delay_time=2, fps=0.5, port=18845, tele_bot_token='', config=my_config)
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,511
JamesKai/recording_server
refs/heads/main
/imaging_tools/parsing_text.py
import pyautogui as pag import numpy as np import cv2 from typing import Dict DEFAULT_CONFIDENCE = 0.7 class ParsingText: def _rpyc_getattr(self, name): if name.startswith("_"): # disallow special and private attributes raise AttributeError("cannot accept private/special names") # allow all other attributes return getattr(self, name) def __init__(self, config, ocr_reader): self.ocr_reader = None try: self.ocr_reader = ocr_reader except Exception: print('ocr reader initializing fail') return self.config = config @staticmethod def is_valid(input_number): if not (type(input_number) == float or type(input_number) == int): return False elif input_number > min(pag.size()) or input_number < 0: return False return True @staticmethod def is_valid_confidence(confidence): if confidence is None: return False if 1 > confidence > 0: return True return False def get_info_of(self, item: str) -> str or None: try: _config = self.config[item] except KeyError: print(f'{item}: key is not found') return None # parse the configuration info img, confidence, x_off, y_off, new_width, new_height = _config.values() # read image and get location of image try: left, top, width, height = pag.locateOnScreen(img, confidence=confidence if ParsingText.is_valid_confidence( confidence) else DEFAULT_CONFIDENCE) except TypeError: return None else: # take screen shot for new location info_img_pil = pag.screenshot( region=(left + x_off, top + y_off, new_width if ParsingText.is_valid(new_width) else width, new_height if ParsingText.is_valid(new_height) else height)) # convert PIL image to numpy array info_img = cv2.cvtColor(np.array(info_img_pil), cv2.COLOR_RGB2BGR) # parse the text from the image out_char = self.ocr_reader.ocr_for_single_line(info_img) print(f'{item}: {out_char}') # join the string out_string = "".join(out_char) try: output = int(out_string) except ValueError: output = out_string # return result return output def get_all_info(self) -> Dict or str: # if ocr_reader cannot be set up in parsing object, stop parsing image if not self.ocr_reader: return "no info as ocr reader is not found" # create new dictionary object to store parsing values config_keys = self.config.keys() info_storage = {} # iterate and populate info storage for item in config_keys: info_storage[item] = self.get_info_of(item) return info_storage
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,176,512
JamesKai/recording_server
refs/heads/main
/recording_tools/closable_server/lab_closable_server.py
from contextlib import closing import socket from rpyc.utils.authenticators import AuthenticationError from rpyc.utils.server import ThreadedServer from abc import abstractmethod, ABC class Closable(ABC): @abstractmethod def continue_or_kill_server(self): pass class RecordingServer(ThreadedServer, Closable): def __init__(self, service, port=0, protocol_config=None): super(ThreadedServer, self).__init__(service, port=port, protocol_config=protocol_config) def continue_or_kill_server(self): """implementing logic for closing server here""" try: will_shut_down = self.service.shutdown_service_flag except AttributeError: print('did not define service shutdown flag in your service. Server cannot be closed with this flag') else: if will_shut_down: self.active = False self.close() def _authenticate_and_serve_client(self, sock): try: if self.authenticator: addrinfo = sock.getpeername() try: sock2, credentials = self.authenticator(sock) except AuthenticationError: self.logger.info("%s failed to authenticate, rejecting connection", addrinfo) return else: self.logger.info("%s authenticated successfully", addrinfo) else: credentials = None sock2 = sock try: self._serve_client(sock2, credentials) except Exception: self.logger.exception("client connection terminated abruptly") raise finally: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass closing(sock) self.clients.discard(sock) self.continue_or_kill_server()
{"/recording_tools/lab_start_record.py": ["/recording_tools/closable_server/lab_closable_server.py", "/recording_tools/recording_service/lab_record_service.py"], "/recording_tools/recording_service/lab_record_service.py": ["/imaging_tools/calculator.py", "/imaging_tools/parsing_text.py", "/telegram_tools/telegram_service.py"], "/imaging_tools/calculator.py": ["/imaging_tools/parsing_text.py"]}
25,308,362
pxue/torontopoly
refs/heads/master
/app.py
import settings import time import ujson import uuid from flask import (Flask, flash, make_response, \ render_template, redirect, request,\ session, url_for) from flask.ext.socketio import SocketIO, emit, send, join_room from flask.ext.login import LoginManager, login_user, current_user from lib.exception import * from lib.game import Game from lib.player import Player # application app = Flask(__name__) app.config.from_object(settings.DevelopmentConfig) # socketio #TODO: centrifugal? http://fzambia.gitbooks.io/centrifugal/ socketio = SocketIO(app) # login manager login_manager = LoginManager(app) # globals game = Game() @socketio.on("add_bank", namespace="/game") def on_add_bank(idx): # add card to bank card = current_user.hand.pop(int(idx)) current_user._bank.add(card) # data on current players emit("players", ujson.dumps([{ "name": p.name, "money": p.money, "cards": len(p.hand) } for p in game.players]), json=True, broadcast=True) @socketio.on("user_connected", namespace="/game") def on_user_connected(message): if not current_user.is_anonymous(): send("{0} has connected".format(current_user.name)) join_room(current_user.id) # user's own channel # data on current players emit("players", ujson.dumps([{ "name": p.name, "money": p.money, "cards": len(p.hand) } for p in game.players]), json=True, broadcast=True) if game._started and current_user.in_game: emit("player_hand", ujson.dumps(current_user.hand), json=True, room=current_user.id) @socketio.on("message", namespace="/game") def on_message(message): if message["data"][0] == "/": command = message["data"][1:] if command == "start": game.run() send("{0} has started the game".format(current_user.name), broadcast=True) # show each player their hands for token in socketio.rooms["/game"].keys(): hand = ujson.dumps(game.get_player(token).hand) emit("player_hand", hand, json=True, room=token) # update player box with current data emit("players", ujson.dumps([{ "name": p.name, "money": p.money, "cards": len(p.hand) } for p in game.players]), json=True, broadcast=True) else: send("{0}: {1}".format(current_user.name, message["data"]), broadcast=True) @app.route("/") def index(): if current_user.is_anonymous(): resp = make_response(render_template("login.html")) resp.set_cookie("token", str(uuid.uuid4())) else: resp = make_response(render_template("index.html")) #resp = make_response(render_template("index.html")) return resp @app.route("/session", methods=["POST"]) def session(): #TODO: fblogin name = request.form.get("name", "Player%d" % (len(game.players) + 1)) token = request.cookies.get("token") if not game.get_player(token): try: player = Player(token, name) game.add_player(player) login_user(player, True) # log the guy in except TooManyPlayers: flash("too many players!") return redirect(url_for("index")) @login_manager.user_loader def load_player(token): if game == None: return None return game.get_player(token) if __name__ == "__main__": socketio.run(app)
{"/tp/player.py": ["/tp/bank.py"], "/app.py": ["/settings.py"], "/tp/game.py": ["/tp/exceptions.py", "/tp/deck.py", "/tp/bank.py", "/tp/player.py", "/tp/card.py"], "/tp/deck.py": ["/tp/card.py"]}
25,308,363
pxue/torontopoly
refs/heads/master
/settings.py
import os HOST = "0.0.0.0" PORT = 8080 class Config(object): SECRET_KEY = os.urandom(56) class DevelopmentConfig(Config): DEBUG = True
{"/tp/player.py": ["/tp/bank.py"], "/app.py": ["/settings.py"], "/tp/game.py": ["/tp/exceptions.py", "/tp/deck.py", "/tp/bank.py", "/tp/player.py", "/tp/card.py"], "/tp/deck.py": ["/tp/card.py"]}
25,412,408
OzBlumenfeld/chess.comTrackerApp
refs/heads/master
/db_connection.py
import pymongo def getDbConnection(db, collection): file = open("dbCredentials.txt", "r") credentials = file.read() client = pymongo.MongoClient(credentials) return client[db][collection] # db = client["AppDB"] # collection = db["RegisteredUsers"] def findDocument(collection, json): return collection.find_one(json)
{"/chess_games_played.py": ["/chess_utils.py"], "/app.py": ["/db_connection.py", "/chess_utils.py"], "/chess_stats.py": ["/chess_utils.py"], "/cli.py": ["/chess_games_played.py", "/chess_stats.py"]}
25,412,409
OzBlumenfeld/chess.comTrackerApp
refs/heads/master
/app.py
from flask import Flask import db_connection app = Flask(__name__) # check how to turn on debug mode @app.route("/") def home_page(): json = {'name': 'Oz'} coll = db_connection.getDbConnection('test', 'test') print(db_connection.findDocument(coll, json)) # coll.insert_one({'name': 'Oz'}) return 'fuck you !!!' # online_users = mongo.db.users.find({"online": True}) # return render_template("index.html", # online_users=online_users) # def email_request(): # def main(): # print('hi there!') # if __name__ == "__main__": # # execute only if run as a script # main()
{"/chess_games_played.py": ["/chess_utils.py"], "/app.py": ["/db_connection.py", "/chess_utils.py"], "/chess_stats.py": ["/chess_utils.py"], "/cli.py": ["/chess_games_played.py", "/chess_stats.py"]}
25,435,623
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/models.py
from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class book_manager(models.Manager): def custom(self, work): namee =self.get_queryset().filter(name__contains=work) authorr=self.get_queryset().filter(author__contains=work) Publisherr =self.get_queryset().filter(Publisher__contains=work) e = book.objects.none() f = e.union(namee, authorr, Publisherr) return f class book(models.Model): name = models.CharField(max_length=505, default='نام کتاب') author = models.CharField(max_length=505, default='نویسنده') Publisher = models.CharField(max_length=50005, default='ناشر') description = models.TextField(default='توضیحاتی ندارد') image = models.ImageField(default='image/Pottawatomie County State Lake #2 in Manhattan, KS.png') file = models.FileField(default=False, null=True, blank=True) objects = book_manager() def __str__(self): return self.name @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,624
DRlight-HHR/camera-cctv
refs/heads/main
/rest/models.py
from django.db import models class checker(models.Model): active = models.CharField(null=True, blank=True, default="on", max_length=6) def __str__(self): return 'camera_off_on' class camera(models.Model): image = models.FileField(blank=True, null=True, upload_to='camera_video/') def __str__(self): return 'camera'
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,625
DRlight-HHR/camera-cctv
refs/heads/main
/rest/admin.py
from django.contrib import admin from .models import camera, checker admin.site.register(camera) admin.site.register(checker)
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,626
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/urls.py
from django.urls import path from .views import home, home_d, vid, deletee urlpatterns = [ path('main/home/', home), path('delete/', deletee), path('main/home/vid/', vid), path('main/home/book/<pk>/<name>/', home_d) ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,627
DRlight-HHR/camera-cctv
refs/heads/main
/project_3/urls.py
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from .main_app import sing_up, log_in, log_out, home_, check urlpatterns = [ path('admin/', admin.site.urls), path('', sing_up), path('login/', log_in), path('long_out/', log_out), path('home/', home_), path('check/', check), path('book/', include('test_app.urls')), path('rest/', include('rest.urls')) ] urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,628
DRlight-HHR/camera-cctv
refs/heads/main
/rest/urls.py
from django.urls import path from .views import check_off_on, get, maker, search, post_photo, delete_data, deletedata, movie, movie_get, delete_movie from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('get/', get.as_view()), path('check/', check_off_on.as_view()), path('get-movie/', movie_get.as_view()), path('make/', maker.as_view()), path('post/', post_photo.as_view()), path('movie/<pk>/', movie.as_view()), path('search/', search.as_view()), path('delete2/', deletedata), path('delete_movie/<pk>/', delete_movie.as_view()), path('login/', obtain_auth_token, name='api-tokn-auth'), path('delete/<id>', delete_data.as_view()) ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,629
DRlight-HHR/camera-cctv
refs/heads/main
/rest/migrations/0008_alter_camera_active.py
# Generated by Django 3.2 on 2021-05-10 13:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rest', '0007_alter_camera_active'), ] operations = [ migrations.AlterField( model_name='camera', name='active', field=models.BooleanField(default=True, null=True), ), ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,630
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/migrations/0005_alter_book_image.py
# Generated by Django 3.2 on 2021-04-22 05:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_app', '0004_auto_20210422_1014'), ] operations = [ migrations.AlterField( model_name='book', name='image', field=models.ImageField(default='image/Pottawatomie County State Lake #2 in Manhattan, KS.png', upload_to=''), ), ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,631
DRlight-HHR/camera-cctv
refs/heads/main
/project_3/main_app.py
from django.http import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from django.core.mail import send_mail from random import randrange from django.conf import settings from rest_framework.authtoken.models import Token passlist = [52608088] check_limit = [0] u_s_e_r = ['amir', 'amir', 'amir'] def sendmail(_name, _mail): ran = randrange(1000000, 10000000) subject = 'ساخت حساب:' message = "{0} عزیز رمز شما جهت ساخت حساب در سایت عبارت اند از {1}".format(_name, ran) send_mail(subject=subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[_mail]) return ran def check(request): if request.user.is_authenticated is True: return redirect('book/main/home/') if request.method == 'POST': global passlist get_pass = request.POST.get('__pass__') get_pass = int(get_pass) if get_pass != passlist[0]: if check_limit[0] == 3: return redirect('/') error = {"error": "رمزی که وارد کرده اید اشتباه است دوباره وارد کنید"} check_limit[0] = check_limit[0] + 1 return render(request, 'check.html', error) else: global u_s_e_r user = User.objects.create_user(username=u_s_e_r[0], password=u_s_e_r[1], email=u_s_e_r[2]) user_check = authenticate(request=request, username=u_s_e_r[0], password=u_s_e_r[1]) if user_check is not None: login(request, user_check) return redirect('book/main/home/') return render(request, 'check.html') def sing_up(request): if request.user.is_authenticated is True: return redirect('/book/main/home/') else: if request.method == 'POST': _username_ = request.POST.get('_username_') _fullname_ = request.POST.get('_name_') _email_ = request.POST.get('_email_') _pass1_ = request.POST.get('_pass1_') _pass2_ = request.POST.get('_pass2_') if _username_ == "" or _fullname_ == "" or _email_ == "" or _pass1_ == "" or _pass2_ == "": error = {"error": "فیلد ها نباید خالی باشند"} return render(request, 'Singup.html', error) else: username = User.objects.filter(username=_username_) email = User.objects.filter(email=_email_) if username.exists(): _error = {"username_error": "نام کاربری که انتخاب کرداید موجود است لطفا نام کاربری دیگری وارد کنید"} return render(request, 'Singup.html', _error) elif email.exists(): _error_ = { "email_error": "ایمیلی که وارد کرده اید قبلا انتخاب شده است یا وارد شوید یا از ایمیل دیگری استفاده کنید"} return render(request, 'Singup.html', _error_) else: pa = sendmail(_fullname_, _email_) global passlist, u_s_e_r passlist[0] = pa u_s_e_r[0] = _username_ u_s_e_r[1] = _pass1_ u_s_e_r[2] = _email_ return redirect('/check/') return render(request, 'Singup.html') def log_in(request): if request.user.is_authenticated is True: return redirect('/book/main/home/') if request.method == 'POST': u = request.POST.get('_username_') p = request.POST.get('_pass1_') user_check = authenticate(request, username=u, password=p) '''token = Token.objects.get(user=user_check).key print(token)''' if user_check is not None: login(request, user_check) return redirect('/book/main/home/') else: return HttpResponse('bad request') else: return render(request, 'Login.html') def log_out(request): logout(request) return redirect('/login/') def home_(request): if request.user.is_authenticated is False: return redirect('/login/') else: return render(request, 'book_home.html')
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,632
DRlight-HHR/camera-cctv
refs/heads/main
/rest/migrations/0009_alter_camera_active.py
# Generated by Django 3.2 on 2021-05-10 13:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rest', '0008_alter_camera_active'), ] operations = [ migrations.AlterField( model_name='camera', name='active', field=models.BooleanField(blank=True, default='True', null=True), ), ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,633
DRlight-HHR/camera-cctv
refs/heads/main
/rest/views.py
from test_app.models import book from .models import camera, checker from .serilizations import book_s, camera_s, checker_s from django.http import HttpResponse from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import permissions from django.shortcuts import get_object_or_404 class delete_movie(APIView): def delete(self, request, pk): query = camera.objects.get(pk=pk) query.delete() return Response(status=status.HTTP_200_OK) class check_off_on(APIView): def get(self, request): query = get_object_or_404(checker) seri = checker_s(query, context={'request': request}) return Response(seri.data, status=status.HTTP_200_OK) class post_photo(APIView): def post(self, request): seri = camera_s(data=request.data) if seri.is_valid(): seri.save() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) class movie(APIView): permission_classes = [permissions.IsAdminUser] def put(self, request, pk): query = camera.objects.get(pk=pk) seri = camera_s(query, request.data) if seri.is_valid(): seri.save() return Response(status=status.HTTP_426_UPGRADE_REQUIRED) else: return Response(status=status.HTTP_400_BAD_REQUEST) class movie_get(APIView): def get(self, request): query = camera.objects.all() seri = camera_s(query, context={'request': request}, many=True) return Response(seri.data, status=status.HTTP_200_OK) ################################################################################ class get(APIView): def get(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') # return HttpResponse("Welcome Home<br>You are visiting from: {}".format(ip)) if ip == '127.0.0.1': # Set ip here query = book.objects.all() seri = book_s(query, many=True, context={'request': request}) return Response(seri.data, status=status.HTTP_200_OK) else: return HttpResponse(status=status.HTTP_400_BAD_REQUEST) class maker(APIView): permission_classes = [permissions.IsAdminUser] def post(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') # return HttpResponse("Welcome Home<br>You are visiting from: {}".format(ip)) if ip == '127.0.0.1': # Set ip here seri = book_s(data=request.data) if seri.is_valid(): seri.save() return Response(seri.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) else: return HttpResponse(status=status.HTTP_400_BAD_REQUEST) def check(request, string): try: ser = request.GET[string] return ser except Exception as error: return 0 class search(APIView): def get(self, request): ser = '' stri = '' for i in ['name', 'author', 'Publisher']: b = check(request, i) if b != 0: ser = b print(ser) if i == 'name': query = book.objects.filter(name=ser) elif i == 'author': query = book.objects.filter(author=ser) else: query = book.objects.filter(Publisher=ser) print(query) seri = book_s(query, many=True) return Response(seri.data, status=status.HTTP_200_OK) class delete_data(APIView): def delete(self, request, id): query = book.objects.get(id=id) query.delete() return Response(status=status.HTTP_200_OK) from rest_framework.decorators import api_view @api_view(['GET']) def deletedata(request): a = request.GET['name'] query = book.objects.filter(name=a) query.delete() return Response(status=status.HTTP_200_OK)
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,634
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/migrations/0006_auto_20210423_1653.py
# Generated by Django 3.2 on 2021-04-23 12:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_app', '0005_alter_book_image'), ] operations = [ migrations.AlterField( model_name='book', name='Publisher', field=models.CharField(default='ناشر', max_length=50005), ), migrations.AlterField( model_name='book', name='author', field=models.CharField(default='نویسنده', max_length=505), ), migrations.AlterField( model_name='book', name='name', field=models.CharField(default='نام کتاب', max_length=505), ), ]
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,635
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/admin.py
from django.contrib import admin from .models import book class edit(admin.ModelAdmin): search_fields = ['name', 'author', 'Publisher'] list_display = ['name', 'author', 'Publisher'] admin.site.register(book, edit)
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,636
DRlight-HHR/camera-cctv
refs/heads/main
/rest/serilizations.py
from rest_framework import serializers from test_app.models import book from .models import camera, checker class checker_s(serializers.ModelSerializer): class Meta: model = checker fields = '__all__' class camera_s(serializers.ModelSerializer): class Meta: model = camera fields = '__all__' class book_s(serializers.ModelSerializer): class Meta: model = book fields = '__all__'
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,435,637
DRlight-HHR/camera-cctv
refs/heads/main
/test_app/views.py
from django.shortcuts import render, get_object_or_404 from .models import book from rest.models import camera import os from django.shortcuts import redirect, Http404 from django.http import HttpResponse def deletee(reqeust): try: d = "/home/cameracctv/camera-cctv/upload_M_ROOT/camera_video" for path in os.listdir(d): full_path = os.path.join(d, path) if os.path.isfile(full_path): os.remove(full_path) return HttpResponse('ok i delete') except: return HttpResponse('whats wrong') def vid(request): query = camera.objects.all() data = {'data': query} return render(request, 'video.html', data) def home(request): if request.user.is_authenticated is False: return redirect('/login/') r = request.user rr = r.username if request.method == 'POST': search_ = request.POST.get('search') query = book.objects.custom(search_) '''for i in query: print(i is None)''' data = {'data': query, 'name': rr} return render(request, 'book_home.html', data) query = book.objects.all() data = {'data': query, 'name': rr} return render(request, 'book_home.html', data) def home_d(request, pk, name): if request.user.is_authenticated is False: return redirect('/login/') r = request.user rr = r.username if request.method == 'POST': search = request.POST.get('search') query = book.objects.custom(search) if query is None: return Http404('this page is not found') for i in query: print(i.id) data = {'data': query, 'name': rr} return render(request, 'book_home.html', data) query = get_object_or_404(book, name=name, pk=pk) data = {'data': query, 'name': rr} return render(request, 'home_d.html', data) '''def home_d(request, pk): if request.user.is_authenticated is False: return redirect('/login/') r = request.user rr = r.username if request.method == 'POST': search = request.POST.get('search') query = book.objects.custom(search) if query is None: return Http404('this page is not found') for i in query: print(i.id) data = {'data': query, 'name': rr} return render(request, 'book_home.html', data) query = get_object_or_404(book, pk=pk) data = {'data': query, 'name': rr} return render(request, 'home_d.html', data) '''
{"/rest/admin.py": ["/rest/models.py"], "/rest/urls.py": ["/rest/views.py"], "/test_app/urls.py": ["/test_app/views.py"], "/project_3/urls.py": ["/project_3/main_app.py"], "/rest/views.py": ["/test_app/models.py", "/rest/models.py", "/rest/serilizations.py"], "/test_app/admin.py": ["/test_app/models.py"], "/rest/serilizations.py": ["/test_app/models.py", "/rest/models.py"], "/test_app/views.py": ["/test_app/models.py", "/rest/models.py"]}
25,443,809
PatKuz/BostonHacks2020
refs/heads/master
/thebeginning.py
print("The Beginning")
{"/base_files/webcam_capture_baseline.py": ["/evaluation.py", "/drawRect.py", "/send_sms.py"], "/main.py": ["/evaluation.py", "/drawRect.py", "/send_sms.py"]}
25,465,191
PiaFormas/Fase3_Formas_Formas_Troncoso_010V
refs/heads/master
/categorias/urls.py
from django.urls import path from . views import index,InicioVendedor,Productos,Registrarse,RegistrarseComprador,RegistrarseVendedor,ListarVendedores,ListarProductos,ListarPedidos, ModificarProductos urlpatterns = [ path('',index,name='index'), path('InicioVendedor/',InicioVendedor,name='InicioVendedor'), path('Productos/',Productos,name='Productos'), path('Registrarse/',Registrarse,name='Registrarse'), path('RegistrarseComprador/',RegistrarseComprador,name="RegistrarseComprador"), path('RegistrarseVendedor/',RegistrarseVendedor,name="RegistrarseVendedor"), path('Listar-vendedores/',ListarVendedores,name="ListarVendedores"), path('Listar-productos/',ListarProductos,name="ListarProductos"), path('Listar-pedido/',ListarPedidos,name="ListarPedidos"), path('Modificar-producto/<id>/',ModificarProductos,name="ModificarProducto"), ]
{"/categorias/tests/test_comprador.py": ["/categorias/models.py"], "/categorias/tests/test_vendedor.py": ["/categorias/models.py"], "/categorias/tests/test_views.py": ["/categorias/models.py"], "/categorias/admin.py": ["/categorias/models.py"], "/categorias/forms.py": ["/categorias/models.py"], "/categorias/views.py": ["/categorias/forms.py", "/categorias/models.py"], "/categorias/tests/test_forms.py": ["/categorias/forms.py"], "/categorias/urls.py": ["/categorias/views.py"]}