How can I prevent an existing product in a remission/sale from altering the stock again when editing the sale? [closed]

  django, python, stock

Good morning world, what I try to do is edit my referral/sale, in case you want to add some other items, the problem is that when you save the changes it alters the stock of the products that were already registered again. All this I’m working with Python and Django, my database is in SQLite3. I’ll leave you my code blocks, in case something else is required let me know.

"Create" in views.py

class RemisionCreateView(CreateView):
model = Remision
form_class = RemisionForm
template_name = 'remision/create.html'
success_url = reverse_lazy('erp:remision_list')
url_redirect = success_url

@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
    return super().dispatch(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    data = {}
    cur = db.cursor()
    try:
        action = request.POST['action']
        if action == 'search_products':
            data = []
            ids_exclude = json.loads(request.POST['ids'])
            prods = Producto.objects.filter(nombre__icontains=request.POST['term'])
            for i in prods[0:10]:
                cur.execute(
                    'SELECT dt.id , l.codigo FROM erp_detlote dt, erp_lote l WHERE dt.lote_id = l.id AND dt.producto_id=' + str(
                        i.id) + ';')
                r = cur.fetchall()
                cont = 0
                lotes = []
                for c in r:
                    lotes.append(str(c[0]) + " , " + c[1])
                    cont += 1
                item = i.toJSON()
                item['value'] = i.nombre
                item['lotes'] = lotes
                data.append(item)
        elif action == 'add':
            with transaction.atomic():
                rem = json.loads(request.POST['rem'])
                remision = Remision()
                remision.fecha = date.today()
                remision.cli_id = rem['cli']
                remision.prov_id = rem['prov']
                remision.ent_id = rem['ent']
                remision.codigo = rem['codrem']
                remision.sello = rem['sellorem']
                remision.categoria = rem['categoria']
                remision.pzsTot = int(rem['pzsTot'])
                if int(rem['cjsTot']) is None or rem['cjsTot'] == 'Null' or int(rem['cjsTot']) == 0:
                    remision.cjsTot = 'NA'
                else:
                    remision.cjsTot = int(rem['cjsTot'])
                if int(rem['tarTot']) is None or rem['tarTot'] == 'Null' or int(rem['tarTot']) == 0:
                    remision.tarTot = 'NA'
                else:
                    remision.tarTot = int(rem['tarTot'])
                remision.save()
                for i in rem['productos']:
                    det = DetRem()
                    det.rem_id = remision.id
                    det.prod_id = i['id']
                    det.lote_id = int(i['lote'])
                    det.subNumPzs = int(i['subPiezas'])
                    if int(i['subCajas']) is None or i['subCajas'] == 'Null' or int(i['subCajas']) == 0:
                        det.subNumCaj = 'NA'
                    else:
                        det.subNumCaj = int(i['subCajas'])
                    if int(i['subTarimas']) is None or i['subTarimas'] == 'Null' or int(i['subTarimas']) == 0:
                        det.subNumTar = 'NA'
                    else:
                        det.subNumTar = int(i['subTarimas'])
                    tar = det.subNumTar
                    cjs = det.subNumCaj
                    pzs = det.subNumPzs
                    if remision.cjsTot == 'NA' and remision.tarTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    elif remision.cjsTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET tarStock = tarStock - ' + str(
                                tar) + ',pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    elif remision.tarTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET cjsStock = cjsStock - ' + str(cjs) +
                            ', pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    else:
                        cur.execute(
                            'UPDATE erp_detlote SET tarStock = tarStock - ' + str(
                                tar) + ', cjsStock = cjsStock - ' + str(cjs) +
                            ', pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    cur.execute('SELECT l.id '
                                ' FROM erp_detlote dt, erp_lote l '
                                ' WHERE dt.lote_id  = l.id AND dt.id = '+ str(det.lote_id) +';')
                    r = cur.fetchall()
                    for c in r:
                        if remision.cjsTot == 'NA' and remision.tarTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET  pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                        elif remision.cjsTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET tarTot = tarTot - ' + str(
                                    tar) + ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                        elif remision.tarTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET cjsTot = cjsTot - ' + str(cjs) +
                                ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                        else:
                            cur.execute(
                                'UPDATE erp_lote SET tarTot = tarTot - ' + str(
                                    tar) + ', cjsTot = cjsTot - ' + str(cjs) +
                                ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                    det.save()
                data = {'id': remision.id}
        else:
            data['error'] = 'No ha ingresado ninguna opción'
    except Exception as e:
        data['error'] = str(e)
    return JsonResponse(data, safe=False)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['title'] = 'Registro de Nueva Remisión'
    context['entity'] = 'Remisión'
    context['list_url'] = self.success_url
    context['action'] = 'add'
    # context['formt'] = TestForm()
    return context

"Edit" in views.py

class RemisionUpdateView(UpdateView):
model = Remision
form_class = RemisionForm
template_name = 'remision/create.html'
success_url = reverse_lazy('erp:remision_list')
url_redirect = success_url

@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
    return super().dispatch(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    data = {}
    cur = db.cursor()
    try:
        action = request.POST['action']
        if action == 'search_products':
            data = []
            ids_exclude = json.loads(request.POST['ids'])
            prods = Producto.objects.filter(nombre__icontains=request.POST['term'])
            for i in prods[0:10]:
                cur.execute(
                    'SELECT dt.id , l.codigo FROM erp_detlote dt, erp_lote l WHERE dt.lote_id = l.id AND dt.producto_id=' + str(
                        i.id) + ';')
                r = cur.fetchall()
                cont = 0
                lotes = []
                for c in r:
                    lotes.append(str(c[0]) + " , " + c[1])
                    cont += 1
                item = i.toJSON()
                item['value'] = i.nombre
                item['lotes'] = lotes
                data.append(item)
        elif action == 'edit':
            with transaction.atomic():
                rem = json.loads(request.POST['rem'])
                remision = self.get_object()
                remision.fecha = date.today()
                remision.cli_id = rem['cli']
                remision.prov_id = rem['prov']
                remision.ent_id = rem['ent']
                remision.codigo = rem['codrem']
                remision.sello = rem['sellorem']
                remision.categoria = rem['categoria']
                if int(rem['cjsTot']) is None or rem['cjsTot'] == 'Null' or int(rem['cjsTot']) == 0:
                    remision.cjsTot = 'NA'
                else:
                    remision.cjsTot = int(rem['cjsTot'])
                if int(rem['tarTot']) is None or rem['tarTot'] == 'Null' or int(rem['tarTot']) == 0:
                    remision.tarTot = 'NA'
                else:
                    remision.tarTot = int(rem['tarTot'])
                remision.pzsTot = int(rem['pzsTot'])
                remision.save()
                remision.detrem_set.all().delete()
                for i in rem['productos']:
                    det = DetRem()
                    det.rem_id = remision.id
                    det.prod_id = i['id']
                    det.lote_id = int(i['lote'])
                    if int(i['subCajas']) is None or i['subCajas'] == 'Null' or int(i['subCajas']) == 0:
                        det.subNumCaj = 'NA'
                    else:
                        det.subNumCaj = int(i['subCajas'])
                    if int(i['subTarimas']) is None or i['subTarimas'] == 'Null' or int(i['subTarimas']) == 0:
                        det.subNumTar = 'NA'
                    else:
                        det.subNumTar = int(i['subTarimas'])
                    det.subNumPzs = int(i['subPiezas'])
                    cur.execute('SELECT id_prod FROM erp_detrem')
                    r = cur.fetchall()
                    for res in r:
                        print(res[0])
                    tar = det.subNumTar
                    cjs = det.subNumCaj
                    pzs = det.subNumPzs
                    if remision.cjsTot == 'NA' and remision.tarTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(
                                det.lote_id) + ';')
                    elif remision.cjsTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET tarStock = tarStock - ' + str(
                                tar) + ',pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(
                                det.lote_id) + ';')
                    elif remision.tarTot == 'NA':
                        cur.execute(
                            'UPDATE erp_detlote SET cjsStock = cjsStock - ' + str(cjs) +
                            ', pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    else:
                        cur.execute(
                            'UPDATE erp_detlote SET tarStock = tarStock - ' + str(
                                tar) + ', cjsStock = cjsStock - ' + str(cjs) +
                            ', pzsStock = pzsStock - ' + str(pzs) + ' WHERE id = ' + str(det.lote_id) + ';')
                    cur.execute('SELECT l.id '
                                ' FROM erp_detlote dt, erp_lote l '
                                ' WHERE dt.lote_id  = l.id AND dt.id = ' + str(det.lote_id) + ';')
                    r = cur.fetchall()
                    for c in r:
                        if remision.cjsTot == 'NA' and remision.tarTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET  pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(
                                    c[0]) + ';')
                        elif remision.cjsTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET tarTot = tarTot - ' + str(
                                    tar) + ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                        elif remision.tarTot == 'NA':
                            cur.execute(
                                'UPDATE erp_lote SET cjsTot = cjsTot - ' + str(cjs) +
                                ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                        else:
                            cur.execute(
                                'UPDATE erp_lote SET tarTot = tarTot - ' + str(
                                    tar) + ', cjsTot = cjsTot - ' + str(cjs) +
                                ', pzsTot = pzsTot - ' + str(pzs) + ' WHERE id = ' + str(c[0]) + ';')
                    det.save()
                data = {'id': remision.id}
        else:
            data['error'] = 'No ha ingresado ninguna opción'
    except Exception as e:
        data['error'] = str(e)
    return JsonResponse(data, safe=False)

def get_detalle_productos(self):
    data = []
    lotes = []
    cur = db.cursor()
    try:
        for i in DetRem.objects.filter(rem=self.get_object().id):
            item = i.prod.toJSON()
            if i.subNumTar == "NA":
                item['subTarimas'] = ''
            else:
                item['subTarimas'] = i.subNumTar
            if i.subNumCaj == "NA":
                item['subCajas'] = ''
            else:
                item['subCajas'] = i.subNumCaj
            item['subPiezas'] = i.subNumPzs
            cur.execute('SELECT dt.id , l.codigo FROM erp_detlote dt, erp_lote l WHERE dt.lote_id = l.id AND dt.producto_id =' + str(i.prod_id) + ';')
            c = cur.fetchall()
            for r in c:
                lotes.append(str(r[0]) + " , " + r[1])
            item['lotes'] = lotes
            data.append(item)
    except:
        pass
    return data

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['title'] = 'Edición de Remisión'
    context['entity'] = 'Remisión'
    context['list_url'] = self.success_url
    context['action'] = 'edit'
    context['det'] = json.dumps(self.get_detalle_productos())
    return context

Source: Python Questions

LEAVE A COMMENT