예제 #1
0
파일: views.py 프로젝트: siserin/henryFACT
def create_bodega_page(request):
    form = CreateBodegaForm()
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : '',
            'action' : reverse('productos.views.create_bodega_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Producto',
           }
    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    #handles post
    form = CreateBodegaForm(request.POST)
    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    #Now the form is valid

    #enter transaction
    data = form.cleaned_data
    bodega = Bodega(nombre=data['nombre'])

    bodega.save()

    meta['st_message'] = 'Bodega <b> %s </b> es creado con exito' % bodega.nombre
    return render_form(meta, RequestContext(request))
예제 #2
0
파일: views.py 프로젝트: qihqi/henryFACT
def create_cat_page(request):
    form = CreateCatForm()
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : '',
            'action' : reverse('productos.views.create_cat_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Producto',
           }
    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    #handles post
    form = CreateCatForm(request.POST)
    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    #Now the form is valid

    #enter transaction
    cat = form.save()

    meta['st_message'] = 'Categoria <b> %s </b> es creado con exito' % cat.nombre
    return render_form(meta, RequestContext(request))
예제 #3
0
파일: views.py 프로젝트: siserin/henryFACT
def create_client_page(request):
    form = CreateClientForm()
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : '',
            'action' : reverse('clientes.views.create_client_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Cliente',
           }
    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    elif request.method == 'POST':
    #process the data, redirect to itself.
        form = CreateClientForm(request.POST)
        if not form.is_valid():
            meta['form'] = form
            return render_form(meta, RequestContext(request))
        #ahora es valid
        nombres = form.cleaned_data['nombres']
        apellidos = form.cleaned_data['apellidos']
        direccion = form.cleaned_data['direccion']
        codigo = form.cleaned_data['no_de_cedula']
        telefono = form.cleaned_data['telefono']

        client = Cliente(nombres=nombres,
                         apellidos=apellidos,
                         direccion=direccion,
                         codigo=codigo,
                         telefono=telefono)
        client.save()
        meta['st_message'] = 'Cliente <b> %s %s </b> es creado con exito' \
                            % (client.apellidos, client.nombres)
        return render_form(meta, RequestContext(request))
예제 #4
0
파일: views.py 프로젝트: siserin/henryFACT
def create_product_page(request):
    form = CreateProductForm()
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : '',
            'action' : reverse('productos.views.create_product_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Producto',
           }
    if request.method == 'GET':
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    #handles post
    form = CreateProductForm(request.POST)
    if not form.is_valid():
        meta['form'] = form
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    #Now the form is valid

    #enter transaction
    #Crear producto
    data = form.cleaned_data
    codigo = form.cleaned_data['codigo']
    nombre = form.cleaned_data['nombre']
    print data
    prod = Producto(nombre=nombre, codigo=codigo)
    try:
        prod.save()
    except IntegrityError:
        prod = Producto.objects.get(codigo=codigo)
        if nombre != '' and prod.nombre != nombre:
            meta['st_message'] = 'El codigo <b> %s </b> ya esta usado \
                                  para el producto <b> %s </b>; <br /> \
                                  Utilice otro codigo o deje el nombre libre.' % (codigo, prod.nombre)
            transaction.rollback()
            return render_form(meta, RequestContext(request))

    print data

    #Crear transaction
    try:
        cont = Contenido(prod=prod,
                         precio=data['precio_menorista'],
                         precio2=data['precio_mayorista'],
                         bodega=Bodega(data['bodega']),
                         cant=data['cantidad'])
        cont.save()
    except IntegrityError:
        meta['st_message'] = 'Este producto ya existe en esta bodega'
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    meta['st_message'] = 'Producto <b> %s </b> es creado con exito' % prod.nombre
    transaction.commit()
    return render_form(meta, RequestContext(request))
