@sensolus/create-snt-agent-app 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/template/CLAUDE.md +218 -0
  3. package/template/Dockerfile +32 -0
  4. package/template/Jenkinsfile +28 -0
  5. package/template/README.md +477 -16
  6. package/template/_env.example +4 -0
  7. package/template/backend/app.py +630 -49
  8. package/template/backend/db_config.py +16 -0
  9. package/template/backend/extensions.py +3 -0
  10. package/template/backend/init_db.py +75 -0
  11. package/template/backend/migrations/README +1 -0
  12. package/template/backend/migrations/alembic.ini +50 -0
  13. package/template/backend/migrations/env.py +113 -0
  14. package/template/backend/migrations/script.py.mako +24 -0
  15. package/template/backend/migrations/versions/001_add_favourite_organisations.py +31 -0
  16. package/template/backend/migrations/versions/002_add_org_daily_stats.py +36 -0
  17. package/template/backend/models.py +31 -0
  18. package/template/backend/requirements.txt +8 -2
  19. package/template/eslint.config.js +6 -2
  20. package/template/index.html +11 -8
  21. package/template/infra/docker-compose.yml +15 -0
  22. package/template/openapi.json +40357 -0
  23. package/template/package.json +8 -1
  24. package/template/scripts/create-ecr-repo.sh +42 -0
  25. package/template/src/App.jsx +12 -34
  26. package/template/src/hooks/useFavourites.js +44 -0
  27. package/template/src/i18n/index.js +3 -0
  28. package/template/src/i18n/messages.js +8 -14
  29. package/template/src/i18n/translations/de.js +96 -0
  30. package/template/src/i18n/translations/en.js +103 -0
  31. package/template/src/i18n/translations/es.js +96 -0
  32. package/template/src/i18n/translations/fr.js +96 -0
  33. package/template/src/i18n/translations/nl.js +96 -0
  34. package/template/src/main.jsx +2 -3
  35. package/template/src/pages/Home.jsx +170 -0
  36. package/template/src/pages/OrganisationDetail.jsx +259 -0
  37. package/template/src/pages/OrganisationList.jsx +457 -0
  38. package/template/src/pages/Overview.jsx +199 -0
  39. package/template/src/pages/WidgetShowcase.jsx +522 -0
  40. package/template/src/styles/app.css +543 -4
  41. package/template/start-backend.sh +4 -0
  42. package/template/start-frontend.sh +3 -0
