KintoneAppBuilder created

This commit is contained in:
2023-07-10 09:40:49 +09:00
commit 80446a3860
94 changed files with 13622 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
.vscode
.mypy_cache
docker-stack.yml

1
.prettierignore Normal file
View File

@@ -0,0 +1 @@
docker-compose.yml

126
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,126 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyderproject2
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# VS Code settings
.vscode/

13
backend/Dockerfile Normal file
View File

@@ -0,0 +1,13 @@
FROM python:3.8
RUN mkdir /app
WORKDIR /app
RUN apt update && \
apt install -y postgresql-client
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

159
backend/README.en.md Normal file
View File

@@ -0,0 +1,159 @@
# KintoneAppBuilder
## Features
- **FastAPI** with Python 3.8
- **React 16** with Typescript, Redux, and react-router
- Postgres
- SqlAlchemy with Alembic for migrations
- Pytest for backend tests
- Jest for frontend tests
- Perttier/Eslint (with Airbnb style guide)
- Docker compose for easier development
- Nginx as a reverse proxy to allow backend and frontend on the same port
## Development
The only dependencies for this project should be docker and docker-compose.
### Quick Start
Starting the project with hot-reloading enabled
(the first time it will take a while):
```bash
docker-compose up -d
```
To run the alembic migrations (for the users table):
```bash
docker-compose run --rm backend alembic upgrade head
```
And navigate to http://localhost:8000
_Note: If you see an Nginx error at first with a `502: Bad Gateway` page, you may have to wait for webpack to build the development server (the nginx container builds much more quickly)._
Auto-generated docs will be at
http://localhost:8000/api/docs
### Rebuilding containers:
```
docker-compose build
```
### Restarting containers:
```
docker-compose restart
```
### Bringing containers down:
```
docker-compose down
```
### Frontend Development
Alternatively to running inside docker, it can sometimes be easier
to use npm directly for quicker reloading. To run using npm:
```
cd frontend
npm install
npm start
```
This should redirect you to http://localhost:3000
### Frontend Tests
```
cd frontend
npm install
npm test
```
## Migrations
Migrations are run using alembic. To run all migrations:
```
docker-compose run --rm backend alembic upgrade head
```
To create a new migration:
```
alembic revision -m "create users table"
```
And fill in `upgrade` and `downgrade` methods. For more information see
[Alembic's official documentation](https://alembic.sqlalchemy.org/en/latest/tutorial.html#create-a-migration-script).
## Testing
There is a helper script for both frontend and backend tests:
```
./scripts/test.sh
```
### Backend Tests
```
docker-compose run backend pytest
```
any arguments to pytest can also be passed after this command
### Frontend Tests
```
docker-compose run frontend test
```
This is the same as running npm test from within the frontend directory
## Logging
```
docker-compose logs
```
Or for a specific service:
```
docker-compose logs -f name_of_service # frontend|backend|db
```
## Project Layout
```
backend
└── app
├── alembic
│ └── versions # where migrations are located
├── api
│ └── api_v1
│ └── endpoints
├── core # config
├── db # db models
├── tests # pytest
└── main.py # entrypoint to backend
frontend
└── public
└── src
├── components
│ └── Home.tsx
├── config
│ └── index.tsx # constants
├── __tests__
│ └── test_home.tsx
├── index.tsx # entrypoint
└── App.tsx # handles routing
```

18
backend/Temp/app.json Normal file
View File

@@ -0,0 +1,18 @@
{
"appId": "5",
"code": "",
"name": "日報",
"description": "<div>日々の業務内容、報告事項、所感などを記載していくアプリです。<div>記録を行うだけでなく、あとからの振り返りやメンバー間のコミュニケーションにも活用できます。</div></div>",
"createdAt": "2023-07-08T02:03:27.000Z",
"creator": {
"code": "MXZ",
"name": "馬 小哲"
},
"modifiedAt": "2023-07-08T02:26:06.000Z",
"modifier": {
"code": "MXZ",
"name": "馬 小哲"
},
"spaceId": null,
"threadId": null
}

View File

77
backend/Temp/form.json Normal file
View File

@@ -0,0 +1,77 @@
{
"properties": [
{
"type": "CREATOR",
"label": "作成者",
"noLabel": "false",
"code": "作成者"
},
{
"type": "MULTI_LINE_TEXT",
"label": "業務内容",
"noLabel": "false",
"code": "文字列__複数行_",
"required": "false",
"defaultValue": ""
},
{
"type": "MULTI_LINE_TEXT",
"label": "所感、学び",
"noLabel": "false",
"code": "文字列__複数行__0",
"required": "false",
"defaultValue": ""
},
{
"type": "FILE",
"label": "添付ファイル",
"noLabel": "false",
"code": "添付ファイル",
"required": "false"
},
{
"type": "DATE",
"label": "日付",
"noLabel": "false",
"code": "日付",
"required": "false",
"unique": "false",
"defaultValue": null,
"defaultExpression": "NOW"
},
{
"type": "DROP_DOWN",
"label": "部署",
"noLabel": "false",
"code": "ドロップダウン",
"required": "false",
"options": [
"営業",
"マーケティング",
"総務",
"サポート",
"開発"
],
"defaultValue": null
},
{
"type": "RADIO_BUTTON",
"label": "目標達成度",
"noLabel": "false",
"code": "ラジオボタン",
"required": "true",
"options": [
"達成",
"未達"
],
"defaultValue": "達成"
},
{
"type": "USER_SELECT",
"label": "確認者",
"noLabel": "true",
"code": "ユーザー選択",
"required": "false"
}
]
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,145 @@
{
"revision": "16",
"properties": {
"レコード番号": {
"type": "RECORD_NUMBER",
"code": "レコード番号",
"label": "レコード番号",
"noLabel": false
},
"作業者": {
"type": "STATUS_ASSIGNEE",
"code": "作業者",
"label": "作業者",
"enabled": true
},
"更新者": {
"type": "MODIFIER",
"code": "更新者",
"label": "更新者",
"noLabel": false
},
"作成者": {
"type": "CREATOR",
"code": "作成者",
"label": "作成者",
"noLabel": false
},
"ステータス": {
"type": "STATUS",
"code": "ステータス",
"label": "ステータス",
"enabled": true
},
"ラジオボタン": {
"type": "RADIO_BUTTON",
"code": "ラジオボタン",
"label": "目標達成度",
"noLabel": false,
"required": true,
"options": {
"未達": {
"label": "未達",
"index": "1"
},
"達成": {
"label": "達成",
"index": "0"
}
},
"defaultValue": "達成",
"align": "HORIZONTAL"
},
"ドロップダウン": {
"type": "DROP_DOWN",
"code": "ドロップダウン",
"label": "部署",
"noLabel": false,
"required": false,
"options": {
"総務": {
"label": "総務",
"index": "2"
},
"サポート": {
"label": "サポート",
"index": "3"
},
"マーケティング": {
"label": "マーケティング",
"index": "1"
},
"営業": {
"label": "営業",
"index": "0"
},
"開発": {
"label": "開発",
"index": "4"
}
},
"defaultValue": ""
},
"ユーザー選択": {
"type": "USER_SELECT",
"code": "ユーザー選択",
"label": "確認者",
"noLabel": true,
"required": false,
"entities": [],
"defaultValue": []
},
"更新日時": {
"type": "UPDATED_TIME",
"code": "更新日時",
"label": "更新日時",
"noLabel": false
},
"カテゴリー": {
"type": "CATEGORY",
"code": "カテゴリー",
"label": "カテゴリー",
"enabled": false
},
"文字列__複数行__0": {
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行__0",
"label": "所感、学び",
"noLabel": false,
"required": false,
"defaultValue": ""
},
"文字列__複数行_": {
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行_",
"label": "業務内容",
"noLabel": false,
"required": false,
"defaultValue": ""
},
"添付ファイル": {
"type": "FILE",
"code": "添付ファイル",
"label": "添付ファイル",
"noLabel": false,
"required": false,
"thumbnailSize": "150"
},
"作成日時": {
"type": "CREATED_TIME",
"code": "作成日時",
"label": "作成日時",
"noLabel": false
},
"日付": {
"type": "DATE",
"code": "日付",
"label": "日付",
"noLabel": false,
"required": false,
"unique": false,
"defaultValue": "",
"defaultNowValue": true
}
}
}

View File

@@ -0,0 +1,83 @@
{
"layout": [
{
"type": "ROW",
"fields": [
{
"type": "DATE",
"code": "日付",
"size": {
"width": "117"
}
},
{
"type": "CREATOR",
"code": "作成者",
"size": {
"width": "120"
}
},
{
"type": "DROP_DOWN",
"code": "ドロップダウン",
"size": {
"width": "142"
}
},
{
"type": "USER_SELECT",
"code": "ユーザー選択",
"size": {
"width": "344"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行_",
"size": {
"width": "444",
"innerHeight": "115"
}
},
{
"type": "RADIO_BUTTON",
"code": "ラジオボタン",
"size": {
"width": "194"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行__0",
"size": {
"width": "444",
"innerHeight": "115"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "FILE",
"code": "添付ファイル",
"size": {
"width": "207"
}
}
]
}
],
"revision": "16"
}

View File

@@ -0,0 +1,83 @@
{
"layout": [
{
"type": "ROW",
"fields": [
{
"type": "DATE",
"code": "日付",
"size": {
"width": "117"
}
},
{
"type": "CREATOR",
"code": "作成者",
"size": {
"width": "120"
}
},
{
"type": "DROP_DOWN",
"code": "ドロップダウン",
"size": {
"width": "142"
}
},
{
"type": "USER_SELECT",
"code": "ユーザー選択",
"size": {
"width": "344"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行_",
"size": {
"width": "444",
"innerHeight": "115"
}
},
{
"type": "RADIO_BUTTON",
"code": "ラジオボタン",
"size": {
"width": "194"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "MULTI_LINE_TEXT",
"code": "文字列__複数行__0",
"size": {
"width": "444",
"innerHeight": "115"
}
}
]
},
{
"type": "ROW",
"fields": [
{
"type": "FILE",
"code": "添付ファイル",
"size": {
"width": "207"
}
}
]
}
],
"revision": "16"
}

82
backend/alembic.ini Normal file
View File

@@ -0,0 +1,82 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = app/alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
timezone = America/Los_Angeles
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

0
backend/app/__init__.py Normal file
View File

85
backend/app/alembic.ini Normal file
View File

@@ -0,0 +1,85 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

View File

@@ -0,0 +1 @@
Generic single-database configuration.

View File

View File

@@ -0,0 +1,81 @@
import os
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from app.db.models import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_url():
return os.getenv("DATABASE_URL")
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
# url = config.get_main_option("sqlalchemy.url")
url = get_url()
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,34 @@
"""create users table
Revision ID: 91979b40eb38
Revises:
Create Date: 2020-03-23 14:53:53.101322
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "91979b40eb38"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"user",
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("email", sa.String(50), nullable=False),
sa.Column("first_name", sa.String(100)),
sa.Column("last_name", sa.String(100)),
sa.Column("address", sa.String(100)),
sa.Column("hashed_password", sa.String(100), nullable=False),
sa.Column("is_active", sa.Boolean, nullable=False),
sa.Column("is_superuser", sa.Boolean, nullable=False),
)
def downgrade():
op.drop_table("user")

View File

View File

View File

@@ -0,0 +1,63 @@
from fastapi.security import OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, status
from datetime import timedelta
from app.db.session import get_db
from app.core import security
from app.core.auth import authenticate_user, sign_up_new_user
auth_router = r = APIRouter()
@r.post("/token")
async def login(
db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
user = authenticate_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = security.create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
@r.post("/signup")
async def signup(
db=Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
user = sign_up_new_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Account already exists",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(
minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES
)
if user.is_superuser:
permissions = "admin"
else:
permissions = "user"
access_token = security.create_access_token(
data={"sub": user.email, "permissions": permissions},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}

View File

@@ -0,0 +1,66 @@
from app.core import security
# Monkey patch function we can use to shave a second off our tests by skipping the password hashing check
def verify_password_mock(first: str, second: str):
return True
def test_login(client, test_user, monkeypatch):
# Patch the test to skip password hashing check for speed
monkeypatch.setattr(security, "verify_password", verify_password_mock)
response = client.post(
"/api/token",
data={"username": test_user.email, "password": "nottheactualpass"},
)
assert response.status_code == 200
def test_signup(client, monkeypatch):
def get_password_hash_mock(first: str, second: str):
return True
monkeypatch.setattr(security, "get_password_hash", get_password_hash_mock)
response = client.post(
"/api/signup",
data={"username": "some@email.com", "password": "randompassword"},
)
assert response.status_code == 200
def test_resignup(client, test_user, monkeypatch):
# Patch the test to skip password hashing check for speed
monkeypatch.setattr(security, "verify_password", verify_password_mock)
response = client.post(
"/api/signup",
data={
"username": test_user.email,
"password": "password_hashing_is_skipped_via_monkey_patch",
},
)
assert response.status_code == 409
def test_wrong_password(
client, test_db, test_user, test_password, monkeypatch
):
def verify_password_failed_mock(first: str, second: str):
return False
monkeypatch.setattr(
security, "verify_password", verify_password_failed_mock
)
response = client.post(
"/api/token", data={"username": test_user.email, "password": "wrong"}
)
assert response.status_code == 401
def test_wrong_login(client, test_db, test_user, test_password):
response = client.post(
"/api/token", data={"username": "fakeuser", "password": test_password}
)
assert response.status_code == 401

View File

@@ -0,0 +1,110 @@
from app.db import models
def test_get_users(client, test_superuser, superuser_token_headers):
response = client.get("/api/v1/users", headers=superuser_token_headers)
assert response.status_code == 200
assert response.json() == [
{
"id": test_superuser.id,
"email": test_superuser.email,
"is_active": test_superuser.is_active,
"is_superuser": test_superuser.is_superuser,
}
]
def test_delete_user(client, test_superuser, test_db, superuser_token_headers):
response = client.delete(
f"/api/v1/users/{test_superuser.id}", headers=superuser_token_headers
)
assert response.status_code == 200
assert test_db.query(models.User).all() == []
def test_delete_user_not_found(client, superuser_token_headers):
response = client.delete(
"/api/v1/users/4321", headers=superuser_token_headers
)
assert response.status_code == 404
def test_edit_user(client, test_superuser, superuser_token_headers):
new_user = {
"email": "newemail@email.com",
"is_active": False,
"is_superuser": True,
"first_name": "Joe",
"last_name": "Smith",
"password": "new_password",
}
response = client.put(
f"/api/v1/users/{test_superuser.id}",
json=new_user,
headers=superuser_token_headers,
)
assert response.status_code == 200
new_user["id"] = test_superuser.id
new_user.pop("password")
assert response.json() == new_user
def test_edit_user_not_found(client, test_db, superuser_token_headers):
new_user = {
"email": "newemail@email.com",
"is_active": False,
"is_superuser": False,
"password": "new_password",
}
response = client.put(
"/api/v1/users/1234", json=new_user, headers=superuser_token_headers
)
assert response.status_code == 404
def test_get_user(
client,
test_user,
superuser_token_headers,
):
response = client.get(
f"/api/v1/users/{test_user.id}", headers=superuser_token_headers
)
assert response.status_code == 200
assert response.json() == {
"id": test_user.id,
"email": test_user.email,
"is_active": bool(test_user.is_active),
"is_superuser": test_user.is_superuser,
}
def test_user_not_found(client, superuser_token_headers):
response = client.get("/api/v1/users/123", headers=superuser_token_headers)
assert response.status_code == 404
def test_authenticated_user_me(client, user_token_headers):
response = client.get("/api/v1/users/me", headers=user_token_headers)
assert response.status_code == 200
def test_unauthenticated_routes(client):
response = client.get("/api/v1/users/me")
assert response.status_code == 401
response = client.get("/api/v1/users")
assert response.status_code == 401
response = client.get("/api/v1/users/123")
assert response.status_code == 401
response = client.put("/api/v1/users/123")
assert response.status_code == 401
response = client.delete("/api/v1/users/123")
assert response.status_code == 401
def test_unauthorized_routes(client, user_token_headers):
response = client.get("/api/v1/users", headers=user_token_headers)
assert response.status_code == 403
response = client.get("/api/v1/users/123", headers=user_token_headers)
assert response.status_code == 403

View File

@@ -0,0 +1,107 @@
from fastapi import APIRouter, Request, Depends, Response, encoders
import typing as t
from app.db.session import get_db
from app.db.crud import (
get_users,
get_user,
create_user,
delete_user,
edit_user,
)
from app.db.schemas import UserCreate, UserEdit, User, UserOut
from app.core.auth import get_current_active_user, get_current_active_superuser
users_router = r = APIRouter()
@r.get(
"/users",
response_model=t.List[User],
response_model_exclude_none=True,
)
async def users_list(
response: Response,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Get all users
"""
users = get_users(db)
# This is necessary for react-admin to work
response.headers["Content-Range"] = f"0-9/{len(users)}"
return users
@r.get("/users/me", response_model=User, response_model_exclude_none=True)
async def user_me(current_user=Depends(get_current_active_user)):
"""
Get own user
"""
return current_user
@r.get(
"/users/{user_id}",
response_model=User,
response_model_exclude_none=True,
)
async def user_details(
request: Request,
user_id: int,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Get any user details
"""
user = get_user(db, user_id)
return user
# return encoders.jsonable_encoder(
# user, skip_defaults=True, exclude_none=True,
# )
@r.post("/users", response_model=User, response_model_exclude_none=True)
async def user_create(
request: Request,
user: UserCreate,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Create a new user
"""
return create_user(db, user)
@r.put(
"/users/{user_id}", response_model=User, response_model_exclude_none=True
)
async def user_edit(
request: Request,
user_id: int,
user: UserEdit,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Update existing user
"""
return edit_user(db, user_id, user)
@r.delete(
"/users/{user_id}", response_model=User, response_model_exclude_none=True
)
async def user_delete(
request: Request,
user_id: int,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Delete existing user
"""
return delete_user(db, user_id)

View File

View File

75
backend/app/core/auth.py Normal file
View File

@@ -0,0 +1,75 @@
import jwt
from fastapi import Depends, HTTPException, status
from jwt import PyJWTError
from app.db import models, schemas, session
from app.db.crud import get_user_by_email, create_user
from app.core import security
async def get_current_user(
db=Depends(session.get_db), token: str = Depends(security.oauth2_scheme)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(
token, security.SECRET_KEY, algorithms=[security.ALGORITHM]
)
email: str = payload.get("sub")
if email is None:
raise credentials_exception
permissions: str = payload.get("permissions")
token_data = schemas.TokenData(email=email, permissions=permissions)
except PyJWTError:
raise credentials_exception
user = get_user_by_email(db, token_data.email)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(
current_user: models.User = Depends(get_current_user),
):
if not current_user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
async def get_current_active_superuser(
current_user: models.User = Depends(get_current_user),
) -> models.User:
if not current_user.is_superuser:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
return current_user
def authenticate_user(db, email: str, password: str):
user = get_user_by_email(db, email)
if not user:
return False
if not security.verify_password(password, user.hashed_password):
return False
return user
def sign_up_new_user(db, email: str, password: str):
user = get_user_by_email(db, email)
if user:
return False # User already exists
new_user = create_user(
db,
schemas.UserCreate(
email=email,
password=password,
is_active=True,
is_superuser=False,
),
)
return new_user

View File

@@ -0,0 +1,5 @@
from celery import Celery
celery_app = Celery("worker", broker="redis://redis:6379/0")
celery_app.conf.task_routes = {"app.tasks.*": "main-queue"}

View File

@@ -0,0 +1,7 @@
import os
PROJECT_NAME = "KintoneAppBuilder"
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL")
API_V1_STR = "/api/v1"

View File

@@ -0,0 +1,31 @@
import jwt
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from datetime import datetime, timedelta
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "alicorns"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

View File

69
backend/app/db/crud.py Normal file
View File

@@ -0,0 +1,69 @@
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
import typing as t
from . import models, schemas
from app.core.security import get_password_hash
def get_user(db: Session, user_id: int):
user = db.query(models.User).filter(models.User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
def get_user_by_email(db: Session, email: str) -> schemas.UserBase:
return db.query(models.User).filter(models.User.email == email).first()
def get_users(
db: Session, skip: int = 0, limit: int = 100
) -> t.List[schemas.UserOut]:
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
hashed_password = get_password_hash(user.password)
db_user = models.User(
first_name=user.first_name,
last_name=user.last_name,
email=user.email,
is_active=user.is_active,
is_superuser=user.is_superuser,
hashed_password=hashed_password,
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def delete_user(db: Session, user_id: int):
user = get_user(db, user_id)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
db.delete(user)
db.commit()
return user
def edit_user(
db: Session, user_id: int, user: schemas.UserEdit
) -> schemas.User:
db_user = get_user(db, user_id)
if not db_user:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
update_data = user.dict(exclude_unset=True)
if "password" in update_data:
update_data["hashed_password"] = get_password_hash(user.password)
del update_data["password"]
for key, value in update_data.items():
setattr(db_user, key, value)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user

15
backend/app/db/models.py Normal file
View File

@@ -0,0 +1,15 @@
from sqlalchemy import Boolean, Column, Integer, String
from .session import Base
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
first_name = Column(String)
last_name = Column(String)
hashed_password = Column(String, nullable=False)
is_active = Column(Boolean, default=True)
is_superuser = Column(Boolean, default=False)

45
backend/app/db/schemas.py Normal file
View File

@@ -0,0 +1,45 @@
from pydantic import BaseModel
import typing as t
class UserBase(BaseModel):
email: str
is_active: bool = True
is_superuser: bool = False
first_name: str = None
last_name: str = None
class UserOut(UserBase):
pass
class UserCreate(UserBase):
password: str
class Config:
orm_mode = True
class UserEdit(UserBase):
password: t.Optional[str] = None
class Config:
orm_mode = True
class User(UserBase):
id: int
class Config:
orm_mode = True
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
email: str = None
permissions: str = "user"

21
backend/app/db/session.py Normal file
View File

@@ -0,0 +1,21 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core import config
engine = create_engine(
config.SQLALCHEMY_DATABASE_URI,
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

View File

@@ -0,0 +1,26 @@
#!/usr/bin/env python3
from app.db.session import get_db
from app.db.crud import create_user
from app.db.schemas import UserCreate
from app.db.session import SessionLocal
def init() -> None:
db = SessionLocal()
create_user(
db,
UserCreate(
email="maxiaozhe@alicorns.co.jp",
password="maxz1205",
is_active=True,
is_superuser=True,
),
)
if __name__ == "__main__":
print("Creating superuser maxiaozhe@alicorns.co.jp")
init()
print("Superuser created")

49
backend/app/main.py Normal file
View File

@@ -0,0 +1,49 @@
from fastapi import FastAPI, Depends
from starlette.requests import Request
import uvicorn
from app.api.api_v1.routers.users import users_router
from app.api.api_v1.routers.auth import auth_router
from app.core import config
from app.db.session import SessionLocal
from app.core.auth import get_current_active_user
from app.core.celery_app import celery_app
from app import tasks
app = FastAPI(
title=config.PROJECT_NAME, docs_url="/api/docs", openapi_url="/api"
)
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
request.state.db = SessionLocal()
response = await call_next(request)
request.state.db.close()
return response
@app.get("/api/v1")
async def root():
return {"message": "Hello World"}
@app.get("/api/v1/task")
async def example_task():
celery_app.send_task("app.tasks.example_task", args=["Hello World"])
return {"message": "success"}
# Routers
app.include_router(
users_router,
prefix="/api/v1",
tags=["users"],
dependencies=[Depends(get_current_active_user)],
)
app.include_router(auth_router, prefix="/api", tags=["auth"])
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", reload=True, port=8888)

6
backend/app/tasks.py Normal file
View File

@@ -0,0 +1,6 @@
from app.core.celery_app import celery_app
@celery_app.task(acks_late=True)
def example_task(word: str) -> str:
return f"test task returns {word}"

View File

View File

@@ -0,0 +1,4 @@
def test_read_main(client):
response = client.get("/api/v1")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}

View File

@@ -0,0 +1,6 @@
from app import tasks
def test_example_task():
task_output = tasks.example_task("Hello World")
assert task_output == "test task returns Hello World"

169
backend/conftest.py Normal file
View File

@@ -0,0 +1,169 @@
import pytest
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database, drop_database
from fastapi.testclient import TestClient
import typing as t
from app.core import config, security
from app.db.session import Base, get_db
from app.db import models
from app.main import app
def get_test_db_url() -> str:
return f"{config.SQLALCHEMY_DATABASE_URI}_test"
@pytest.fixture
def test_db():
"""
Modify the db session to automatically roll back after each test.
This is to avoid tests affecting the database state of other tests.
"""
# Connect to the test database
engine = create_engine(
get_test_db_url(),
)
connection = engine.connect()
trans = connection.begin()
# Run a parent transaction that can roll back all changes
test_session_maker = sessionmaker(
autocommit=False, autoflush=False, bind=engine
)
test_session = test_session_maker()
test_session.begin_nested()
@event.listens_for(test_session, "after_transaction_end")
def restart_savepoint(s, transaction):
if transaction.nested and not transaction._parent.nested:
s.expire_all()
s.begin_nested()
yield test_session
# Roll back the parent transaction after the test is complete
test_session.close()
trans.rollback()
connection.close()
@pytest.fixture(scope="session", autouse=True)
def create_test_db():
"""
Create a test database and use it for the whole test session.
"""
test_db_url = get_test_db_url()
# Create the test database
assert not database_exists(
test_db_url
), "Test database already exists. Aborting tests."
create_database(test_db_url)
test_engine = create_engine(test_db_url)
Base.metadata.create_all(test_engine)
# Run the tests
yield
# Drop the test database
drop_database(test_db_url)
@pytest.fixture
def client(test_db):
"""
Get a TestClient instance that reads/write to the test database.
"""
def get_test_db():
yield test_db
app.dependency_overrides[get_db] = get_test_db
yield TestClient(app)
@pytest.fixture
def test_password() -> str:
return "securepassword"
def get_password_hash() -> str:
"""
Password hashing can be expensive so a mock will be much faster
"""
return "supersecrethash"
@pytest.fixture
def test_user(test_db) -> models.User:
"""
Make a test user in the database
"""
user = models.User(
email="fake@email.com",
hashed_password=get_password_hash(),
is_active=True,
)
test_db.add(user)
test_db.commit()
return user
@pytest.fixture
def test_superuser(test_db) -> models.User:
"""
Superuser for testing
"""
user = models.User(
email="fakeadmin@email.com",
hashed_password=get_password_hash(),
is_superuser=True,
)
test_db.add(user)
test_db.commit()
return user
def verify_password_mock(first: str, second: str) -> bool:
return True
@pytest.fixture
def user_token_headers(
client: TestClient, test_user, test_password, monkeypatch
) -> t.Dict[str, str]:
monkeypatch.setattr(security, "verify_password", verify_password_mock)
login_data = {
"username": test_user.email,
"password": test_password,
}
r = client.post("/api/token", data=login_data)
tokens = r.json()
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
return headers
@pytest.fixture
def superuser_token_headers(
client: TestClient, test_superuser, test_password, monkeypatch
) -> t.Dict[str, str]:
monkeypatch.setattr(security, "verify_password", verify_password_mock)
login_data = {
"username": test_superuser.email,
"password": test_password,
}
r = client.post("/api/token", data=login_data)
tokens = r.json()
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
return headers

2
backend/pyproject.toml Normal file
View File

@@ -0,0 +1,2 @@
[tool.black]
line-length = 80

27
backend/readme.md Normal file
View File

@@ -0,0 +1,27 @@
### 1: Pythonインストール
https://www.python.org/downloads/
### 2. venv設定
```
#仮想環境を設定する
python -m venv env
#仮想環境をアクティベート
.\env\Scripts\activate
```
### 4FastAPIとUvicornのインストール
仮想環境にFastAPIとUvicornASGIサーバーをインストールします。
1. fastapi
```bash
pip install fastapi
```
2. Uvicornをインストールします
```bash
pip install uvicorn
```
3. すべて依頼をインストール
```bash
pip install -r requirements.txt
```

159
backend/readme.zh.md Normal file
View File

@@ -0,0 +1,159 @@
# KintoneAppBuilder
## 特性
- 使用 Python 3.8 的 **FastAPI**
- 结合 Typescript、Redux 和 react-router 的 **React 16**
- Postgres 数据库
- 用于迁移的 SqlAlchemy 和 Alembic
- 后端测试的 Pytest
- 前端测试的 Jest
- 遵循 Airbnb 代码风格的 Prettier/Eslint
- 方便开发的 Docker compose
- 用于实现后端和前端在同一端口上的 Nginx 反向代理
## 开发
此项目唯一的依赖应为 docker 和 docker-compose。
### 快速开始
启动项目并启用热加载
(首次操作可能需要一些时间):
```bash
docker-compose up -d
```
运行 alembic 迁移(针对 users 表):
```bash
docker-compose run --rm backend alembic upgrade head
```
然后,导航到 http://localhost:8000
_注如果你最初看到一个带有 `502Bad Gateway` 页面的 Nginx 错误,你可能需要等待 webpack 构建开发服务器nginx 容器构建得更快。_
自动生成的文档将位于
http://localhost:8000/api/docs
### 重建容器:
```
docker-compose build
```
### 重启容器:
```
docker-compose restart
```
### 关闭容器:
```
docker-compose down
```
### 前端开发
作为 docker 内部运行的替代方案,直接使用 npm 有时更简单,
以便于更快的重加载。使用 npm 运行:
```
cd frontend
npm install
npm start
```
这应将你重定向到 http://localhost:3000
### 前端测试
```
cd frontend
npm install
npm test
```
## 迁移
使用 alembic 运行迁移。运行所有迁移:
```
docker-compose run --rm backend alembic upgrade head
```
创建新的迁移:
```
alembic revision -m "create users table"
```
并填写 `upgrade``downgrade` 方法。更多信息请参阅
[Alembic 的官方文档](https://alembic.sqlalchemy.org/en/latest/tutorial.html#create-a-migration-script)。
## 测试
存在一个用于前端和后端测试的辅助脚本:
```
./scripts/test.sh
```
### 后端测试
```
docker-compose run backend pytest
```
此命令之后也可以传递给 pytest 的任何参数
### 前端测试
```
docker-compose run frontend test
```
这与从前端目录内运行 npm test 是相同的
## 日志
```
docker-compose logs
```
或针对特定服务:
```
docker-compose logs -f name_of_service # frontend|backend|db
```
## 项目布局
```
backend
└── app
├── alembic
│ └── versions # 迁移位置
├── api
│ └── api_v1
│ └── endpoints
├── core # 配置
├── db # 数据库模型
├── tests # pytest
└── main.py # 后端入口点
frontend
└── public
└── src
├── components
│ └── Home.tsx
├── config
│ └── index.tsx # 常量
├── __tests__
│ └── test_home.tsx
├── index.tsx # 入口点
└── App.tsx # 处理路由
```

19
backend/requirements.txt Normal file
View File

@@ -0,0 +1,19 @@
alembic==1.4.3
Authlib==0.14.3
fastapi==0.65.2
celery==5.0.0
redis==3.5.3
httpx==0.15.5
ipython==7.31.1
itsdangerous==1.1.0
Jinja2==2.11.3
psycopg2
pytest==6.1.0
requests==2.24.0
SQLAlchemy==1.3.19
uvicorn==0.12.1
passlib==1.7.2
bcrypt==3.2.0
sqlalchemy-utils==0.36.8
python-multipart==0.0.5
pyjwt==1.7.1

71
docker-compose.yml Normal file
View File

@@ -0,0 +1,71 @@
version: '3.7'
services:
nginx:
image: nginx:1.17
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
ports:
- 8000:80
depends_on:
- backend
# - frontend
redis:
image: redis
ports:
- 6379:6379
postgres:
image: postgres:12
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: psadmin
ports:
- '5432:5432'
volumes:
- db-data:/var/lib/postgresql/data:cached
worker:
build:
context: backend
dockerfile: Dockerfile
command: celery --app app.tasks worker --loglevel=DEBUG -Q main-queue -c 1
flower:
image: mher/flower
command: celery flower --broker=redis://redis:6379/0 --port=5555
ports:
- 5555:5555
depends_on:
- "redis"
backend:
build:
context: backend
dockerfile: Dockerfile
command: python app/main.py
tty: true
volumes:
- ./backend:/app/:cached
- ./.docker/.ipython:/root/.ipython:cached
environment:
PYTHONPATH: .
DATABASE_URL: 'postgresql://postgres:psadmin@postgres:5432/postgres'
depends_on:
- "postgres"
# frontend:
# build:
# context: frontend
# dockerfile: Dockerfile
# stdin_open: true
# volumes:
# - './frontend:/app:cached'
# - './frontend/node_modules:/app/node_modules:cached'
# environment:
# - NODE_ENV=development
volumes:
db-data:

9
frontend/.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

2
frontend/.env Normal file
View File

@@ -0,0 +1,2 @@
KAB_BACKEND_URL="http://localhost:8000/api/"

View File

@@ -0,0 +1,2 @@
VUE_BACKEND_URL="http://localhost:8000/api/"

8
frontend/.eslintignore Normal file
View File

@@ -0,0 +1,8 @@
/dist
/src-capacitor
/src-cordova
/.quasar
/node_modules
.eslintrc.js
/src-ssr
/quasar.config.*.temporary.compiled*

90
frontend/.eslintrc.cjs Normal file
View File

@@ -0,0 +1,90 @@
module.exports = {
// https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
// This option interrupts the configuration hierarchy at this file
// Remove this if you have an higher level ESLint config file (it usually happens into a monorepos)
root: true,
// https://eslint.vuejs.org/user-guide/#how-to-use-a-custom-parser
// Must use parserOptions instead of "parser" to allow vue-eslint-parser to keep working
// `parser: 'vue-eslint-parser'` is already included with any 'plugin:vue/**' config and should be omitted
parserOptions: {
parser: require.resolve('@typescript-eslint/parser'),
extraFileExtensions: [ '.vue' ]
},
env: {
browser: true,
es2021: true,
node: true,
'vue/setup-compiler-macros': true
},
// Rules order is important, please avoid shuffling them
extends: [
// Base ESLint recommended rules
// 'eslint:recommended',
// https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage
// ESLint typescript rules
'plugin:@typescript-eslint/recommended',
// Uncomment any of the lines below to choose desired strictness,
// but leave only one uncommented!
// See https://eslint.vuejs.org/rules/#available-rules
'plugin:vue/vue3-essential', // Priority A: Essential (Error Prevention)
// 'plugin:vue/vue3-strongly-recommended', // Priority B: Strongly Recommended (Improving Readability)
// 'plugin:vue/vue3-recommended', // Priority C: Recommended (Minimizing Arbitrary Choices and Cognitive Overhead)
// https://github.com/prettier/eslint-config-prettier#installation
// usage with Prettier, provided by 'eslint-config-prettier'.
'prettier'
],
plugins: [
// required to apply rules which need type information
'@typescript-eslint',
// https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-files
// required to lint *.vue files
'vue'
// https://github.com/typescript-eslint/typescript-eslint/issues/389#issuecomment-509292674
// Prettier has not been included as plugin to avoid performance impact
// add it as an extension for your IDE
],
globals: {
ga: 'readonly', // Google Analytics
cordova: 'readonly',
__statics: 'readonly',
__QUASAR_SSR__: 'readonly',
__QUASAR_SSR_SERVER__: 'readonly',
__QUASAR_SSR_CLIENT__: 'readonly',
__QUASAR_SSR_PWA__: 'readonly',
process: 'readonly',
Capacitor: 'readonly',
chrome: 'readonly'
},
// add your custom rules here
rules: {
'prefer-promise-reject-errors': 'off',
quotes: ['warn', 'single', { avoidEscape: true }],
// this rule, if on, would require explicit return type on the `render` function
'@typescript-eslint/explicit-function-return-type': 'off',
// in plain CommonJS modules, you can't use `import foo = require('foo')` to pass this rule, so it has to be disabled
'@typescript-eslint/no-var-requires': 'off',
// The core 'no-unused-vars' rules (in the eslint:recommended ruleset)
// does not work with type definitions
'no-unused-vars': 'off',
// allow debugger during development only
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}

37
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
.DS_Store
.thumbs.db
node_modules
# Quasar core related directories
.quasar
/dist
/quasar.config.*.temporary.compiled*
# Cordova related directories and files
/src-cordova/node_modules
/src-cordova/platforms
/src-cordova/plugins
/src-cordova/www
# Capacitor related directories and files
/src-capacitor/www
/src-capacitor/node_modules
# BEX related directories and files
/src-bex/www
/src-bex/js/core
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
# local .env files
.env.local*

3
frontend/.npmrc Normal file
View File

@@ -0,0 +1,3 @@
# pnpm-related options
shamefully-hoist=true
strict-peer-dependencies=false

4
frontend/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"semi": true
}

45
frontend/README.md Normal file
View File

@@ -0,0 +1,45 @@
# alicorns.co.jp (kintone-app-builder)
Kintoneアプリの自動生成とデプロイを支援ツールです
## VsCode 拡張機能
* Vue Language Features (Volar)
* Vue Plugin for TypeScript server
## Install the dependencies
```bash
yarn
# or
npm install
```
### Start the app in development mode (hot-code reloading, error reporting, etc.)
```bash
quasar dev
```
### Lint the files
```bash
yarn lint
# or
npm run lint
```
### Format the files
```bash
yarn format
# or
npm run format
```
### Build the app for production
```bash
quasar build
```
### Customize the configuration
See [Configuring quasar.config.js](https://v2.quasar.dev/quasar-cli-vite/quasar-config-js).

21
frontend/index.html Normal file
View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<title><%= productName %></title>
<meta charset="utf-8">
<meta name="description" content="<%= productDescription %>">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width<% if (ctx.mode.cordova || ctx.mode.capacitor) { %>, viewport-fit=cover<% } %>">
<link rel="icon" type="image/png" sizes="128x128" href="icons/favicon-128x128.png">
<link rel="icon" type="image/png" sizes="96x96" href="icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="32x32" href="icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="icons/favicon-16x16.png">
<link rel="icon" type="image/ico" href="favicon.ico">
</head>
<body>
<!-- quasar:entry-point -->
</body>
</html>

3654
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
frontend/package.json Normal file
View File

@@ -0,0 +1,39 @@
{
"name": "kintone-app-builder",
"version": "0.0.1",
"description": "Kintoneアプリの自動生成とデプロイを支援ツールです",
"productName": "Kintone App Builder",
"author": "maxiaozhe@alicorns.co.jp <maxiaozhe@alicorns.co.jp>",
"private": true,
"scripts": {
"lint": "eslint --ext .js,.ts,.vue ./",
"format": "prettier --write \"**/*.{js,ts,vue,scss,html,md,json}\" --ignore-path .gitignore",
"test": "echo \"No test specified\" && exit 0",
"dev": "quasar dev",
"build": "quasar build"
},
"dependencies": {
"@quasar/extras": "^1.16.4",
"quasar": "^2.6.0",
"vue": "^3.0.0",
"vue-router": "^4.0.0"
},
"devDependencies": {
"@quasar/app-vite": "^1.3.0",
"@types/node": "^12.20.21",
"@typescript-eslint/eslint-plugin": "^5.10.0",
"@typescript-eslint/parser": "^5.10.0",
"autoprefixer": "^10.4.2",
"dotenv": "^16.3.1",
"eslint": "^8.10.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-vue": "^9.0.0",
"prettier": "^2.5.1",
"typescript": "^4.5.4"
},
"engines": {
"node": "^18 || ^16 || ^14.19",
"npm": ">= 6.13.4",
"yarn": ">= 1.21.1"
}
}

View File

@@ -0,0 +1,27 @@
/* eslint-disable */
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
plugins: [
// https://github.com/postcss/autoprefixer
require('autoprefixer')({
overrideBrowserslist: [
'last 4 Chrome versions',
'last 4 Firefox versions',
'last 4 Edge versions',
'last 4 Safari versions',
'last 4 Android versions',
'last 4 ChromeAndroid versions',
'last 4 FirefoxAndroid versions',
'last 4 iOS versions'
]
})
// https://github.com/elchininet/postcss-rtlcss
// If you want to support RTL css, then
// 1. yarn/npm install postcss-rtlcss
// 2. optionally set quasar.config.js > framework > lang to an RTL language
// 3. uncomment the following line:
// require('postcss-rtlcss')
]
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 859 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

214
frontend/quasar.config.js Normal file
View File

@@ -0,0 +1,214 @@
/* eslint-env node */
/*
* This file runs in a Node context (it's NOT transpiled by Babel), so use only
* the ES6 features that are supported by your Node version. https://node.green/
*/
// Configuration for your app
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js
const { configure } = require('quasar/wrappers');
const dotenv = require('dotenv').config().parsed;
const package = require('./package.json');
const version = package.version;
module.exports = configure(function (/* ctx */) {
return {
eslint: {
// fix: true,
// include: [],
// exclude: [],
// rawOptions: {},
warnings: true,
errors: true
},
// https://v2.quasar.dev/quasar-cli-vite/prefetch-feature
// preFetch: true,
// app boot file (/src/boot)
// --> boot files are part of "main.js"
// https://v2.quasar.dev/quasar-cli-vite/boot-files
boot: [
],
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#css
css: [
'app.scss'
],
// https://github.com/quasarframework/quasar/tree/dev/extras
extras: [
// 'ionicons-v4',
// 'mdi-v5',
// 'fontawesome-v6',
// 'eva-icons',
// 'themify',
// 'line-awesome',
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
'roboto-font', // optional, you are not bound to it
'material-icons', // optional, you are not bound to it
],
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#build
build: {
target: {
browser: ['es2019', 'edge88', 'firefox78', 'chrome87', 'safari13.1'],
node: 'node16'
},
vueRouterMode: 'hash', // available values: 'hash', 'history'
// vueRouterBase,
// vueDevtools,
// vueOptionsAPI: false,
// rebuildCache: true, // rebuilds Vite/linter/etc cache on startup
// publicPath: '/',
// analyze: true,
env: { ...dotenv, version },
// rawDefine: {}
// ignorePublicFolder: true,
// minify: false,
// polyfillModulePreload: true,
// distDir
// extendViteConf (viteConf) {},
// viteVuePluginOptions: {},
// vitePlugins: [
// [ 'package-name', { ..options.. } ]
// ]
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#devServer
devServer: {
// https: true
open: true, // opens browser window automatically
env: { ...dotenv },
},
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework
framework: {
config: {},
// iconSet: 'material-icons', // Quasar icon set
// lang: 'en-US', // Quasar language pack
// For special cases outside of where the auto-import strategy can have an impact
// (like functional components as one of the examples),
// you can manually specify Quasar components/directives to be available everywhere:
//
// components: [],
// directives: [],
// Quasar plugins
plugins: []
},
// animations: 'all', // --- includes all animations
// https://v2.quasar.dev/options/animations
animations: [],
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#sourcefiles
// sourceFiles: {
// rootComponent: 'src/App.vue',
// router: 'src/router/index',
// store: 'src/store/index',
// registerServiceWorker: 'src-pwa/register-service-worker',
// serviceWorker: 'src-pwa/custom-service-worker',
// pwaManifestFile: 'src-pwa/manifest.json',
// electronMain: 'src-electron/electron-main',
// electronPreload: 'src-electron/electron-preload'
// },
// https://v2.quasar.dev/quasar-cli-vite/developing-ssr/configuring-ssr
ssr: {
// ssrPwaHtmlFilename: 'offline.html', // do NOT use index.html as name!
// will mess up SSR
// extendSSRWebserverConf (esbuildConf) {},
// extendPackageJson (json) {},
pwa: false,
// manualStoreHydration: true,
// manualPostHydrationTrigger: true,
prodPort: 3000, // The default port that the production server should use
// (gets superseded if process.env.PORT is specified at runtime)
middlewares: [
'render' // keep this as last one
]
},
// https://v2.quasar.dev/quasar-cli-vite/developing-pwa/configuring-pwa
pwa: {
workboxMode: 'generateSW', // or 'injectManifest'
injectPwaMetaTags: true,
swFilename: 'sw.js',
manifestFilename: 'manifest.json',
useCredentialsForManifestTag: false,
// useFilenameHashes: true,
// extendGenerateSWOptions (cfg) {}
// extendInjectManifestOptions (cfg) {},
// extendManifestJson (json) {}
// extendPWACustomSWConf (esbuildConf) {}
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-cordova-apps/configuring-cordova
cordova: {
// noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-capacitor-apps/configuring-capacitor
capacitor: {
hideSplashscreen: true
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/configuring-electron
electron: {
// extendElectronMainConf (esbuildConf)
// extendElectronPreloadConf (esbuildConf)
inspectPort: 5858,
bundler: 'packager', // 'packager' or 'builder'
packager: {
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
// OS X / Mac App Store
// appBundleId: '',
// appCategoryType: '',
// osxSign: '',
// protocol: 'myapp://path',
// Windows only
// win32metadata: { ... }
},
builder: {
// https://www.electron.build/configuration/configuration
appId: 'kintone-app-builder'
}
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-browser-extensions/configuring-bex
bex: {
contentScripts: [
'my-content-script'
],
// extendBexScriptsConf (esbuildConf) {}
// extendBexManifestJson (json) {}
}
}
});

7
frontend/src/App.vue Normal file
View File

@@ -0,0 +1,7 @@
<template>
<router-view />
</template>
<script setup lang="ts">
</script>

View File

@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 356 360">
<path
d="M43.4 303.4c0 3.8-2.3 6.3-7.1 6.3h-15v-22h14.4c4.3 0 6.2 2.2 6.2 5.2 0 2.6-1.5 4.4-3.4 5 2.8.4 4.9 2.5 4.9 5.5zm-8-13H24.1v6.9H35c2.1 0 4-1.3 4-3.8 0-2.2-1.3-3.1-3.7-3.1zm5.1 12.6c0-2.3-1.8-3.7-4-3.7H24.2v7.7h11.7c3.4 0 4.6-1.8 4.6-4zm36.3 4v2.7H56v-22h20.6v2.7H58.9v6.8h14.6v2.3H58.9v7.5h17.9zm23-5.8v8.5H97v-8.5l-11-13.4h3.4l8.9 11 8.8-11h3.4l-10.8 13.4zm19.1-1.8V298c0-7.9 5.2-10.7 12.7-10.7 7.5 0 13 2.8 13 10.7v1.4c0 7.9-5.5 10.8-13 10.8s-12.7-3-12.7-10.8zm22.7 0V298c0-5.7-3.9-8-10-8-6 0-9.8 2.3-9.8 8v1.4c0 5.8 3.8 8.1 9.8 8.1 6 0 10-2.3 10-8.1zm37.2-11.6v21.9h-2.9l-15.8-17.9v17.9h-2.8v-22h3l15.6 18v-18h2.9zm37.9 10.2v1.3c0 7.8-5.2 10.4-12.4 10.4H193v-22h11.2c7.2 0 12.4 2.8 12.4 10.3zm-3 0c0-5.3-3.3-7.6-9.4-7.6h-8.4V307h8.4c6 0 9.5-2 9.5-7.7V298zm50.8-7.6h-9.7v19.3h-3v-19.3h-9.7v-2.6h22.4v2.6zm34.4-2.6v21.9h-3v-10.1h-16.8v10h-2.8v-21.8h2.8v9.2H296v-9.2h2.9zm34.9 19.2v2.7h-20.7v-22h20.6v2.7H316v6.8h14.5v2.3H316v7.5h17.8zM24 340.2v7.3h13.9v2.4h-14v9.6H21v-22h20v2.7H24zm41.5 11.4h-9.8v7.9H53v-22h13.3c5.1 0 8 1.9 8 6.8 0 3.7-2 6.3-5.6 7l6 8.2h-3.3l-5.8-8zm-9.8-2.6H66c3.1 0 5.3-1.5 5.3-4.7 0-3.3-2.2-4.1-5.3-4.1H55.7v8.8zm47.9 6.2H89l-2 4.3h-3.2l10.7-22.2H98l10.7 22.2h-3.2l-2-4.3zm-1-2.3l-6.3-13-6 13h12.2zm46.3-15.3v21.9H146v-17.2L135.7 358h-2.1l-10.2-15.6v17h-2.8v-21.8h3l11 16.9 11.3-17h3zm35 19.3v2.6h-20.7v-22h20.6v2.7H166v6.8h14.5v2.3H166v7.6h17.8zm47-19.3l-8.3 22h-3l-7.1-18.6-7 18.6h-3l-8.2-22h3.3L204 356l6.8-18.5h3.4L221 356l6.6-18.5h3.3zm10 11.6v-1.4c0-7.8 5.2-10.7 12.7-10.7 7.6 0 13 2.9 13 10.7v1.4c0 7.9-5.4 10.8-13 10.8-7.5 0-12.7-3-12.7-10.8zm22.8 0v-1.4c0-5.7-4-8-10-8s-9.9 2.3-9.9 8v1.4c0 5.8 3.8 8.2 9.8 8.2 6.1 0 10-2.4 10-8.2zm28.3 2.4h-9.8v7.9h-2.8v-22h13.2c5.2 0 8 1.9 8 6.8 0 3.7-2 6.3-5.6 7l6 8.2h-3.3l-5.8-8zm-9.8-2.6h10.2c3 0 5.2-1.5 5.2-4.7 0-3.3-2.1-4.1-5.2-4.1h-10.2v8.8zm40.3-1.5l-6.8 5.6v6.4h-2.9v-22h2.9v12.3l15.2-12.2h3.7l-9.9 8.1 10.3 13.8h-3.6l-8.9-12z" />
<path fill="#050A14"
d="M188.4 71.7a10.4 10.4 0 01-20.8 0 10.4 10.4 0 1120.8 0zM224.2 45c-2.2-3.9-5-7.5-8.2-10.7l-12 7c-3.7-3.2-8-5.7-12.6-7.3a49.4 49.4 0 00-9.7 13.9 59 59 0 0140.1 14l7.6-4.4a57 57 0 00-5.2-12.5zM178 125.1c4.5 0 9-.6 13.4-1.7v-14a40 40 0 0012.5-7.2 47.7 47.7 0 00-7.1-15.3 59 59 0 01-32.2 27.7v8.7c4.4 1.2 8.9 1.8 13.4 1.8zM131.8 45c-2.3 4-4 8.1-5.2 12.5l12 7a40 40 0 000 14.4c5.7 1.5 11.3 2 16.9 1.5a59 59 0 01-8-41.7l-7.5-4.3c-3.2 3.2-6 6.7-8.2 10.6z" />
<path fill="#00B4FF"
d="M224.2 98.4c2.3-3.9 4-8 5.2-12.4l-12-7a40 40 0 000-14.5c-5.7-1.5-11.3-2-16.9-1.5a59 59 0 018 41.7l7.5 4.4c3.2-3.2 6-6.8 8.2-10.7zm-92.4 0c2.2 4 5 7.5 8.2 10.7l12-7a40 40 0 0012.6 7.3c4-4.1 7.3-8.8 9.7-13.8a59 59 0 01-40-14l-7.7 4.4c1.2 4.3 3 8.5 5.2 12.4zm46.2-80c-4.5 0-9 .5-13.4 1.7V34a40 40 0 00-12.5 7.2c1.5 5.7 4 10.8 7.1 15.4a59 59 0 0132.2-27.7V20a53.3 53.3 0 00-13.4-1.8z" />
<path fill="#00B4FF"
d="M178 9.2a62.6 62.6 0 11-.1 125.2A62.6 62.6 0 01178 9.2m0-9.2a71.7 71.7 0 100 143.5A71.7 71.7 0 00178 0z" />
<path fill="#050A14"
d="M96.6 212v4.3c-9.2-.8-15.4-5.8-15.4-17.8V180h4.6v18.4c0 8.6 4 12.6 10.8 13.5zm16-31.9v18.4c0 8.9-4.3 12.8-10.9 13.5v4.4c9.2-.7 15.5-5.6 15.5-18v-18.3h-4.7zM62.2 199v-2.2c0-12.7-8.8-17.4-21-17.4-12.1 0-20.7 4.7-20.7 17.4v2.2c0 12.8 8.6 17.6 20.7 17.6 1.5 0 3-.1 4.4-.3l11.8 6.2 2-3.3-8.2-4-6.4-3.1a32 32 0 01-3.6.2c-9.8 0-16-3.9-16-13.3v-2.2c0-9.3 6.2-13.1 16-13.1 9.9 0 16.3 3.8 16.3 13.1v2.2c0 5.3-2.1 8.7-5.6 10.8l4.8 2.4c3.4-2.8 5.5-7 5.5-13.2zM168 215.6h5.1L156 179.7h-4.8l17 36zM143 205l7.4-15.7-2.4-5-15.1 31.4h5.1l3.3-7h18.3l-1.8-3.7H143zm133.7 10.7h5.2l-17.3-35.9h-4.8l17 36zm-25-10.7l7.4-15.7-2.4-5-15.1 31.4h5.1l3.3-7h18.3l-1.7-3.7h-14.8zm73.8-2.5c6-1.2 9-5.4 9-11.4 0-8-4.5-10.9-12.9-10.9h-21.4v35.5h4.6v-31.3h16.5c5 0 8.5 1.4 8.5 6.7 0 5.2-3.5 7.7-8.5 7.7h-11.4v4.1h10.7l9.3 12.8h5.5l-9.9-13.2zm-117.4 9.9c-9.7 0-14.7-2.5-18.6-6.3l-2.2 3.8c5.1 5 11 6.7 21 6.7 1.6 0 3.1-.1 4.6-.3l-1.9-4h-3zm18.4-7c0-6.4-4.7-8.6-13.8-9.4l-10.1-1c-6.7-.7-9.3-2.2-9.3-5.6 0-2.5 1.4-4 4.6-5l-1.8-3.8c-4.7 1.4-7.5 4.2-7.5 8.9 0 5.2 3.4 8.7 13 9.6l11.3 1.2c6.4.6 8.9 2 8.9 5.4 0 2.7-2.1 4.7-6 5.8l1.8 3.9c5.3-1.6 8.9-4.7 8.9-10zm-20.3-21.9c7.9 0 13.3 1.8 18.1 5.7l1.8-3.9a30 30 0 00-19.6-5.9c-2 0-4 .1-5.7.3l1.9 4 3.5-.2z" />
<path fill="#00B4FF"
d="M.5 251.9c29.6-.5 59.2-.8 88.8-1l88.7-.3 88.7.3 44.4.4 44.4.6-44.4.6-44.4.4-88.7.3-88.7-.3a7981 7981 0 01-88.8-1z" />
<path fill="none" d="M-565.2 324H-252v15.8h-313.2z" />
</svg>

After

Width:  |  Height:  |  Size: 4.4 KiB

View File

View File

@@ -0,0 +1,52 @@
<template>
<div class="q-pa-md">
<q-uploader
style="max-width: 400px"
:url="uploadUrl"
:label="title"
accept=".csv,.xlsx"
:on-rejected="onRejected"
></q-uploader>
</div>
</template>
<script setup lang="ts">
import { useQuasar } from 'quasar';
const $q=useQuasar();
// const allowTypes=['.xlsx','.csv'];
// function checkFileType(files : File[] ):File[]{
// return files.filter((file)=>{
// let filename = file.name.toLowerCase();
// for(let ext of allowTypes){
// if(filename.endsWith(ext)){
// return true;
// }
// }
// return false;
// });
// }
function onRejected (rejectedEntries:any) {
// Notify plugin needs to be installed
// https://quasar.dev/quasar-plugins/notify#Installation
$q.notify({
type: 'negative',
message: `CSVおよびExcelファイルを選択してください。`
})
}
interface Props {
title: string;
uploadUrl:string;
}
const props = withDefaults(defineProps<Props>(), {
title:"設計書から導入する(csv or excel)",
uploadUrl:process.env.KAB_BACKEND_URL
});
</script>
<style lang="scss">
</style>

View File

@@ -0,0 +1,34 @@
<template>
<q-item
clickable
tag="a"
target="_blank"
:href="link"
>
<q-item-section
v-if="icon"
avatar
>
<q-icon :name="icon" />
</q-item-section>
<q-item-section>
<q-item-label>{{ title }}</q-item-label>
<q-item-label caption>{{ caption }}</q-item-label>
</q-item-section>
</q-item>
</template>
<script setup lang="ts">
export interface EssentialLinkProps {
title: string;
caption?: string;
link?: string;
icon?: string;
}
withDefaults(defineProps<EssentialLinkProps>(), {
caption: '',
link: '#',
icon: '',
});
</script>

View File

@@ -0,0 +1,37 @@
<template>
<div>
<p>{{ title }}</p>
<ul>
<li v-for="todo in todos" :key="todo.id" @click="increment">
{{ todo.id }} - {{ todo.content }}
</li>
</ul>
<p>Count: {{ todoCount }} / {{ meta.totalCount }}</p>
<p>Active: {{ active ? 'yes' : 'no' }}</p>
<p>Clicks on todos: {{ clickCount }}</p>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { Todo, Meta } from './models';
interface Props {
title: string;
todos?: Todo[];
meta: Meta;
active: boolean;
}
const props = withDefaults(defineProps<Props>(), {
todos: () => [],
});
const clickCount = ref(0);
function increment() {
clickCount.value += 1;
return clickCount.value;
}
const todoCount = computed(() => props.todos.length);
</script>

View File

@@ -0,0 +1,8 @@
export interface Todo {
id: number;
content: string;
}
export interface Meta {
totalCount: number;
}

View File

@@ -0,0 +1 @@
// app global css in SCSS form

View File

@@ -0,0 +1,25 @@
// Quasar SCSS (& Sass) Variables
// --------------------------------------------------
// To customize the look and feel of this app, you can override
// the Sass/SCSS variables found in Quasar's source Sass/SCSS files.
// Check documentation for full list of Quasar variables
// Your own variables (that are declared here) and Quasar's own
// ones will be available out of the box in your .vue/.scss/.sass files
// It's highly recommended to change the default colors
// to match your app's branding.
// Tip: Use the "Theme Builder" on Quasar's documentation website.
$primary : #1976D2;
$secondary : #26A69A;
$accent : #9C27B0;
$dark : #1D1D1D;
$dark-page : #121212;
$positive : #21BA45;
$negative : #C10015;
$info : #31CCEC;
$warning : #F2C037;

9
frontend/src/env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* eslint-disable */
declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: string;
VUE_ROUTER_MODE: 'hash' | 'history' | 'abstract' | undefined;
VUE_ROUTER_BASE: string | undefined;
}
}

View File

@@ -0,0 +1,104 @@
<template>
<q-layout view="lHh Lpr lFf">
<q-header elevated>
<q-toolbar>
<q-btn
flat
dense
round
icon="menu"
aria-label="Menu"
@click="toggleLeftDrawer"
/>
<q-toolbar-title>
Kintone App Builder
</q-toolbar-title>
<div>ver {{ env.version }}</div>
</q-toolbar>
</q-header>
<q-drawer
v-model="leftDrawerOpen"
:show-if-above="false"
bordered
>
<q-list>
<q-item-label
header
>
Essential Links
</q-item-label>
<EssentialLink
v-for="link in essentialLinks"
:key="link.title"
v-bind="link"
/>
</q-list>
</q-drawer>
<q-page-container>
<router-view />
</q-page-container>
</q-layout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import EssentialLink, { EssentialLinkProps } from 'components/EssentialLink.vue';
const essentialLinks: EssentialLinkProps[] = [
{
title: 'Docs',
caption: 'quasar.dev',
icon: 'school',
link: 'https://quasar.dev'
},
{
title: 'Github',
caption: 'github.com/quasarframework',
icon: 'code',
link: 'https://github.com/quasarframework'
},
{
title: 'Discord Chat Channel',
caption: 'chat.quasar.dev',
icon: 'chat',
link: 'https://chat.quasar.dev'
},
{
title: 'Forum',
caption: 'forum.quasar.dev',
icon: 'record_voice_over',
link: 'https://forum.quasar.dev'
},
{
title: 'Twitter',
caption: '@quasarframework',
icon: 'rss_feed',
link: 'https://twitter.quasar.dev'
},
{
title: 'Facebook',
caption: '@QuasarFramework',
icon: 'public',
link: 'https://facebook.quasar.dev'
},
{
title: 'Quasar Awesome',
caption: 'Community Quasar projects',
icon: 'favorite',
link: 'https://awesome.quasar.dev'
}
];
const leftDrawerOpen = ref(false)
const env=process.env;
function toggleLeftDrawer() {
leftDrawerOpen.value = !leftDrawerOpen.value
}
</script>

View File

@@ -0,0 +1,27 @@
<template>
<div class="fullscreen bg-blue text-white text-center q-pa-md flex flex-center">
<div>
<div style="font-size: 30vh">
404
</div>
<div class="text-h2" style="opacity:.4">
Oops. Nothing here...
</div>
<q-btn
class="q-mt-xl"
color="white"
text-color="blue"
unelevated
to="/"
label="Go Home"
no-caps
/>
</div>
</div>
</template>
<script setup lang="ts">
</script>

View File

@@ -0,0 +1,42 @@
<template>
<q-page>
<div class="q-pa-md">
<div class="q-gutter-sm row items-start">
<doc-uploader></doc-uploader>
</div>
</div>
</q-page>
</template>
<script setup lang="ts">
import { Todo, Meta } from 'components/models';
import DocUploader from 'components/DocUpload.vue';
// import ExampleComponent from 'components/ExampleComponent.vue';
import { ref } from 'vue';
const todos = ref<Todo[]>([
{
id: 1,
content: 'ct1'
},
{
id: 2,
content: 'ct2'
},
{
id: 3,
content: 'ct3'
},
{
id: 4,
content: 'ct4'
},
{
id: 5,
content: 'ct5'
}
]);
const meta = ref<Meta>({
totalCount: 1200
});
</script>

9
frontend/src/quasar.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* eslint-disable */
// Forces TS to apply `@quasar/app-vite` augmentations of `quasar` package
// Removing this would break `quasar/wrappers` imports as those typings are declared
// into `@quasar/app-vite`
// As a side effect, since `@quasar/app-vite` reference `quasar` to augment it,
// this declaration also apply `quasar` own
// augmentations (eg. adds `$q` into Vue component context)
/// <reference types="@quasar/app-vite" />

View File

@@ -0,0 +1,36 @@
import { route } from 'quasar/wrappers';
import {
createMemoryHistory,
createRouter,
createWebHashHistory,
createWebHistory,
} from 'vue-router';
import routes from './routes';
/*
* If not building with SSR mode, you can
* directly export the Router instantiation;
*
* The function below can be async too; either use
* async/await or return a Promise which resolves
* with the Router instance.
*/
export default route(function (/* { store, ssrContext } */) {
const createHistory = process.env.SERVER
? createMemoryHistory
: (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);
const Router = createRouter({
scrollBehavior: () => ({ left: 0, top: 0 }),
routes,
// Leave this as is and make changes in quasar.conf.js instead!
// quasar.conf.js -> build -> vueRouterMode
// quasar.conf.js -> build -> publicPath
history: createHistory(process.env.VUE_ROUTER_BASE),
});
return Router;
});

View File

@@ -0,0 +1,18 @@
import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
{
path: '/',
component: () => import('layouts/MainLayout.vue'),
children: [{ path: '', component: () => import('pages/IndexPage.vue') }],
},
// Always leave this as last one,
// but you can also remove it
{
path: '/:catchAll(.*)*',
component: () => import('pages/ErrorNotFound.vue'),
},
];
export default routes;

10
frontend/src/shims-vue.d.ts vendored Normal file
View File

@@ -0,0 +1,10 @@
/* eslint-disable */
/// <reference types="vite/client" />
// Mocks all files ending in `.vue` showing them as plain Vue instances
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}

6
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,6 @@
{
"extends": "@quasar/app-vite/tsconfig-preset",
"compilerOptions": {
"baseUrl": "."
}
}

3009
frontend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

22
nginx/nginx.conf Normal file
View File

@@ -0,0 +1,22 @@
server {
listen 80;
server_name KintoneAppBuilder;
# location / {
# proxy_set_header X-Forwarded-Host $host;
# proxy_set_header X-Forwarded-Server $host;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_pass http://frontend:3000;
# proxy_redirect off;
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection "upgrade";
# }
location /api {
proxy_pass http://backend:8888/api;
}
}

1631
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

16
scripts/build.sh Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/bash
# Exit in case of error
set -e
# Build and run containers
docker-compose up -d
# Hack to wait for postgres container to be up before running alembic migrations
sleep 5;
# Run migrations
docker-compose run --rm backend alembic upgrade head
# Create initial data
docker-compose run --rm backend python3 app/initial_data.py

7
scripts/test.sh Normal file
View File

@@ -0,0 +1,7 @@
#! /usr/bin/env bash
# Exit in case of error
set -e
docker-compose run backend pytest
docker-compose run frontend test

6
scripts/test_backend.sh Normal file
View File

@@ -0,0 +1,6 @@
#! /usr/bin/env bash
# Exit in case of error
set -e
docker-compose run backend pytest $@