Initial commit

This commit is contained in:
Lizandro Guarnizo
2025-02-06 14:22:29 -05:00
commit 6d8f1bcd6f
452 changed files with 250835 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
# Config file for [Air](https://github.com/cosmtrek/air) in TOML format
# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "."
tmp_dir = "tmp"
[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o main ."
# Binary file yields from `cmd`.
bin = "main"
# Customize binary.
full_bin = "APP_ENV=dev APP_USER=air ./main"
# Watch these filename extensions.
include_ext = ["go", "tpl", "tmpl", "html"]
# Ignore these filename extensions or directories.
exclude_dir = ["assets", "tmp", "vendor", "node_modules", "build"]
# Watch these directories if you specified.
include_dir = []
# Exclude files.
exclude_file = []
# This log file places in your tmp_dir.
log = "air.log"
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms
# Stop running old binary when build errors occur.
stop_on_error = true
# Send Interrupt signal before killing process (windows does not support this feature)
send_interrupt = false
# Delay after sending Interrupt signal
kill_delay = 500 # ms
[log]
# Show log time
time = false
[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"
[misc]
# Delete tmp directory on exit
clean_on_exit = true
+5
View File
@@ -0,0 +1,5 @@
{
"plugins": [
"syntax-dynamic-import"
]
}
+8
View File
@@ -0,0 +1,8 @@
version = 1
[[analyzers]]
name = "go"
enabled = true
[analyzers.meta]
import_paths = ["github.com/sujit-baniya/fiber-boilerplate"]
+25
View File
@@ -0,0 +1,25 @@
#VITE_API_URL=
#VITE_WS_URL=
APP_URL=https://admin.u-site.app
DB_DRIVER=mysql
DB_HOST=46.202.93.92
DB_PORT=3306
DB_USER=pym
DB_PASS=Nicolas2796*+
DB_NAME=usite
MAIL_HOST=smtp.hostinger.com
MAIL_USERNAME=soporte@u-site.app
MAIL_PASSWORD=Nicolas2796*+
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=soporte@u-site.app
MAIL_FROM_NAME=Usite
MAIL_PORT=465
APP_PREFORK=true
SESSION_DATABASE=./session.db
+8
View File
@@ -0,0 +1,8 @@
VITE_API_URL=https://verify.rest
VITE_WS_URL=ws://verify.rest/ws
DB_DRIVER=sqlserver
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASS=postgres
DB_NAME=casbin
+6
View File
@@ -0,0 +1,6 @@
*.css linguist-detectable=false
*.js linguist-detectable=false
*.html linguist-detectable=false
*.vue linguist-detectable=false
*.scss linguist-detectable=false
*.go linguist-detectable=true
+18
View File
@@ -0,0 +1,18 @@
.idea/
fiber-app.iml
main
/tmp
/node_modules/
*.fiber.gz
#.env
.DS_Store
dump.rdb
#uploads
/storage/
build/
awstats-icon
awstatsicons
icon/
stats/
pnpm-lock.yaml
package-lock.json
+142
View File
@@ -0,0 +1,142 @@
dpl ?= .env
include $(dpl)
export $(shell sed 's/=.*//' $(dpl))
TAG_COMMIT := $(shell git rev-list --abbrev-commit --tags --max-count=1)
TAG := $(shell git describe --abbrev=0 --tags ${TAG_COMMIT} 2>/dev/null || true)
COMMIT := $(shell git rev-parse --short HEAD)
DATE := $(shell git log -1 --format=%cd --date=format:"%Y%m%d%H%M%S")
VERSION := v$(TAG:v%=%)-$(DATE)-$(COMMIT)
BLACK := $(shell tput -Txterm setaf 0)
RED := $(shell tput -Txterm setaf 1)
GREEN := $(shell tput -Txterm setaf 2)
YELLOW := $(shell tput -Txterm setaf 3)
LIGHTPURPLE := $(shell tput -Txterm setaf 4)
PURPLE := $(shell tput -Txterm setaf 5)
BLUE := $(shell tput -Txterm setaf 6)
WHITE := $(shell tput -Txterm setaf 7)
RESET := $(shell tput -Txterm sgr0)
APPLICATION_NAME := $(shell echo $(APP_NAME) | sed -e 's/[^[:alnum:]]/-/g' | tr -s '-' | tr A-Z a-z)
ifneq ($(shell git status --porcelain),)
VERSION := $(VERSION)-dirty
endif
FLAGS := -ldflags "-X github.com/sujit-baniya/fiber-boilerplate/app.Version=$(VERSION)"
BUILD_PATH := $(shell pwd)/build
PID := $(shell lsof -t -i:$(APP_PORT))
RELEASE_PATH := $(BUILD_PATH)/releases
SHARED_PATH := $(BUILD_PATH)/shared
CURRENT_PATH := $(BUILD_PATH)/current
CURRENT_RELEASE := "dev"
PREVIOUS_RELEASE := "dev"
ifneq ("$(wildcard $(CURRENT_PATH)/CURRENT-RELEASE)","")
CURRENT_RELEASE := $(shell cat $(CURRENT_PATH)/CURRENT-RELEASE)
endif
ifneq ("$(wildcard $(CURRENT_PATH)/PREVIOUS-RELEASE)","")
PREVIOUS_RELEASE := $(shell cat $(CURRENT_PATH)/PREVIOUS-RELEASE)
endif
ROLLBACK_RELEASE := $(RELEASE_PATH)/$(RELEASE_TAG)
LATEST_RELEASE := $(APPLICATION_NAME)-$(VERSION)
LATEST_RELEASE_PATH := $(RELEASE_PATH)/$(LATEST_RELEASE)
create-folder:
$(info $(GREEN)Create Release Folder: $(LATEST_RELEASE)$(RESET))
$(shell mkdir -p $(RELEASE_PATH)/$(LATEST_RELEASE))
$(shell mkdir -p $(SHARED_PATH)/$(STORAGE_PATH))
$(shell mkdir -p $(SHARED_PATH)/$(UPLOAD_PATH))
git-stash:
$(info $(GREEN)Stashing current changes$(RESET))
cd $(LATEST_RELEASE_PATH) && git stash
git-checkout:
$(info $(GREEN)Checkingout Master branch$(RESET))
cd $(LATEST_RELEASE_PATH) && git checkout master && git pull origin master
git-push:
$(info $(GREEN)Adding all changed files and push $(RESET))
cd $(LATEST_RELEASE_PATH) && git add . && git commit -m $(COMMIT_MESSAGE) && git push origin master
dev-push:
$(info $(GREEN)Adding all changed files and push for dev $(RESET))
git add . && git commit -m "$(COMMIT_MESSAGE)" && git push origin master
build-app:
$(info $(GREEN)Building the application: $(APPLICATION_NAME)$(RESET))
$(shell go build $(FLAGS) -o $(RELEASE_PATH)/$(LATEST_RELEASE)/$(APPLICATION_NAME) main.go)
copy-config:
$(info $(GREEN)Copying config, assets and .env file$(RESET))
$(shell cp .env $(RELEASE_PATH)/$(LATEST_RELEASE)/ && \
cp config.yml $(RELEASE_PATH)/$(LATEST_RELEASE)/ && \
cp -R assets $(RELEASE_PATH)/$(LATEST_RELEASE)/ \
)
install-fe-dependencies:
$(info $(GREEN)Installing Frontend dependencies$(RESET))
$(shell yarn install >/dev/null)
compile-fe:
$(info $(GREEN)Compiling Frontend assets$(RESET))
$(shell yarn install >/dev/null && \
yarn run prod >/dev/null || true \
)
copy-assets:
$(info $(GREEN)Copying Assets$(RESET))
$(shell cp -R public $(RELEASE_PATH)/$(LATEST_RELEASE)/ && \
cp -R resources $(RELEASE_PATH)/$(LATEST_RELEASE)/ \
)
create-symlink:
$(info $(GREEN)Creating Current folder symlink$(RESET))
$(shell ln -snf $(SHARED_PATH)/$(STORAGE_PATH) $(RELEASE_PATH)/$(LATEST_RELEASE)/$(STORAGE_PATH))
$(shell ln -snf $(SHARED_PATH)/$(UPLOAD_PATH) $(RELEASE_PATH)/$(LATEST_RELEASE)/$(UPLOAD_PATH))
$(shell ln -snf $(RELEASE_PATH)/$(LATEST_RELEASE) $(CURRENT_PATH))
$(shell echo $(CURRENT_RELEASE) > $(CURRENT_PATH)/PREVIOUS-RELEASE)
$(shell echo $(LATEST_RELEASE_PATH) > $(CURRENT_PATH)/CURRENT-RELEASE)
migrate:
$(info $(GREEN)Starting migrating$(RESET))
cd $(CURRENT_PATH) && ./$(APPLICATION_NAME) --migrate
build: create-folder git-checkout build-app copy-config copy-assets create-symlink migrate
deploy: build restart
push: install-fe-dependencies compile-fe dev-push
start:
$(info $(GREEN)Starting application$(RESET))
cd $(CURRENT_PATH) && ./$(APPLICATION_NAME) </dev/null &>/dev/null &
kill:
ifneq ($(PID),)
$(info $(RED)Stopping application on port $(APP_PORT)$(RESET))
kill -9 $(PID)
else
$(info $(YELLOW)Application not found on port $(APP_PORT)$(RESET))
endif
restart: kill start
rollback:
ifneq ($(PREVIOUS_RELEASE),)
$(info Rolling Back to Previous Release: $(PREVIOUS_RELEASE))
$(shell ln -snf $(PREVIOUS_RELEASE) $(CURRENT_PATH))
endif
rollback-to:
ifneq ($(wildcard $(ROLLBACK_RELEASE)),)
$(info Rolling Back to Release: $(ROLLBACK_RELEASE))
$(shell ln -snf $(ROLLBACK_RELEASE) $(CURRENT_PATH))
endif
run:
go run $(FLAGS) main.go
install:
go install $(FLAGS)
+42
View File
@@ -0,0 +1,42 @@
# SISTEMA DE WEBSITE
Este sistema ha sido desarrollado por U-Site para Gases del Oriente con el propósito de optimizar la gestión administrativa, mejorar la experiencia del usuario y facilitar el acceso a información clave. Está diseñado para centralizar la administración de contenidos web, trámites virtuales y configuraciones del sistema, asegurando eficiencia, seguridad y personalización según las necesidades de la organización y sus usuarios.
## Descripción
El software permite crear una plataforma moderna y segura que optimiza la experiencia del usuario y asegura la protección de datos. Ofrece una página web con un diseño atractivo y funcional, adaptado a diversos dispositivos y navegadores, mientras que la oficina virtual proporciona herramientas colaborativas y de comunicación para la gestión interna. Entre sus principales funcionalidades, incluye una interfaz intuitiva, medidas de seguridad avanzadas, y una experiencia optimizada para dispositivos móviles y de escritorio. Además, ofrece soporte continuo y mantenimiento para asegurar el buen funcionamiento de la plataforma, mejorando la seguridad cibernética y reforzando la presencia digital de GASES DEL ORIENTE S.A E.S.P.
## Requisitos del Sistema
- Go - Fiber
- OBDC para SQLServer, Postgres, Informix
## Instalación
1. Clona el repositorio de GitHub: `git clone https://github.com/lizandrogd/gases.git`
2. Accede al directorio del proyecto: `cd gases`
3. Instala las dependencias de go: `go mod tidy`
## Uso
1. Inicia el servidor GO: `go run main.go`
2. Accede al sistema desde tu navegador web: [http://localhost:8084](http://localhost:8084)
3. Utiliza las funcionalidades proporcionadas por el sistema según tus necesidades.
## Contribución
Si deseas contribuir al proyecto, sigue estos pasos:
1. Haz un fork del repositorio.
2. Crea una nueva rama (`git checkout -b feature/nueva-funcionalidad`).
3. Realiza tus cambios y haz commit (`git commit -am 'Añadir nueva funcionalidad'`).
4. Sube los cambios a tu repositorio remoto (`git push origin feature/nueva-funcionalidad`).
5. Crea un nuevo Pull Request.
## Licencia
Este proyecto está licenciado bajo la Licencia MIT.
## Contacto
Para cualquier consulta o sugerencia, no dudes en contactar al equipo de u-site en [info@u-site.app](mailto:info@u-site.app).
+86
View File
@@ -0,0 +1,86 @@
package app
import (
"regexp"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/etag"
"github.com/gofiber/fiber/v2/middleware/pprof"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/sirupsen/logrus"
"github.com/sujit-baniya/fiber-boilerplate/config"
)
var Http *config.AppConfig
var Version = "v1.0"
func Load(configFile string) {
Http = &config.AppConfig{ConfigFile: configFile}
Http.Setup()
LoadBuiltInMiddlewares(Http)
}
func LoadBuiltInMiddlewares(app *config.AppConfig) {
app.Server.Use(recover.New())
app.Server.Use(etag.New())
app.Server.Use(compress.New(compress.Config{
Level: 1,
}))
if app.Server.Debug {
app.Server.Use(pprof.New())
}
}
func Location(c *fiber.Ctx) (string, error) {
ip := IP(c)
_, err := Http.GeoIP.GetLocation(ip)
if err != nil {
return "127.0.0.1", err
}
return "127.0.0.1", err
}
var fetchIpFromString = regexp.MustCompile(`(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
var possibleHeaderes = []string{
"X-Original-Forwarded-For",
"X-Forwarded-For",
"X-Real-Ip",
"X-Client-Ip",
"Forwarded-For",
"Forwarded",
"Remote-Addr",
"Client-Ip",
"CF-Connecting-IP",
}
// determine user ip
func IP(c *fiber.Ctx) string {
headerValue := []byte{}
if Http.Server.Config().ProxyHeader == "*" {
for _, headerName := range possibleHeaderes {
headerValue = c.Request().Header.Peek(headerName)
if len(headerValue) > 3 {
return string(fetchIpFromString.Find(headerValue))
}
}
}
headerValue = []byte(c.IP())
if len(headerValue) <= 3 {
headerValue = []byte("0.0.0.0")
}
// find ip address in string
return string(fetchIpFromString.Find(headerValue))
}
var Logger *logrus.Logger
func InitLogger() {
Logger = logrus.New()
Logger.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
Logger.SetLevel(logrus.InfoLevel)
}
+14
View File
@@ -0,0 +1,14 @@
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
+80
View File
@@ -0,0 +1,80 @@
database:
drivers:
mysql: &mysql
driver: mysql
host: localhost
username: root
password: root
db_name: casbin
port: 3306
postgres: &postgres
driver: postgres
host: localhost
username: postgres
password: postgres
port: 5432
db_name: casbin
default: *postgres
server:
name: "iSend.to"
host: localhost
port: 8080
redis:
instances:
redis: &redis
driver: redis
name: redis
host: "localhost"
port: 6379
db: 0
default: *redis
cache: *redis
session: *redis
storage: *redis
queue: *redis
mail:
host:
port:
username:
password:
encryption: tls
from_address: "itsursujit@gmail.com"
from_name: "Sujit Baniya"
token:
app_jwt_secret: SECRET_APP
api_jwt_secret: SECRET_API
expires_in: 3600
jwt:
app:
secret: SECRET_APP
expire: 3600
api:
secret: SECRET_API
expire: 3600
template:
path: "resources/view"
extension: ".html"
log:
timefield: "timestamp"
timeformat: "2006-01-02 15:04:05"
graylog: &graylog
host: localhost
port: 12201
file: &file
path: "storage/logs"
timeformat: "2006-01-02"
console: &console
level: "error"
show: false
info: *file
warn: *file
error: *file
monitor: *graylog
+96
View File
@@ -0,0 +1,96 @@
database:
drivers:
mysql: &mysql
driver: mysql
host: localhost
username: root
password: root
db_name: casbin
port: 3306
postgres: &postgres
driver: postgres
host: localhost
username: postgres
password: postgres
port: 5432
db_name: casbin
sqlserver: &sqlserver
driver: sqlserver
host: localhost
username: sa # Cambia esto según tu configuración
password: your_password # Cambia esto según tu configuración
db_name: casbin
port: 1433
sqlite: &sqlite
driver: sqlite
db_name: "data.db" # Nombre del archivo de la base de datos SQLite
sqlserver: *sqlite # Cambia esto si quieres usar otra base de datos como predeterminada
server: &server
name: "USITE "
host: localhost
port: 8084
profiler:
enabled: false
server: "http://localhost:4040"
# Elimina las configuraciones de Redis
# cache: *redis
# session: *redis
# storage: *redis
# queue: *redis
mail:
host:
port:
username:
password:
encryption: tls
from_address: ""
from_name: ""
token:
app_jwt_secret: SECRET_APP
api_jwt_secret: SECRET_API
expires_in: 3600
jwt:
app:
secret: SECRET_APP
expire: 3600
api:
secret: SECRET_API
expire: 3600
template:
path: "resources/view"
extension: ".html"
log:
timefield: "timestamp"
timeformat: "2006-01-02 15:04:05"
graylog: &graylog
host: localhost
port: 12201
file: &file
path: "storage/logs"
timeformat: "2006-01-02"
console: &console
level: "error"
show: false
info: *file
warn: *file
error: *file
monitor: *graylog
shortlink:
link_length: 8
server: *server
enable_csp: true
link_type: l
spam:
train_file: "spam.csv"
auth:
type: "simple"
+58
View File
@@ -0,0 +1,58 @@
package config
import (
"fmt"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
type AuthConfig struct {
*gormadapter.Adapter
Type string `yaml:"type" env:"AUTH_TYPE" env-default:"simple"`
Casbin *Casbin
Enforcer *casbin.Enforcer
}
func (d *AuthConfig) Setup(db *gorm.DB, file string) {
adapter, err := gormadapter.NewAdapterByDB(db)
if err != nil {
panic(fmt.Sprintf("failed to initialize casbin adapter: %v", err))
}
d.Adapter = adapter
enforcer, err := casbin.NewEnforcer(file)
if err != nil {
panic(err)
}
enforcer.SetAdapter(adapter)
err = enforcer.LoadPolicy()
if err != nil {
panic(err)
}
d.Enforcer = enforcer
authConf := CasbinAuthConfig{
Enforcer: d.Enforcer,
PolicyAdapter: d.Adapter,
Lookup: func(ctx *fiber.Ctx) string {
userId := ctx.Locals("user_id")
if userId != nil {
return userId.(string)
}
return ""
},
Unauthorized: func(c *fiber.Ctx) error {
var err fiber.Error
err.Code = fiber.StatusUnauthorized
return CustomErrorHandler(c, &err)
},
Forbidden: func(c *fiber.Ctx) error {
var err fiber.Error
err.Code = fiber.StatusForbidden
return CustomErrorHandler(c, &err)
},
}
d.Casbin = CasbinAuth(authConf)
}
+19
View File
@@ -0,0 +1,19 @@
package config
// CacheConfig es la configuración para el almacenamiento en caché
type CacheConfig struct {
Driver string `yaml:"driver" env:"CACHE_DRIVER"`
Name string `yaml:"name" env:"CACHE_NAME"`
}
// Setup inicializa el almacenamiento en caché
func (c *CacheConfig) Setup() {
switch c.Driver {
case "memory":
// Aquí puedes inicializar un almacenamiento en memoria si es necesario
// Por ejemplo, utilizando un mapa o una biblioteca específica para el almacenamiento en memoria.
default:
// Otras configuraciones de almacenamiento en caché
// Puedes agregar lógica para otros controladores aquí si los usas
}
}
+288
View File
@@ -0,0 +1,288 @@
package config
import (
"strings"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"github.com/gofiber/fiber/v2"
)
// Config holds the configuration for the middleware
type CasbinAuthConfig struct {
// ModelFilePath is path to model file for Casbin.
// Optional. Default: "./model.conf".
Enforcer *casbin.Enforcer
// PolicyAdapter is an interface for different persistent providers.
// Optional. Default: fileadapter.NewAdapter("./policy.csv").
PolicyAdapter *gormadapter.Adapter
// Lookup is a function that is used to look up current subject.
// An empty string is considered as unauthenticated user.
// Optional. Default: func(c *fiber.Ctx) string { return "" }
Lookup func(*fiber.Ctx) string
// Unauthorized defines the response body for unauthorized responses.
// Optional. Default: func(c *fiber.Ctx) error { return c.SendStatus(401) }
Unauthorized fiber.Handler
// Forbidden defines the response body for forbidden responses.
// Optional. Default: func(c *fiber.Ctx) error { return c.SendStatus(403) }
Forbidden fiber.Handler
}
// Casbin ...
type Casbin struct {
config CasbinAuthConfig
enforcer *casbin.Enforcer
}
// New creates an authorization middleware for use in Fiber
func CasbinAuth(config ...CasbinAuthConfig) *Casbin {
var cfg CasbinAuthConfig
if len(config) > 0 {
cfg = config[0]
}
if cfg.Lookup == nil {
cfg.Lookup = func(c *fiber.Ctx) string { return "" }
}
if cfg.Unauthorized == nil {
cfg.Unauthorized = func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusUnauthorized)
}
}
if cfg.Forbidden == nil {
cfg.Forbidden = func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusForbidden)
}
}
return &Casbin{
config: cfg,
enforcer: cfg.Enforcer,
}
}
type validationRule int
const (
matchAll validationRule = iota
atLeastOne
)
// MatchAll is an option that defines all permissions
// or roles should match the user.
var MatchAll = func(o *Options) {
o.ValidationRule = matchAll
}
// AtLeastOne is an option that defines at least on of
// permissions or roles should match to pass.
var AtLeastOne = func(o *Options) {
o.ValidationRule = atLeastOne
}
// PermissionParserFunc is used for parsing the permission
// to extract object and action usually
type PermissionParserFunc func(str string) []string
func permissionParserWithSeperator(sep string) PermissionParserFunc {
return func(str string) []string {
return strings.Split(str, sep)
}
}
// PermissionParserWithSeperator is an option that parses permission
// with seperators
func PermissionParserWithSeperator(sep string) func(o *Options) {
return func(o *Options) {
o.PermissionParser = permissionParserWithSeperator(sep)
}
}
// Options holds options of middleware
type Options struct {
ValidationRule validationRule
PermissionParser PermissionParserFunc
}
// RequiresPermissions tries to find the current subject and determine if the
// subject has the required permissions according to predefined Casbin policies.
func (cm *Casbin) RequiresPermissions(permissions []string, opts ...func(o *Options)) fiber.Handler {
options := &Options{
ValidationRule: matchAll,
PermissionParser: permissionParserWithSeperator(":"),
}
for _, o := range opts {
o(options)
}
return func(c *fiber.Ctx) error {
if len(permissions) == 0 {
return c.Next()
}
sub := cm.config.Lookup(c)
if sub == "" {
return cm.config.Unauthorized(c)
}
if options.ValidationRule == matchAll {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.enforcer.Enforce(convertToInterface(vals)...); err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
} else if !ok {
return cm.config.Forbidden(c)
}
}
return c.Next()
} else if options.ValidationRule == atLeastOne {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.enforcer.Enforce(convertToInterface(vals)...); err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
} else if ok {
return c.Next()
}
}
return cm.config.Forbidden(c)
}
return c.Next()
}
}
// RequiresPermissions tries to find the current subject and determine if the
// subject has the required permissions according to predefined Casbin policies.
func (cm *Casbin) Can(sub string, perm string, opts ...func(o *Options)) bool {
permissions := []string{perm}
options := &Options{
ValidationRule: matchAll,
PermissionParser: permissionParserWithSeperator(":"),
}
for _, o := range opts {
o(options)
}
if len(permissions) == 0 {
return false
}
if sub == "" {
return false
}
if options.ValidationRule == matchAll {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.enforcer.Enforce(convertToInterface(vals)...); err != nil {
return false
} else if !ok {
return false
}
}
return true
} else if options.ValidationRule == atLeastOne {
for _, permission := range permissions {
vals := append([]string{sub}, options.PermissionParser(permission)...)
if ok, err := cm.enforcer.Enforce(convertToInterface(vals)...); err != nil {
return false
} else if ok {
return true
}
}
return false
}
return false
}
// RoutePermission tries to find the current subject and determine if the
// subject has the required permissions according to predefined Casbin policies.
// This method uses http Path and Method as object and action.
func (cm *Casbin) RoutePermission() fiber.Handler {
return func(c *fiber.Ctx) error {
sub := cm.config.Lookup(c)
if sub == "" {
return cm.config.Unauthorized(c)
}
if ok, err := cm.enforcer.Enforce(sub, c.Path(), c.Method()); err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
} else if !ok {
return cm.config.Forbidden(c)
}
return c.Next()
}
}
// RequiresRoles tries to find the current subject and determine if the
// subject has the required roles according to predefined Casbin policies.
func (cm *Casbin) RequiresRoles(roles []string, opts ...func(o *Options)) fiber.Handler {
options := &Options{
ValidationRule: matchAll,
PermissionParser: permissionParserWithSeperator(":"),
}
for _, o := range opts {
o(options)
}
return func(c *fiber.Ctx) error {
if len(roles) == 0 {
return c.Next()
}
sub := cm.config.Lookup(c)
if sub == "" {
return cm.config.Unauthorized(c)
}
userRoles, err := cm.enforcer.GetRolesForUser(sub)
if err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
if options.ValidationRule == matchAll {
for _, role := range roles {
if !contains(userRoles, role) {
return cm.config.Forbidden(c)
}
}
return c.Next()
} else if options.ValidationRule == atLeastOne {
for _, role := range roles {
if contains(userRoles, role) {
return c.Next()
}
}
return cm.config.Forbidden(c)
}
return c.Next()
}
}
func contains(s []string, v string) bool {
for _, vv := range s {
if vv == v {
return true
}
}
return false
}
func convertToInterface(arr []string) []interface{} {
in := make([]interface{}, 0)
for _, a := range arr {
in = append(in, a)
}
return in
}
+110
View File
@@ -0,0 +1,110 @@
package config
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/gofiber/fiber/v2"
"github.com/ilyakaznacheev/cleanenv"
"github.com/joho/godotenv"
"github.com/oarkflow/log"
"github.com/sujit-baniya/flash"
"github.com/sujit-baniya/ip"
)
// Config is a application configuration structure
type AppConfig struct {
Auth AuthConfig `yaml:"auth"`
Mail Mail `yaml:"mail"`
Hash Hash
View ViewConfig `yaml:"view"`
Cache CacheConfig `yaml:"cache"`
Database DatabaseConfig `yaml:"database"`
Session SessionConfig `yaml:"session"`
Queue QueueConfig `yaml:"queue"`
JwtSecrets JwtSecrets `yaml:"jwt"`
Storage StorageConfig `yaml:"storage"`
Server ServerConfig `yaml:"server"`
Log LogConfig `yaml:"log"`
Token Token `yaml:"token"`
Profiler ProfilerConfig `yaml:"profiler"`
Flash *flash.Flash
GeoIP *ip.GeoIpDB
ConfigFile string
}
func (cfg *AppConfig) Setup() {
err := godotenv.Load()
// read configuration from the file and environment variables
if err = cleanenv.ReadConfig(cfg.ConfigFile, cfg); err != nil {
fmt.Println(err)
os.Exit(2)
}
cfg.Server.LoadPath()
cfg.View.Load(cfg.Server.Path)
cfg.Mail.View = &cfg.View
cfg.Server.TemplateEngine = cfg.View.Template.TemplateEngine
cfg.Server.Setup()
cfg.LoadComponents()
if cfg.Auth.Type == "casbin" {
modelFile := filepath.Join(cfg.Server.AssetPath, "rbac_model.conf")
cfg.Auth.Setup(cfg.Database.DB, modelFile)
}
path := MakeDir(filepath.Join(cfg.Server.AssetPath, "GeoLite2-City.mmdb"))
cfg.GeoIP = ip.NewGeoIpDB(path)
}
func (cfg *AppConfig) PrepareLog() {
writer := &log.MultiWriter{}
path := MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.InfoLevel.Path))
writer.InfoWriter = &log.FileWriter{Filename: filepath.Join(path, "INFO.log"), EnsureFolder: true, TimeFormat: cfg.Log.InfoLevel.TimeFormat}
path = MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.WarnLevel.Path))
writer.WarnWriter = &log.FileWriter{Filename: filepath.Join(cfg.Server.Path, cfg.Log.WarnLevel.Path, "WARN.log"), EnsureFolder: true, TimeFormat: cfg.Log.WarnLevel.TimeFormat}
path = MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.ErrorLevel.Path))
writer.ErrorWriter = &log.FileWriter{Filename: filepath.Join(cfg.Server.Path, cfg.Log.ErrorLevel.Path, "ERROR.log"), EnsureFolder: true, TimeFormat: cfg.Log.ErrorLevel.TimeFormat}
if cfg.Log.ConsoleLog.Show {
writer.ConsoleWriter = &log.IOWriter{Writer: os.Stderr}
writer.ConsoleLevel = log.InfoLevel
}
log.DefaultLogger = log.Logger{
TimeField: cfg.Log.TimeField,
TimeFormat: cfg.Log.TimeFormat,
Writer: writer,
}
}
func (cfg *AppConfig) Route404() {
cfg.Server.Use(func(c *fiber.Ctx) error {
return c.Status(fiber.StatusNotFound).SendString("Page not found")
})
}
func (cfg *AppConfig) LoadComponents() {
cfg.Flash = flash.New(flash.Config{
Name: "fiber",
HTTPOnly: true,
})
cfg.LoadStatic()
cfg.PrepareLog()
_ = cfg.Database.Setup()
_ = cfg.Session.Setup()
cfg.Cache.Setup()
cfg.Storage.Setup()
}
func (cfg *AppConfig) LoadStatic() {
cfg.Server.Static("/websocket", "./resources/views/websocket.html")
cfg.Server.Static("/", filepath.Join(cfg.Server.Path, cfg.Server.PublicPath), fiber.Static{
Compress: true,
ByteRange: true,
CacheDuration: 24 * time.Hour,
})
}
func (cfg *AppConfig) LoadSpamDetectionEngine() {
}
+161
View File
@@ -0,0 +1,161 @@
package config
import (
"context"
"fmt"
"time"
"github.com/oarkflow/log"
"gorm.io/gorm/logger"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlserver" // SQL Server driver
"gorm.io/gorm"
"gorm.io/plugin/dbresolver"
)
type DatabaseDriver struct {
Driver string `yaml:"driver" env:"DB_DRIVER"`
Host string `yaml:"host" env:"DB_HOST"`
Username string `yaml:"username" env:"DB_USER"`
Password string `yaml:"password" env:"DB_PASS"`
DBName string `yaml:"db_name" env:"DB_NAME"`
Port int `yaml:"port" env:"DB_PORT"`
Connections int `yaml:"connections" env:"DB_CONNECTIONS"`
}
type DatabaseConfig struct {
*gorm.DB
Drivers map[string]DatabaseDriver `yaml:"drivers"`
Default DatabaseDriver `yaml:"default" env:"DEFAULT_DB_DRIVER"`
}
func (d *DatabaseConfig) Setup() error {
var err error
connectionString := ""
if d.DB != nil {
return nil
}
gormLogger := New(&log.DefaultLogger, logger.Config{
LogLevel: 0,
}, false)
newLogger := gormLogger.LogMode(logger.Info)
switch d.Default.Driver {
case "postgres":
connectionString = fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s", d.Default.Host, d.Default.Port, d.Default.Username, d.Default.DBName, d.Default.Password)
d.DB, err = gorm.Open(postgres.Open(connectionString), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: newLogger,
})
case "mysql":
connectionString = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", d.Default.Username, d.Default.Password, d.Default.Host, d.Default.Port, d.Default.DBName)
d.DB, err = gorm.Open(mysql.Open(connectionString), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: newLogger,
})
case "sqlserver":
connectionString = fmt.Sprintf(
"sqlserver://%s:%s@%s:%d?database=%s&charset=utf8mb4",
d.Default.Username,
d.Default.Password,
d.Default.Host,
d.Default.Port,
d.Default.DBName,
)
d.DB, err = gorm.Open(sqlserver.Open(connectionString), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: newLogger,
})
default:
return fmt.Errorf("unsupported database driver: %s", d.Default.Driver)
}
if err != nil {
fmt.Println(d.Default)
panic(err)
}
d.DB.Use(
dbresolver.Register(dbresolver.Config{}).
SetConnMaxLifetime(24 * time.Hour).
SetMaxIdleConns(100).
SetMaxOpenConns(100),
)
return nil
}
func New(logger *log.Logger, config logger.Config, slient bool) logger.Interface {
return &gormLogger{
Log: logger,
Config: config,
Slient: slient,
}
}
type gormLogger struct {
Log *log.Logger
Config logger.Config
Slient bool
}
func (l *gormLogger) LogMode(level logger.LogLevel) logger.Interface {
var newLogger = gormLogger{Log: l.Log}
switch level {
case logger.Silent:
newLogger.Slient = true
case logger.Error:
newLogger.Log.SetLevel(log.ErrorLevel)
case logger.Warn:
newLogger.Log.SetLevel(log.WarnLevel)
case logger.Info:
newLogger.Log.SetLevel(log.InfoLevel)
}
return &newLogger
}
func (l *gormLogger) Info(ctx context.Context, format string, args ...interface{}) {
l.Log.Info().Msgf(format, args...)
}
func (l *gormLogger) Warn(ctx context.Context, format string, args ...interface{}) {
l.Log.Warn().Msgf(format, args...)
}
func (l *gormLogger) Error(ctx context.Context, format string, args ...interface{}) {
l.Log.Error().Msgf(format, args...)
}
func (l *gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.Slient {
return
}
elapsed := time.Since(begin)
switch {
case err != nil && l.Log.Level >= log.ErrorLevel:
sql, rows := fc()
if rows == -1 {
l.Log.Error().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Msg("")
} else {
l.Log.Error().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Int64("rows", rows).Msg("")
}
case elapsed > l.Config.SlowThreshold && l.Config.SlowThreshold != 0 && l.Log.Level >= log.WarnLevel:
sql, rows := fc()
if rows == -1 {
l.Log.Warn().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Msgf("SLOW SQL >= %v", l.Config.SlowThreshold)
} else {
l.Log.Warn().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Int64("rows", rows).Msgf("SLOW SQL >= %v", l.Config.SlowThreshold)
}
case l.Log.Level == log.InfoLevel:
sql, rows := fc()
if rows == -1 {
l.Log.Info().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Msg("")
} else {
l.Log.Info().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Int64("rows", rows).Msg("")
}
}
}
+24
View File
@@ -0,0 +1,24 @@
package config
import (
"github.com/alexedwards/argon2id"
)
type Hash struct {
// Argon2id configuration
Params *argon2id.Params
}
func (d *Hash) Create(password string) (hash string, err error) {
if d.Params == nil {
d.Params = argon2id.DefaultParams
}
return argon2id.CreateHash(password, d.Params)
}
func (d *Hash) Match(password string, hash string) (match bool, err error) {
if d.Params == nil {
d.Params = argon2id.DefaultParams
}
return argon2id.ComparePasswordAndHash(password, hash)
}
+11
View File
@@ -0,0 +1,11 @@
package config
type JwtConfig struct {
Secret string `yaml:"secret"`
Expire string `yaml:"expire"`
}
type JwtSecrets struct {
App JwtConfig `yaml:"app"`
Api JwtConfig `yaml:"api"`
}
+26
View File
@@ -0,0 +1,26 @@
package config
type Graylog struct {
Host string `mapstructure:"GRAYLOG_HOST" yaml:"host" env:"GRAYLOG_HOST" env-default:"localhost"`
Port string `mapstructure:"GRAYLOG_PORT" yaml:"port" env:"GRAYLOG_PORT" env-default:"12201"`
}
type FileLog struct {
Path string `mapstructure:"LOG_PATH" yaml:"path" env-default:"storage/logs"`
TimeFormat string `mapstructure:"LOG_TIME_FORMAT" yaml:"timeformat" env-default:"2006-01-02"`
}
type ConsoleLog struct {
Level string `mapstructure:"CONSOLE_LOG_LEVEL" yaml:"level" env-default:"info"`
Show bool `mapstructure:"CONSOLE_LOG_SHOW" yaml:"show" env-default:"false"`
}
type LogConfig struct {
TimeField string `yaml:"timefield"`
TimeFormat string `yaml:"timeformat"`
ConsoleLog ConsoleLog `yaml:"console"`
Monitor Graylog `yaml:"monitor"`
InfoLevel FileLog `yaml:"info"`
WarnLevel FileLog `yaml:"warn"`
ErrorLevel FileLog `yaml:"error"`
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"fmt"
"log"
"os"
"time"
"github.com/gofiber/fiber/v2"
"github.com/valyala/bytebufferpool"
mail "github.com/xhit/go-simple-mail/v2"
)
type Mail struct {
*mail.SMTPServer
*mail.SMTPClient
Host string `mapstructure:"MAIL_HOST" yaml:"host" env:"MAIL_HOST" env-default:"smtp-mail.outlook.com"`
Username string `mapstructure:"MAIL_USERNAME" yaml:"username" env:"MAIL_USERNAME" env-default:"ovirtual@gasesdeloriente.com.co"`
Password string `mapstructure:"MAIL_PASSWORD" yaml:"password" env:"MAIL_PASSWORD" env-default:"Gases2023**"`
Encryption string `mapstructure:"MAIL_ENCRYPTION" yaml:"encryption" env:"MAIL_ENCRYPTION" env-default:"tls"`
FromAddress string `mapstructure:"MAIL_FROM_ADDRESS" yaml:"from_address" env:"MAIL_FROM_ADDRESS" env-default:"ovirtual@gasesdeloriente.com.co"`
FromName string `mapstructure:"MAIL_FROM_NAME" yaml:"from_name" env:"MAIL_FROM_NAME" env-default:"Gases"`
View *ViewConfig
Port int `mapstructure:"MAIL_PORT" yaml:"port" env:"MAIL_PORT" env-default:"587"` // Cambié a 465 para SSL
}
// Enviar correo
func (m *Mail) Send(to string, subject string, body string, ccEmails ...string) error {
// Configurar el cliente SMTP antes de enviar cada correo
if m.SMTPServer == nil {
m.SetupMailer()
}
// Obtener el remitente desde el archivo .env
from := os.Getenv("MAIL_FROM_ADDRESS")
if from == "" {
log.Println("Error: MAIL_FROM_ADDRESS no está configurado en el archivo .env")
return fmt.Errorf("MAIL_FROM_ADDRESS no está configurado")
}
// Crear nuevo mensaje de correo
email := mail.NewMSG()
email.SetFrom(from).
AddTo(to).
SetSubject(subject).
SetBody(mail.TextHTML, body)
// Crear un nuevo cliente SMTP
client, err := m.SMTPServer.Connect()
if err != nil {
log.Printf("Error conectando al servidor SMTP: %s", err)
return err
}
// Enviar el correo usando el cliente SMTP nuevo
err = email.Send(client)
if err != nil {
log.Printf("Error enviando el correo: %s", err)
return err
}
log.Println("Correo enviado con éxito")
return nil
}
// Preparar HTML para el cuerpo del correo
func (m *Mail) PrepareHtml(view string, body fiber.Map) string {
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)
// app.Settings.Views.Render (asegúrate de que el motor de plantillas esté configurado)
if err := m.View.Template.TemplateEngine.Render(buf, view, body, "layouts/email"); err != nil {
log.Printf("Error rendering HTML: %s", err)
}
return buf.String()
}
// Configuración inicial del cliente SMTP
func (m *Mail) SetupMailer() {
var err error
m.SMTPServer = mail.NewSMTPClient()
m.SMTPServer.Host = m.Host
m.SMTPServer.Port = m.Port
m.SMTPServer.Username = m.Username
m.SMTPServer.Password = m.Password
if m.Encryption == "tls" {
m.SMTPServer.Encryption = mail.EncryptionTLS
} else {
m.SMTPServer.Encryption = mail.EncryptionSSL
}
// Configuración de tiempo y conexión
m.SMTPServer.KeepAlive = false
m.SMTPServer.ConnectTimeout = 10 * time.Second
m.SMTPServer.SendTimeout = 10 * time.Second
// Conectar al servidor SMTP
m.SMTPClient, err = m.SMTPServer.Connect()
if err != nil {
log.Printf("Error conectando al servidor SMTP: %s", err)
}
}
+6
View File
@@ -0,0 +1,6 @@
package config
type ProfilerConfig struct {
Server string `yaml:"server" env:"PROFILER_SERVER" env-default:"http://localhost:4040"`
Enabled bool `yaml:"enabled" env:"PROFILER_ENABLED" env-default:"false"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
type QueueConfig struct {
Driver string `yaml:"driver" env:"CACHE_DRIVER"`
Name string `yaml:"name" env:"CACHE_NAME"`
Host string `yaml:"host" env:"CACHE_HOST"`
Port string `yaml:"port" env:"CACHE_PORT"`
DB string `yaml:"db" env:"CACHE_DB"`
}
+1
View File
@@ -0,0 +1 @@
package config
+349
View File
@@ -0,0 +1,349 @@
package config
import (
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"github.com/pkg/errors"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/oarkflow/log"
)
type ServerConfig struct {
*fiber.App
TemplateEngine *html.Engine
Name string `mapstructure:"APP_NAME" yaml:"name" env:"APP_NAME" env-default:"iSend.to"`
Version string `mapstructure:"APP_VERSION" yaml:"version" env:"APP_VERSION" env-default:"dev"`
Mode string `mapstructure:"APP_MODE" yaml:"mode" env:"APP_MODE" env-default:"app"`
Env string `mapstructure:"APP_ENV" yaml:"env" env:"APP_ENV" env-default:"dev"`
Key string `mapstructure:"APP_KEY" yaml:"key" env:"APP_KEY" env-default:"1894cde6c936a294a478cff0a9227fd276d86df6573b51af5dc59c9064edf426"`
Url string `mapstructure:"APP_URL" yaml:"url" env:"APP_URL" env-default:"http://localhost"`
Host string `mapstructure:"APP_HOST" yaml:"host" env:"APP_HOST" env-default:"localhost"`
Port string `mapstructure:"APP_PORT" yaml:"port" env:"APP_PORT" env-default:"8080"`
Path string `mapstructure:"APP_PATH" yaml:"path" env:"APP_PATH"`
ProxyHeader string `mapstructure:"PROXY_HEADER" yaml:"PROXY_HEADER" env:"PROXY_HEADER" env-default:"*"`
AssetPath string `mapstructure:"ASSET_PATH" yaml:"asset_path" env:"ASSET_PATH" env-default:"assets"`
PublicPath string `mapstructure:"PUBLIC_PATH" yaml:"public_path" env:"PUBLIC_PATH" env-default:"public"`
UploadPath string `mapstructure:"UPLOAD_PATH" yaml:"upload_path" env:"UPLOAD_PATH" env-default:"uploads"`
StoragePath string `mapstructure:"STORAGE_PATH" yaml:"storage_path" env:"STORAGE_PATH" env-default:"storage"`
LogPath string `mapstructure:"LOG_PATH" yaml:"log_path" env:"LOG_PATH" env-default:"storage/logs"`
ExecPath bool `mapstructure:"EXEC_PATH" yaml:"exec_path" env:"EXEC_PATH" env-default:"false"`
Debug bool `mapstructure:"APP_DEBUG" yaml:"debug" env:"APP_DEBUG" env-default:"true"`
UploadSize int `mapstructure:"UPLOAD_SIZE" yaml:"upload_size" env:"UPLOAD_SIZE" env-default:"400"`
}
func (s *ServerConfig) LoadPath() {
if s.Url == "" {
s.Url = fmt.Sprintf("http://localhost:%s", s.Port)
}
path, _ := os.Getwd()
if s.ExecPath {
path = getPath()
}
s.Path = path
s.UploadPath = MakeDir(filepath.Join(path, s.UploadPath))
s.AssetPath = MakeDir(filepath.Join(path, s.AssetPath))
s.StoragePath = MakeDir(filepath.Join(path, s.StoragePath))
s.LogPath = MakeDir(filepath.Join(path, s.LogPath))
s.UploadSize = s.UploadSize * 1024 * 1024
}
func (s *ServerConfig) Setup() {
s.App = fiber.New(fiber.Config{
Views: s.TemplateEngine,
Concurrency: 256 * 1024 * 1024,
ServerHeader: s.Name,
BodyLimit: s.UploadSize,
ReduceMemoryUsage: true,
ErrorHandler: CustomErrorHandler,
DisableStartupMessage: true,
ProxyHeader: s.ProxyHeader,
Prefork: true, // Cambia a 'true' para habilitar Preforking
})
}
func (s *ServerConfig) Serve(addr ...string) error {
a := s.Host + ":" + s.Port
if len(addr) != 0 {
a = addr[0]
}
s.startupMessage(a, false, "")
return s.Listen(a)
}
func (s *ServerConfig) ServeWithGraceFullShutdown(addr ...string) error {
a := s.Host + ":" + s.Port
if len(addr) != 0 {
a = addr[0]
}
s.startupMessage(a, false, "")
// Listen from a different goroutine
go func() {
if err := s.Listen(a); err != nil {
log.Fatal().Err(err)
}
}()
c := make(chan os.Signal, 1) // Create channel to signify a signal being sent
signal.Notify(c,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGABRT,
syscall.SIGQUIT,
) // When an interrupt is sent, notify the channel
<-c // This blocks the main thread until an interrupt is received
fmt.Println("I'm shutting down")
return s.Shutdown()
}
func (s *ServerConfig) startupMessage(addr string, tls bool, processIds string) {
// ignore child processes
if fiber.IsChild() {
return
}
var logo string
logo += "%s"
logo += " ┌─────────────────────────────────────────────────────┐\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ │\n"
logo += " │ Handlers %s Processes %s │\n"
logo += " │ Prefork .%s PID ....%s │\n"
logo += " └─────────────────────────────────────────────────────┘"
logo += "%s"
const (
cBlack = "\u001b[90m"
// cRed = "\u001b[91m"
cCyan = "\u001b[96m"
// cGreen = "\u001b[92m"
// cYellow = "\u001b[93m"
// cBlue = "\u001b[94m"
// cMagenta = "\u001b[95m"
// cWhite = "\u001b[97m"
cReset = "\u001b[0m"
)
value := func(s string, width int) string {
pad := width - len(s)
str := ""
for i := 0; i < pad; i++ {
str += "."
}
if s == "Disabled" {
str += " " + s
} else {
str += fmt.Sprintf(" %s%s%s", cCyan, s, cBlack)
}
return str
}
center := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += s
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str) < width {
str += " "
}
return str
}
centerValue := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += fmt.Sprintf("%s%s%s", cCyan, s, cBlack)
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str)-10 < width {
str += " "
}
return str
}
pad := func(s string, width int) (str string) {
toAdd := width - len(s)
str += s
for i := 0; i < toAdd; i++ {
str += " "
}
return
}
host, port := parseAddr(addr)
if host == "" || host == "0.0.0.0" {
host = "127.0.0.1"
}
addr = "http://" + host + ":" + port
if tls {
addr = "https://" + host + ":" + port
}
isPrefork := "Disabled"
if s.Config().Prefork {
isPrefork = "Enabled"
}
procs := strconv.Itoa(runtime.GOMAXPROCS(0))
if !s.Config().Prefork {
procs = "1"
}
routeCount := 0
for _, route := range s.Stack() {
routeCount += len(route)
}
mainLogo := fmt.Sprintf(logo,
cBlack,
centerValue(s.Name+" "+s.Version, 49),
center(addr, 49),
value(strconv.Itoa(routeCount), 14), value(procs, 12),
value(isPrefork, 14), value(strconv.Itoa(os.Getpid()), 14),
cReset,
)
var childPidsLogo string
if s.Config().Prefork {
var childPidsTemplate string
childPidsTemplate += "%s"
childPidsTemplate += " ┌───────────────────────────────────────────────────┐\n%s"
childPidsTemplate += " └───────────────────────────────────────────────────┘"
childPidsTemplate += "%s"
newLine := " │ %s%s%s │"
// Turn the `processIds` variable (in the form ",a,b,c,d,e,f,etc") into a slice of PIDs
var pidSlice []string
for _, v := range strings.Split(processIds, ",") {
if v != "" {
pidSlice = append(pidSlice, v)
}
}
var lines []string
thisLine := "Child PIDs ... "
var itemsOnThisLine []string
addLine := func() {
lines = append(lines,
fmt.Sprintf(
newLine,
cBlack,
thisLine+cCyan+pad(strings.Join(itemsOnThisLine, ", "), 49-len(thisLine)),
cBlack,
),
)
}
for _, pid := range pidSlice {
if len(thisLine+strings.Join(append(itemsOnThisLine, pid), ", ")) > 49 {
addLine()
thisLine = ""
itemsOnThisLine = []string{pid}
} else {
itemsOnThisLine = append(itemsOnThisLine, pid)
}
}
// Add left over items to their own line
if len(itemsOnThisLine) != 0 {
addLine()
}
// Form logo
childPidsLogo = fmt.Sprintf(childPidsTemplate,
cBlack,
strings.Join(lines, "\n")+"\n",
cReset,
)
}
// Combine both the child PID logo and the main Fiber logo
// Pad the shorter logo to the length of the longer one
splitMainLogo := strings.Split(mainLogo, "\n")
splitChildPidsLogo := strings.Split(childPidsLogo, "\n")
mainLen := len(splitMainLogo)
childLen := len(splitChildPidsLogo)
if mainLen > childLen {
diff := mainLen - childLen
for i := 0; i < diff; i++ {
splitChildPidsLogo = append(splitChildPidsLogo, "")
}
} else {
diff := childLen - mainLen
for i := 0; i < diff; i++ {
splitMainLogo = append(splitMainLogo, "")
}
}
// Combine the two logos, line by line
output := "\n"
for i := range splitMainLogo {
output += cBlack + splitMainLogo[i] + " " + splitChildPidsLogo[i] + "\n"
}
out := colorable.NewColorableStdout()
if os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
out = colorable.NewNonColorable(os.Stdout)
}
_, _ = fmt.Fprintln(out, output)
}
func (s *ServerConfig) Stop() {
_ = s.Shutdown()
}
func getPath() string {
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
return exPath
}
func MakeDir(path string) string {
if _, err := os.Stat(path); os.IsNotExist(err) {
_ = os.MkdirAll(path, os.ModePerm)
}
return path
}
func CustomErrorHandler(c *fiber.Ctx, err error) error {
// StatusCode defaults to 500
code := fiber.StatusInternalServerError
//nolint:misspell // Retrieve the custom statuscode if it's an fiber.*Error
if e, ok := err.(*fiber.Error); ok {
code = e.Code
} //nolint:gofmt,wsl
er := errors.WithStack(err)
fmt.Printf("%+v", er)
fmt.Printf("%+v", err)
if c.Is("json") {
return c.Status(code).JSON(err)
}
return c.Status(code).Render(fmt.Sprintf("errors/%d", code), fiber.Map{ //nolint:nolintlint,errcheck
"error": err,
})
}
func parseAddr(raw string) (host, port string) {
if i := strings.LastIndex(raw, ":"); i != -1 {
return raw[:i], raw[i+1:]
}
return raw, ""
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"fmt"
"time"
"github.com/gofiber/session/v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type SessionConfig struct {
Database string `yaml:"database" env:"SESSION_DATABASE"` // Ruta de la base de datos SQLite
*session.Session
}
func (s *SessionConfig) Setup() error {
// Abrir conexión a la base de datos SQLite
db, err := gorm.Open(sqlite.Open(s.Database), &gorm.Config{})
if err != nil {
return fmt.Errorf("failed to connect to the database: %v", err)
}
// Migrar la estructura de la tabla para sesiones
err = db.AutoMigrate(&Session{}) // Define la estructura de la sesión según sea necesario
if err != nil {
return fmt.Errorf("failed to migrate database: %v", err)
}
// Configurar el proveedor de sesiones en memoria
store := session.New() // Usar el proveedor de sesiones en memoria
// Crear una nueva sesión
s.Session = store
return nil
}
// Estructura para las sesiones (ajusta según tus necesidades)
type Session struct {
ID uint `gorm:"primaryKey"`
SessionID string `gorm:"unique"`
Data string `gorm:"type:text"`
CreatedAt time.Time
UpdatedAt time.Time
ExpireAt time.Time
}
+54
View File
@@ -0,0 +1,54 @@
package config
import (
"database/sql"
"log"
"time"
_ "github.com/mattn/go-sqlite3" // Importar el controlador SQLite
)
type StorageConfig struct {
DBFile string `yaml:"db_file" env:"STORAGE_DB_FILE"`
}
// Setup inicializa el almacenamiento utilizando SQLite
func (c *StorageConfig) Setup() (*sql.DB, error) {
db, err := sql.Open("sqlite3", c.DBFile)
if err != nil {
log.Fatalf("Error al conectar a la base de datos SQLite: %v", err)
return nil, err
}
// Crear la tabla si no existe
createTableQuery := `
CREATE TABLE IF NOT EXISTS storage (
key TEXT PRIMARY KEY,
value TEXT,
expire_at INTEGER
);
`
_, err = db.Exec(createTableQuery)
if err != nil {
log.Fatalf("Error al crear la tabla de almacenamiento: %v", err)
return nil, err
}
return db, nil
}
// Función para guardar un valor en el almacenamiento
func (c *StorageConfig) Set(db *sql.DB, key string, value string, expireAt int64) error {
_, err := db.Exec("INSERT OR REPLACE INTO storage (key, value, expire_at) VALUES (?, ?, ?)", key, value, expireAt)
return err
}
// Función para obtener un valor del almacenamiento
func (c *StorageConfig) Get(db *sql.DB, key string) (string, error) {
var value string
err := db.QueryRow("SELECT value FROM storage WHERE key = ? AND (expire_at IS NULL OR expire_at > ?)", key, time.Now().Unix()).Scan(&value)
if err != nil {
return "", err
}
return value, nil
}
+89
View File
@@ -0,0 +1,89 @@
package config
import (
"errors"
"time"
"github.com/form3tech-oss/jwt-go"
"github.com/gofiber/fiber/v2"
)
type Token struct {
Hash string `json:"token"`
Expire int64 `mapstructure:"JWT_EXPIRE" json:"expires_in" yaml:"expires_in"`
AppJwtSecret string `mapstructure:"APP_JWT_SECRET" yaml:"app_jwt_secret"`
ApiJwtSecret string `mapstructure:"API_JWT_SECRET" yaml:"api_jwt_secret"`
}
//CreateToken authenticates the user
func (t *Token) CreateToken(c *fiber.Ctx, userID uint, secret string, expire ...int64) (*Token, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["id"] = userID
if len(expire) > 0 {
t.Expire = expire[0]
} else {
t.Expire = 3600
}
expiresIn := time.Now().Add(time.Duration(t.Expire) * time.Second).Unix()
claims["exp"] = expiresIn
tokenHash, err := token.SignedString([]byte(secret))
if err != nil {
return nil, err
}
c.Cookie(&fiber.Cookie{
Name: "Verify-Rest-Token",
Value: tokenHash,
Secure: false,
HTTPOnly: true,
})
t.Hash = tokenHash
t.Expire = expiresIn
return t, nil
}
//ParseToken returns the users id or error
func (t *Token) ParseToken(c *fiber.Ctx, secret string) (uint, error) {
tokenString := c.Cookies("Verify-Rest-Token")
if tokenString == "" {
return 0, errors.New("Empty auth cookie")
}
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return 0, err
}
//Checks if the token is valid if it is not then it deletes it
err2 := claims.Valid()
if err2 != nil {
t.DeleteToken(c)
return 0, err2
}
return uint(claims["id"].(float64)), nil
}
//DeleteToken deletes the jwt token
func (t *Token) DeleteToken(c *fiber.Ctx) {
c.ClearCookie("Verify-Rest-Token")
}
//RefreshToken refreshes the token
func (t *Token) RefreshToken(c *fiber.Ctx, secret string) (*Token, error) {
u, err := t.ParseToken(c, secret)
if err != nil {
return nil, nil
}
return t.CreateToken(c, u, secret)
}
+42
View File
@@ -0,0 +1,42 @@
package config
import (
"path/filepath"
"github.com/gofiber/template/html"
"github.com/markbates/pkger"
)
// TemplateConfig para la configuración del motor de plantillas
type TemplateConfig struct {
TemplateEngine *html.Engine
Path string `yaml:"path" env-default:"resources/views"`
Extension string `yaml:"extension" env-default:".html"`
}
// ViewConfig para la configuración de vistas
type ViewConfig struct {
Template TemplateConfig `yaml:"template"`
}
// Load carga la configuración de las vistas
func (v *ViewConfig) Load(path string) {
path = MakeDir(filepath.Join(path, v.Template.Path))
v.Template.TemplateEngine = html.NewFileSystem(pkger.Dir(path), v.Template.Extension)
}
// NewDict crea un mapa para usar en las plantillas
func NewDict(data ...interface{}) map[string]interface{} {
dict := make(map[string]interface{})
if len(data)%2 != 0 {
return dict // Retorna un mapa vacío si hay un número impar de argumentos
}
for i := 0; i < len(data); i += 2 {
key, ok := data[i].(string)
if !ok {
continue // Salta si la clave no es un string
}
dict[key] = data[i+1]
}
return dict
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
import{S as x}from"./SectionTitle-CrHOP_mf.js";import{I as h}from"./IconoLlama-BavanhPF.js";import{g as y,_ as b,u as q,c as p,r as C,d as e,f as m,F as _,b as s,l as g,w as F,m as V,t as w,e as n,i as B,z as T,s as A}from"./index-BmU8V2V2.js";const L=async()=>{try{const{data:o}=await y.get("/preguntas-frecuentes-all");return o}catch(o){throw console.log(o),new Error("Error getting preguntas frecuentes")}},M=["onClick"],N={class:"flex items-center"},j={class:"font-medium"},E={key:0,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},I={key:1,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},S={key:0,class:"p-4"},z=["innerHTML"],H={__name:"AskFrequentlyView",setup(o){const{data:l}=q({queryKey:["preguntasFrecuentes"],queryFn:()=>L(),staleTime:6e4}),f=p(()=>{var t;return((t=l==null?void 0:l.value)==null?void 0:t.categorias)||[]}),u=p(()=>A.contrast),r=C({}),k=t=>{r.value[t]=!r.value[t]};return(t,a)=>(s(!0),e(_,null,m(f.value,c=>(s(),e("div",{class:"faq-container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl select-none",key:c.id},[g(x,null,{default:F(()=>[V(w(c.categoria_nombre),1)]),_:2},1024),(s(!0),e(_,null,m(c.preguntas,({pregunta:d,respuesta:v,id:i})=>(s(),e("div",{key:d.id,class:"faq-item mb-2"},[n("div",{onClick:O=>k(i),class:B([{"bg-black":u.value,"bg-white":!u.value},"cursor-pointer shadow-[0_5px_5px_rgba(0,0,0,0.1)] rounded-lg p-4 flex items-center justify-between"])},[n("div",N,[g(h),n("span",j,w(d),1)]),r.value[i]?(s(),e("svg",E,a[0]||(a[0]=[n("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 15l7-7 7 7"},null,-1)]))):(s(),e("svg",I,a[1]||(a[1]=[n("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 9l-7 7-7-7"},null,-1)])))],10,M),r.value[i]?(s(),e("div",S,[n("p",{class:"mb-4 faq-response",innerHTML:v},null,8,z)])):T("",!0)]))),128))]))),128))}},$=b(H,[["__scopeId","data-v-5af61f57"]]);export{$ as default};
+1
View File
@@ -0,0 +1 @@
.faq-response[data-v-5af61f57]{white-space:pre-line}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{S as h}from"./SectionTitle-CrHOP_mf.js";import{g as b,_ as g,r as f,u as x,c as u,d as r,e,l as _,w as v,F as y,f as C,b as t,m as j,i as B,t as n,z as w,s as V}from"./index-BmU8V2V2.js";const A=async()=>{try{const{data:a}=await b.get("/loadoficinasatencionall");return a}catch(a){throw console.log(a),new Error("Error getting oficinas atencion")}},L={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},M={class:"w-full"},N=["onClick"],O={class:"font-semibold"},z={key:0,class:""},F={key:1,class:""},T={key:0,class:"p-4 mt-2 rounded-b shadow-lg"},E={class:""},I={key:0,class:"flex items-center mb-2 break-words word-break"},S={class:"break-words word-break"},q={key:1,class:"flex items-center mb-2 break-words word-break"},D={class:"break-words word-break"},G={class:"flex items-center mb-2 break-words word-break"},K={class:"break-words word-break"},Q={class:"flex items-center mb-2 break-words word-break"},H={class:"break-words word-break"},P={class:"flex items-center mb-2 break-words word-break"},U={class:"break-words word-break"},X={class:"flex items-center mb-2 break-words word-break"},$={class:"break-words word-break"},J={__name:"AttentionOfficesView",setup(a){const i=f(null),m=l=>{i.value=i.value===l?null:l},{data:d}=x({queryKey:["oficinasAtencion"],queryFn:()=>A(),staleTime:1e3*60}),p=u(()=>{var l;return((l=d==null?void 0:d.value)==null?void 0:l.registros)||[]}),k=u(()=>V.contrast);return(l,s)=>(t(),r("div",L,[s[8]||(s[8]=e("div",{class:"w-full flex justify-center items-center mb-6"},[e("iframe",{class:"w-full h-[700px] rounded",src:"https://www.google.com/maps/d/u/0/embed?mid=1kxsADxuCL8sQL8ItVDXPjlG1k2gueNKF&ll=7.546385018476524%2C-72.46072375000001&z=10",width:"640",height:"900",allowfullscreen:"",loading:"lazy"})],-1)),e("div",M,[_(h,null,{default:v(()=>s[0]||(s[0]=[j("Oficinas de atención Gases del Oriente")])),_:1}),s[7]||(s[7]=e("p",{class:"mb-4"},"Hacer click o tocar en el nombre de cada oficina para ver la información",-1)),(t(!0),r(y,null,C(p.value,(o,c)=>(t(),r("div",{key:o.id,class:"mb-2"},[e("div",{onClick:R=>m(c),class:B([{"bg-black":k.value,"bg-white":!k.value},"cursor-pointer flex justify-between items-center p-4 rounded shadow-lg"])},[e("h3",O,n(o.ciudad),1),i.value===c?(t(),r("span",z,"-")):(t(),r("span",F,"+"))],10,N),i.value===c?(t(),r("div",T,[e("ul",E,[o.direccion1?(t(),r("li",I,[s[1]||(s[1]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",S,n(o.direccion1),1)])):w("",!0),o.direccion2!="NULL"?(t(),r("li",q,[s[2]||(s[2]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",D,n(o.direccion2),1)])):w("",!0),e("li",G,[s[3]||(s[3]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",K,n(o.horario),1)]),e("li",Q,[s[4]||(s[4]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",H,"Tel "+n(o.telefono),1)]),e("li",P,[s[5]||(s[5]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",U,"Línea de emergencias "+n(o.linea_emergencia),1)]),e("li",X,[s[6]||(s[6]=e("svg",{class:"w-4 h-4 flex-shrink-0 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[e("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M9 5l7 7-7 7"})],-1)),e("span",$,n(o.email),1)])])])):w("",!0)]))),128))])]))}},Z=g(J,[["__scopeId","data-v-3ab4c4e7"]]);export{Z as default};
+1
View File
@@ -0,0 +1 @@
body[data-v-3ab4c4e7]{background-color:#002b5c}.word-break[data-v-3ab4c4e7]{word-break:break-word}
+1
View File
@@ -0,0 +1 @@
.embedded-site[data-v-1d3df865]{width:100%;height:100vh}
+1
View File
@@ -0,0 +1 @@
import{_ as r,b as s,d as a,e as c,M as d}from"./index-BmU8V2V2.js";const o={},n={class:"embedded-site max-w-4xl mx-auto rounded-3xl shadow-lg"};function _(t,e){return s(),a("div",n,e[0]||(e[0]=[c("iframe",{src:"https://fnbgasesdeloriente.com/credit-simulator",frameborder:"0",class:"w-full h-screen"},null,-1)]))}const l=r(o,[["render",_],["__scopeId","data-v-1d3df865"]]),f={__name:"CheckCreditView",setup(t){return(e,m)=>(s(),d(l,{class:"mt-10 mb-10"}))}};export{f as default};
+1
View File
@@ -0,0 +1 @@
import{P as l}from"./PdfDownload-B_7ePhU0.js";import{g as u,u as d,c as g,d as p,f as i,F as f,b as e,M as _,h as s}from"./index-BmU8V2V2.js";import"./SectionTitle-CrHOP_mf.js";import"./SecondaryButton-CAqGmnmb.js";const w=async()=>{try{const{data:r}=await u.get("/loadcodigoetica");return r}catch(r){throw console.log(r),new Error("Error getting codigo etica")}},A={__name:"CodEthicsView",setup(r){const t="https://www.gasesdeloriente.com.co",{data:a}=d({queryKey:["codigoEtica"],queryFn:()=>w(),staleTime:6e4}),n=g(()=>{var c;return((c=a==null?void 0:a.value)==null?void 0:c.records)||[]});return(c,h)=>(e(!0),p(f,null,i(n.value,o=>(e(),_(l,{title:o==null?void 0:o.title,description:o==null?void 0:o.description,imageSrc:`${s(t)}/${o==null?void 0:o.imagen}`,imageAlt:o==null?void 0:o.title,buttonText:o==null?void 0:o.text_button,fileUrl:`${s(t)}/${o==null?void 0:o.archivo}`},null,8,["title","description","imageSrc","imageAlt","buttonText","fileUrl"]))),256))}};export{A as default};
+1
View File
@@ -0,0 +1 @@
import{S as x}from"./SectionTitle-CrHOP_mf.js";import{S as b}from"./SecondaryButton-CAqGmnmb.js";import{g as f,u as S,c as v,d as A,l as r,w as d,e as t,i as c,t as E,h as u,b as T,m,s as h}from"./index-BmU8V2V2.js";const C=async()=>{try{const{data:a}=await f.get("/loadpoliticas");return console.log(a),a}catch(a){throw console.log(a),new Error("Error getting publicaciones")}},L={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},P={class:"flex flex-col lg:flex-row items-center lg:items-start lg:space-x-8 mb-8"},y={class:"lg:w-3/5 mb-6 lg:mb-0"},I={class:""},k={class:"mt-4"},O={class:"w-full lg:w-1/3"},N={class:"mt-4"},V={class:"w-full lg:w-1/2"},D={class:"lg:w-2/5"},M=["src"],B=["innerHTML"],G=["innerHTML"],q={__name:"CompanyPoliticView",setup(a){const i="https://www.gasesdeloriente.com.co",{data:n}=S({queryKey:["politicas"],queryFn:()=>C(),staleTime:6e4}),o=v(()=>(n==null?void 0:n.value)||[]),l=v(()=>h.contrast),p=g=>{window.open(g,"_blank")};return(g,s)=>{var _;return T(),A("div",L,[r(x,null,{default:d(()=>s[2]||(s[2]=[m("Políticas")])),_:1}),t("div",P,[t("div",y,[t("div",{class:c([{"bg-black":l.value,"bg-white":!l.value},"p-6 rounded-2xl shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[t("p",I,E(o.value.description),1),t("div",k,[s[4]||(s[4]=t("h3",{class:"font-bold mb-2"},"POLÍTICAS GASES DEL ORIENTE S.A. E.S.P.",-1)),t("div",O,[r(b,{onClick:s[0]||(s[0]=w=>{var e;return p(u(i)+"/"+((e=o.value)==null?void 0:e.archivo_gases))}),class:"mb-2"},{default:d(()=>s[3]||(s[3]=[m("Política de ventas ")])),_:1})])]),t("div",N,[s[6]||(s[6]=t("h3",{class:"font-bold mb-2"},"POLÍTICAS DEL PLAN ESTRATÉGICO DE SEGURIDAD VIAL - PESV -",-1)),t("div",V,[r(b,{onClick:s[1]||(s[1]=w=>{var e;return p(u(i)+"/"+((e=o.value)==null?void 0:e.archivo_plan))})},{default:d(()=>s[5]||(s[5]=[m("Política de seguridad vial ")])),_:1})])])],2)]),t("div",D,[t("img",{src:`${u(i)}/${(_=o.value)==null?void 0:_.imagen}/`,alt:"Gas Natural",class:"rounded-lg shadow-md mx-auto lg:mx-0"},null,8,M)])]),t("div",{class:c([{"bg-black":l.value,"bg-white":!l.value},"p-6 rounded-2xl shadow-[0_5px_25px_rgba(0,0,0,0.1)] mt-8"])},[s[7]||(s[7]=t("h3",{class:"font-bold mb-4"},"POLÍTICA SOCIAL",-1)),t("p",{innerHTML:o.value.politica_social,class:"mb-4"},null,8,B)],2),t("div",{class:c([{"bg-black":l.value,"bg-white":!l.value},"p-6 rounded-2xl shadow-[0_5px_25px_rgba(0,0,0,0.1)] mt-8"])},[s[8]||(s[8]=t("h3",{class:"font-bold mb-4"},"POLÍTICA ECONÓMICA",-1)),t("p",{innerHTML:o.value.politica_economica,class:"mb-4"},null,8,G)],2)])}}};export{q as default};
+1
View File
@@ -0,0 +1 @@
import{P as i}from"./PdfDownload-B_7ePhU0.js";import{u as n,M as c,h as e,b as s,k as p}from"./index-BmU8V2V2.js";import"./SectionTitle-CrHOP_mf.js";import"./SecondaryButton-CAqGmnmb.js";const b={__name:"ContractView",setup(l){const a="https://www.gasesdeloriente.com.co",{data:o}=n({queryKey:["parametrizacionweb"],queryFn:()=>p(),retry:!1});return(m,d)=>{var t,r;return s(),c(i,{title:"Contrato condiciones",description:(t=e(o))==null?void 0:t.contrato_condiciones_descripcion,imageSrc:"/assets/img39.webp",imageAlt:"CONTRATO CONDICIONES",buttonText:"Contrato condiciones 072024",fileUrl:`${e(a)}/${(r=e(o))==null?void 0:r.contrato_condiciones}`},null,8,["description","fileUrl"])}}};export{b as default};
+1
View File
@@ -0,0 +1 @@
import{S as p}from"./SectionTitle-CrHOP_mf.js";import{g as w,c as h,u as x,d as b,l as u,w as _,e,i as n,h as t,b as f,m as g,s as v}from"./index-BmU8V2V2.js";const L=async()=>{try{const{data:a}=await w.get("/loadlineaetica");return a}catch(a){throw console.log(a),new Error("Error getting linea etica")}},T={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},y={class:"flex flex-col lg:flex-row items-stretch mt-4"},E={class:"w-full lg:w-1/2 lg:pr-4 mb-4 lg:mb-0 flex flex-col space-y-8"},H=["innerHTML"],M={class:"font-semibold mb-2"},k=["innerHTML"],V={class:"w-full lg:w-1/2 lg:pl-4 flex items-center"},q=["src"],B=["innerHTML"],C={__name:"EthicLineView",setup(a){const m="https://www.gasesdeloriente.com.co",s=h(()=>v.contrast),{data:l}=x({queryKey:["lineaEtica"],queryFn:()=>L(),staleTime:1e3*60});return(N,o)=>{var i,c,r,d;return f(),b("div",T,[u(p,null,{default:_(()=>o[0]||(o[0]=[g("Linea Ética")])),_:1}),e("div",y,[e("div",E,[e("div",{class:n([{"bg-black":s.value,"bg-white":!s.value},"p-6 rounded-lg shadow-[0_5px_25px_rgba(0,0,0,0.1)] h-full flex flex-col"])},[e("p",{class:"mb-4 whitespace-pre-line",innerHTML:(i=t(l))==null?void 0:i.description},null,8,H)],2),e("div",{class:n([{"bg-black":s.value,"bg-white":!s.value},"p-6 rounded-lg shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",M,[e("p",{class:"whitespace-pre-line",innerHTML:(c=t(l))==null?void 0:c.contacto},null,8,k)])],2)]),e("div",V,[e("img",{src:`${t(m)}/${(r=t(l))==null?void 0:r.imagen}`,alt:"Valores corporativos",class:"shadow-md w-full h-full object-cover"},null,8,q)])]),u(p,{class:"pt-12"},{default:_(()=>o[1]||(o[1]=[g("Situaciones que pueden ser reportadas:")])),_:1}),e("div",{class:n([{"bg-black":s.value,"bg-white":!s.value},"mt-8 mb-8 p-6 rounded-lg shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",{class:"whitespace-pre-line",innerHTML:(d=t(l))==null?void 0:d.situaciones},null,8,B)],2)])}}};export{C as default};
+1
View File
@@ -0,0 +1 @@
import{S as g}from"./SectionTitle-CrHOP_mf.js";import{g as m,u as x,c as h,d as b,l as w,w as v,e,i,h as a,b as f,m as y,s as T}from"./index-BmU8V2V2.js";const k="/assets/img33-B9b8dcQm.webp",F=async()=>{try{const{data:o}=await m.get("/loadfcr");return o}catch(o){throw console.log(o),new Error("Error getting fcr")}},H={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},L={class:"mt-8 flex flex-col lg:flex-row lg:space-x-8"},M={class:"lg:w-1/2 space-y-4"},C=["innerHTML"],R=["innerHTML"],B=["innerHTML"],V={class:"mt-8 space-y-4"},$=["innerHTML"],z={class:"mt-8 flex flex-col gap-6 mb-8"},A=["href"],E=["href"],q={__name:"FcrView",setup(o){const n="https://www.gasesdeloriente.com.co",{data:t}=x({queryKey:["fcr"],queryFn:()=>F(),staleTime:6e4}),s=h(()=>T.contrast);return(N,r)=>{var c,l,d,p,_,u;return f(),b("div",H,[w(g,null,{default:v(()=>r[0]||(r[0]=[y("FCR - Firmas Constructoras y / o Reparadoras")])),_:1}),r[2]||(r[2]=e("p",{class:"mt-4 text-lg leading-7 text-gray-600"}," Para el registro de Firmas Constructoras y Reparadoras, deben seguir el siguiente procedimiento: ",-1)),e("div",L,[e("div",M,[e("div",{class:i([{"bg-black":s.value,"bg-white":!s.value},"rounded-2xl p-6 shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",{class:"whitespace-pre-line",innerHTML:(c=a(t))==null?void 0:c.paso_1},null,8,C)],2),e("div",{class:i([{"bg-black":s.value,"bg-white":!s.value},"rounded-2xl p-6 shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",{class:"whitespace-pre-line",innerHTML:(l=a(t))==null?void 0:l.paso_2},null,8,R)],2),e("div",{class:i([{"bg-black":s.value,"bg-white":!s.value},"rounded-2xl p-6 shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",{class:"whitespace-pre-line",innerHTML:(d=a(t))==null?void 0:d.paso_3},null,8,B)],2)]),r[1]||(r[1]=e("div",{class:"lg:w-1/2 flex justify-center items-center"},[e("img",{src:k,alt:"Trabajador con casco y herramientas",class:"rounded-2xl shadow-md"})],-1))]),e("div",V,[e("div",{class:i([{"bg-black":s.value,"bg-white":!s.value},"rounded-2xl p-6 shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[e("p",{class:"whitespace-pre-line",innerHTML:(p=a(t))==null?void 0:p.paso_4},null,8,$)],2)]),e("div",z,[e("a",{href:`${a(n)}/${(_=a(t))==null?void 0:_.archivo_inscripcion}`,class:"text-[#1941c5] hover:underline font-semibold",target:"_blank"},"Descargar Solicitud de inscripción y/o actualización en registro FCR",8,A),e("a",{href:`${a(n)}/${(u=a(t))==null?void 0:u.archivo_instructivo}`,class:"text-[#1941c5] hover:underline font-semibold",target:"_blank"},"Instructivo; Inscripción y/o Actualización en el Registro de Firmas Constructoras y Reparadoras",8,E)])])}}};export{q as default};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
button[data-v-50e28b44]:focus{outline:none}.transition-transform[data-v-50e28b44]{transition:transform .5s}
+1
View File
@@ -0,0 +1 @@
.form-control-doble[data-v-20076456]{border-radius:.25rem;border-width:1px;padding:.75rem .5rem;--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.form-control[data-v-20076456]{width:100%;border-radius:.25rem;border-width:1px;padding:.75rem .5rem;--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.input[type=checkbox][data-v-20076456]{display:none}.custom-checkbox[data-v-20076456]{display:inline-block;width:30px;height:30px;border:1px solid #bcbcbc;border-radius:50%;position:relative;cursor:pointer;background-color:#fff}.custom-checkbox[data-v-20076456]:after{content:"";position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:10px;height:10px;background-color:#284c91;border-radius:50%;opacity:0}.input[type=checkbox]:checked+.custom-checkbox[data-v-20076456]:after{opacity:1}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
button[data-v-5d7f05e4]:focus{outline:none}.transition-transform[data-v-5d7f05e4]{transition:transform .5s}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{_ as c,b as n,d as l,e as d,g as u,u as _,M as p,h as s}from"./index-BmU8V2V2.js";const v={name:"VideoPreview",props:{videoUrl:{type:String,required:!0}}},w={class:"max-w-6xl mx-auto p-8"},f=["src"];function m(e,r,t,i,a,o){return n(),l("div",w,[d("video",{src:t.videoUrl,controls:"",class:"w-full border-none"},null,8,f)])}const g=c(v,[["render",m]]),h=async()=>{try{const{data:e}=await u.get("/loadvideoinstitucional");return e}catch(e){throw console.log(e),new Error("Error getting video institucional")}},x={__name:"InstitutionalVideoView",setup(e){const r="https://www.gasesdeloriente.com.co",{data:t}=_({queryKey:["videoInstitucional"],queryFn:()=>h(),retry:!1});return(i,a)=>{var o;return n(),p(g,{videoUrl:`${s(r)}/${(o=s(t))==null?void 0:o.video_institucional}`},null,8,["videoUrl"])}}};export{x as default};
+1
View File
@@ -0,0 +1 @@
button[data-v-b0bbcf36]:focus{outline:none}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{g as h,r as _,u as y,c as m,o as b,d as l,l as p,w as C,F as w,f as v,$,b as r,m as B,e as n,t as N,i as S,M as T,h as f,z as V,s as q}from"./index-BmU8V2V2.js";import{S as A}from"./SectionTitle-CrHOP_mf.js";import{P as I}from"./PdfDownload-B_7ePhU0.js";import{I as M}from"./IconoLlama-BavanhPF.js";import"./SecondaryButton-CAqGmnmb.js";const j=async()=>{try{const{data:i}=await h.get("/comunicados-all");return i}catch(i){throw console.log(i),new Error("Error getting comunicados")}},F={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},L=["onClick"],U={class:"flex items-center"},z={key:0,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},E={key:1,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},P={key:0,class:"space-y-4"},H={__name:"LatestNewsView",setup(i){const c="https://www.gasesdeloriente.com.co",d=$(),a=_(null),{data:u}=y({queryKey:["comunicados"],queryFn:()=>j(),staleTime:1e3*60}),k=m(()=>{var s;return((s=u==null?void 0:u.value)==null?void 0:s.categorias)||[]}),g=m(()=>q.contrast),x=s=>{a.value=a.value===s?null:s};return b(()=>{const s=d.query.categoria,o=d.query.comunicado;s&&(a.value=Number(s),setTimeout(()=>{const t=document.querySelector(`#comunicado-${o}`);t==null||t.scrollIntoView({behavior:"smooth",block:"start"})},300))}),(s,o)=>(r(),l("div",F,[p(A,null,{default:C(()=>o[0]||(o[0]=[B("Comunicados informativos")])),_:1}),(r(!0),l(w,null,v(k.value,t=>(r(),l("div",{key:t.categoria_id,class:"select-none"},[n("div",{class:S([{"bg-black":g.value,"bg-white":!g.value},"text-lg font-bold mb-4 cursor-pointer shadow-lg p-4 rounded-lg flex items-center justify-between"]),onClick:e=>x(t.categoria_id)},[n("div",U,[p(M),n("span",null,N(t.categoria_nombre),1)]),a.value===t.categoria_id?(r(),l("svg",z,o[1]||(o[1]=[n("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 15l7-7 7 7"},null,-1)]))):(r(),l("svg",E,o[2]||(o[2]=[n("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 9l-7 7-7-7"},null,-1)])))],10,L),a.value===t.categoria_id?(r(),l("div",P,[(r(!0),l(w,null,v(t.comunicados,e=>(r(),T(I,{key:e.id,title:e==null?void 0:e.title,id:"comunicado-"+(e==null?void 0:e.id),description:e.description,imageSrc:`${f(c)}/${e.imagen}`,imageAlt:e.title,buttonText:e.text_button,fileUrl:`${f(c)}/${e.archivo}`},null,8,["title","id","description","imageSrc","imageAlt","buttonText","fileUrl"]))),128))])):V("",!0)]))),128))]))}};export{H as default};
+1
View File
@@ -0,0 +1 @@
import{S as m}from"./SectionTitle-CrHOP_mf.js";import{O as c,d as t,l as i,w as l,e as a,F as d,f as p,b as s,m as u,t as g}from"./index-BmU8V2V2.js";const _={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},x={class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 mt-8"},w=["src","alt"],b={class:"mt-2 text-center font-semibold"},v={__name:"LocationBuyView",setup(f){const n=c({paymentPoints:[{name:"Colchones Dormi",image:"colchonesDormi.webp"},{name:"Credinorte",image:"credinorte.webp"},{name:"Comultrasan",image:"multicomultrasan.webp"},{name:"Dubo",image:"dubo.webp"},{name:"Asycon",image:"asycon.webp"}]});return(h,o)=>(s(),t("div",_,[i(m,null,{default:l(()=>o[0]||(o[0]=[u("¿Dónde puedes comprar?")])),_:1}),a("div",x,[(s(!0),t(d,null,p(n.paymentPoints,(e,r)=>(s(),t("div",{key:r,class:"shadow-lg rounded-lg p-4 flex flex-col items-center"},[a("img",{src:e.image,alt:e.name,class:"w-32 h-32 object-contain"},null,8,w),a("p",b,g(e.name),1)]))),128))])]))}};export{v as default};
+1
View File
@@ -0,0 +1 @@
import{g as P,p as A,c as I,B as z,C as f,d as b,e,l,w as i,v as E,x,y as v,h as r,E as y,G as _,t as F,z as M,i as T,F as U,L as q,b as k,m as d,s as G}from"./index-BmU8V2V2.js";import{S as h}from"./SectionTitle-CrHOP_mf.js";import{P as N}from"./PrimaryButton-Bm01EosZ.js";import{S as j}from"./SecondaryButton-CAqGmnmb.js";import{u as R}from"./vee-validate-uNXg2txt.js";const D="/assets/img20-MIOigyB8.webp",L=async(p,n)=>{try{const{data:o}=await P.post("/do/login",{nombre_usuario:p,password:n});return o}catch(o){throw console.log(o),new Error("Error logging in")}},$={class:"max-w-5xl mx-auto p-8"},Q={class:"relative w-full max-w-5xl shadow-lg rounded-[35px] overflow-hidden"},H={class:"relative w-full h-0 pb-[120%] md:pb-[60%] lg:pb-[50%]"},J={class:"absolute inset-0 z-10 flex flex-col justify-center p-8 lg:max-w-md lg:ml-8"},K={class:"mb-4"},W={class:"mb-8"},X={class:"flex justify-center"},Y={key:0,class:"mt-4 text-red-500 text-center"},Z={class:"max-w-5xl mx-auto p-8 mb-8"},ss={class:"grid grid-cols-1 md:grid-cols-2 gap-8"},ns={__name:"LoginView",setup(p){const n=A(),o=I(()=>G.contrast),S=z({username:f().required(),password:f()}),{values:es,defineField:c,errors:g,handleSubmit:B,resetForm:rs}=R({validationSchema:S}),[u,V]=c("username"),[m,C]=c("password"),w=B(async a=>{try{const s=await L(a.username,a.password);switch(s.status){case"success":window.location.href="/app/dashboard";break;case"missing":window.location.href="/update-credentials";break;case"error":s.message=="no_password"?window.location.href="/update-credentials":n.error(s.message,{timeout:8e3});break;default:break}}catch(s){switch(s.status){case"success":window.location.href="/app/dashboard";break;case"missing":window.location.href="/update-credentials";break;case"error":s.message=="no_password"?window.location.href="/update-credentials":n.error(s.message,{timeout:8e3});break}}});return(a,s)=>{const O=q("router-link");return k(),b(U,null,[e("div",$,[l(h,null,{default:i(()=>s[3]||(s[3]=[d("Oficina Virtual Gases del Oriente")])),_:1}),s[10]||(s[10]=e("p",{class:"mb-12"}," Bienvenid@ a la Oficina Virtual de Gases del Oriente SA ESP. Si ya está registrado(a), puede iniciar sesión con el Usuario y Contraseña asignados durante el registro. Si aún no tiene Usuario y Contraseña, es necesario registrarse según las acciones que desee realizar. ",-1)),e("div",Q,[e("div",H,[s[9]||(s[9]=e("img",{src:D,alt:"Background Image",class:"absolute inset-0 w-full h-full object-cover rounded-[35px]"},null,-1)),e("div",J,[s[8]||(s[8]=e("h1",{class:"text-2xl lg:text-4xl font-bold mb-6 text-[#404e7b] text-center"}," Iniciar sesión ",-1)),e("form",{onSubmit:s[2]||(s[2]=E((...t)=>r(w)&&r(w)(...t),["prevent"])),method:"POST"},[e("div",K,[s[4]||(s[4]=e("label",{for:"usuario",class:"block text-md font-medium"},"Usuario",-1)),x(e("input",y({"onUpdate:modelValue":s[0]||(s[0]=t=>_(u)?u.value=t:null)},r(V),{type:"text",id:"usuario",required:"",name:"nombre_usuario",class:["mt-1 block w-full px-3 border py-3 lg:py-4 rounded-xl shadow-[0_5px_25px_rgba(0,0,0,0.1)]",{"border-red-500":r(g).username}],placeholder:"Ingrese su usuario"}),null,16),[[v,r(u)]])]),e("div",W,[s[5]||(s[5]=e("label",{for:"password",class:"block text-md font-medium"},[e("p",null,"Contraseña")],-1)),x(e("input",y({"onUpdate:modelValue":s[1]||(s[1]=t=>_(m)?m.value=t:null)},r(C),{type:"password",id:"password",name:"password",class:["mt-1 block w-full px-3 border py-3 lg:py-4 rounded-xl shadow-[0_5px_25px_rgba(0,0,0,0.1)]",{"border-red-500":r(g).password}],placeholder:"Ingrese su contraseña"}),null,16),[[v,r(m)]])]),s[7]||(s[7]=e("a",{href:"/request-password-reset",class:"text-black"},"¿Olvidaste tu contraseña?",-1)),e("div",X,[l(N,null,{default:i(()=>s[6]||(s[6]=[d("Iniciar sesión")])),_:1})]),a.errorMessage?(k(),b("p",Y,F(a.errorMessage),1)):M("",!0)],32)])])])]),e("div",Z,[l(h,null,{default:i(()=>s[11]||(s[11]=[d(" ¿Aún no estás registrado?")])),_:1}),e("div",ss,[e("div",{class:T([{"bg-black":o.value,"bg-white":!o.value},"flex-grow p-10 rounded-lg shadow-[0_5px_25px_rgba(0,0,0,0.1)]"])},[s[13]||(s[13]=e("p",{class:"mb-4"}," Podrá ver o imprimir facturas, consultar o registrar PQRs, consultar estado de créditos, realizar pagos. ",-1)),l(O,{to:"/register-gas"},{default:i(()=>[l(j,null,{default:i(()=>s[12]||(s[12]=[d(" Registrarse como usuario del Gas ")])),_:1})]),_:1})],2)])])],64)}}};export{ns as default};
+1
View File
@@ -0,0 +1 @@
import{S as p}from"./SectionTitle-CrHOP_mf.js";import{P as i}from"./PdfDownload-B_7ePhU0.js";import{g,u as x,c as f,d as c,e as w,l as _,w as y,F as l,f as h,b as e,m as A,M as T,h as u}from"./index-BmU8V2V2.js";import"./SecondaryButton-CAqGmnmb.js";const b=async()=>{try{const{data:a}=await g.get("/loadintegridadanticorrupcion");return a}catch(a){throw console.log(a),new Error("Error getting codigo etica")}},v={class:"mx-auto pt-8 px-4 sm:px-6 lg:px-8 max-w-6xl"},k={__name:"ManualPteeView",setup(a){const n="https://www.gasesdeloriente.com.co",{data:o}=x({queryKey:["integridadAnticorrupcion"],queryFn:()=>b(),staleTime:6e4}),d=f(()=>{var t;return((t=o==null?void 0:o.value)==null?void 0:t.records)||[]});return(t,s)=>(e(),c(l,null,[w("div",v,[_(p,null,{default:y(()=>s[0]||(s[0]=[A("Integridad y anticorrupción")])),_:1})]),(e(!0),c(l,null,h(d.value,r=>(e(),T(i,{title:r==null?void 0:r.title,description:r==null?void 0:r.description,imageSrc:`${u(n)}/${r==null?void 0:r.imagen}`,imageAlt:r==null?void 0:r.title,buttonText:r==null?void 0:r.text_button,fileUrl:`${u(n)}/${r==null?void 0:r.archivo}`},null,8,["title","description","imageSrc","imageAlt","buttonText","fileUrl"]))),256))],64))}};export{k as default};
+1
View File
@@ -0,0 +1 @@
.grid-cols-2>div[data-v-661d645b]{display:flex;flex-direction:column}.grid-cols-2>div[data-v-661d645b]>*{display:flex;flex-direction:column;flex-grow:1}.grid-cols-2>div img[data-v-661d645b]{margin-top:auto}
+1
View File
@@ -0,0 +1 @@
import{S as l}from"./SectionTitle-CrHOP_mf.js";import{g as V,_ as y,u as k,c as M,d as $,e as s,l as c,w as r,i as v,t as d,h as o,b as A,m as _,s as B}from"./index-BmU8V2V2.js";const C=async()=>{try{const{data:i}=await V.get("/loadmisionvision");return i}catch(i){throw console.log(i),new Error("Error getting parametrizacion")}},E={class:"service-info-container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-10"},I={class:"grid grid-cols-1 md:grid-cols-2 gap-6"},N={class:"flex flex-col"},S={class:"p-6 flex-grow"},T={class:"text-center mb-2"},j=["src"],q={class:"flex flex-col"},z={class:"p-6 flex-grow"},D={class:"text-center mb-2"},F=["src"],K={class:"mt-8"},Q={__name:"MisionVisionView",setup(i){const a="https://www.gasesdeloriente.com.co",{data:h}=k({queryKey:["misionVision"],queryFn:()=>C(),staleTime:6e4}),n=M(()=>B.contrast),t=h,b=u=>{window.open(u,"_blank")};return(u,e)=>{var p,m,x,g,f;return A(),$("div",E,[s("div",I,[s("div",N,[c(l,null,{default:r(()=>e[1]||(e[1]=[_("Misión")])),_:1}),s("div",{class:v([{"bg-black":n.value,"bg-white":!n.value},"rounded-[35px] overflow-hidden flex flex-col h-full shadow-[0_15px_30px_rgba(0,0,0,0.2)]"])},[s("div",S,[s("p",T,d((p=o(t))==null?void 0:p.description_mision),1)]),s("img",{src:`${o(a)}/${(m=o(t))==null?void 0:m.imagen_mision}`,alt:"Imagen Misión",class:"w-full h-48 object-cover"},null,8,j)],2)]),s("div",q,[c(l,null,{default:r(()=>e[2]||(e[2]=[_("Visión")])),_:1}),s("div",{class:v([{"bg-black":n.value,"bg-white":!n.value},"rounded-[35px] overflow-hidden flex flex-col h-full shadow-[0_15px_30px_rgba(0,0,0,0.2)]"])},[s("div",z,[s("p",D,d((x=o(t))==null?void 0:x.description_vision),1)]),s("img",{src:`${o(a)}/${(g=o(t))==null?void 0:g.imagen_vision}`,alt:"Imagen Visión",class:"w-full h-48 object-cover"},null,8,F)],2)])]),s("div",K,[c(l,null,{default:r(()=>e[3]||(e[3]=[_("Alcance")])),_:1}),s("button",{onClick:e[0]||(e[0]=U=>{var w;return b(o(a)+"/"+((w=o(t))==null?void 0:w.archivo))}),class:"bg-[#284d92] text-white rounded-full px-8 py-4"},d((f=o(t))==null?void 0:f.text_button),1)])])}}},J=y(Q,[["__scopeId","data-v-661d645b"]]);export{J as default};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{g as v,u as _,c as m,r as h,d as t,l as g,w as y,F as p,f as w,b as s,m as B,e as l,t as C,i as A,M as N,h as x,z as S,s as T}from"./index-BmU8V2V2.js";import{S as V}from"./SectionTitle-CrHOP_mf.js";import{P as $}from"./PdfDownload-B_7ePhU0.js";import{I as j}from"./IconoLlama-BavanhPF.js";import"./SecondaryButton-CAqGmnmb.js";const E=async()=>{try{const{data:n}=await v.get("/boletines-all");return n}catch(n){throw console.log(n),new Error("Error getting boletines")}},F={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},M=["onClick"],U={class:"flex items-center"},q={key:0,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},z={key:1,xmlns:"http://www.w3.org/2000/svg",class:"flex-shrink-0 h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},I={key:0,class:"space-y-4"},G={__name:"NewslettersView",setup(n){const u="https://www.gasesdeloriente.com.co",{data:i}=_({queryKey:["boletines"],queryFn:()=>E(),staleTime:6e4}),f=m(()=>{var r;return((r=i==null?void 0:i.value)==null?void 0:r.categorias)||[]}),d=m(()=>T.contrast),c=h(null),k=r=>{c.value=c.value===r?null:r};return(r,a)=>(s(),t("div",F,[g(V,null,{default:y(()=>a[0]||(a[0]=[B("Boletines")])),_:1}),(s(!0),t(p,null,w(f.value,o=>(s(),t("div",{key:o.categoria_id,class:"select-none"},[l("div",{class:A([{"bg-black":d.value,"bg-white":!d.value},"text-lg font-bold mb-4 cursor-pointer shadow-lg p-4 rounded-lg flex items-center justify-between"]),onClick:e=>k(o.categoria_id)},[l("div",U,[g(j),l("span",null,C(o.categoria_nombre),1)]),c.value===o.categoria_id?(s(),t("svg",q,a[1]||(a[1]=[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 15l7-7 7 7"},null,-1)]))):(s(),t("svg",z,a[2]||(a[2]=[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 9l-7 7-7-7"},null,-1)])))],10,M),c.value===o.categoria_id?(s(),t("div",I,[(s(!0),t(p,null,w(o.boletines,e=>(s(),N($,{key:e==null?void 0:e.id,title:e==null?void 0:e.title,description:e==null?void 0:e.description,imageSrc:`${x(u)}/${e==null?void 0:e.imagen}`,imageAlt:e==null?void 0:e.title,buttonText:e==null?void 0:e.text_button,fileUrl:`${x(u)}/${e==null?void 0:e.archivo}`},null,8,["title","description","imageSrc","imageAlt","buttonText","fileUrl"]))),128))])):S("",!0)]))),128))]))}};export{G as default};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{S as f}from"./SectionTitle-CrHOP_mf.js";import{S as w}from"./SecondaryButton-CAqGmnmb.js";import{g as v,u as b,c as y,d as k,e as s,l as n,w as r,i as $,h as t,b as S,m as i,t as c,s as T}from"./index-BmU8V2V2.js";const B=async()=>{try{const{data:a}=await v.get("/loadorganismos");return a}catch(a){throw console.log(a),new Error("Error getting organismos")}},O={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},V={class:"flex flex-col lg:flex-row items-center lg:items-start lg:space-x-8 mb-8"},C={class:"lg:w-3/5"},E=["innerHTML"],N={class:"flex flex-col lg:flex-row items-start lg:space-x-4 space-y-4 lg:space-y-0 mt-4"},P={class:"w-full"},q={class:"w-full"},A=["href"],H={class:"lg:w-2/5 mt-6 lg:mt-0"},L=["src"],F={__name:"OrganismsOiaView",setup(a){const d="https://www.gasesdeloriente.com.co",h=_=>{window.open(_,"_blank")},{data:o}=b({queryKey:["revisionPeriodica"],queryFn:()=>B(),staleTime:6e4}),m=y(()=>T.contrast);return(_,l)=>{var g,p,u;return S(),k("div",O,[s("div",V,[s("div",C,[n(f,null,{default:r(()=>{var e;return[i(c((e=t(o))==null?void 0:e.titulo),1)]}),_:1}),s("div",{class:$([{"bg-black":m.value,"bg-white":!m.value},"p-6 rounded-2xl shadow-[0_5px_25px_rgba(0,0,0,0.1)] mt-4"])},[s("p",{class:"whitespace-pre-line",innerHTML:(g=t(o))==null?void 0:g.descripcion},null,8,E)],2),l[1]||(l[1]=s("p",{class:"mt-6"},"Para ver la lista de Organismos de inspección acreditados haga click en:",-1)),s("div",N,[s("div",P,[n(w,{onClick:l[0]||(l[0]=e=>{var x;return h(`${t(d)}/${(x=t(o))==null?void 0:x.archivo_organismos}`)})},{default:r(()=>{var e;return[i(c((e=t(o))==null?void 0:e.texto_boton_archivo),1)]}),_:1})]),s("div",q,[s("a",{href:`${(p=t(o))==null?void 0:p.enlace}`,target:"_blank"},[n(w,null,{default:r(()=>{var e;return[i(c((e=t(o))==null?void 0:e.texto_boton_enlace),1)]}),_:1})],8,A)])])]),s("div",H,[s("img",{src:`${t(d)}/${(u=t(o))==null?void 0:u.imagen}`,alt:"Inspectora",class:"rounded-lg shadow-md mx-auto lg:mx-0"},null,8,L)])])])}}};export{F as default};
+1
View File
@@ -0,0 +1 @@
.lg\:w-2\/3[data-v-73abbb49]{display:flex;flex-direction:column}.mt-auto[data-v-73abbb49]{margin-top:auto}
+1
View File
@@ -0,0 +1 @@
import{S as c}from"./SectionTitle-CrHOP_mf.js";import{S as d}from"./SecondaryButton-CAqGmnmb.js";import{_ as u,c as m,b as p,d as g,e as t,l as o,w as l,m as x,t as r,i as f,s as w}from"./index-BmU8V2V2.js";const _={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},h={class:"mb-6"},v={class:"lg:w-2/3 flex flex-col"},b=["innerHTML"],S={class:"mt-auto pt-4"},y={class:"mt-6 lg:mt-0 lg:w-1/3 flex justify-center"},k=["src","alt"],T={__name:"PdfDownload",props:{title:{type:String,required:!0},description:{type:String,required:!0},imageSrc:{type:String,required:!0},imageAlt:{type:String,default:"Image"},buttonText:{type:String,required:!0},fileUrl:{type:String,required:!0}},setup(e){const n=e,s=m(()=>w.contrast),i=()=>{window.open(n.fileUrl,"_blank")};return(q,a)=>(p(),g("div",_,[t("div",h,[o(c,null,{default:l(()=>[x(r(e.title),1)]),_:1})]),t("div",{class:f([{"bg-black":s.value,"bg-white":!s.value},"p-6 rounded-2xl shadow-[0_5px_25px_rgba(0,0,0,0.1)] lg:flex lg:items-stretch lg:space-x-8"])},[t("div",v,[t("p",{innerHTML:e.description,class:"whitespace-pre-line"},null,8,b),t("div",S,[o(d,{onClick:i,class:"flex items-center justify-center space-x-2"},{default:l(()=>[a[0]||(a[0]=t("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"h-6 w-6 flex-shrink-0"},[t("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m.75 12 3 3m0 0 3-3m-3 3v-6m-1.5-9H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"})],-1)),t("span",null,r(e.buttonText),1)]),_:1})])]),t("div",y,[t("img",{src:e.imageSrc,alt:e.imageAlt,class:"object-contain aspect-auto"},null,8,k)])],2)]))}},H=u(T,[["__scopeId","data-v-73abbb49"]]);export{H as P};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{_ as f}from"./img12--vpC50aS.js";import{S as n}from"./SectionTitle-CrHOP_mf.js";import{u as b,c as p,d as l,l as i,w as c,e as s,F as _,f as v,i as m,j as w,b as d,m as u,h as y,t as h,s as V}from"./index-BmU8V2V2.js";import{g as k}from"./get-puntos-recaudo.action-CN43BqeK.js";const N={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},P={class:"payment-locations-container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},S={class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 mt-8"},$=["src","alt"],j={class:"mt-2 text-center"},B={class:"payment-info-container mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl"},L={__name:"PointsView",setup(C){const g="https://www.gasesdeloriente.com.co",{data:o}=b({queryKey:["puntosRecaudo"],queryFn:()=>k(),staleTime:6e4}),x=p(()=>{var r;return((r=o==null?void 0:o.value)==null?void 0:r.records)||[]}),a=p(()=>V.contrast);return(r,e)=>(d(),l("div",N,[i(n,null,{default:c(()=>e[0]||(e[0]=[u("Puntos de recaudo")])),_:1}),s("div",P,[i(n,null,{default:c(()=>e[1]||(e[1]=[u("¿Dónde puedo pagar la factura del gas natural?")])),_:1}),s("div",S,[(d(!0),l(_,null,v(x.value,t=>(d(),l("div",{class:m([{"bg-black":a.value,"bg-white":!a.value},"shadow-lg rounded-lg p-4 flex flex-col items-center"]),key:t.id},[s("img",{src:`${y(g)}/${t.ruta}`,alt:t.nombre,class:"w-24 h-24 object-contain"},null,8,$),s("p",j,h(t.nombre),1)],2))),128))])]),s("div",B,[i(n,null,{default:c(()=>e[2]||(e[2]=[u("La importancia del pago oportuno de su factura")])),_:1}),s("div",{class:m([{"bg-black":a.value,"bg-white":!a.value},"p-8 rounded-xl shadow-[0_15px_30px_rgba(0,0,0,0.2)]"])},e[3]||(e[3]=[w('<p class="mb-6"> Con el <strong class="font-bold">NO</strong> pago de una o más facturas dentro de las fechas indicadas se suspenderá el servicio y se cobrará el valor de la reconexión el mes siguiente. Para el año <strong class="font-bold">2024</strong>, el valor por reconexión está cifrado en <strong class="font-bold">$ 44.322</strong> y la reinstalación si fuera el caso en <strong class="font-bold">$ 290.310</strong>. </p><div class="bg-[#274e93] text-white p-4 rounded-xl flex items-center"><img src="'+f+'" alt="info" class="w-12 h-12 mr-4 object-contain"><span> En caso de no recibir o extraviar su factura genere un duplicado en nuestra <strong class="font-bold">Oficina Virtual</strong>, el no recibir la factura no exime del pago oportuno. </span></div>',2)]),2)])]))}};export{L as default};
+1
View File
@@ -0,0 +1 @@
import{P as i}from"./PdfDownload-B_7ePhU0.js";import{g as c,r as l,u,c as m,d as g,f as d,F as p,b as a,M as _}from"./index-BmU8V2V2.js";import"./SectionTitle-CrHOP_mf.js";import"./SecondaryButton-CAqGmnmb.js";const f=async(o=1)=>{try{const{data:t}=await c.get(`/loadpoliticashseq?page=${o}`);return{politicas:t.records.map(e=>({id:e.ID,title:e.title,description:e.description,imagen:e.imagen,descripcion_img:e.descripcion_img,text_button:e.text_button,archivo:e.archivo})),totalPages:t.totalPages}}catch(t){throw console.log(t),new Error("Error getting publicaciones")}},P={__name:"PoliticHseqView",setup(o){const t=l(1),{data:e}=u({queryKey:["politicas",{page:t}],queryFn:()=>f(t.value),staleTime:1e3*60}),n=m(()=>{var s;return((s=e==null?void 0:e.value)==null?void 0:s.politicas)||[]});return(s,b)=>(a(!0),g(p,null,d(n.value,r=>(a(),_(i,{key:r.id,title:r.title,description:r.description,imageSrc:r.imagen,imageAlt:r.descripcion_img,buttonText:r.text_button,fileUrl:r.archivo},null,8,["title","description","imageSrc","imageAlt","buttonText","fileUrl"]))),128))}};export{P as default};
+1
View File
@@ -0,0 +1 @@
import{S as b}from"./SectionTitle-CrHOP_mf.js";import{I as y}from"./IconoLlama-BavanhPF.js";import{g,u as k,c as i,d as l,l as c,w as S,F as f,f as p,b as t,m as x,e as n,t as _,i as d,h as N,z as V,s as B}from"./index-BmU8V2V2.js";const C=async()=>{try{const{data:o}=await g.get("/prevencionseguridad-all");return o}catch(o){throw console.log(o),new Error("Error getting prevencion seguridad")}},E={class:"mx-auto py-8 px-4 sm:px-6 lg:px-8 max-w-5xl mb-8"},F={class:"text-xl font-bold mb-4"},P={class:"space-y-2"},T={key:0,class:"w-full lg:w-1/2 flex items-center"},q=["src"],L={__name:"PrevenSafetyView",setup(o){const w="https://www.gasesdeloriente.com.co",{data:u}=k({queryKey:["prevencionSeguridad"],queryFn:()=>C(),staleTime:6e4}),v=i(()=>{var m;return((m=u==null?void 0:u.value)==null?void 0:m.categorias)||[]}),r=i(()=>B.contrast);return(m,a)=>(t(),l("div",E,[c(b,null,{default:S(()=>a[0]||(a[0]=[x("Prevención y Seguridad")])),_:1}),(t(!0),l(f,null,p(v.value,(s,h)=>(t(),l("div",{class:"mb-8",key:s==null?void 0:s.categoria_id},[n("h2",F,_(s==null?void 0:s.categoria_nombre),1),n("div",{class:d(["flex flex-col gap-6 lg:flex-row items-stretch mt-4 mb-8",{"lg:flex-row-reverse":h%2!==0}])},[n("div",{class:d(["w-full lg:w-1/2 mb-4 lg:mb-0",{"lg:w-full":!(s!=null&&s.imagen)}])},[n("div",{class:d([{"bg-black":r.value,"bg-white":!r.value},"p-6 rounded-lg shadow-[0_5px_25px_rgba(0,0,0,0.1)] h-full flex flex-col"])},[n("ul",P,[(t(!0),l(f,null,p(s==null?void 0:s.records,e=>(t(),l("li",{class:"flex items-start",key:e==null?void 0:e.id},[c(y),x(" "+_(e==null?void 0:e.nombre),1)]))),128))])],2)],2),s!=null&&s.imagen?(t(),l("div",T,[n("img",{src:`${N(w)}/${s==null?void 0:s.imagen}`,alt:"Recomendaciones de Uso del Gas Natural",class:"shadow-md w-full h-full object-cover rounded-lg"},null,8,q)])):V("",!0)],2)]))),128))]))}};export{L as default};
+1
View File
@@ -0,0 +1 @@
import{_ as e,b as o,d as s,P as r}from"./index-BmU8V2V2.js";const n={},a={type:"submit",class:"primary-button py-2 px-5 bg-[#284c91] text-white font-medium rounded shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"};function c(t,d){return o(),s("button",a,[r(t.$slots,"default")])}const l=e(n,[["render",c]]);export{l as P};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{P as i}from"./PdfDownload-B_7ePhU0.js";import{u as c,M as n,h as e,b as s,k as p}from"./index-BmU8V2V2.js";import"./SectionTitle-CrHOP_mf.js";import"./SecondaryButton-CAqGmnmb.js";const P={__name:"ProtectionDataView",setup(l){const r="https://www.gasesdeloriente.com.co",{data:t}=c({queryKey:["parametrizacionweb"],queryFn:()=>p(),retry:!1});return(m,d)=>{var a,o;return s(),n(i,{title:"Protección de datos",description:(a=e(t))==null?void 0:a.proteccion_datos_descripcion,imageSrc:"/assets/img39.webp",imageAlt:"PROTECCION DE DATOS",buttonText:"PI-CIN-001 Politica de tratamiento de la información personal v5",fileUrl:`${e(r)}/${(o=e(t))==null?void 0:o.proteccion_datos}`},null,8,["description","fileUrl"])}}};export{P as default};
+1
View File
@@ -0,0 +1 @@
import{P as n}from"./PdfDownload-B_7ePhU0.js";import{g as c,r as l,u as m,c as g,d,f as u,F as p,b as a,M as _}from"./index-BmU8V2V2.js";import"./SectionTitle-CrHOP_mf.js";import"./SecondaryButton-CAqGmnmb.js";const f=async(o=1)=>{try{const{data:t}=await c.get(`/loadpublicaciones?page=${o}`);return{publicaciones:t.records.map(e=>({id:e.ID,title:e.title,description:e.description,imagen:e.imagen,descripcion_img:e.descripcion_img,archivo:e.archivo,text_button:e.text_button})),totalPages:t.totalPages}}catch(t){throw console.log(t),new Error("Error getting publicaciones")}},w={__name:"PublicationsView",setup(o){const t=l(1),{data:e}=m({queryKey:["publicaciones",{page:t}],queryFn:()=>f(t.value),staleTime:1e3*60}),i=g(()=>{var s;return((s=e==null?void 0:e.value)==null?void 0:s.publicaciones)||[]});return(s,x)=>(a(!0),d(p,null,u(i.value,r=>(a(),_(n,{key:r.id,title:r.title,description:r.description,imageSrc:r.imagen,imageAlt:r.descripcion_img,buttonText:r.text_button,fileUrl:r.archivo},null,8,["title","description","imageSrc","imageAlt","buttonText","fileUrl"]))),128))}};export{w as default};

Some files were not shown because too many files have changed in this diff Show More