@@ -0,0 +1,16 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from pathlib import Path
4
+
5
+ # Load .env file from project root
6
+ env_path = Path(__file__).parent.parent / '.env'
7
+ load_dotenv(env_path)
8
+
9
+
10
+ def get_database_uri():
11
+ host = os.getenv('DB_HOST', 'localhost')
12
+ port = os.getenv('DB_PORT', '5432')
13
+ db = os.getenv('DB_NAME', '{{APP_NAME}}')
14
+ user = os.getenv('DB_USER', 'snt')
15
+ password = os.getenv('DB_PASSWORD', 'snt')
16
+ return f'postgresql://{user}:{password}@{host}:{port}/{db}'
@@ -0,0 +1,3 @@
1
+ from flask_sqlalchemy import SQLAlchemy
2
+
3
+ db = SQLAlchemy()
@@ -0,0 +1,75 @@
1
+ """
2
+ Database initialization script.
3
+ Run before starting gunicorn to ensure the database exists and migrations are applied.
4
+ """
5
+ import os
6
+ import sys
7
+ import logging
8
+
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s',
12
+ datefmt='%Y-%m-%d %H:%M:%S'
13
+ )
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # Ensure backend/ is on the path
17
+ sys.path.insert(0, os.path.dirname(__file__))
18
+
19
+ from db_config import get_database_uri
20
+ from sqlalchemy import create_engine, text
21
+
22
+
23
+ def ensure_database():
24
+ uri = get_database_uri()
25
+ db_name = os.getenv('DB_NAME', '{{APP_NAME}}')
26
+
27
+ # Connect to 'postgres' maintenance DB to check/create ours
28
+ maintenance_uri = uri.rsplit('/', 1)[0] + '/postgres'
29
+ engine = create_engine(maintenance_uri, isolation_level='AUTOCOMMIT')
30
+ with engine.connect() as conn:
31
+ exists = conn.execute(
32
+ text("SELECT 1 FROM pg_database WHERE datname = :name"),
33
+ {'name': db_name}
34
+ ).fetchone()
35
+ if not exists:
36
+ conn.execute(text(f'CREATE DATABASE "{db_name}"'))
37
+ logger.info(f"Created database '{db_name}'")
38
+ else:
39
+ logger.info(f"Database '{db_name}' already exists")
40
+ engine.dispose()
41
+
42
+
43
+ def repair_dirty_state():
44
+ """One-time fix: drop dirty tables left by failed migration races."""
45
+ uri = get_database_uri()
46
+ engine = create_engine(uri, isolation_level='AUTOCOMMIT')
47
+ with engine.connect() as conn:
48
+ tables = [row[0] for row in conn.execute(
49
+ text("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
50
+ )]
51
+ if 'favourite_organisations' in tables and 'alembic_version' in tables:
52
+ # Check if alembic is stuck on a revision that no longer exists (e.g. 002 was removed)
53
+ row = conn.execute(text("SELECT version_num FROM alembic_version")).fetchone()
54
+ if row and row[0] not in ('001',):
55
+ logger.info(f"Repairing dirty alembic state (stuck at {row[0]})...")
56
+ conn.execute(text("DROP TABLE IF EXISTS favourite_organisations CASCADE"))
57
+ conn.execute(text("DROP TABLE IF EXISTS alembic_version CASCADE"))
58
+ logger.info("Cleaned up — migrations will re-run from scratch")
59
+ engine.dispose()
60
+
61
+
62
+ def run_migrations():
63
+ from app import app
64
+ from flask_migrate import upgrade
65
+
66
+ with app.app_context():
67
+ logger.info("Running database migrations...")
68
+ upgrade()
69
+ logger.info("Database migrations complete")
70
+
71
+
72
+ if __name__ == '__main__':
73
+ ensure_database()
74
+ repair_dirty_state()
75
+ run_migrations()
@@ -0,0 +1 @@
1
+ Single-database configuration for Flask.
@@ -0,0 +1,50 @@
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # template used to generate migration files
5
+ # file_template = %%(rev)s_%%(slug)s
6
+
7
+ # set to 'true' to run the environment during
8
+ # the 'revision' command, regardless of autogenerate
9
+ # revision_environment = false
10
+
11
+
12
+ # Logging configuration
13
+ [loggers]
14
+ keys = root,sqlalchemy,alembic,flask_migrate
15
+
16
+ [handlers]
17
+ keys = console
18
+
19
+ [formatters]
20
+ keys = generic
21
+
22
+ [logger_root]
23
+ level = WARN
24
+ handlers = console
25
+ qualname =
26
+
27
+ [logger_sqlalchemy]
28
+ level = WARN
29
+ handlers =
30
+ qualname = sqlalchemy.engine
31
+
32
+ [logger_alembic]
33
+ level = INFO
34
+ handlers =
35
+ qualname = alembic
36
+
37
+ [logger_flask_migrate]
38
+ level = INFO
39
+ handlers =
40
+ qualname = flask_migrate
41
+
42
+ [handler_console]
43
+ class = StreamHandler
44
+ args = (sys.stderr,)
45
+ level = NOTSET
46
+ formatter = generic
47
+
48
+ [formatter_generic]
49
+ format = %(levelname)-5.5s [%(name)s] %(message)s
50
+ datefmt = %H:%M:%S
@@ -0,0 +1,113 @@
1
+ import logging
2
+ from logging.config import fileConfig
3
+
4
+ from flask import current_app
5
+
6
+ from alembic import context
7
+
8
+ # this is the Alembic Config object, which provides
9
+ # access to the values within the .ini file in use.
10
+ config = context.config
11
+
12
+ # Interpret the config file for Python logging.
13
+ # This line sets up loggers basically.
14
+ fileConfig(config.config_file_name)
15
+ logger = logging.getLogger('alembic.env')
16
+
17
+
18
+ def get_engine():
19
+ try:
20
+ # this works with Flask-SQLAlchemy<3 and Alchemical
21
+ return current_app.extensions['migrate'].db.get_engine()
22
+ except (TypeError, AttributeError):
23
+ # this works with Flask-SQLAlchemy>=3
24
+ return current_app.extensions['migrate'].db.engine
25
+
26
+
27
+ def get_engine_url():
28
+ try:
29
+ return get_engine().url.render_as_string(hide_password=False).replace(
30
+ '%', '%%')
31
+ except AttributeError:
32
+ return str(get_engine().url).replace('%', '%%')
33
+
34
+
35
+ # add your model's MetaData object here
36
+ # for 'autogenerate' support
37
+ # from myapp import mymodel
38
+ # target_metadata = mymodel.Base.metadata
39
+ config.set_main_option('sqlalchemy.url', get_engine_url())
40
+ target_db = current_app.extensions['migrate'].db
41
+
42
+ # other values from the config, defined by the needs of env.py,
43
+ # can be acquired:
44
+ # my_important_option = config.get_main_option("my_important_option")
45
+ # ... etc.
46
+
47
+
48
+ def get_metadata():
49
+ if hasattr(target_db, 'metadatas'):
50
+ return target_db.metadatas[None]
51
+ return target_db.metadata
52
+
53
+
54
+ def run_migrations_offline():
55
+ """Run migrations in 'offline' mode.
56
+
57
+ This configures the context with just a URL
58
+ and not an Engine, though an Engine is acceptable
59
+ here as well. By skipping the Engine creation
60
+ we don't even need a DBAPI to be available.
61
+
62
+ Calls to context.execute() here emit the given string to the
63
+ script output.
64
+
65
+ """
66
+ url = config.get_main_option("sqlalchemy.url")
67
+ context.configure(
68
+ url=url, target_metadata=get_metadata(), literal_binds=True
69
+ )
70
+
71
+ with context.begin_transaction():
72
+ context.run_migrations()
73
+
74
+
75
+ def run_migrations_online():
76
+ """Run migrations in 'online' mode.
77
+
78
+ In this scenario we need to create an Engine
79
+ and associate a connection with the context.
80
+
81
+ """
82
+
83
+ # this callback is used to prevent an auto-migration from being generated
84
+ # when there are no changes to the schema
85
+ # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
86
+ def process_revision_directives(context, revision, directives):
87
+ if getattr(config.cmd_opts, 'autogenerate', False):
88
+ script = directives[0]
89
+ if script.upgrade_ops.is_empty():
90
+ directives[:] = []
91
+ logger.info('No changes in schema detected.')
92
+
93
+ conf_args = current_app.extensions['migrate'].configure_args
94
+ if conf_args.get("process_revision_directives") is None:
95
+ conf_args["process_revision_directives"] = process_revision_directives
96
+
97
+ connectable = get_engine()
98
+
99
+ with connectable.connect() as connection:
100
+ context.configure(
101
+ connection=connection,
102
+ target_metadata=get_metadata(),
103
+ **conf_args
104
+ )
105
+
106
+ with context.begin_transaction():
107
+ context.run_migrations()
108
+
109
+
110
+ if context.is_offline_mode():
111
+ run_migrations_offline()
112
+ else:
113
+ run_migrations_online()
@@ -0,0 +1,24 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from alembic import op
9
+ import sqlalchemy as sa
10
+ ${imports if imports else ""}
11
+
12
+ # revision identifiers, used by Alembic.
13
+ revision = ${repr(up_revision)}
14
+ down_revision = ${repr(down_revision)}
15
+ branch_labels = ${repr(branch_labels)}
16
+ depends_on = ${repr(depends_on)}
17
+
18
+
19
+ def upgrade():
20
+ ${upgrades if upgrades else "pass"}
21
+
22
+
23
+ def downgrade():
24
+ ${downgrades if downgrades else "pass"}
@@ -0,0 +1,31 @@
1
+ """Add favourite_organisations table.
2
+
3
+ Revision ID: 001
4
+ Revises:
5
+ Create Date: 2026-05-16
6
+ """
7
+ from alembic import op
8
+ import sqlalchemy as sa
9
+
10
+ revision = '001'
11
+ down_revision = None
12
+ branch_labels = None
13
+ depends_on = None
14
+
15
+
16
+ def upgrade():
17
+ op.create_table(
18
+ 'favourite_organisations',
19
+ sa.Column('id', sa.Integer(), primary_key=True),
20
+ sa.Column('user_key', sa.String(255), nullable=False),
21
+ sa.Column('org_id', sa.Integer(), nullable=False),
22
+ sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('now()')),
23
+ )
24
+ op.create_index('ix_favourite_organisations_user_key', 'favourite_organisations', ['user_key'])
25
+ op.create_unique_constraint('uq_user_org', 'favourite_organisations', ['user_key', 'org_id'])
26
+
27
+
28
+ def downgrade():
29
+ op.drop_constraint('uq_user_org', 'favourite_organisations', type_='unique')
30
+ op.drop_index('ix_favourite_organisations_user_key', table_name='favourite_organisations')
31
+ op.drop_table('favourite_organisations')
@@ -0,0 +1,36 @@
1
+ """Add org_daily_stats table.
2
+
3
+ Revision ID: 002
4
+ Revises: 001
5
+ Create Date: 2026-06-08
6
+ """
7
+ from alembic import op
8
+ import sqlalchemy as sa
9
+
10
+ revision = '002'
11
+ down_revision = '001'
12
+ branch_labels = None
13
+ depends_on = None
14
+
15
+
16
+ def upgrade():
17
+ op.create_table(
18
+ 'org_daily_stats',
19
+ sa.Column('id', sa.Integer(), primary_key=True),
20
+ sa.Column('org_id', sa.Integer(), nullable=False),
21
+ sa.Column('org_name', sa.String(255)),
22
+ sa.Column('snapshot_date', sa.Date(), nullable=False),
23
+ sa.Column('tracker_count', sa.Integer(), nullable=False, server_default='0'),
24
+ sa.Column('user_count', sa.Integer(), nullable=False, server_default='0'),
25
+ sa.Column('captured_at', sa.DateTime(), nullable=False, server_default=sa.text('now()')),
26
+ )
27
+ op.create_index('ix_org_daily_stats_org_id', 'org_daily_stats', ['org_id'])
28
+ op.create_index('ix_org_daily_stats_snapshot_date', 'org_daily_stats', ['snapshot_date'])
29
+ op.create_unique_constraint('uq_org_day', 'org_daily_stats', ['org_id', 'snapshot_date'])
30
+
31
+
32
+ def downgrade():
33
+ op.drop_constraint('uq_org_day', 'org_daily_stats', type_='unique')
34
+ op.drop_index('ix_org_daily_stats_snapshot_date', table_name='org_daily_stats')
35
+ op.drop_index('ix_org_daily_stats_org_id', table_name='org_daily_stats')
36
+ op.drop_table('org_daily_stats')
@@ -0,0 +1,31 @@
1
+ from datetime import datetime, timezone
2
+ from extensions import db
3
+
4
+
5
+ class FavouriteOrganisation(db.Model):
6
+ __tablename__ = 'favourite_organisations'
7
+
8
+ id = db.Column(db.Integer, primary_key=True)
9
+ user_key = db.Column(db.String(255), nullable=False, index=True)
10
+ org_id = db.Column(db.Integer, nullable=False)
11
+ created_at = db.Column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
12
+
13
+ __table_args__ = (
14
+ db.UniqueConstraint('user_key', 'org_id', name='uq_user_org'),
15
+ )
16
+
17
+
18
+ class OrgDailyStat(db.Model):
19
+ __tablename__ = 'org_daily_stats'
20
+
21
+ id = db.Column(db.Integer, primary_key=True)
22
+ org_id = db.Column(db.Integer, nullable=False, index=True)
23
+ org_name = db.Column(db.String(255))
24
+ snapshot_date = db.Column(db.Date, nullable=False, index=True)
25
+ tracker_count = db.Column(db.Integer, nullable=False, default=0)
26
+ user_count = db.Column(db.Integer, nullable=False, default=0)
27
+ captured_at = db.Column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
28
+
29
+ __table_args__ = (
30
+ db.UniqueConstraint('org_id', 'snapshot_date', name='uq_org_day'),
31
+ )
@@ -1,2 +1,8 @@
1
- flask>=3.0
2
- requests>=2.31
1
+ flask
2
+ flask-apscheduler
3
+ flask-socketio
4
+ flask-sqlalchemy
5
+ flask-migrate
6
+ requests
7
+ python-dotenv
8
+ psycopg2-binary
@@ -1,5 +1,7 @@
1
1
  import js from '@eslint/js'
