Autosave: 20260209-044603

This commit is contained in:
Flatlogic Bot 2026-02-09 04:46:04 +00:00
parent 4c2a5f7938
commit 45bc0c273e
14 changed files with 93 additions and 141 deletions

View File

@ -5,7 +5,7 @@ FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1 ENV PYTHONUNBUFFERED 1
# Install system dependencies required for mysqlclient # Install system dependencies
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
default-libmysqlclient-dev \ default-libmysqlclient-dev \
build-essential \ build-essential \

View File

@ -1,54 +1,26 @@
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 5.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
import os import os
from dotenv import load_dotenv import sys
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR.parent / ".env")
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", "change-me")
DEBUG = os.getenv("DJANGO_DEBUG", "true").lower() == "true"
ALLOWED_HOSTS = [
"127.0.0.1",
"localhost",
os.getenv("HOST_FQDN", ""),
]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
CSRF_TRUSTED_ORIGINS = [
origin for origin in [
os.getenv("HOST_FQDN", ""),
os.getenv("CSRF_TRUSTED_ORIGIN", "")
] if origin
]
CSRF_TRUSTED_ORIGINS = [
f"https://{host}" if not host.startswith(("http://", "https://")) else host
for host in CSRF_TRUSTED_ORIGINS
]
# Cookies must always be HTTPS-only; SameSite=None is required for iframes.
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SAMESITE = "None"
LANGUAGE_COOKIE_SECURE = True
LANGUAGE_COOKIE_SAMESITE = "None"
# Quick-start development settings - unsuitable for production # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-change-me-locally')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'True') == 'True'
ALLOWED_HOSTS = ['*']
CSRF_TRUSTED_ORIGINS = [
'https://*.flatlogic.app',
'http://localhost:8000',
'http://127.0.0.1:8000',
]
# Application definition # Application definition
@ -66,34 +38,29 @@ INSTALLED_APPS = [
MIDDLEWARE = [ MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware', 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'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',
# Disable X-Frame-Options middleware to allow Flatlogic preview iframes. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ]
X_FRAME_OPTIONS = 'ALLOWALL'
ROOT_URLCONF = 'config.urls' ROOT_URLCONF = 'config.urls'
TEMPLATES = [ TEMPLATES = [
{ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], 'DIRS': [BASE_DIR / 'templates'], # For global templates
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request', 'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n', 'core.context_processors.deployment_timestamp', # Custom CP
# IMPORTANT: do not remove injects PROJECT_DESCRIPTION/PROJECT_IMAGE_URL and cache-busting timestamp
'core.context_processors.project_context',
'core.context_processors.global_settings',
], ],
}, },
}, },
@ -103,25 +70,22 @@ WSGI_APPLICATION = 'config.wsgi.application'
# Database # Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases # https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = { DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.mysql',
'NAME': os.getenv('DB_NAME', ''), 'NAME': os.environ.get('DB_NAME', 'flatlogic_db'),
'USER': os.getenv('DB_USER', ''), 'USER': os.environ.get('DB_USER', 'flatlogic_user'),
'PASSWORD': os.getenv('DB_PASS', ''), 'PASSWORD': os.environ.get('DB_PASS', 'flatlogic_password'),
'HOST': os.getenv('DB_HOST', '127.0.0.1'), 'HOST': os.environ.get('DB_HOST', '127.0.0.1'),
'PORT': os.getenv('DB_PORT', '3306'), 'PORT': os.environ.get('DB_PORT', '3306'),
'OPTIONS': { }
'charset': 'utf8mb4',
},
},
} }
# Password validation # Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [ AUTH_PASSWORD_VALIDATORS = [
{ {
@ -140,15 +104,9 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/ # https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en' LANGUAGE_CODE = 'en-us'
LANGUAGES = [
('en', 'English'),
('ar', 'Arabic'),
]
LOCALE_PATHS = [BASE_DIR / 'locale']
TIME_ZONE = 'UTC' TIME_ZONE = 'UTC'
@ -156,63 +114,44 @@ USE_I18N = True
USE_TZ = True USE_TZ = True
# Static files (CSS, JavaScript, Images) # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/ # https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = os.getenv("STATIC_URL", "/static/") STATIC_URL = 'static/'
MEDIA_URL = os.getenv("MEDIA_URL", "/media/")
# Collect static into a separate folder; avoid overlapping with STATICFILES_DIRS.
STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'media'
STATICFILES_DIRS = [ STATICFILES_DIRS = [
BASE_DIR / 'static', BASE_DIR / "static",
BASE_DIR / 'assets', BASE_DIR / "assets",
] ]
# Only include node_modules if it exists to avoid warnings/errors # Conditionally add node_modules if it exists (prevents W004 warning)
if (BASE_DIR / 'node_modules').exists(): if (BASE_DIR / 'node_modules').exists():
STATICFILES_DIRS.append(BASE_DIR / 'node_modules') STATICFILES_DIRS.append(BASE_DIR / 'node_modules')
# Email
EMAIL_BACKEND = os.getenv(
"EMAIL_BACKEND",
"django.core.mail.backends.smtp.EmailBackend"
)
EMAIL_HOST = os.getenv("EMAIL_HOST", "127.0.0.1")
EMAIL_PORT = int(os.getenv("EMAIL_PORT", "587"))
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_TLS = os.getenv("EMAIL_USE_TLS", "true").lower() == "true"
EMAIL_USE_SSL = os.getenv("EMAIL_USE_SSL", "false").lower() == "true"
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "no-reply@example.com")
CONTACT_EMAIL_TO = [
item.strip()
for item in os.getenv("CONTACT_EMAIL_TO", DEFAULT_FROM_EMAIL).split(",")
if item.strip()
]
# When both TLS and SSL flags are enabled, prefer SSL explicitly
if EMAIL_USE_SSL:
EMAIL_USE_TLS = False
# Authentication
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'
LOGIN_URL = '/accounts/login/'
# Default primary key field type # Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Whitenoise configuration for production # Security settings for iframe/proxy support
# Only enable if whitenoise is installed SESSION_COOKIE_SECURE = True
try: CSRF_COOKIE_SECURE = True
import whitenoise SESSION_COOKIE_SAMESITE = "None"
MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') CSRF_COOKIE_SAMESITE = "None"
# Use CompressedStaticFilesStorage instead of Manifest to avoid build crashes on missing files
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Email Settings
except ImportError: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
pass EMAIL_HOST = os.environ.get('EMAIL_HOST', 'smtp.gmail.com')
EMAIL_PORT = int(os.environ.get('EMAIL_PORT', 587))
EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS', 'True') == 'True'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', EMAIL_HOST_USER)
CONTACT_EMAIL_TO = os.environ.get('CONTACT_EMAIL_TO', '').split(',')
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