예제 #5
0
파일: views.py 프로젝트: qihqi/henryFACT
def testPage(request):
    meta = {'method': 'post',
            'form': None,
            'st_message': '',
            'action': reverse('facturas.views.testPage'),
            'submit_name': 'Eliminar',
            'title': 'Eliminar Factura',
    }
    if request.method == 'GET':
        meta['form'] = EliminarForm()
        return render_form(meta, RequestContext(request))

    form = EliminarForm(request.POST)
    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    try:
        user = request.user
        codigo = form.cleaned_data['no_de_factura']
        motivo = form.cleaned_data['motivo']
        bodega_id = form.cleaned_data['bodega']

        #hacer un record
        desp = OrdenDeDespacho.objects.get(codigo=codigo, bodega_id=bodega_id)
        if desp.eliminado:
            raise OrdenDeDespacho.DoesNotExist()

        bodega = desp.bodega
        record = OrdenEliminado(codigo=desp,
                                motivo=motivo,
                                eliminado_por=user)

        #devolver marcaderia
        items = ItemDeDespacho.objects.filter(desp_cod=desp)
        for item in items:
            cont = Contenido.objects.get(prod=item.producto, bodega=bodega)
            cont.cant += item.cantidad
            cont.save()
            #insertar record
        record.save()
        #mark the factura
        desp.eliminado = True
        desp.save()

        meta['form'] = EliminarForm()
        meta['st_message'] = 'Factura <b> %s </b> eliminado con exito' % codigo
    except OrdenDeDespacho.DoesNotExist:
        meta['form'] = EliminarForm()
        meta['st_message'] = 'Factura <b> %s </b> no existe' % codigo

    return render_form(meta, RequestContext(request))
예제 #6
0
def ver_reglas_page(request):
    form = VerProdForm(request.GET)
    if not form.is_valid():
        meta = {'method' : 'get',
                'form' : form,
                'st_message' : '',
                'action' : reverse('productos.reempaque.ver_reglas_page'),
                'submit_name' : 'Ver',
                'title' : 'Ver Reglas',
               }
        return render_form(meta, None)


    bodega = int(form.cleaned_data['bodega'])
    categoria = int(form.cleaned_data['categoria'])
    nombre = form.cleaned_data['nombre']

    result = Transform.objects.all()
    if categoria != -1:
        result = result.filter(origin__categoria=Categoria(categoria))
    if nombre:
        result = result.filter(origin__nombre__istartswith=nombre)

    url = reverse('productos.reempaque.ver_reglas_page') + '?'
    for key, val in request.GET.iteritems():
        url += key + '=' + val + '%26'
    return render_to_response('ver_reglas.html', {'ordenes' : result,
                                                  'next' : url})
예제 #7
0
파일: views.py 프로젝트: qihqi/henryFACT
def ver_resumen_total(request):
    form = ResumenForm(request.GET)
    print 'total resumen'
    if not form.is_valid():
        form = ResumenForm(initial={'desde': date.today(), 'hasta': date.today()})
        meta = {'method': 'get',
                'form': form,
                'st_message': 'Datos invalidos',
                'action': reverse('facturas.views.get_resumen_total'),
                'submit_name': 'Buscar',
                'title': 'Resumen de Venta',
        }
        return render_form(meta, RequestContext(request))

    desde = form.cleaned_data['desde']
    hasta = form.cleaned_data['hasta']
    bodega = form.cleaned_data['bodega']
    #get all the users
    users = UserJava.objects.all()
    totales = []
    for user in users:
        totales.append(get_totales(user, desde, hasta, bodega))

    print 'i am here'
    return render_to_response('totales.html', {'totales': totales})
예제 #8
0
파일: views.py 프로젝트: qihqi/henryFACT
def reenviar_trans(request):
    meta = {'method' : 'post',
            'form' : PosteoForm(),
            'st_message' : '',
            'action' : reverse('productos.views.reenviar_trans'),
            'submit_name' : 'Reenviar',
            'title' : 'Reenviar Form',
           }

    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    form = PosteoForm(request.POST)
    if not form.is_valid():
        meta['st_message'] = 'El documento con codigo <b>%s</b> no existe' % request.POST['codigo']
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    try:
        codigo = form.cleaned_data['codigo']
        ing = Ingreso.objects.get(id=codigo)

        if ing.tipo != Ingreso.TIPO_EXTERNA:
            raise Ingreso.DoesNotExist()

        items = [(str(c.cantidad), c.producto_id) for c in ing.ingresoitem_set.all()]
        origen = 'CENTRO: ' + ing.bodega.nombre
        header_enviar = dict(origen=origen,
                             entrada=True,
                             numero_externa=ing.id,
                             posteado=False)
        datos = serialize(header_enviar, items)
        url = BodegaExterna.objects.get(id=1).url
        num = enviar(url, datos)
        if num != -1:
            detalle = ing.ingresodetalle
            detalle.numero_externa = num
            detalle.save()
            meta['st_message'] = 'Recibio conforme'
        else:
            meta['st_message'] = 'No recibio de nuevo'
    except Ingreso.DoesNotExist:
        meta['st_message'] = 'El documento con codigo <b>%s</b> no existe' % request.POST['codigo']

    return render_form(meta, RequestContext(request))