2
2
  import react from 'eslint-plugin-react'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import globals from 'globals'
3
5
 
4
6
  /**
5
7
  * Guardrails for the locked @sensolus/snt-agent-kit (do not remove):
@@ -14,12 +16,14 @@ export default [
14
16
  ecmaVersion: 'latest',
15
17
  sourceType: 'module',
16
18
  parserOptions: { ecmaFeatures: { jsx: true } },
17
- globals: { fetch: 'readonly', console: 'readonly', window: 'readonly', document: 'readonly' },
19
+ globals: { ...globals.browser },
18
20
  },
19
- plugins: { react },
21
+ plugins: { react, 'react-hooks': reactHooks },
20
22
  rules: {
23
+ ...reactHooks.configs.recommended.rules,
21
24
  'react/jsx-uses-react': 'error',
22
25
  'react/jsx-uses-vars': 'error',
26
+ 'no-unused-vars': ['error', { caughtErrors: 'none' }],
23
27
  'no-restricted-imports': ['error', {
24
28
  patterns: [{
25
29
  group: ['@sensolus/snt-agent-kit/*', '!@sensolus/snt-agent-kit/theme.css'],
@@ -1,12 +1,15 @@
1
- <!doctype html>
1
+ <!DOCTYPE html>
2
2
  <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <title>{{APP_NAME}}</title>
7
- </head>
8
- <body>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Sensolus Organisations Dashboard</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet">
10
+ </head>
11
+ <body>
9
12
  <div id="root"></div>
10
13
  <script type="module" src="/src/main.jsx"></script>
11
- </body>
14
+ </body>
12
15
  </html>
@@ -0,0 +1,15 @@
1
+ services:
2
+ postgres:
3
+ image: postgis/postgis:17-3.5
4
+ restart: always
5
+ ports:
6
+ - "5432:5432"
7
+ volumes:
8
+ - pgdata:/var/lib/postgresql/data
9
+ environment:
10
+ POSTGRES_USER: snt
11
+ POSTGRES_PASSWORD: snt
12
+ POSTGRES_DB: {{APP_NAME}}
13
+
14
+ volumes:
15
+ pgdata: