back 12 dic 2024

This commit is contained in:
2024-12-12 21:44:35 +00:00
parent d681b2ec3e
commit 2e875218a2
4 changed files with 300 additions and 499 deletions

View File

@@ -1,219 +1,219 @@
from pathlib import Path from pathlib import Path
import os import os
import pytz import pytz
#print time zones #print time zones
# for x in pytz.all_timezones_set: # for x in pytz.all_timezones_set:
# print(x) # print(x)
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("adminAS_KEY") SECRET_KEY = os.getenv("adminAS_KEY")
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = False
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['*']
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
#'django.contrib.sites', #'django.contrib.sites',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'allauth', 'allauth',
'allauth.account', 'allauth.account',
'allauth.socialaccount', 'allauth.socialaccount',
'rest_framework', 'rest_framework',
'rest_framework.authtoken', 'rest_framework.authtoken',
'widget_tweaks', 'widget_tweaks',
'import_export', 'import_export',
'Clientes', 'Clientes',
'IMMEX', 'IMMEX',
'Sistemas', 'Sistemas',
] ]
REST_FRAMEWORK = { REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [ 'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.BasicAuthentication',
], ],
# 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
# 'PAGE_SIZE': 100, # 'PAGE_SIZE': 100,
} }
SITE_ID = 1 SITE_ID = 1
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ]
ROOT_URLCONF = 'Admin.urls' ROOT_URLCONF = 'Admin.urls'
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Templates')], 'DIRS': [os.path.join(BASE_DIR,'Templates')],
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
'django.template.context_processors.debug', 'django.template.context_processors.debug',
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
# `allauth` needs this from django # `allauth` needs this from django
'django.template.context_processors.request', 'django.template.context_processors.request',
#custom context processor #custom context processor
'Clientes.saldo_context_proc.get_saldo', 'Clientes.saldo_context_proc.get_saldo',
], ],
}, },
}, },
] ]
AUTHENTICATION_BACKENDS = [ AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth` # Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail # `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend', 'allauth.account.auth_backends.AuthenticationBackend',
] ]
WSGI_APPLICATION = 'Admin.wsgi.application' WSGI_APPLICATION = 'Admin.wsgi.application'
ACCOUNT_FORMS = { ACCOUNT_FORMS = {
'login': 'allauth.account.forms.LoginForm', 'login': 'allauth.account.forms.LoginForm',
'signup': 'allauth.account.forms.SignupForm', 'signup': 'allauth.account.forms.SignupForm',
'add_email': 'allauth.account.forms.AddEmailForm', 'add_email': 'allauth.account.forms.AddEmailForm',
'change_password': 'allauth.account.forms.ChangePasswordForm', 'change_password': 'allauth.account.forms.ChangePasswordForm',
'set_password': 'allauth.account.forms.SetPasswordForm', 'set_password': 'allauth.account.forms.SetPasswordForm',
'reset_password': 'allauth.account.forms.ResetPasswordForm', 'reset_password': 'allauth.account.forms.ResetPasswordForm',
'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm', 'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm',
'disconnect': 'allauth.socialaccount.forms.DisconnectForm', 'disconnect': 'allauth.socialaccount.forms.DisconnectForm',
} }
LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL = '/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/accounts/login/' ACCOUNT_LOGOUT_REDIRECT_URL = '/accounts/login/'
ACCOUNT_SIGNUP_REDIRECT_URL =LOGIN_REDIRECT_URL ACCOUNT_SIGNUP_REDIRECT_URL =LOGIN_REDIRECT_URL
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
#for email auth #for email auth
ACCOUNT_EMAIL_REQUIRED =True ACCOUNT_EMAIL_REQUIRED =True
ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_TIMEOUT = 10 EMAIL_TIMEOUT = 20
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_SUBJECT_PREFIX = 'AS Timbres' EMAIL_SUBJECT_PREFIX = 'AS Timbres'
# if DEBUG : # if DEBUG :
EMAIL_USE_TLS = True EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587 EMAIL_PORT = 587
EMAIL_HOST_USER = 'aduanasoftpruebas@gmail.com' EMAIL_HOST_USER = 'aduanasoftpruebas@gmail.com'
EMAIL_HOST_PASSWORD = os.getenv("test_pwd_email") EMAIL_HOST_PASSWORD = 'gsaqrudenwnkglox'#os.getenv("test_pwd_email")
#EMAIL_USE_SSL=False #EMAIL_USE_SSL=False
# else: # else:
# EMAIL_USE_TLS = True # EMAIL_USE_TLS = True
# EMAIL_HOST = 'secure.emailsrvr.com' # EMAIL_HOST = 'secure.emailsrvr.com'
# EMAIL_PORT = 465 # EMAIL_PORT = 465
# EMAIL_HOST_USER = 'noreply@aduanasoft.com.mx' # EMAIL_HOST_USER = 'noreply@aduanasoft.com.mx'
# EMAIL_HOST_PASSWORD = 'N036p7y!'#os.getenv("pwd_email") # EMAIL_HOST_PASSWORD = 'N036p7y!'#os.getenv("pwd_email")
# #EMAIL_USE_SSL=True # #EMAIL_USE_SSL=True
# Database # Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases # https://docs.djangoproject.com/en/4.1/ref/settings/#databases
if DEBUG: if DEBUG:
DATABASES = { DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.mysql',
'NAME': 'cfdi_as', 'NAME': 'cfdi_as',
'USER': 'root', 'USER': 'root',
'PASSWORD':os.getenv("BD_PASS"), 'PASSWORD':os.getenv("BD_PASS"),
'HOST': '127.0.0.1', 'HOST': '127.0.0.1',
'PORT': '', 'PORT': '',
'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"}, 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
}, },
} }
else: else:
DATABASES={ DATABASES={
'default': { 'default': {
'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.mysql',
'NAME': 'Aduanasoft$cfdi_as', 'NAME': 'Aduanasoft$cfdi_as',
'USER': 'Aduanasoft', 'USER': 'Aduanasoft',
'PASSWORD':'Soluciones28@', 'PASSWORD':'Soluciones28@',
'HOST': 'Aduanasoft.mysql.pythonanywhere-services.com', 'HOST': 'Aduanasoft.mysql.pythonanywhere-services.com',
'PORT': '3306', 'PORT': '3306',
'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"}, 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
} }
} }
# Password validation # Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [ AUTH_PASSWORD_VALIDATORS = [
{ {
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
}, },
{ {
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
}, },
{ {
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
}, },
{ {
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
}, },
] ]
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/ # https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'es-MX' LANGUAGE_CODE = 'es-MX'
TIME_ZONE = 'America/Chihuahua' TIME_ZONE = 'America/Chihuahua'
USE_I18N = True USE_I18N = True
USE_TZ = True USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/ # https://docs.djangoproject.com/en/4.1/howto/static-files/
if not DEBUG: if not DEBUG:
#STATIC_ROOT = os.path.join(BASE_DIR, "static") #STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = [ STATICFILES_DIRS = [
BASE_DIR / 'static' BASE_DIR / 'static'
] ]
MEDIA_URL = '/media/' MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media' MEDIA_ROOT = BASE_DIR / 'media'
STATIC_URL = '/static/' STATIC_URL = '/static/'
if DEBUG: if DEBUG:
STATICFILES_DIRS = [ STATICFILES_DIRS = [
BASE_DIR / 'static', BASE_DIR / 'static',
] ]
MEDIA_URL = '/media/' MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media' MEDIA_ROOT = BASE_DIR / 'media'
STATIC_URL = '/static/' STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "static") #STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Default primary key field type # Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@@ -1,216 +0,0 @@
from pathlib import Path
import os
import pytz
#print time zones
# for x in pytz.all_timezones_set:
# print(x)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'asdasd'#os.getenv("adminAS_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
#'django.contrib.sites',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'allauth',
'allauth.account',
'allauth.socialaccount',
'widget_tweaks',
'import_export',
'Clientes',
'IMMEX',
'Sistemas',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Admin.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# `allauth` needs this from django
'django.template.context_processors.request',
#custom context processor
'Clientes.saldo_context_proc.get_saldo',
],
},
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
WSGI_APPLICATION = 'Admin.wsgi.application'
ACCOUNT_FORMS = {
'login': 'allauth.account.forms.LoginForm',
'signup': 'allauth.account.forms.SignupForm',
'add_email': 'allauth.account.forms.AddEmailForm',
'change_password': 'allauth.account.forms.ChangePasswordForm',
'set_password': 'allauth.account.forms.SetPasswordForm',
'reset_password': 'allauth.account.forms.ResetPasswordForm',
'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm',
'disconnect': 'allauth.socialaccount.forms.DisconnectForm',
}
LOGIN_REDIRECT_URL = '/'
ACCOUNT_LOGOUT_REDIRECT_URL = '/accounts/login/'
ACCOUNT_SIGNUP_REDIRECT_URL =LOGIN_REDIRECT_URL
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
#for email auth
ACCOUNT_EMAIL_REQUIRED =True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
EMAIL_TIMEOUT = 10
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_SUBJECT_PREFIX = 'AS Timbres'
# if DEBUG :
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'aduanasoftpruebas@gmail.com'
EMAIL_HOST_PASSWORD = 'zsgtbxsuwyacyhqq'#os.getenv("test_pwd_email")
#EMAIL_USE_SSL=False
# else:
# EMAIL_USE_TLS = True
# EMAIL_HOST = 'secure.emailsrvr.com'
# EMAIL_PORT = 465
# EMAIL_HOST_USER = 'noreply@aduanasoft.com.mx'
# EMAIL_HOST_PASSWORD = 'N036p7y!'#os.getenv("pwd_email")
# #EMAIL_USE_SSL=True
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
if DEBUG:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cfdi_as2',
'USER': 'root',
'PASSWORD':'bardo28',#os.getenv("BD_PASS"),
'HOST': '127.0.0.1',
'PORT': '',
'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
},
}
else:
DATABASES={
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'fjrodriguez$default',
'USER': 'fjrodriguez',
'PASSWORD':'Soluciones28@',
'HOST': 'fjrodriguez.mysql.pythonanywhere-services.com',
'PORT': '3306',
'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'es-MX'
TIME_ZONE = 'America/Chihuahua'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
if not DEBUG:
#STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@@ -58,9 +58,9 @@ def read_env_file():
for x in lista: for x in lista:
data.append(x) data.append(x)
res= ' '.join(data) res= ' '.join(data)
final = '"'+res+'"' final = '"'+res+'"'
with open(env_file, 'w') as newFile: with open(env_file, 'w') as newFile:
newFile.write("export hosts="+final) newFile.write("export hosts="+final)
except: except:
pass pass
@@ -73,22 +73,22 @@ def send_timbres_Email(request):
if req == "POST": if req == "POST":
form = EmailForm(request.POST, request.FILES) form = EmailForm(request.POST, request.FILES)
if not form.is_valid(): if not form.is_valid():
messages.add_message(request, messages.ERROR, f'{form.errors}') messages.add_message(request, messages.ERROR, f'{form.errors}')
return redirect('index') return redirect('index')
today = datetime.date.today() today = datetime.date.today()
year = today.year year = today.year
RFC = request.GET.get('RFC', None) if req=='GET' else form.cleaned_data["RFC"] RFC = request.GET.get('RFC', None) if req=='GET' else form.cleaned_data["RFC"]
mes = request.GET.get('mes', None) if req=='GET' else form.cleaned_data["mes"] mes = request.GET.get('mes', None) if req=='GET' else form.cleaned_data["mes"]
if mes is None or mes =='None': if mes is None or mes =='None':
mes = today.month mes = today.month
Cli = Clientes.objects.get(RFC=RFC) Cli = Clientes.objects.get(RFC=RFC)
subject = f'Timbres del Mes:{mes} RFC:{RFC}' if req=='GET' else ( form.cleaned_data["subject"] if 'subject' in form.cleaned_data.keys() else '' ) subject = f'Timbres del Mes:{mes} RFC:{RFC}' if req=='GET' else ( form.cleaned_data["subject"] if 'subject' in form.cleaned_data.keys() else '' )
message = 'Envio de timbres por AS_Admin' if req=='GET' else ( form.cleaned_data["message"] if 'message' in form.cleaned_data.keys() else '' ) message = 'Envio de timbres por AS_Admin' if req=='GET' else ( form.cleaned_data["message"] if 'message' in form.cleaned_data.keys() else '' )
if req=='POST': if req=='POST':
email = form.cleaned_data["email"] if 'email' in form.cleaned_data.keys() else '' email = form.cleaned_data["email"] if 'email' in form.cleaned_data.keys() else ''
emails = [Cli.email] if req=='GET' else [ Cli.email, email ] emails = [Cli.email] if req=='GET' else [ Cli.email, email ]
if len(emails) ==0 : if len(emails) ==0 :
@@ -96,7 +96,7 @@ def send_timbres_Email(request):
return redirect('index') return redirect('index')
dat =datetime.datetime(int(year), int(mes),1) dat =datetime.datetime(int(year), int(mes),1)
if dat.month in(1,3,5,7,8,10,12): if dat.month in(1,3,5,7,8,10,12):
findate = dat +datetime.timedelta(days=30) findate = dat +datetime.timedelta(days=30)
elif dat.month in (4,6,9,11): elif dat.month in (4,6,9,11):
@@ -104,35 +104,35 @@ def send_timbres_Email(request):
else: else:
findate = dat+datetime.timedelta(days=28) findate = dat+datetime.timedelta(days=28)
findate +=datetime.timedelta(days=1) findate +=datetime.timedelta(days=1)
if mes is not None and RFC is not None: if mes is not None and RFC is not None:
objeto_a_trabajar = Timbres.objects.filter(rfcc=RFC, created_at__range=[dat,findate]) objeto_a_trabajar = Timbres.objects.filter(rfcc=RFC, created_at__range=[dat,findate])
else: else:
objeto_a_trabajar = Clientes.objects.all() objeto_a_trabajar = Clientes.objects.all()
for i,ii in enumerate(objeto_a_trabajar): for i,ii in enumerate(objeto_a_trabajar):
ii.timbres_X_MES(mes=mes ) ii.timbres_X_MES(mes=mes )
wb = Workbook() wb = Workbook()
ws = wb.active ws = wb.active
if RFC is not None: if RFC is not None:
#Encabezado #Encabezado
ws['A1']='RFC_EXPEDIDO' ws['A1']='RFC_EXPEDIDO'
ws['B1']='UUID' ws['B1']='UUID'
ws['C1']='Fecha' ws['C1']='Fecha'
for q,qq in enumerate(objeto_a_trabajar,start=2): for q,qq in enumerate(objeto_a_trabajar,start=2):
ws['A' + str(q)] = qq.rfcc ws['A' + str(q)] = qq.rfcc
ws['B'+ str(q)] = qq.uuid ws['B'+ str(q)] = qq.uuid
ws['C'+ str(q)] = qq.fecha ws['C'+ str(q)] = qq.fecha
else:#cuando no es pro RFC y es para contabilizar los timbres del mes de cada cliente else:#cuando no es pro RFC y es para contabilizar los timbres del mes de cada cliente
ws['A1']='RFC_EXPEDIDO' ws['A1']='RFC_EXPEDIDO'
ws['B1']='Nombre' ws['B1']='Nombre'
ws['C1']='Timbres' ws['C1']='Timbres'
for q,qq in enumerate(objeto_a_trabajar,start=2): for q,qq in enumerate(objeto_a_trabajar,start=2):
ws['A' + str(q)] = qq.RFC ws['A' + str(q)] = qq.RFC
ws['B'+ str(q)] = qq.Nombre ws['B'+ str(q)] = qq.Nombre
ws['C'+ str(q)] = qq.conteo_mes ws['C'+ str(q)] = qq.conteo_mes
nombre_archivo = f"Timbres_{RFC if RFC is not None else 'Clientes_MES'}_{str(mes)}_AÑO_{str(year)}.xlsx" nombre_archivo = f"Timbres_{RFC if RFC is not None else 'Clientes_MES'}_{str(mes)}_AÑO_{str(year)}.xlsx"
response = HttpResponse(content_type="application/ms-excel") response = HttpResponse(content_type="application/ms-excel")
contenido = "attachment; filename = {0}".format(nombre_archivo) contenido = "attachment; filename = {0}".format(nombre_archivo)
@@ -142,36 +142,36 @@ def send_timbres_Email(request):
files = BytesIO(response.content) files = BytesIO(response.content)
try: try:
mail = EmailMessage(subject,message,settings.EMAIL_HOST_USER,emails) mail = EmailMessage(subject,message,settings.EMAIL_HOST_USER,emails)
mail.attach(filename='Timbres.xls',content=files.getbuffer(),mimetype='application/vnd.ms-excel') mail.attach(filename='Timbres.xls',content=files.getbuffer(),mimetype='application/vnd.ms-excel')
adjunto = request.FILES.getlist('adjunto') adjunto = request.FILES.getlist('adjunto')
if req=='POST' and len(adjunto) >0: if req=='POST' and len(adjunto) >0:
total = functools.reduce(lambda a, b: a+b,[adj.size for adj in adjunto]) total = functools.reduce(lambda a, b: a+b,[adj.size for adj in adjunto])
total += files.getbuffer().nbytes total += files.getbuffer().nbytes
if total > 2.5e+7: if total > 2.5e+7:
messages.add_message(request, messages.ERROR, f'Se excedio el limite de 25 MegaBytes para los adjuntos') messages.add_message(request, messages.ERROR, f'Se excedio el limite de 25 MegaBytes para los adjuntos')
return redirect('index') return redirect('index')
try: try:
for adj in adjunto: for adj in adjunto:
mail.attach(filename=adj.name,content=adj.read(),mimetype=adj.content_type) mail.attach(filename=adj.name,content=adj.read(),mimetype=adj.content_type)
except Exception as E: except Exception as E:
messages.add_message(request, messages.ERROR, f'Error Adjuntos {E}') messages.add_message(request, messages.ERROR, f'Error Adjuntos {E}')
return redirect('index') return redirect('index')
mail.send() mail.send()
messages.success(request, 'Email Enviado correctamente.') messages.success(request, 'Email Enviado correctamente.')
except Exception as E: except Exception as E:
messages.error(request, f'Email no se envio correctamente.{E}') messages.error(request, f'Email no se envio correctamente.{E}')
return redirect('index') return redirect('index')
@login_required @login_required
def index(request): def index(request):
#read_env_file() #read_env_file()
clientes_list = Clientes.objects.all() clientes_list = Clientes.objects.all()
PAC = request.GET.get('PAC',None) PAC = request.GET.get('PAC',None)
mes = request.GET.get('mes', None) mes = request.GET.get('mes', None)
today = datetime.date.today() today = datetime.date.today()
year = request.GET.get('year',None) year = request.GET.get('year',None)
if year is None or year =='None': if year is None or year =='None':
year= today.year year= today.year
@@ -240,7 +240,7 @@ def timbres_cliente(request, RFC):
lista = Timbres.objects.filter(rfcc=RFC) lista = Timbres.objects.filter(rfcc=RFC)
else: else:
lista = Timbres.objects.filter(rfcc=RFC,modo='Normal') lista = Timbres.objects.filter(rfcc=RFC,modo='Normal')
mes = request.GET.get('mes', None) mes = request.GET.get('mes', None)
year = request.GET.get('year',None) year = request.GET.get('year',None)
@@ -252,9 +252,9 @@ def timbres_cliente(request, RFC):
page = request.GET.get('page', 1) page = request.GET.get('page', 1)
datepicker = request.GET.get('datepicker', None) datepicker = request.GET.get('datepicker', None)
datepickerFin = request.GET.get('datepickerFin', None) datepickerFin = request.GET.get('datepickerFin', None)
tipo = request.GET.get('tipo',None) tipo = request.GET.get('tipo',None)
PAC= request.GET.get('PAC',None) PAC= request.GET.get('PAC',None)
if PAC is not None and PAC !='00': if PAC is not None and PAC !='00':
lista = lista.filter(rfcp=PAC) lista = lista.filter(rfcp=PAC)
@@ -316,14 +316,14 @@ def timbres_cliente(request, RFC):
@login_required @login_required
@is_staff_access() @is_staff_access()
def export_Excel(request): def export_Excel(request):
RFC = request.GET.get('RFC', None) RFC = request.GET.get('RFC', None)
mes = request.GET.get('mes',None) mes = request.GET.get('mes',None)
today = datetime.date.today() today = datetime.date.today()
month = today.month month = today.month
year = today.year year = today.year
if mes is None or mes =='None' or mes=='': if mes is None or mes =='None' or mes=='':
mes = month mes = month
@@ -338,9 +338,9 @@ def export_Excel(request):
findate +=datetime.timedelta(days=1) findate +=datetime.timedelta(days=1)
if mes is not None and RFC is not None: if mes is not None and RFC is not None:
objeto_a_trabajar = Timbres.objects.filter(rfcc=RFC, created_at__range=[dat,findate]) objeto_a_trabajar = Timbres.objects.filter(rfcc=RFC, created_at__range=[dat,findate])
else: else:
objeto_a_trabajar = Clientes.objects.all() objeto_a_trabajar = Clientes.objects.all()
for i,ii in enumerate(objeto_a_trabajar): for i,ii in enumerate(objeto_a_trabajar):
ii.timbres_X_MES(mes=mes ) ii.timbres_X_MES(mes=mes )
@@ -348,27 +348,27 @@ def export_Excel(request):
ws = wb.active ws = wb.active
if RFC is not None: if RFC is not None:
#Encabezado #Encabezado
ws['A1']='RFC_EXPEDIDO' ws['A1']='RFC_EXPEDIDO'
ws['B1']='UUID' ws['B1']='UUID'
ws['C1']='Fecha' ws['C1']='Fecha'
for q,qq in enumerate(objeto_a_trabajar,start=2): for q,qq in enumerate(objeto_a_trabajar,start=2):
ws['A' + str(q)] = qq.rfcc ws['A' + str(q)] = qq.rfcc
ws['B'+ str(q)] = qq.uuid ws['B'+ str(q)] = qq.uuid
ws['C'+ str(q)] = qq.fecha ws['C'+ str(q)] = qq.fecha
else:#cuando no es pro RFC y es para contabilizar los timbres del mes de cada cliente else:#cuando no es pro RFC y es para contabilizar los timbres del mes de cada cliente
ws['A1']='RFC_EXPEDIDO' ws['A1']='RFC_EXPEDIDO'
ws['B1']='Nombre' ws['B1']='Nombre'
ws['C1']='Timbres' ws['C1']='Timbres'
for q,qq in enumerate(objeto_a_trabajar,start=2): for q,qq in enumerate(objeto_a_trabajar,start=2):
ws['A' + str(q)] = qq.RFC ws['A' + str(q)] = qq.RFC
ws['B'+ str(q)] = qq.Nombre ws['B'+ str(q)] = qq.Nombre
ws['C'+ str(q)] = qq.conteo_mes ws['C'+ str(q)] = qq.conteo_mes
nombre_archivo = f"Timbres_{RFC if RFC is not None else 'Clientes_MES'}_{str(mes)}_AÑO_{str(year)}.xlsx" nombre_archivo = f"Timbres_{RFC if RFC is not None else 'Clientes_MES'}_{str(mes)}_AÑO_{str(year)}.xlsx"
response = HttpResponse(content_type="application/ms-excel") response = HttpResponse(content_type="application/ms-excel")
contenido = "attachment; filename = {0}".format(nombre_archivo) contenido = "attachment; filename = {0}".format(nombre_archivo)
response["Content-Disposition"] = contenido response["Content-Disposition"] = contenido
wb.save( response) wb.save( response)
return response return response
@http_basic_auth() @http_basic_auth()
@@ -385,13 +385,13 @@ def PACS_Retrive_RFCS(request):
if request.method == 'GET': if request.method == 'GET':
RFC= request.GET.get('RFC','') RFC= request.GET.get('RFC','')
rfcp = urllib.parse.unquote(RFC) rfcp = urllib.parse.unquote(RFC)
if RFC !='': if RFC !='':
timbres =list(Timbres.objects.values('rfcp').filter(rfcc__in=[RFC])) timbres =list(Timbres.objects.values('rfcp').filter(rfcc__in=[RFC]))
else: else:
timbres =list(Timbres.objects.values('rfcp').filter(rfcp__isnull=False)) timbres =list(Timbres.objects.values('rfcp').filter(rfcp__isnull=False))
else: else:
status=403 status=403
return JsonResponse({'PACS':timbres},status=status) return JsonResponse({'PACS':timbres},status=status)
#-----------------------------------API VIEWS #-----------------------------------API VIEWS
@@ -446,23 +446,23 @@ class CancelaTimbre(APIView):
msn = f'UUID:{UUID} \nCliente:{rfcc} \n {str(ex)}' msn = f'UUID:{UUID} \nCliente:{rfcc} \n {str(ex)}'
BitacoraErrores.objects.create(level=2, message=msn, traceback=traceback.format_exc(), view='Sistemas.CancelaTimbre') BitacoraErrores.objects.create(level=2, message=msn, traceback=traceback.format_exc(), view='Sistemas.CancelaTimbre')
return Response({'Error':f'{ex}','isError':True}, status=status.HTTP_200_OK) return Response({'Error':f'{ex}','isError':True}, status=status.HTTP_200_OK)
def get(self,request,*args, **kwargs): def get(self,request,*args, **kwargs):
uuid=request.query_params.get('uuid',None) uuid=request.query_params.get('uuid',None)
tim=Timbres.objects.filter(uuid=uuid).first() tim=Timbres.objects.filter(uuid=uuid).first()
if tim is not None: if tim is not None:
print(tim.rfcp) print(tim.rfcp)
return Response({"rfcp":tim.rfcp,"detail":""}) return Response({"rfcp":tim.rfcp,"detail":""})
return Response({"rfcp":"",'detail':"404 not found uuid"}) return Response({"rfcp":"",'detail':"404 not found uuid"})
class add_timbre(APIView): class add_timbre(APIView):
@@ -500,7 +500,7 @@ class add_timbre2(APIView):
modo=modo modo=modo
) )
return Response({'Error':f'{e}'}) return Response({'Error':f'{e}'})
def post(self,request): def post(self,request):
try: try:
serializer = TimbresSerializer(data=request.data) serializer = TimbresSerializer(data=request.data)
@@ -588,8 +588,8 @@ class ClientesCreateView(UserPassesTestMixin,LoginRequiredMixin,CreateView):
form_class = ClienteForm form_class = ClienteForm
success_url='/' success_url='/'
template_name='Clientes/edit_cliente.html' template_name='Clientes/edit_cliente.html'
def test_func(self): def test_func(self):
return self.request.user.groups.filter(name= 'admin_soft') return self.request.user.groups.filter(name= 'admin_soft')
def form_valid(self, form): def form_valid(self, form):
@@ -599,7 +599,7 @@ class ClientesCreateView(UserPassesTestMixin,LoginRequiredMixin,CreateView):
'id':self.object.id, 'id':self.object.id,
'RFC':self.object.RFC, 'RFC':self.object.RFC,
'Nombre':self.object.Nombre, 'Nombre':self.object.Nombre,
'Activo':self.object.Activo, 'Activo':self.object.Activo,
} }
return JsonResponse(data) return JsonResponse(data)
else: else:
@@ -621,13 +621,13 @@ class SendTimbresDisponibleEmail(APIView):
subject='Alerta Timbres Comercio', subject='Alerta Timbres Comercio',
message=f""" message=f"""
La cantidad de timbres son {saldoRequest.text} a fecha {datetime.date.today()} La cantidad de timbres son {saldoRequest.text} a fecha {datetime.date.today()}
este correo se envio automaticamente desde server, no es necesario contestar, solo es informativo. este correo se envio automaticamente desde server, no es necesario contestar, solo es informativo.
Saludos Saludos
atte: atte:
FJRR FJRR
""", """,
from_email='aduanasoftpruebas@gmail.com', from_email='aduanasoftpruebas@gmail.com',
recipient_list=['fjrodriguez@aduanasoft.com.mx']#,'mcervantes@aduanasoft.com.mx','ddominguez@aduanasoft.com.mx'], recipient_list=['fjrodriguez@aduanasoft.com.mx','mcervantes@aduanasoft.com.mx','ddominguez@aduanasoft.com.mx'],
) )
return Response({'message':'Correo enviado exitosamente'}) return Response({'message':'Correo enviado exitosamente'})

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.1.3 on 2024-02-04 05:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("IMMEX", "0010_alter_suspensionpermiso_suspension_modulo"),
]
operations = [
migrations.AlterModelOptions(
name="suspensionpermiso",
options={"ordering": ["suspension_modulo"]},
),
]