View File

@ -17,7 +17,7 @@ class Migration(migrations.Migration):
migrations.AddField( migrations.AddField(
model_name='systemsetting', model_name='systemsetting',
name='logo', name='logo',
field=models.ImageField(blank=True, null=True, upload_to='business_logos/', verbose_name='Logo'), field=models.FileField(blank=True, null=True, upload_to='business_logos/', verbose_name='Logo'),
), ),
migrations.AddField( migrations.AddField(
model_name='systemsetting', model_name='systemsetting',

View File

@ -39,7 +39,7 @@ class Migration(migrations.Migration):
migrations.AlterField( migrations.AlterField(
model_name='product', model_name='product',
name='image', name='image',
field=models.ImageField(blank=True, null=True, upload_to='product_images/', verbose_name='Product Image'), field=models.FileField(blank=True, null=True, upload_to='product_images/', verbose_name='Product Image'),
), ),
migrations.AlterField( migrations.AlterField(
model_name='product', model_name='product',

View File

@ -17,7 +17,7 @@ class Migration(migrations.Migration):
name='UserProfile', name='UserProfile',
fields=[ fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(blank=True, null=True, upload_to='profile_pics/', verbose_name='Profile Picture')), ('image', models.FileField(blank=True, null=True, upload_to='profile_pics/', verbose_name='Profile Picture')),
('phone', models.CharField(blank=True, max_length=20, verbose_name='Phone Number')), ('phone', models.CharField(blank=True, max_length=20, verbose_name='Phone Number')),
('bio', models.TextField(blank=True, verbose_name='Bio')), ('bio', models.TextField(blank=True, verbose_name='Bio')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),

View File

@ -40,7 +40,7 @@ class Product(models.Model):
min_stock_level = models.DecimalField(_("Stock Level (Alert)"), max_digits=15, decimal_places=2, default=0) min_stock_level = models.DecimalField(_("Stock Level (Alert)"), max_digits=15, decimal_places=2, default=0)
has_expiry = models.BooleanField(_("Has Expiry Date"), default=False) has_expiry = models.BooleanField(_("Has Expiry Date"), default=False)
expiry_date = models.DateField(_("Expiry Date"), null=True, blank=True) expiry_date = models.DateField(_("Expiry Date"), null=True, blank=True)
image = models.ImageField(_("Product Image"), upload_to="product_images/", blank=True, null=True) image = models.FileField(_("Product Image"), upload_to="product_images/", blank=True, null=True)
is_active = models.BooleanField(_("Active"), default=True) is_active = models.BooleanField(_("Active"), default=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
@ -392,7 +392,7 @@ class SystemSetting(models.Model):
currency_symbol = models.CharField(_("Currency Symbol"), max_length=10, default="OMR") currency_symbol = models.CharField(_("Currency Symbol"), max_length=10, default="OMR")
tax_rate = models.DecimalField(_("Tax Rate (%)"), max_digits=5, decimal_places=2, default=0) tax_rate = models.DecimalField(_("Tax Rate (%)"), max_digits=5, decimal_places=2, default=0)
decimal_places = models.PositiveSmallIntegerField(_("Decimal Places"), default=3) decimal_places = models.PositiveSmallIntegerField(_("Decimal Places"), default=3)
logo = models.ImageField(_("Logo"), upload_to="business_logos/", blank=True, null=True) logo = models.FileField(_("Logo"), upload_to="business_logos/", blank=True, null=True)
vat_number = models.CharField(_("VAT Number"), max_length=50, blank=True) vat_number = models.CharField(_("VAT Number"), max_length=50, blank=True)
registration_number = models.CharField(_("Registration Number"), max_length=50, blank=True) registration_number = models.CharField(_("Registration Number"), max_length=50, blank=True)
@ -444,7 +444,7 @@ class Device(models.Model):
class UserProfile(models.Model): class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
image = models.ImageField(_("Profile Picture"), upload_to="profile_pics/", blank=True, null=True) image = models.FileField(_("Profile Picture"), upload_to="profile_pics/", blank=True, null=True)
phone = models.CharField(_("Phone Number"), max_length=20, blank=True) phone = models.CharField(_("Phone Number"), max_length=20, blank=True)
bio = models.TextField(_("Bio"), blank=True) bio = models.TextField(_("Bio"), blank=True)

View File

@ -1,15 +1,13 @@
#!/bin/bash #!/bin/bash
set -e set -e
echo "Starting deployment script..." # Collect static files
echo "Collecting static files..." echo "Collecting static files..."
# Run collectstatic but allow it to fail without crashing the container immediately, python3 manage.py collectstatic --noinput
# so we can see the logs if something goes wrong.
python manage.py collectstatic --noinput || echo "WARNING: collectstatic failed! Check static files."
# Apply database migrations
echo "Applying migrations..." echo "Applying migrations..."
python manage.py migrate python3 manage.py migrate --noinput
echo "Starting Gunicorn..." # Start the application
exec gunicorn config.wsgi:application --bind 0.0.0.0:8000 exec gunicorn --bind 0.0.0.0:8000 config.wsgi:application

View File

@ -2,7 +2,7 @@
"""Django's command-line utility for administrative tasks.""" """Django's command-line utility for administrative tasks."""
import os import os
import sys import sys
import traceback
def main(): def main():
"""Run administrative tasks.""" """Run administrative tasks."""
@ -10,13 +10,28 @@ def main():
try: try:
from django.core.management import execute_from_command_line from django.core.management import execute_from_command_line
except ImportError as exc: except ImportError as exc:
try:
with open('startup_error.log', 'w') as f:
f.write("ImportError:\n")
f.write(traceback.format_exc())
except:
pass
raise ImportError( raise ImportError(
"Couldn't import Django. Are you sure it's installed and " "Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you " "available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?" "forget to activate a virtual environment?"
) from exc ) from exc
execute_from_command_line(sys.argv)
try:
execute_from_command_line(sys.argv)
except Exception:
try:
with open('startup_error.log', 'w') as f:
f.write("RuntimeError:\n")
f.write(traceback.format_exc())
except:
pass
raise
if __name__ == '__main__': if __name__ == '__main__':
main() main()