예제 #9
0
def ver_reglas_form(request):
    meta = {'method' : 'get',
            'form' : VerProdForm(),
            'st_message' : '',
            'action' : reverse('productos.reempaque.ver_reglas_page'),
            'submit_name' : 'Ver',
            'title' : 'Ver Reglas',
           }
    return render_form(meta, None)
예제 #10
0
파일: views.py 프로젝트: qihqi/henryFACT
def postear_transferencia_form(request, msg=''):
    meta = {'method' : 'get',
            'form' : PosteoForm(),
            'st_message' : msg,
            'action' : reverse('productos.views.postear_transferencia'),
            'submit_name' : 'Ver',
            'title' : 'Postear Form',
           }
    return render_form(meta, None)
예제 #11
0
파일: views.py 프로젝트: qihqi/henryFACT
def ventas_por_productos(request):
    meta = {'method': 'get',
            'form': VerVentaPorProducto(),
            'st_message': '',
            'action': reverse('facturas.views.ventas_por_productos_detalle'),
            'submit_name': 'Ver',
            'title': 'Ver Ventas por Productos',
    }
    return render_form(meta, None)
예제 #12
0
파일: views.py 프로젝트: qihqi/henryFACT
def ver_doc_page(request, msg=''):
    form = VerDocForm()
    meta = {'method': 'get',
            'form': form,
            'st_message': msg,
            'action': reverse('facturas.views.show_doc_page'),
            'submit_name': 'Ver',
            'title': 'Ver Documentos',
    }
    return render_form(meta, None)
예제 #13
0
파일: views.py 프로젝트: qihqi/henryFACT
def get_totales_form(request):
    form = ResumenForm(initial={'desde': date.today(), 'hasta': date.today()})
    meta = {'method': 'get',
            'form': form,
            'st_message': '',
            'action': reverse('facturas.views.ver_resumen_total'),
            'submit_name': 'Buscar',
            'title': 'Resumen de Venta',
    }
    return render_form(meta, RequestContext(request))
예제 #14
0
파일: views.py 프로젝트: qihqi/henryFACT
def ver_producto_page(request):
    meta = {'method' : 'get',
            'form' : VerProdForm(),
            'st_message' : '',
            'action' : reverse('productos.views.ver_page'),
            'submit_name' : 'Aceptar',
            'title' : 'Crear Producto',
           }

    return render_form(meta, RequestContext(request));
예제 #15
0
파일: views.py 프로젝트: qihqi/henryFACT
def ventas_por_productos_detalle(request):
    meta = {'method': 'get',
            'form': VerVentaPorProducto(),
            'st_message': '',
            'action': reverse('facturas.views.ventas_por_productos_detalle'),
            'submit_name': 'Ver',
            'title': 'Ver Ventas por Productos',
    }
    form = VerVentaPorProducto(request.GET)
    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, None)


    desde = form.cleaned_data['desde']
    hasta = form.cleaned_data['hasta']
    codigo = form.cleaned_data['codigo']
    bodega_id = int(form.cleaned_data['bodega'])

    if not len(Producto.objects.filter(codigo=codigo)):
        meta['st_message'] = 'Producto %s no existe' % codigo
        return render_form(meta, None)

    all_venta_row = ItemDeDespacho.objects.filter(
            producto_id=codigo,
            desp_cod__fecha__gte=desde,
            desp_cod__fecha__lte=hasta,
            desp_cod__bodega_id=bodega_id)

    total = sum((i.cantidad for i in all_venta_row))

    return render_to_response('ventas_por_productos_detalle.html', {
        'total': total,
        'items': all_venta_row,
        'form': form,
        'prod': Producto.objects.get(codigo=codigo),
        'request': {
            'desde': desde,
            'hasta': hasta,
            'bodega': bodega_id
            }
        })
예제 #16
0
파일: views.py 프로젝트: qihqi/henryFACT
def search_client_page(request):
    form = SearchClientForm()
    meta = {'method' : 'get',
            'form' : form,
            'st_message' : '',
            'action' : reverse('clientes.views.display_client_page'),
            'submit_name' : 'Buscar',
            'title' : 'Buscar Cliente',
           }

    return render_form(meta, None)
