Example #1
0
// Modifica si hay, Crea si no hay
// Requiere IdEmp. IdSuc es opcional, si no hay lo crea, si hay modifica
func SucMod(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Errorf("R-EMP: %v", r.FormValue("IdEmp"))
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		fd, valid := sucForm(w, r, true)
		empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		sucursal := sucFill(r)
		if valid {
			if empresa != nil {
				newsuc, err := empresa.PutSuc(c, u, &sucursal, r.FormValue("IdEmp"))
				//fmt.Fprintf(w, "IdSuc: %s", newsuc.IdSuc);
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				fd = sucToForm(*newsuc)
				fd.Ackn = "Ok"
			}
		}
		fd.Entidades = model.ListEnt(c, strings.TrimSpace(r.FormValue("DirEnt")))
		tc["Empresa"] = empresa
		tc["FormDataSuc"] = fd
		sucadmTpl.ExecuteTemplate(w, "sucursal", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #2
0
func NewEmp(w http.ResponseWriter, r *http.Request) {
	// formato con validación
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		_, valid := formatoEmp(w, r, s, true)
		if !valid {
			return
		}
		u, _ := model.GetCta(c, s.User)
		fe := fillEmpresa(r)

		// Se añade una empresa
		//e, err := u.NewEmpresa(c, &fe)
		_, err := u.NewEmpresa(c, &fe)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		err1 := model.PutCtaEmp(c, fe.IdEmp, u.Email, u.EmailAlt)
		if err1 != nil {
			http.Error(w, err1.Error(), http.StatusInternalServerError)
			return
		}
		//formEmp(c, w, &s, e)
		ShowListEmp(w, r)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #3
0
func micrositio(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		emp, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else {
			img := model.GetLogo(c, r.FormValue("IdEmp"))
			if img == nil {
				img = new(model.Image)
				img.IdEmp = emp.IdEmp
			}
			fd := imgToForm(*img)
			tc := make(map[string]interface{})
			tc["Sess"] = s
			tc["Empresa"] = emp
			tc["FormData"] = fd
			micrositioTpl.Execute(w, tc)
		}
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #4
0
func CtaMod(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		if u, err := model.GetCta(c, s.User); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else {
			if fd, valid := ctaForm(w, r, s, true, ctadmTpl); !valid {
				return
			} else {
				ctaFill(r, u)
				if _, err := model.PutCta(c, u); err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				tc := make(map[string]interface{})
				tc["Sess"] = s
				tc["FormDataCta"] = fd
				ctadmTpl.ExecuteTemplate(w, "cta", tc)
			}
		}
	} else {
		http.Redirect(w, r, "/", http.StatusFound)
	}
}
Example #5
0
func municipios(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	_, ok := sess.IsSess(w, r, c)
	if ok {
		if item, err := memcache.Get(c, "msp_"+r.FormValue("CveEnt")); err == memcache.ErrCacheMiss {
			if entidad, err := model.GetEntidad(c, r.FormValue("CveEnt")); err == nil {
				if municipios, _ := entidad.GetMunicipios(c); err == nil {
					b, _ := json.Marshal(municipios)
					item := &memcache.Item{
						Key:   "msp_" + r.FormValue("CveEnt"),
						Value: b,
					}
					if err := memcache.Add(c, item); err == memcache.ErrNotStored {
						c.Infof("item with key %q already exists", item.Key)
					} else if err != nil {
						c.Errorf("Error memcache.Add Municipio : %v", err)
					}
					c.Infof("CveMun generado: %v", item.Key)
					htmlComboMuns(w, municipios, r.FormValue("CveMun"))
				}
			}
		} else {
			//c.Infof("Memcache activo: %v", item.Key)
			var municipios []model.Municipio
			if err := json.Unmarshal(item.Value, &municipios); err != nil {
				c.Errorf("error adding item: %v", err)
			}
			htmlComboMuns(w, &municipios, r.FormValue("CveMun"))
		}
	}
	return
}
Example #6
0
func materiales(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		tc := make(map[string]interface{})
		tc["Sess"] = s
		materialesTpl.Execute(w, tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #7
0
func modData(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		emp, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		imgo := model.GetLogo(c, r.FormValue("IdEmp"))
		if imgo == nil {
			imgo = new(model.Image)
			imgo.IdEmp = emp.IdEmp
		}
		fd := imgToForm(*imgo)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		tc["Empresa"] = emp
		tc["FormData"] = fd
		if r.Method != "POST" {
			// No upload; show the upload form.
			micrositio(w, r)
			return
		}

		idemp := r.FormValue("IdEmp")
		name := r.FormValue("Name")
		desc := r.FormValue("Desc")
		url := r.FormValue("Url")
		sp1 := r.FormValue("Sp1")
		sp2 := r.FormValue("Sp2")

		//	key := datastore.NewKey(c, "EmpLogo", r.FormValue("id"), 0, nil)
		//	im := new(model.Image)
		// Save the image under a unique key, a hash of the image.
		imgo = &model.Image{
			Data: imgo.Data, IdEmp: idemp, IdImg: imgo.IdImg,
			Kind: "EmpLogo", Name: name, Desc: desc,
			Sizepx: 0, Sizepy: 0, Url: url, Type: "",
			Sp1: sp1, Sp2: sp2, Sp3: imgo.Sp3, Sp4: imgo.Sp4,
			Np1: 0, Np2: 0, Np3: 0, Np4: 0,
		}
		_, err = model.PutLogo(c, imgo)
		if err != nil {
			tc["Error"] = struct{ Cantsave string }{"cantsave"}
			micrositioTpl.Execute(w, tc)
			return
		}

		micrositio(w, r)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #8
0
func SucDel(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); ok {
		if err := model.DelSuc(c, r.FormValue("IdSuc")); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		ShowListSuc(w, r)
		return
	}
	http.Redirect(w, r, "/r/sucursales", http.StatusFound)
}
Example #9
0
func descargamg(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); ok {
		// Stream de materiales
		//w.Header().Set("Content-type", "application/octet-stream")
		//w.Header().Set("Content-disposition", "attachment; filename=test.zip")
		http.Redirect(w, r, "/ElBuenFin_Materiales.zip", http.StatusFound)

	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #10
0
func OfDel(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); ok {
		if err := model.DelOferta(c, r.FormValue("IdOft")); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		OfShowList(w, r)
		return
	}
	http.Redirect(w, r, "/r/ofertas", http.StatusFound)
}
Example #11
0
func registro(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); !ok {
		var fd FormDataCta
		tc := make(map[string]interface{})
		//tc["Sess"] = s
		tc["FormDataCta"] = fd
		registroTpl.ExecuteTemplate(w, "cta", tc)
		return
	} else {
		http.Redirect(w, r, "/r/dash", http.StatusFound)
	}
}
Example #12
0
func DelEmp(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		if err := u.DelEmpresa(c, r.FormValue("IdEmp")); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		ShowListEmp(w, r)
		return
	}
	http.Redirect(w, r, "/r/registro", http.StatusFound)
}
Example #13
0
func Salir(w http.ResponseWriter, r *http.Request) {
	now := time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		s.Expiration = now.AddDate(-1, 0, 0)
		_, err := datastore.Put(c, datastore.NewKey(c, "Sess", s.User, 0, nil), &s)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
	w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sesscontrol-ua=%s; expires=%s; path=/;", "", "Thu, 18 Oct 2012 01:01:23 GMT;"))
	w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sessid-ua=%s; expires=%s; path=/;", "", "Thu, 18 Oct 2012 01:01:23 GMT;"))
	http.Redirect(w, r, "/r/registro", http.StatusFound)
}
Example #14
0
func Acceso(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var st sess.Sess
	if _, ok := sess.IsSess(w, r, c); !ok {
		//fmt.Fprintf(w, "u:%s, p:%s", r.FormValue("u"), r.FormValue("p"))
		if r.FormValue("u") != "" && r.FormValue("p") != "" {
			user := strings.TrimSpace(r.FormValue("u"))
			pass := strings.TrimSpace(r.FormValue("p"))
			/* validar usuario y pass */
			if model.ValidEmail.MatchString(user) && model.ValidPass.MatchString(pass) {
				q := datastore.NewQuery("Cta").Filter("Email =", user).Filter("Pass ="******"Status =", true)
				if count, _ := q.Count(c); count != 0 {
					for t := q.Run(c); ; {
						var g model.Cta
						key, err := t.Next(&g)
						if err == datastore.Done {
							break
						}
						// Coincide contraseña, se activa una sesión
						_, _, err = sess.SetSess(w, c, key, g.Email, g.Nombre)
						if err != nil {
							http.Error(w, err.Error(), http.StatusInternalServerError)
							return
						}

						// Redireccion
						http.Redirect(w, r, "/r/dash", http.StatusFound)
						return
					}
				}
			}
			st.User = r.FormValue("u")
			st.ErrMsg = "Usuario o contraseña incorrectos"
			st.ErrClass = "show"
		} else {
			st.User = r.FormValue("u")
			st.ErrMsg = "Proporcione usuario y contraseña"
			st.ErrClass = "show"
		}
	} else {
		// hay sesión
		http.Redirect(w, r, "/r/dash", http.StatusFound)
		return
	}
	tc := make(map[string]interface{})
	tc["Sess"] = st
	accesoErrorTpl.Execute(w, tc)
}
Example #15
0
func CtaShow(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		if g, err := model.GetCta(c, s.User); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			tc := make(map[string]interface{})
			tc["Sess"] = s
			tc["FormDataCta"] = ctaToForm(*g)
			ctadmTpl.ExecuteTemplate(w, "cta", tc)
			return
		}
	} else {
		http.Redirect(w, r, "/", http.StatusFound)
	}
}
Example #16
0
func pendienteVerifica(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	s, ok := sess.IsSess(w, r, c)
	if ok {
		http.Redirect(w, r, "/r/cta", http.StatusFound)
		return
	}
	fd, valid := ctaForm(w, r, s, true, registroTpl)
	if valid {
		u, err := model.GetCta(c, fd.Email)
		ctaFill(r, u)
		if err != nil {
			// No hay Cuenta registrada
			u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
			u.Status = false
			u.CodigoCfm = "Verificar"

			// Generar código de confirmación distindo cada vez. Md5 del email + fecha-hora
			h := md5.New()
			io.WriteString(h, fmt.Sprintf("%s%s%s%s", time.Now().Add(time.Duration(model.GMTADJ)*time.Second), u.Email, u.Pass, model.RandId(12)))
			u.CodigoCfm = fmt.Sprintf("%x", h.Sum(nil))
		}

		u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
		u.Status = true
		u.CodigoCfm = "Verificar"
		// Se agrega la cuenta sin activar para realizar el proceso de código de confirmación
		if u, err = model.PutCta(c, u); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		/* Prende la sesion */
		_, _, err = sess.SetSess(w, c, u.Key(c), u.Email, u.Nombre)

		// avisa del éxito independientemente del correo
		if err := activationMessageTpl.ExecuteTemplate(w, "verify", u); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		if err := activationMessageTpl.ExecuteTemplate(w, "codeerr", nil); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}
Example #17
0
func registroprefill(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); !ok {
		var fd FormDataCta
		fd.Nombre = r.FormValue("nombre")
		fd.Apellidos = r.FormValue("apellidos")
		fd.Email = r.FormValue("email")
		fd.Puesto = r.FormValue("puesto")
		fd.Tel = r.FormValue("tel")
		fd.Cel = r.FormValue("cel")
		tc := make(map[string]interface{})
		tc["FormDataCta"] = fd
		registroTpl.ExecuteTemplate(w, "cta", tc)
		return
	} else {
		http.Redirect(w, r, "/dash", http.StatusFound)
	}
}
Example #18
0
func OfShowList(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		tc["Empresa"] = empresa
		tc["Oferta"] = model.ListOf(c, empresa.IdEmp)
		ofadmTpl.ExecuteTemplate(w, "ofertas", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #19
0
func OfShow(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		oferta, _ := model.GetOferta(c, r.FormValue("IdOft"))
		var id string
		if oferta.IdEmp != "none" {
			id = oferta.IdEmp
		} else {
			id = r.FormValue("IdEmp")
		}
		fd := ofToForm(*oferta)
		empresa, err := u.GetEmpresa(c, id)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		tc["Empresa"] = empresa
		fd.IdEmp = empresa.IdEmp
		oferta.Empresa = empresa.Nombre
		fd.Categorias = model.ListCat(c, oferta.IdCat)

		/*
		 * Se crea el form para el upload del blob
		 */
		blobOpts := blobstore.UploadURLOptions{
			MaxUploadBytesPerBlob: 1048576,
		}
		uploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts)
		if err != nil {
			serveError(c, w, err)
			return
		}
		fd.UploadURL = strings.Replace(uploadURL.String(), "http", "https", 1)
		//fd.UploadURL = uploadURL

		tc["FormDataOf"] = fd
		ofadmTpl.ExecuteTemplate(w, "oferta", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #20
0
func sucursales(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	_, ok := sess.IsSess(w, r, c)
	if ok {
		q := datastore.NewQuery("Sucursal").Filter("IdEmp =", r.FormValue("IdEmp"))
		tpl, _ := template.New("Suc").Parse(SucListTpl)
		//fmt.Fprintf(w, "<div class=\"col-100PR first marg-U20pix\">")
		for i := q.Run(c); ; {
			var s model.Sucursal
			_, err := i.Next(&s)
			if err == datastore.Done {
				break
			}
			//Despliega sucursales
			tpl.Execute(w, s)
		}
		//fmt.Fprintf(w, "</div>")
	}
	return
}
Example #21
0
func ShowListEmp(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		tc["Empresa"] = listEmp(c, u)
		if r.FormValue("d") == "a" {
			empadmTpl.ExecuteTemplate(w, "empresa", tc)
		} else if r.FormValue("d") == "s" {
			//empadmTpl.ExecuteTemplate(w, "vistasucursal", tc)
			empadmTpl.ExecuteTemplate(w, "empresassucursales", tc)
		} else if r.FormValue("d") == "m" {
			empadmTpl.ExecuteTemplate(w, "vistamicrositio", tc)
		} else if r.FormValue("d") == "o" {
			empadmTpl.ExecuteTemplate(w, "vistaoferta", tc)
		}
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #22
0
func ModEmp(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		// formato con validación
		_, valid := formatoEmp(w, r, s, true)
		if !valid {
			return
		}

		/*
		 * Se carga un struct con los datos de la forma
		 */
		fe := fillEmpresa(r)

		/*
		 * Se requiere leer la estructura para insertar el folio y el status
		 * y otros campos que se deben conservar
		 */
		e, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			c.Errorf("ModEmp() GetEmpresa() Error al intentar actualizar Empresa : %v", e.IdEmp)
		} else {
			fe.Folio = e.Folio
			fe.Status = e.Status
			fe.Benef = e.Benef

			_, err := u.PutEmpresa(c, &fe)
			if err == datastore.ErrNoSuchEntity {
				c.Errorf("ModEmp() PutEmpresa() Error al intentar actualizar Empresa : %v", e.IdEmp)
			}
		}
		ShowListEmp(w, r)
	} else {
		defer http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #23
0
func SucShow(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		sucursal := model.GetSuc(c, u, r.FormValue("IdSuc"), r.FormValue("IdEmp"))
		if sucursal == nil {
			sucursal.IdEmp = empresa.IdEmp
		}
		tc["Empresa"] = empresa
		fd := sucToForm(*sucursal)
		fd.Entidades = model.ListEnt(c, sucursal.DirEnt)
		tc["FormDataSuc"] = fd
		sucadmTpl.ExecuteTemplate(w, "sucursal", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #24
0
func CtaDel(w http.ResponseWriter, r *http.Request) {
	now := time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
	if r.Method != "POST" {
		return
	}
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		if u, err := model.GetCta(c, s.User); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else {
			// Sólo desactiva cuenta si no hay empresas dependientes
			e := listEmp(c, u)
			if len(*e) == 0 {
				// Desactiva Status
				if r.FormValue("desactiva") == "1" {
					s.Expiration = now.AddDate(-1, 0, 0)
					_, err := datastore.Put(c, datastore.NewKey(c, "Sess", s.User, 0, nil), &s)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
					u.CodigoCfm = "Desactivado"
					u.Status = false
					_, err = model.PutCta(c, u)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
						return
					}
					w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sesscontrol-ua=%s; expires=%s; path=/;", "", "Wed, 07-Oct-2000 14:23:42 GMT"))
					w.Header().Add("Set-Cookie", fmt.Sprintf("ebfmex-pub-sessid-ua=%s; expires=%s; path=/;", "", "Wed, 07-Oct-2000 14:23:42 GMT"))
					errmsg := struct{ ErrMsg string }{"¡Gracias por participar en El Buen Fin!"}
					ErrorGeneralTpl.Execute(w, errmsg)

					// INICIA ENVIO DE CORREO DE MOTIVOS
					// Este tramo no debe arrojar errores al usuario
					var hbody bytes.Buffer
					u.CodigoCfm = r.FormValue("motivo")
					cancelMessageTpl.Execute(&hbody, u)
					msg := &mail.Message{
						Sender:   "Cancelación de cuenta / Buen Fin <*****@*****.**>",
						To:       []string{"*****@*****.**"},
						Subject:  "Aviso de motivo de cuenta cancelada / El Buen Fin en línea",
						HTMLBody: hbody.String(),
					}
					mail.Send(c, msg)
					// Si el hay usuario admin se despliega el motivo (efectos de prueba
					//if gu := user.Current(c); gu != nil {
					//		cancelMessageTpl.Execute(w, u)
					//	}
					// TERMINA ENVIO DE MOTIVOS
					return
				}
				http.Redirect(w, r, "/r/cta", http.StatusFound)
			} else {
				// Debe borrar empresas antes o Transferir sus empresas a otro usuario
				errmsg := struct {
					ErrMsg string
					Back   string
				}{"Para cancelar una cuenta primero se deben dar de baja las empresas registradas", "1"}
				ErrorGeneralTpl.Execute(w, errmsg)
				return
			}
		}
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}
Example #25
0
func Recover(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if _, ok := sess.IsSess(w, r, c); !ok {
		var email string = strings.TrimSpace(r.FormValue("Email"))
		//var rfc string = strings.TrimSpace(r.FormValue("RFC"))
		if email != "" && model.ValidEmail.MatchString(email) { // && rfc != "" && model.ValidRfc.MatchString(rfc) {
			// intenta buscar en la base un usuario con email y empresa
			if cta, err := model.GetCta(c, email); err == nil {
				if cta.Status {
					if MailServer == "gmail" {
						var hbody bytes.Buffer
						var sender string
						if appengine.AppID(c) == "ebfmxorg" {
							sender = "El Buen Fin <*****@*****.**>"
						} else {
							sender = "El Buen Fin <*****@*****.**>"
						}
						if err := mailRecoverTpl.Execute(&hbody, cta); err != nil {
							http.Error(w, err.Error(), http.StatusInternalServerError)
						}
						// Coincide email y RFC, se manda correo con contraseña
						msg := &mail.Message{
							Sender:   sender,
							To:       []string{cta.Email},
							Subject:  "Recuperación de contraseña / El Buen Fin",
							HTMLBody: hbody.String(),
						}
						if err := mail.Send(c, msg); err != nil {
							http.Error(w, err.Error(), http.StatusInternalServerError)
						} else {
							http.Redirect(w, r, "/recoverok.html", http.StatusFound)
							return
						}
						//fmt.Fprintf(w, mailRecover, cta.Email, cta.Pass)
						return
					} else {
						client := urlfetch.Client(c)
						url := fmt.Sprintf("http://envia-m.mekate.com.mx/?Sender=%s&Tipo=Recupera&Email=%s&Nombre=%s&Pass=%s&AppId=ebfmxorg",
							"*****@*****.**",
							cta.Email,
							url.QueryEscape(cta.Nombre),
							url.QueryEscape(cta.Pass))
						r1, err := client.Get(url)
						if err != nil {
							http.Error(w, err.Error(), http.StatusInternalServerError)
							return
						}

						if r1.StatusCode != 200 {
							http.Error(w, "Error de Transporte de Mail", http.StatusInternalServerError)
						}
						defer r1.Body.Close()
						http.Redirect(w, r, "/recoverok.html", http.StatusFound)
						return
					}
				} else {
					http.Redirect(w, r, "/nocta.html", http.StatusFound)
					return
				}
			}
		}
		http.Redirect(w, r, "/nocta.html", http.StatusFound)
		return
	} else {
		http.Redirect(w, r, "/r/dash", http.StatusFound)
	}
}
Example #26
0
// Modifica si hay, Crea si no hay
// Requiere IdEmp. IdOft es opcional, si no hay lo crea, si hay modifica
func OfMod(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		var fd FormDataOf
		var valid bool
		var ofertamod model.Oferta

		if r.FormValue("IdOft") == "new" {
			if empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp")); err != nil {
				http.Redirect(w, r, "/r/le?d=o", http.StatusFound)
			} else {
				tc["Empresa"] = empresa
				fd.IdEmp = empresa.IdEmp
				fd.Empresa = empresa.Nombre
				ofertamod.IdEmp = empresa.IdEmp
				ofertamod.Oferta = "Nueva oferta"
				ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)    // 5 horas menos
				ofertamod.FechaHoraPub = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) // 5 horas menos
				ofertamod.Empresa = strings.ToUpper(empresa.Nombre)
				ofertamod.BlobKey = "none"
				o, err := model.NewOferta(c, &ofertamod)
				model.Check(err)
				fd = ofToForm(*o)
				fd.Ackn = "Ok"
			}
		} else {
			/*
			 * Se pide un id oferta que en teoría existe, se consulta y se cambia
			 * Se valida y si no existe se informa un error
			 */
			fd, valid = ofForm(w, r, true)

			ofertamod.IdOft = fd.IdOft
			ofertamod.IdEmp = fd.IdEmp
			ofertamod.IdCat = fd.IdCat
			ofertamod.Oferta = fd.Oferta
			ofertamod.Descripcion = fd.Descripcion
			ofertamod.Enlinea = fd.Enlinea
			ofertamod.Url = fd.Url
			ofertamod.FechaHoraPub = fd.FechaHoraPub
			ofertamod.StatusPub = fd.StatusPub
			//ofertamod.BlobKey = fd.BlobKey
			ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)

			oferta, keyOferta := model.GetOferta(c, ofertamod.IdOft)
			if oferta.IdOft != "none" {
				ofertamod.BlobKey = oferta.BlobKey
				ofertamod.Codigo = oferta.Codigo
				empresa, err := u.GetEmpresa(c, ofertamod.IdEmp)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				tc["Empresa"] = empresa
				fd.IdEmp = empresa.IdEmp
				fd.Empresa = empresa.Nombre
				ofertamod.Empresa = strings.ToUpper(empresa.Nombre)
				emplogo := model.GetLogo(c, empresa.IdEmp)
				if emplogo != nil {
					// Tenga lo que tenga, se pasa Sp4 a Oferta.Promocion
					if emplogo.Sp4 != "" {
						ofertamod.Promocion = emplogo.Sp4
						ofertamod.Descuento = strings.Replace(emplogo.Sp4, "s180", "s70", 1)
					}
				}
				// TODO
				// es preferible poner un regreso avisando que no existe la empresa
				if valid {
					// Ya existe
					err := model.PutOferta(c, &ofertamod)
					model.Check(err)

					// Se borran las relaciones oferta-sucursal
					err = model.DelOfertaSucursales(c, oferta.IdOft)
					model.Check(err)

					// Se crea un mapa de Estados para agregar a OfertaEstado
					edomap := make(map[string]string, 32)

					// Se reconstruyen las Relaciones oferta-sucursal con las solicitadas
					idsucs := strings.Fields(r.FormValue("schain"))

					for _, idsuc := range idsucs {
						suc := model.GetSuc(c, u, idsuc, ofertamod.IdEmp)

						lat, _ := strconv.ParseFloat(suc.Geo1, 64)
						lng, _ := strconv.ParseFloat(suc.Geo2, 64)

						var ofsuc model.OfertaSucursal
						ofsuc.IdOft = ofertamod.IdOft
						ofsuc.IdSuc = idsuc
						ofsuc.IdEmp = ofertamod.IdEmp
						ofsuc.Sucursal = suc.Nombre
						ofsuc.Lat = lat
						ofsuc.Lng = lng
						ofsuc.Empresa = ofertamod.Empresa
						ofsuc.Oferta = ofertamod.Oferta
						ofsuc.Descripcion = ofertamod.Descripcion
						ofsuc.Promocion = ofertamod.Promocion
						ofsuc.Descuento = ofertamod.Descuento
						ofsuc.Url = ofertamod.Url
						ofsuc.StatusPub = ofertamod.StatusPub
						ofsuc.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)

						// Se añade el estado de la sucursal al mapa de estados
						edomap[suc.DirEnt] = oferta.IdOft

						errOs := ofertamod.PutOfertaSucursal(c, &ofsuc)
						model.Check(errOs)

					}
					// Se limpia la relación OfertaEstado
					_ = ofertamod.DelOfertaEstado(c)

					// Se guarda la relación OfertaEstado
					errOe := ofertamod.PutOfertaEstado(c, edomap)
					model.Check(errOe)

					var tituloOf string
					tituloOf = ""
					if strings.ToLower(strings.TrimSpace(ofertamod.Oferta)) != "nueva oferta" {
						tituloOf = ofertamod.Oferta
					}
					putSearchData(c, ofertamod.Empresa+" "+tituloOf+" "+ofertamod.Descripcion+" "+r.FormValue("pchain"), keyOferta, oferta.IdOft, ofertamod.IdCat, ofertamod.Enlinea)

					// Se despacha la generación de diccionario de palabras
					// Se agrega pcves a la descripción
					//fmt.Fprintf(w,"http://movil.%s.appspot.com/backend/generatesearch?kind=Oferta&field=Descripcion&id=%s&value=%s&categoria=%s",
					//appengine.AppID(c), keyOferta.Encode(), ofertamod.Descripcion+" "+r.FormValue("pchain"), strconv.Itoa(ofertamod.IdCat))
					//_ = generatesearch(c, keyOferta, ofertamod.Descripcion+" "+r.FormValue("pchain"), ofertamod.IdCat)

					fd = ofToForm(ofertamod)
					fd.Ackn = "Ok"
				}
			} else {
				// no existe la oferta
			}
		}

		fd.Categorias = model.ListCat(c, ofertamod.IdCat)

		/*
		 * Se crea el form para el upload del blob
		 */
		blobOpts := blobstore.UploadURLOptions{
			MaxUploadBytesPerBlob: 1048576,
		}
		uploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts)
		if err != nil {
			serveError(c, w, err)
			return
		}
		fd.UploadURL = strings.Replace(uploadURL.String(), "http", "https", 1)
		//fd.UploadURL = uploadURL
		tc["FormDataOf"] = fd

		ofadmTpl.ExecuteTemplate(w, "oferta", tc)
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}

	/*
	 * FETCH PARA MVBLOB/GENERATE
	 */
	cronsecs := 3600
	cachename := "mvblob_cron"
	if _, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss {
		slot := strconv.Itoa(cronsecs)
		item := &memcache.Item{
			Key:        cachename,
			Value:      []byte(slot),
			Expiration: time.Duration(cronsecs) * time.Second,
		}
		if err := memcache.Add(c, item); err == memcache.ErrNotStored {
			//c.Errorf("memcache.Add %v : %v", cachename, err)
			if err := memcache.Set(c, item); err == memcache.ErrNotStored {
				c.Errorf("Memcache.Set %v : %v", cachename, err)
			} else {
				c.Infof("memcached %v", cachename)
				mvblobFetch(c)
			}
		} else {
			c.Infof("memcached %v", cachename)
			mvblobFetch(c)
		}
	} else {
		// DO NOTHING
	}
}
Example #27
0
func handleUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var out OfImg
	blobOpts := blobstore.UploadURLOptions{
		MaxUploadBytesPerBlob: 1048576,
	}
	out.Status = "invalidId"
	out.IdBlob = ""
	if _, ok := sess.IsSess(w, r, c); ok {
		blobs, form, err := blobstore.ParseUpload(r)
		file := blobs["image"]
		out.IdBlob = string(file[0].BlobKey)
		out.IdOft = form.Get("IdOft")
		if err != nil {
			out.Status = "invalidUpload"
			berr := blobstore.Delete(c, file[0].BlobKey)
			model.Check(berr)
		} else {
			oferta, _ := model.GetOferta(c, out.IdOft)
			if oferta.IdEmp == "none" {
				out.Status = "invalidUpload"
				berr := blobstore.Delete(c, file[0].BlobKey)
				model.Check(berr)
			} else {
				out.Status = "ok"
				if len(file) == 0 {
					out.Status = "invalidUpload"
					berr := blobstore.Delete(c, file[0].BlobKey)
					model.Check(berr)
				} else {
					var oldblobkey = oferta.BlobKey
					oferta.BlobKey = file[0].BlobKey
					out.IdOft = oferta.IdOft

					// Se crea la URL para servir la oferta desde el CDN, si no se puede
					var imgprops image.ServingURLOptions
					imgprops.Secure = true
					imgprops.Size = 400
					imgprops.Crop = false
					if url, err := image.ServingURL(c, oferta.BlobKey, &imgprops); err != nil {
						c.Errorf("Cannot construct ServingURL : %v", oferta.IdOft)
						oferta.Codigo = ""
					} else {
						oferta.Codigo = url.String()
					}

					err = model.PutOferta(c, oferta)
					if err != nil {
						out.Status = "invalidUpload"
						berr := blobstore.Delete(c, file[0].BlobKey)
						model.Check(berr)
					}
					/*
						Se borra el blob anterior, porque siempre crea uno nuevo
						No se necesita revisar el error
						Si es el blobkey = none no se borra por obvias razones
						Se genera una sesion nueva de upload en caso de que quieran
						cambiar la imágen en la misma pantalla. Esto es debido a que
						se utiliza un form estático con ajax
					*/
					if oldblobkey != "none" {
						blobstore.Delete(c, oldblobkey)
						UploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts)
						out.UploadURL = UploadURL.String()
						if err != nil {
							out.Status = "uploadSessionError"
						}
					}
				}
			}
		}
	}
	w.Header().Set("Content-Type", "application/json")
	b, _ := json.Marshal(out)
	w.Write(b)
}
Example #28
0
func Registrar(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	s, ok := sess.IsSess(w, r, c)
	if ok {
		http.Redirect(w, r, "/r/cta", http.StatusFound)
		return
	}
	fd, valid := ctaForm(w, r, s, true, registroTpl)
	if valid {
		u, err := model.GetCta(c, fd.Email)
		ctaFill(r, u)
		if err != nil {
			// No hay Cuenta registrada
			u.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second)
			u.Status = false

			// Generar código de confirmación distindo cada vez. Md5 del email + fecha-hora
			h := md5.New()
			io.WriteString(h, fmt.Sprintf("%s%s%s%s", time.Now().Add(time.Duration(model.GMTADJ)*time.Second), u.Email, u.Pass, model.RandId(12)))
			u.CodigoCfm = fmt.Sprintf("%x", h.Sum(nil))
		}

		//Si hay estatus es que ya existe
		if u.Status == false {

			// Se agrega la cuenta sin activar para realizar el proceso de código de confirmación
			if u, err = model.PutCta(c, u); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			/* No se ha activado, por tanto se inicia el proceso de código de verificación */
			m := urlCfm{
				Md5:       u.CodigoCfm,
				Nombre:    u.Nombre,
				Email:     u.Email,
				FechaHora: time.Now().Add(time.Duration(model.GMTADJ) * time.Second),
				Llave:     u.Key(c).Encode(),
				AppId:     appengine.AppID(c),
			}
			var hbody bytes.Buffer
			var sender string
			if appengine.AppID(c) == "ebfmxorg" {
				sender = "El Buen Fin <*****@*****.**>"
			} else {
				sender = "El Buen Fin <*****@*****.**>"
			}
			// Envia código activación
			if err := mailActivationCodeTpl.Execute(&hbody, m); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			if MailServer == "gmail" {
				msg := &mail.Message{
					Sender:   sender,
					To:       []string{m.Email},
					Subject:  "Codigo de Activación de Registro / El Buen Fin en línea",
					HTMLBody: hbody.String(),
				}
				if err := mail.Send(c, msg); err != nil {
					/* Problemas para enviar el correo NOK */
					http.Error(w, err.Error(), http.StatusInternalServerError)
					http.Redirect(w, r, "/", http.StatusFound)
				} else {
					if err := activationMessageTpl.ExecuteTemplate(w, "codesend", m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
				// ************************************************************
				// Si el hay usuario admin se despliega el código de activación
				// ************************************************************
				if gu := user.Current(c); gu != nil {
					if err := mailActivationCodeTpl.Execute(w, m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
			} else {
				client := urlfetch.Client(c)
				url := fmt.Sprintf("http://envia-m.mekate.com.mx/?Sender=%s&Tipo=Codigo&Md5=%s&Llave=%s&Email=%s&Nombre=%s&AppId=ebfmxorg",
					"*****@*****.**",
					m.Md5,
					url.QueryEscape(m.Llave),
					m.Email,
					url.QueryEscape(m.Nombre))
				r1, err := client.Get(url)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				//fmt.Fprintf(w, "HTTP GET returned status %v", r.Status)

				if r1.StatusCode != 200 {
					http.Error(w, "Error de Transporte de Mail", http.StatusInternalServerError)
					return
				} else {
					if err := activationMessageTpl.ExecuteTemplate(w, "codesend", m); err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
				}
				defer r1.Body.Close()
			}
		} else {
			if err := registroErrorTpl.Execute(w, nil); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		}
	}
}
Example #29
0
// upload is the HTTP handler for uploading images; it handles "/".
func upload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	var imgprops appimage.ServingURLOptions
	imgprops.Secure = true
	imgprops.Size = 180
	imgprops.Crop = false
	if s, ok := sess.IsSess(w, r, c); ok {
		u, _ := model.GetCta(c, s.User)
		emp, err := u.GetEmpresa(c, r.FormValue("IdEmp"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		imgo := model.GetLogo(c, r.FormValue("IdEmp"))
		if imgo == nil {
			imgo = new(model.Image)
			imgo.IdEmp = emp.IdEmp
		}
		fd := imgToForm(*imgo)
		tc := make(map[string]interface{})
		tc["Sess"] = s
		tc["Empresa"] = emp
		tc["FormData"] = fd
		if r.Method != "POST" {
			// No upload; show the upload form.
			micrositio(w, r)
			return
		}

		idemp := r.FormValue("IdEmp")
		sp1 := r.FormValue("Sp1")
		sp2 := r.FormValue("Sp2")
		f, _, err := r.FormFile("image")
		model.Check(err)
		defer f.Close()

		// Grab the image data
		var buf bytes.Buffer
		io.Copy(&buf, f)
		i, _, err := image.Decode(&buf)
		if err != nil {
			if r.FormValue("tipo") == "async" {
				//w.Header().Set("Content-Type", "application/json")
				fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo, formato no aceptado")
			} else {
				tc["Error"] = struct{ Badformat string }{"badformat"}
				micrositioTpl.Execute(w, tc)
			}
			return
		}
		const max = 600
		// We aim for less than max pixels in any dimension.
		if b := i.Bounds(); b.Dx() > max || b.Dy() > max {
			// If it's gigantic, it's more efficient to downsample first
			// and then resize; resizing will smooth out the roughness.
			if b.Dx() > 2*max || b.Dy() > 2*max {
				w, h := max*2, max*2
				if b.Dx() > b.Dy() {
					h = b.Dy() * h / b.Dx()
				} else {
					w = b.Dx() * w / b.Dy()
				}
				i = resize.Resample(i, i.Bounds(), w, h)
				b = i.Bounds()
			}
			w, h := max, max
			if b.Dx() > b.Dy() {
				h = b.Dy() * h / b.Dx()
			} else {
				w = b.Dx() * w / b.Dy()
			}
			i = resize.Resize(i, i.Bounds(), w, h)
		}

		// Encode as a new JPEG image.
		buf.Reset()
		err = jpeg.Encode(&buf, i, nil)
		if err != nil {
			if r.FormValue("tipo") == "async" {
				fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo, formato no aceptado")
			} else {
				tc["Error"] = struct{ Badencode string }{"badencode"}
				micrositioTpl.Execute(w, tc)
			}
			return
		}
		var blobkey appengine.BlobKey
		blob, err := blobstore.Create(c, "image/jpeg")
		if err != nil {
			c.Errorf("blobstore Create: %v", idemp)
		}
		_, err = blob.Write(buf.Bytes())
		if err != nil {
			c.Errorf("blobstore Write: %v", idemp)
		}
		err = blob.Close()
		if err != nil {
			c.Errorf("blobstore Close: %v", idemp)
		}
		blobkey, err = blob.Key()
		if err != nil {
			c.Errorf("blobstore Key Gen: %v", idemp)
		}
		if url, err := appimage.ServingURL(c, blobkey, &imgprops); err != nil {
			c.Errorf("Cannot construct EmpLogo ServingURL : %v", idemp)
		} else {
			// Save the image under a unique key, a hash of the image.
			img := &model.Image{
				Data: buf.Bytes(), IdEmp: idemp, IdImg: model.RandId(20),
				Kind: "EmpLogo", Name: imgo.Name, Desc: imgo.Desc,
				Sizepx: 0, Sizepy: 0, Url: imgo.Url, Type: "",
				Sp1: sp1, Sp2: sp2, Sp3: string(blobkey), Sp4: url.String(),
				Np1: 0, Np2: 0, Np3: 0, Np4: 0,
			}

			_, err = model.PutLogo(c, img)
			if err != nil {
				if r.FormValue("tipo") == "async" {
					fmt.Fprintf(w, "<p>'%s'</p>", "No se actualizó el logotipo. Sistema en matenimiento, intente en unos minutos")
				} else {
					tc["Error"] = struct{ Cantsave string }{"cantsave"}
					micrositioTpl.Execute(w, tc)
				}
				return
			}
		}

		/*
			se crea icono
		*/
		val := slogores(c, idemp, 70, 0)
		if val != 0 {
			tc["Error"] = struct{ Cantsave string }{"cantsave"}
			micrositioTpl.Execute(w, tc)
			return
		}

		if r.FormValue("tipo") == "async" {
			fmt.Fprintf(w, "<p></p>")
		} else {
			micrositio(w, r)
		}
		return
	} else {
		http.Redirect(w, r, "/r/registro", http.StatusFound)
	}
}