예제 #17
0
파일: views.py 프로젝트: qihqi/henryFACT
def resumen_request_page(request):
    #make an empty form
    form = ResumenForm(initial={'desde': date.today(), 'hasta': date.today()})
    meta = {'method': 'get',
            'form': form,
            'st_message': '',
            'action': reverse('facturas.views.generar_resumen_page'),
            'submit_name': 'Buscar',
            'title': 'Resumen de Venta',
    }

    return render_form(meta, RequestContext(request))
예제 #18
0
파일: views.py 프로젝트: qihqi/henryFACT
def create_client_page(request):

    #hack - add js to validate id numbers
    st_message = '''
    <script type="text/javascript" src="/static/jquery-1.7.2.js" ></script>
    <script>
        $(document).ready(function () {
            $('form').submit(function(event) {
                var id = $('#id_codigo').val();
                if (isNaN(id) || id.length != 10 || id.length!=13) {
                    alert("numero de cedula debe ser 10 digitos de numero, RUC debe ser 13 digitos de numero, si espacio o '-'");
                    event.preventDefault();
                }
            });
        });
    </script>
    '''

    form = CreateClientForm()
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : st_message,
            'action' : reverse('clientes.views.create_client_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Cliente',
           }
    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    elif request.method == 'POST':
    #process the data, redirect to itself.
        form = CreateClientForm(request.POST)
        if not form.is_valid():
            meta['form'] = form
            return render_form(meta, RequestContext(request))
        #ahora es valid
        client = form.save()
        meta['st_message'] = 'Cliente <b> %s %s </b> es creado con exito' \
                            % (client.apellidos, client.nombres)
        return render_form(meta, RequestContext(request))
예제 #19
0
파일: views.py 프로젝트: qihqi/henryFACT
def modificar_precio_page(request):
    script = """<script type="text/javascript" src="/static/jquery-1.7.2.js" ></script>
        <script type="text/javascript" src="/static/get_cont.js" >
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                setup();
            });
        </script>"""
    meta = {'method' : 'post',
            'form' : ModificarPrecioForm(),
            'st_message' : script,
            'action' : reverse('productos.views.modificar_precio_page'),
            'submit_name' : 'Guardar',
            'title' : 'Modificar Precio',
           }
    if request.method == 'GET':
        return render_form(meta, RequestContext(request))

    form = ModificarPrecioForm(request.POST)

    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    nombre = form.cleaned_data['nombre']
    bodega = int(form.cleaned_data['bodega'])
    codigo = form.cleaned_data['codigo']
    cont = Contenido.objects.get(bodega_id=bodega,
                                 prod_id=codigo)
    cont.precio = form.cleaned_data['precio']
    cont.precio2 = form.cleaned_data['precio2']
    cont.cant_mayorista = form.cleaned_data['cantidad_mayorista']
    cont.prod.nombre = nombre
    cont.prod.save()
    cont.save()
    meta['st_message'] += '<p> Precio modificado con exito </p>'
    return render_form(meta, RequestContext(request))
예제 #20
0
파일: views.py 프로젝트: qihqi/henryFACT
def editar_cliente_page(request, codigo):
    meta = {'method' : 'post',
            'form' : None,
            'st_message' : '',
            'action' : reverse('clientes.views.editar_cliente_page', kwargs={'codigo' : codigo}),
            'submit_name' : 'Guardar',
            'title' : 'Editar Cliente',
           }
    if request.method == 'GET':
        c = Cliente.objects.get(codigo=codigo)
        form = CreateClientForm(instance=c, initial={'codigo_embedded' : codigo})
        meta['form'] = form
        return render_form(meta, RequestContext(request))

    cod_true = request.POST.get('codigo_embedded', None)

    cod = request.POST['codigo']

    if cod_true == None:
        meta['st_message'] = 'cliente no fue modificado'
        return render_form(meta, RequestContext(request))
    if cod_true != cod:
        meta['st_message'] = 'No se puede cambiar la numero de cedula, \
                              \n Crea otro cliente!'
        return render_form(meta, RequestContext(request))

    c = Cliente.objects.get(codigo=cod_true)
    form = CreateClientForm(request.POST, instance=c)
    if not form.is_valid():
        meta['form'] = form
        return render_form(meta, RequestContext(request))
    form.save()

    meta['st_message'] = 'cliente modificado'
    meta['form'] = form
    return render_form(meta, RequestContext(request))
예제 #21
0
파일: views.py 프로젝트: siserin/henryFACT
def generar_resumen_page(request):
    #necesita privilegio para ver resumen
    print request.user
    if getUserJava(request.user.username).nivel < 2:
        return HttpResponseRedirect('/')

    form = ResumenForm(request.GET)

    if not form.is_valid():
        form = ResumenForm(initial={'desde' : date.today(), 'hasta' : date.today()})
        meta = {'method' : 'get',
                'form' : form,
                'st_message' : 'Datos invalidos',
                'action' : reverse('facturas.views.generar_resumen'),
                'submit_name' : 'Buscar',
                'title' : 'Resumen de Venta',
               }
        return render_form(meta, RequestContext(request))

    desde = form.cleaned_data['desde']
    hasta = form.cleaned_data['hasta']
    vendido = form.cleaned_data['vendido_por']
    bodega_id = int(form.cleaned_data['bodega'])
    bodega_name = Bodega.objects.get(id=bodega_id)
    resumen = OrdenDeDespacho.objects.filter(fecha__range=(desde, hasta),
                                             vendedor=UserJava(username=vendido),
                                             bodega=Bodega(bodega_id))

    cheques = list(resumen.filter(pago=OrdenDeDespacho.PAGO_CHEQUE))
    efectivos = list(resumen.filter(pago=OrdenDeDespacho.PAGO_EFECTIVO))
    targetas = list(resumen.filter(pago=OrdenDeDespacho.PAGO_TARGETA))

    cheque_total = sum([c.total for c in cheques])
    efectivo_total = sum([c.total for c in efectivos])
    targeta_total = sum([c.total for c in targetas])

    return render_to_response('resumen.html',
                             {'cheques' : cheques,
                              'bodega' : bodega_name,
                              'efectivos' : efectivos,
                              'targetas' : targetas,
                              'ctotal' : cheque_total,
                              'etotal' : efectivo_total,
                              'ttotal' : targeta_total,
                          })
예제 #22
0
파일: views.py 프로젝트: qihqi/henryFACT
def ver_page(request):
    form = VerProdForm(request.GET)
    if not form.is_valid():
        meta = {'method' : 'get',
                'form' : form,
                'st_message' : '',
                'action' : reverse('productos.views.ver_page'),
                'submit_name' : 'Aceptar',
                'title' : 'Crear Producto',
               }
        return render_form(meta, RequestContext(request))
    bodega = int(form.cleaned_data['bodega'])
    categoria = int(form.cleaned_data['categoria'])
    nombre = form.cleaned_data['nombre']

    result = Contenido.objects.all()
    if bodega != -1:
        result = result.filter(bodega=Bodega(bodega))
    if categoria != -1:
        result = result.filter(prod__categoria=Categoria(categoria))
    if nombre:
        result = result.filter(prod__nombre__istartswith=nombre)

    return render_to_response('inventario.html', {'ordenes' : result})
예제 #23
0
파일: views.py 프로젝트: qihqi/henryFACT
def generar_resumen_page(request):
    #necesita privilegio para ver resumen
    form = ResumenForm(request.GET)

    if not form.is_valid():
        form = ResumenForm(initial={'desde': date.today(), 'hasta': date.today()})
        meta = {'method': 'get',
                'form': form,
                'st_message': 'Datos invalidos',
                'action': reverse('facturas.views.generar_resumen_page'),
                'submit_name': 'Buscar',
                'title': 'Resumen de Venta',
        }
        return render_form(meta, RequestContext(request))

    desde = form.cleaned_data['desde']
    hasta = form.cleaned_data['hasta']
    vendido = form.cleaned_data['vendido_por']
    bodega_id = int(form.cleaned_data['bodega'])
    bodega_name = Bodega.objects.get(id=bodega_id)
    resumen = OrdenDeDespacho.objects.filter(fecha__range=(desde, hasta),
                                             vendedor=UserJava(username=vendido),
                                             bodega=Bodega(bodega_id))
    #if nivel no alcanza, no deja:
    bod = Bodega.objects.get(id=bodega_id)
    if not hasNivel(bod.nivel + 1)(request.user):
        form = ResumenForm(initial={'desde': date.today(), 'hasta': date.today()})
        meta = {'method': 'get',
                'form': form,
                'st_message': 'Escoja otra bodega',
                'action': reverse('facturas.views.generar_resumen_page'),
                'submit_name': 'Buscar',
                'title': 'Resumen de Venta',
        }
        return render_form(meta, RequestContext(request))

    condensado = form.cleaned_data['condensado']
    if bodega_id == 1:
        return resumen_menorista(desde, hasta, vendido, condensado)

    validos = resumen.filter(eliminado=False)
    borrados = list(resumen.filter(eliminado=True))
    cheques = list(validos.filter(pago=OrdenDeDespacho.PAGO_CHEQUE))
    efectivos = list(validos.filter(pago=OrdenDeDespacho.PAGO_EFECTIVO))
    depositos = list(validos.filter(pago=OrdenDeDespacho.PAGO_DEPOSITO))
    creditos = list(validos.filter(pago=OrdenDeDespacho.PAGO_CREDITO))
    varios = list(validos.filter(pago=OrdenDeDespacho.PAGO_VARIOS))

    cheque_total = sum([c.total for c in cheques])
    efectivo_total = sum([c.total for c in efectivos])
    deposito_total = sum([c.total for c in depositos])
    btotal = sum([c.total for c in borrados])
    rtotal = sum([c.total for c in creditos])
    vtotal = sum([c.total for c in varios])

    gran_total = cheque_total + efectivo_total + deposito_total + rtotal + vtotal
    total_neto = "%.2f" % (gran_total / Decimal(1.12))
    return render_to_response('resumen.html',
                              {'cheques': cheques,
                               'bodega': bodega_name,
                               'desde': desde.isoformat(),
                               'hasta': hasta.isoformat(),
                               'vendedor': vendido,
                               'efectivos': efectivos,
                               'depositos': depositos,
                               'creditos': creditos,
                               'varios': varios,
                               'ctotal': cheque_total,
                               'etotal': efectivo_total,
                               'ttotal': deposito_total,
                               'borrados': borrados,
                               'btotal': btotal,
                               'rtotal': rtotal,
                               'vtotal': vtotal,
                               'gran_total': gran_total,
                               'total_neto': total_neto
                              })
예제 #24
0
파일: views.py 프로젝트: qihqi/henryFACT
def create_product_page(request):
    form = CreateProductForm()
    num_bod = settings.NUM_BODEGAS
    meta = {'method' : 'post',
            'form' : form,
            'st_message' : '',
            'action' : reverse('productos.views.create_product_page'),
            'submit_name' : 'Crear',
            'title' : 'Crear Producto',
            'num_bodega' : num_bod,
           }
    if request.method == 'GET':
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    #handles post
    form = CreateProductForm(request.POST)
    if not form.is_valid():
        meta['form'] = form
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    #Now the form is valid

    #enter transaction
    #Crear producto
    data = form.cleaned_data
    codigo = form.cleaned_data['codigo']
    nombre = form.cleaned_data['nombre']
    cat = int(form.cleaned_data['categoria'])
    prod = Producto(nombre=nombre, codigo=codigo, categoria=Categoria(cat))
    try:
        prod.save(force_insert=True)
    except IntegrityError:
        prod = Producto.objects.get(codigo=codigo)
        if nombre != '' and prod.nombre != nombre:
            meta['st_message'] = 'El codigo <b> %s </b> ya esta usado \
                                  para el producto <b> %s </b>; <br /> \
                                  Utilice otro codigo ' % (codigo, prod.nombre)
            transaction.rollback()
            return render_form(meta, RequestContext(request))


    #Crear transaction
    try:
        cont = Contenido(prod=prod,
                         precio=data['precio_menorista'],
                         precio2=data['precio_menorista_2'],
                         bodega_id=1,
                         cant=0)
        cont.save()
        cont = Contenido(prod=prod,
                         precio=data['precio_mayorista'],
                         precio2=data['precio_mayorista_2'],
                         bodega_id=2,
                         cant=0)
        cont.save()
    except IntegrityError:
        meta['st_message'] = 'Este producto ya existe en esta bodega'
        transaction.rollback()
        return render_form(meta, RequestContext(request))

    meta['st_message'] = 'Producto <b> %s </b> es creado con exito' % prod.nombre
    transaction.commit()
    return render_form(meta, RequestContext(request))