Compare commits

...

65 commits

Author SHA1 Message Date
d8c1830c71 46 - Tag CI image by composer.lock hash and build it in CI
Some checks failed
Build and Push Docker Image / build (push) Successful in 7m36s
CI / ci-image (push) Failing after 3h0m57s
CI / ci (push) Has been skipped
2026-08-17 23:13:43 +02:00
3c5f2d5df1 Merge pull request 'release/v0.8.0' (#49) from release/v0.8.0 into main
All checks were successful
Build and Push Base Images / images (docker/build/Dockerfile.ci, dishplanner-ci, php8.3-4) (push) Successful in 9m48s
Build and Push Docker Image / build (push) Successful in 8m1s
Reviewed-on: #49
2026-08-17 23:05:19 +02:00
e95932d01c 47 - Document v0.8.0 in CHANGELOG
All checks were successful
CI / ci (push) Successful in 39s
CI / ci (pull_request) Successful in 43s
2026-08-17 21:38:10 +02:00
7954d9499d 46 - Pre-load PHP dependencies into the CI image
All checks were successful
CI / ci (push) Successful in 2m7s
CI / ci (pull_request) Successful in 33s
2026-08-17 21:18:01 +02:00
08d86d9290 50 - Fix tests failing on missing Vite manifest
Some checks failed
CI / ci (push) Successful in 39m29s
CI / ci (pull_request) Has been cancelled
2026-08-17 20:45:45 +02:00
42563511b4 50 - Avoid codeload 429 via prefer-source and baked phpstan
Some checks failed
CI / ci (push) Failing after 57m19s
CI / ci (pull_request) Failing after 34m50s
2026-08-17 18:04:30 +02:00
e38d700612 46 - Retry composer install on transient 429
Some checks failed
CI / ci (push) Has been cancelled
CI / ci (pull_request) Failing after 7m17s
2026-08-17 17:33:18 +02:00
0988f40dac 46 - Add zip extension to CI image
Some checks failed
CI / ci (push) Failing after 1s
CI / ci (pull_request) Has been cancelled
2026-08-17 14:58:10 +02:00
1b6effb5d0 47 - Professionalize documentation
Some checks failed
CI / ci (push) Failing after 3s
CI / ci (pull_request) Failing after 2m32s
2026-08-17 14:11:50 +02:00
abac8509cb 46 - Add CI image and app image build workflows 2026-08-17 14:00:02 +02:00
c4ae6c2e69 45 - Add Forgejo CI workflow 2026-08-17 13:30:49 +02:00
a8b0ed1dc8 44 - Complete nix-shell dev commands 2026-08-17 01:56:01 +02:00
71614848ba Add changelog 2026-08-17 01:21:37 +02:00
e335c64ec9 Merge pull request 'release/v0.7' (#42) from release/v0.7 into main
Reviewed-on: #42
2026-08-17 00:55:59 +02:00
e1f701de0a Add changelog 2026-08-17 00:55:07 +02:00
9a4b8db3c7 Ignore codewhale 2026-08-17 00:51:10 +02:00
143c8e351c Remove stale root-level build/update scripts (#40) 2026-08-17 00:50:06 +02:00
561750dc83 FOSS pivot: retire SaaS, demo, and APP_MODE plumbing (#37 #38 #39 #40 #41)
Remove Stripe/Cashier subscription billing, demo mode, and APP_MODE enum/helpers. Delete frontend-old/ and stale bin scripts. Adopt AGPL-3.0 (LICENSE.md, README, composer.json). Point Docker image, prod scripts, and README at forge.lvl0.xyz/lvl0/dishplanner.
2026-08-16 17:29:19 +02:00
5735b9ba95 Fix old references to lvl0 + cleanup 2026-01-09 02:45:23 +01:00
1d3d05845c Update repo path after move 2026-01-09 02:38:04 +01:00
6c8502f2d1 Fix health check warnings 2026-01-09 01:09:48 +01:00
fa3cb218a9 Fix production issues 2026-01-08 21:56:05 +01:00
ea6f7ebf29 Update prod and dev instructions 2026-01-08 21:40:19 +01:00
1de78bdce3 feature - 23 - purge old demo accounts 2026-01-08 02:09:52 +01:00
f78d97dae5 feature - 22 - demo planner seeding 2026-01-08 02:00:30 +01:00
c80891b25e feature - 20 - demo auto login 2026-01-08 01:40:13 +01:00
4b31f3d315 feature - 30 - Update payment method 2026-01-07 01:29:58 +01:00
592a402d23 feature - 27 - Cancel subscription 2026-01-07 01:18:18 +01:00
fc6fd87c4b feature - 18 - Add billing page 2026-01-07 01:08:58 +01:00
bcbc1ce8e7 feature - 18 - Add payments to subscription flow 2026-01-07 00:29:53 +01:00
71668ea5bd feature - 18 - Add subscriptions 2026-01-05 23:51:50 +01:00
b1cf8b5f22 feature - 17 - Add mode config 2026-01-05 21:53:06 +01:00
0baa87e373 bug - 14 - Add user multi-select 2026-01-04 16:49:06 +01:00
7412316746 bug - 14 - Fix create modal on calendar cell + add remove option for existing 2026-01-04 14:52:46 +01:00
d57af05974 bug - 14 - Fix modal issues, fix alpine.js issue, clean up unused tests 2026-01-04 13:36:13 +01:00
1b7c04e29f Fix dashboard title 2026-01-04 04:07:35 +01:00
7bb1bb4161 Fix default app name 2026-01-04 04:06:03 +01:00
0de6c30dab feature - 3 - Add logos 2026-01-04 04:01:11 +01:00
6723c9813b Fix seeder 2026-01-04 03:30:06 +01:00
01648359b5 Use more reliable db check 2026-01-04 03:26:50 +01:00
efa3f62146 feature - 3 - Fix mobile menu 2026-01-04 03:26:50 +01:00
89184b79a5 feature - 3 - Fix link order 2026-01-04 03:26:50 +01:00
98230a5ef2 feature - 3 - Improve register page layout 2026-01-04 03:26:50 +01:00
197a74ee9b feature - 3 - Improve login page layout 2026-01-04 03:26:50 +01:00
faed07395e feature - 3 - Fix mobile layout for schedule 2026-01-04 03:26:49 +01:00
2ed9dfbdaa feature - 8 - Add code coverage 2026-01-03 21:17:00 +01:00
b93e6cb832 feature - 8 - Fix scheduled user dishes 2026-01-03 21:08:38 +01:00
09236f6f10 feature - 8 - Add other user actions 2025-12-29 23:37:41 +01:00
1174f2fbda feature - 8 - Remove default tests 2025-12-29 23:37:41 +01:00
53840d5ced feature - 8 - Fix e2e tests 2025-12-29 23:37:41 +01:00
8336df4551 feature - 8 - Add development seeder 2025-12-29 23:37:41 +01:00
f226295d72 feature - 8 - Fix session expired issue 2025-12-29 23:37:41 +01:00
28da206043 feature - 8 - Mark failing tests as skipped for now 2025-12-29 23:37:41 +01:00
77817bca14 feature - 8 - Trim down fields from user form
+ move auth forms from livewire to blade
2025-12-29 02:57:25 +01:00
dc00300f44 feature - 7 - Hide users selection if no users exist 2025-12-28 21:15:35 +01:00
ecfadbc2ad feature - 7 - Add e2e tests for dishes crud 2025-12-28 21:07:12 +01:00
01ee82cbac feature - 11 - Add registration test sad paths 2025-12-28 20:22:41 +01:00
9e22c23208 feature - 11 - Add login test 2025-12-28 20:18:27 +01:00
3c32d49977 feature - 4 - Set up e2e with basic tests 2025-12-28 13:48:02 +01:00
94abe140e1 feature - 6 - Structural fixes 2025-12-28 11:01:13 +01:00
6e5fb9cb36 feature - 6 - Update shell.nix with clearer dev/prod separation 2025-12-28 10:47:18 +01:00
71212ef9da feature - 6 - fix production compose issues 2025-12-28 10:47:18 +01:00
630a8cc73f feature - 6 - fix dev compose issues 2025-12-28 10:47:18 +01:00
5a26120141 feature - 6 - port update compose files 2025-12-28 10:47:18 +01:00
71ed93fda0 feature - 6 - port react frontend to laravel blade + livewire 2025-12-28 10:47:18 +01:00
555 changed files with 23558 additions and 22404 deletions

59
.dockerignore Normal file
View file

@ -0,0 +1,59 @@
# Git
.git
.gitignore
.gitattributes
# Documentation
*.md
LICENSE
docs/
# Environment files
.env
.env.*
!.env.example
# Dependencies (will be installed fresh)
vendor/
node_modules/
# Storage (will be mounted as volumes)
storage/app/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
storage/logs/*
bootstrap/cache/*
# Testing
phpunit.xml
.phpunit.result.cache
tests/
coverage/
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Docker
Dockerfile*
docker-compose*.yml
.dockerignore
# Build artifacts
public/build/
public/hot
public/mix-manifest.json
# Development
.php_cs.cache
.php-cs-fixer.cache
phpstan.neon
.editorconfig

24
.env.dusk.local Normal file
View file

@ -0,0 +1,24 @@
APP_NAME=DishPlanner
APP_ENV=testing
APP_KEY=base64:KSKZNT+cJuaBRBv4Y2HQqav6hzREKoLkNIKN8yszU1Q=
APP_DEBUG=true
APP_URL=http://dishplanner_app:8000
LOG_CHANNEL=single
# Test database
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=dishplanner_test
DB_USERNAME=dishplanner
DB_PASSWORD=dishplanner
BROADCAST_DRIVER=log
CACHE_DRIVER=array
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MAIL_MAILER=array

66
.env.example Normal file
View file

@ -0,0 +1,66 @@
# Application Settings
APP_NAME=DishPlanner
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8000
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
# Logging
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
# Database Connection (Docker)
DB_CONNECTION=mysql
DB_HOST=db # Use 'db' for Docker, 'localhost' for local
DB_PORT=3306
DB_DATABASE=dishplanner
DB_USERNAME=dishplanner
DB_PASSWORD=dishplanner
DB_ROOT_PASSWORD=root # For Docker MariaDB root user
# Session & Cache
SESSION_DRIVER=file # Use 'database' for production
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
CACHE_STORE=file
CACHE_PREFIX=dishplanner
# Queue
QUEUE_CONNECTION=sync # Use 'database' for production
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
# Redis (Optional - uncomment if using Redis)
# REDIS_CLIENT=phpredis
# REDIS_HOST=redis # Use 'redis' for Docker
# REDIS_PASSWORD=null
# REDIS_PORT=6379
# Mail Settings
MAIL_MAILER=log # Use 'smtp' for production
MAIL_HOST=mailhog # Use 'mailhog' for Docker dev
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="noreply@dishplanner.local"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

25
.env.testing Normal file
View file

@ -0,0 +1,25 @@
APP_NAME=DishPlanner
APP_ENV=testing
APP_KEY=base64:2ADW3imsmRMo+UDw3GR6852wQu37/aNK1ooxEdaJIC0=
APP_DEBUG=true
APP_URL=http://localhost
APP_MAINTENANCE_DRIVER=file
BCRYPT_ROUNDS=4
LOG_CHANNEL=stack
LOG_STACK=single
DB_CONNECTION=sqlite
DB_DATABASE=:memory:
SESSION_DRIVER=array
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
CACHE_STORE=array
MAIL_MAILER=array

View file

@ -0,0 +1,42 @@
name: Build and Push Docker Image
on:
push:
branches: [main]
tags: ['v*']
jobs:
build:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Set up Docker Buildx
uses: https://data.forgejo.org/docker/setup-buildx-action@v3
- name: Login to Forgejo Registry
uses: https://data.forgejo.org/docker/login-action@v3
with:
registry: forge.lvl0.xyz
username: ${{ github.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Determine tags
id: meta
run: |
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
TAG="${{ github.ref_name }}"
echo "tags=forge.lvl0.xyz/lvl0/dishplanner:${TAG},forge.lvl0.xyz/lvl0/dishplanner:latest" >> $GITHUB_OUTPUT
else
echo "tags=forge.lvl0.xyz/lvl0/dishplanner:latest" >> $GITHUB_OUTPUT
fi
- name: Build and push
uses: https://data.forgejo.org/docker/build-push-action@v5
with:
context: .
file: Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}

68
.forgejo/workflows/ci.yml Normal file
View file

@ -0,0 +1,68 @@
name: CI
on:
push:
branches: ['release/*']
pull_request:
branches: [main, 'release/*']
jobs:
ci-image:
runs-on: docker
container:
image: catthehacker/ubuntu:act-latest
outputs:
tag: ${{ steps.meta.outputs.tag }}
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Set up Docker Buildx
uses: https://data.forgejo.org/docker/setup-buildx-action@v3
- name: Login to Forgejo Registry
uses: https://data.forgejo.org/docker/login-action@v3
with:
registry: forge.lvl0.xyz
username: ${{ github.actor }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Compute image tag from lockfile
id: meta
run: |
HASH="$(sha256sum composer.lock | cut -c1-12)"
echo "tag=php8.3-${HASH}" >> "$GITHUB_OUTPUT"
- name: Build and push CI image
uses: https://data.forgejo.org/docker/build-push-action@v5
with:
context: .
file: docker/build/Dockerfile.ci
push: true
tags: forge.lvl0.xyz/lvl0/dishplanner-ci:${{ steps.meta.outputs.tag }}
cache-from: type=registry,ref=forge.lvl0.xyz/lvl0/dishplanner-ci:buildcache
cache-to: type=registry,ref=forge.lvl0.xyz/lvl0/dishplanner-ci:buildcache,mode=max
ci:
needs: ci-image
runs-on: docker
container:
image: forge.lvl0.xyz/lvl0/dishplanner-ci:${{ needs.ci-image.outputs.tag }}
steps:
- uses: https://data.forgejo.org/actions/checkout@v4
- name: Prepare environment
run: cp .env.testing .env
- name: Restore dependencies
run: |
cp -a /opt/deps/vendor ./vendor
composer install --no-interaction --no-progress
- name: Lint
run: vendor/bin/pint --test
- name: Static analysis
run: vendor/bin/phpstan analyse --memory-limit=1G
- name: Tests
run: php -d memory_limit=512M vendor/bin/phpunit

View file

@ -6,6 +6,4 @@
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

25
.gitignore vendored
View file

@ -1 +1,26 @@
/.phpunit.cache
/coverage
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
/auth.json
/.fleet
/.idea
/.nova
/.vscode
/.zed
/.vite
/.codewhale

View file

@ -0,0 +1,8 @@
{
"hash": "9e76e24f",
"configHash": "16a1459d",
"lockfileHash": "e3b0c442",
"browserHash": "8e8bb46e",
"optimized": {},
"chunks": {}
}

3
.vite/deps/package.json Normal file
View file

@ -0,0 +1,3 @@
{
"type": "module"
}

50
CHANGELOG.md Normal file
View file

@ -0,0 +1,50 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.8.0] - 2026-08-17
### Added
- **Forgejo CI pipeline** (#45) — added a CI workflow that runs Laravel Pint code-style checks, PHPStan static analysis, and the PHPUnit suite against SQLite in memory.
- **Static analysis** — added PHPStan via `larastan/larastan` and `phpstan/phpstan-mockery`, with `phpstan.neon` and a baseline.
- **Code style** — added Laravel Pint configuration (`pint.json`).
- **CI and app image build workflows** (#46) — automated Docker image builds for the app and the CI base image, published to the Forgejo registry.
- **CI base image** (#46) — added `docker/build/Dockerfile.ci`, a Debian-based PHP 8.3 CLI image with the project's PHP dependencies pre-loaded so CI doesn't pay a per-run Composer install.
- **Contributing guide** (#47) — added `CONTRIBUTING.md`.
- **Nix shell completion** (#44) — finished the `nix-shell` development commands.
### Changed
- **Dependencies**`composer.lock` is now committed to the repository.
- **Code style** — reformatted the codebase with Laravel Pint.
- **Documentation** (#47) — professionalized the `README.md`.
- **Git hygiene** — dropped stale `.github`/StyleCI export rules from `.gitattributes`.
### Fixed
- **CI dependency installation** (#46, #50) — retried `composer install` on transient HTTP 429s, switched to `--prefer-source` and pre-loaded dependencies to avoid `codeload.github.com` rate limits, and added the missing `zip` extension to the CI image.
- **Test suite** (#50) — fixed feature tests failing on a missing Vite manifest by disabling Vite resolution during tests.
## [0.7.0] - 2026-08-17
### Removed
- **SaaS mode and subscription billing** (#37) — dropped Laravel Cashier, the `Billable` trait, `SubscriptionController`, the `RequireSubscription`/`RequireSaasMode` middleware, the `/subscription` and `/billing` routes, the billing/subscription views, the Cashier migrations, and the `stripe` service config.
- **Demo mode** (#38) — removed the demo middleware, demo-account seeding and purge commands, and demo-only UI.
- **`APP_MODE` plumbing** (#39) — removed `AppModeEnum`, the `app/helpers.php` global helper, and the `mode`/`demo_subscribe_url` config keys; the app now runs in a single self-hosted mode.
- **Dead code** (#40) — deleted `frontend-old/`, `bin/start-dev`, the unused `welcome.blade.php`, and the stale root-level `build_and_push.sh`/`update.sh` scripts.
### Changed
- **License** (#41) — adopted AGPL-3.0 as the single project license (`LICENSE.md`, `composer.json`, `README.md`).
- **Registry and remote references** — repointed build, push, and update scripts and docs at `forge.lvl0.xyz/lvl0/dishplanner`, removing the stale LAN-registry and old `backend` naming.
- **Documentation** — updated the production and development instructions.
### Fixed
- Fixed health-check warnings in the development shell.
- Fixed schedule regeneration iterating every user instead of the planner's own users.

97
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,97 @@
# Contributing
Thanks for your interest in DishPlanner. It's a small self-hosted project —
issues and pull requests are both welcome.
## Reporting issues
Use [Issues](https://forge.lvl0.xyz/lvl0/dishplanner/issues).
For bugs, include what you expected, what happened, and enough detail to
reproduce it. Relevant log output helps; `dev-logs` follows the application log.
## Development setup
Requires PHP 8.2+ and a container runtime (Podman or Docker). The development
environment runs in containers defined by `docker-compose.yml`.
On NixOS, or anywhere with Nix installed:
```bash
git clone https://forge.lvl0.xyz/lvl0/dishplanner.git
cd dishplanner
nix-shell
```
The shell prints the available commands on entry and can start the containers
for you:
| Command | Description |
|---------|-------------|
| `dev-up` | Start the development environment |
| `dev-down` | Stop the development environment |
| `dev-restart` | Restart the containers |
| `dev-rebuild` | Full rebuild (removes volumes) |
| `dev-rebuild-quick` | Quick rebuild (keeps volumes) |
| `dev-logs [service]` | Follow logs |
| `dev-logs-db` | Tail database logs |
| `dev-shell` | Enter the app container |
| `dev-artisan <cmd>` | Run an artisan command |
| `dev-test [path]` | Run the PHPUnit suite the CI way |
| `dev-fix-permissions` | Fix Docker-created file permissions |
Once running:
| Service | URL |
|---------|-----|
| App | http://localhost:8000 |
| Vite | http://localhost:5173 |
| Mailhog | http://localhost:8025 |
| MariaDB | localhost:3306 |
Without Nix, start the same containers directly from `docker-compose.yml`.
Contributions improving the setup instructions for other platforms are welcome.
## Before opening a pull request
Three checks run in CI, and all three must pass. Run them locally first, from
inside the app container or anywhere the project's dependencies are available:
```bash
vendor/bin/pint --test # code style, Laravel preset
vendor/bin/phpstan analyse --memory-limit=1G # static analysis, level 7
php -d memory_limit=512M vendor/bin/phpunit # PHPUnit on SQLite in memory
```
Or run the test suite the CI way with `dev-test`.
Some conventions:
- **Static analysis.** PHPStan runs at level 7 with a baseline
(`phpstan-baseline.neon`) covering pre-existing findings. Don't add baseline
entries to silence errors in code you're writing — fix the cause instead. The
baseline is for cases where the analyzer or an upstream docblock is wrong,
not real bugs.
- **Tests.** New behaviour needs a test. Tests run against SQLite in memory and
must not reach for the network.
- **Dependencies.** `composer.lock` is committed. If you change dependencies,
commit the updated lockfile alongside `composer.json`.
## Commits
One commit does one thing. Keep each commit passing all three checks so history
stays bisectable. Separate renames from behaviour changes, and mechanical edits
from logic.
Commit messages are a single line, referencing the ticket they belong to:
```
45 - Add Forgejo CI workflow
```
No body, no trailers.
## License
By contributing, you agree that your contributions are licensed under the
[GNU AGPL-3.0](LICENSE.md), the same license as the project.

123
Dockerfile Normal file
View file

@ -0,0 +1,123 @@
# Production Dockerfile with FrankenPHP
FROM dunglas/frankenphp:latest-php8.3-alpine
# Install system dependencies
RUN apk add --no-cache \
nodejs \
npm \
git \
mysql-client
# Install PHP extensions
RUN install-php-extensions \
pdo_mysql \
opcache \
zip \
gd \
intl \
bcmath
# Install Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# Set working directory
WORKDIR /app
# Set fixed production environment variables
ENV APP_ENV=production \
APP_DEBUG=false \
DB_CONNECTION=mysql \
DB_HOST=db \
DB_PORT=3306 \
SESSION_DRIVER=database \
CACHE_DRIVER=file \
QUEUE_CONNECTION=database \
LOG_CHANNEL=stack \
LOG_LEVEL=error \
MAIL_MAILER=smtp \
MAIL_ENCRYPTION=tls
# Copy application code first
COPY . .
# Install PHP dependencies (production only)
RUN composer install --no-dev --no-interaction --optimize-autoloader
# Install ALL Node dependencies (including dev for building)
RUN npm ci
# Build frontend assets
RUN npm run build
# Remove node_modules after build to save space
RUN rm -rf node_modules
# Laravel optimizations
RUN php artisan config:cache \
&& php artisan route:cache \
&& composer dump-autoload --optimize
# Set permissions
RUN chown -R www-data:www-data /app/storage /app/bootstrap/cache
# Configure Caddy
RUN cat > /etc/caddy/Caddyfile <<EOF
{
frankenphp
order php_server before file_server
}
:8000 {
root * /app/public
php_server {
index index.php
}
encode gzip
file_server
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
X-XSS-Protection "1; mode=block"
}
}
EOF
# Expose port
EXPOSE 8000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/up || exit 1
# Create startup script for production
RUN cat > /start-prod.sh <<'EOF'
#!/bin/sh
set -e
# Wait for database to be ready
echo "Waiting for database..."
for i in $(seq 1 30); do
if mysqladmin ping -h "$DB_HOST" -u "$DB_USERNAME" -p"$DB_PASSWORD" --silent 2>/dev/null; then
echo "Database is ready!"
break
fi
echo "Waiting for database... ($i/30)"
sleep 2
done
# Run migrations
echo "Running migrations..."
php artisan migrate --force || echo "Migrations failed or already up-to-date"
# Start FrankenPHP
exec frankenphp run --config /etc/caddy/Caddyfile
EOF
RUN chmod +x /start-prod.sh
# Start with our script
CMD ["/start-prod.sh"]

128
Dockerfile.dev Normal file
View file

@ -0,0 +1,128 @@
# Development Dockerfile with FrankenPHP
FROM dunglas/frankenphp:latest-php8.3-alpine
# Install system dependencies + development tools
RUN apk add --no-cache \
nodejs \
npm \
git \
mysql-client \
vim \
bash \
nano
# Install PHP extensions including xdebug for development
RUN install-php-extensions \
pdo_mysql \
opcache \
zip \
gd \
intl \
bcmath \
xdebug
# Install Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# Set working directory
WORKDIR /app
# Configure PHP for development
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
# Configure Xdebug (disabled by default to reduce noise)
RUN echo "xdebug.mode=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo ";xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo ";xdebug.client_host=host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo ";xdebug.start_with_request=yes" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
# Configure Caddy for development (simpler, no worker mode)
RUN cat > /etc/caddy/Caddyfile <<EOF
{
frankenphp
order php_server before file_server
}
:8000 {
root * /app/public
php_server {
index index.php
}
encode gzip
file_server
# Less strict headers for development
header {
X-Frame-Options "SAMEORIGIN"
}
}
EOF
# Install Node development dependencies globally
RUN npm install -g nodemon
# Create startup script for development (runs as host user)
RUN cat > /start.sh <<'EOF'
#!/bin/sh
set -e
# Create .env file if it doesn't exist
if [ ! -f ".env" ]; then
echo "Creating .env file from .env.example..."
cp .env.example .env
fi
# Install dependencies if volumes are empty
if [ ! -f "vendor/autoload.php" ]; then
echo "Installing composer dependencies..."
composer install
fi
# Handle node_modules with care - clean install if having issues
if [ ! -f "node_modules/.bin/vite" ]; then
echo "Installing npm dependencies..."
# Clean any remnants first
rm -rf node_modules/.* 2>/dev/null || true
rm -rf /app/.npm 2>/dev/null || true
# Fresh install with cache in tmp to avoid permission issues
npm install --cache /tmp/.npm
else
echo "Node modules already installed, skipping npm install"
fi
# Clear Laravel caches
php artisan config:clear || true
php artisan cache:clear || true
# Wait for database and run migrations
echo "Waiting for database..."
sleep 5
php artisan migrate --force || echo "Migration failed or not needed"
# Run development seeder (only in dev environment)
echo "Running development seeder..."
php artisan db:seed --class=DevelopmentSeeder --force || echo "Seeding skipped or already done"
# Generate app key if not set
if [ -z "$APP_KEY" ] || [ "$APP_KEY" = "base64:YOUR_KEY_HERE" ]; then
echo "Generating application key..."
php artisan key:generate
fi
# Start Vite dev server in background
npm run dev &
# Start FrankenPHP
exec frankenphp run --config /etc/caddy/Caddyfile
EOF
RUN chmod +x /start.sh
# Expose ports
EXPOSE 8000 5173
# Use the startup script
CMD ["/start.sh"]

View file

@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@ -26,44 +24,34 @@
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
@ -72,7 +60,7 @@
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@ -549,35 +537,45 @@
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@ -635,40 +633,29 @@
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
DishPlanner Copyright (C) 2025 myrmidex
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

138
README.md Normal file
View file

@ -0,0 +1,138 @@
# 🍽️ Dish Planner
[![CI](https://forge.lvl0.xyz/lvl0/dishplanner/badges/workflows/ci.yml/badge.svg)](https://forge.lvl0.xyz/lvl0/dishplanner/actions)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue)](LICENSE.md)
A Laravel-based meal planning application that helps households organize and schedule their dishes among multiple users. Built with Laravel, Livewire, and FrankenPHP for a modern, single-container deployment.
## ✨ Features
- **Multi-user dish management** - Assign dishes to specific household members
- **Smart scheduling** - Automatic schedule generation with recurrence patterns
- **Calendar view** - Visual 31-day schedule overview
- **Real-time updates** - Livewire-powered reactive interface
- **Dark theme UI** - Modern interface with purple/pink accents
- **Single container deployment** - Simplified hosting with FrankenPHP
## 🚀 Self-hosting
The production image is available at `forge.lvl0.xyz/lvl0/dishplanner:latest`. See [CHANGELOG.md](CHANGELOG.md) before upgrading.
### docker-compose.yml
```yaml
services:
app:
image: forge.lvl0.xyz/lvl0/dishplanner:latest
container_name: dishplanner_app
restart: always
ports:
- "8000:8000"
environment:
APP_KEY: "${APP_KEY}"
APP_URL: "${APP_URL}"
DB_DATABASE: "${DB_DATABASE}"
DB_USERNAME: "${DB_USERNAME}"
DB_PASSWORD: "${DB_PASSWORD}"
MAIL_HOST: "${MAIL_HOST:-}"
MAIL_PORT: "${MAIL_PORT:-587}"
MAIL_USERNAME: "${MAIL_USERNAME:-}"
MAIL_PASSWORD: "${MAIL_PASSWORD:-}"
MAIL_FROM_ADDRESS: "${MAIL_FROM_ADDRESS:-noreply@example.com}"
volumes:
- app_storage:/app/storage
depends_on:
- db
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/up"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
db:
image: mariadb:11
container_name: dishplanner_db
restart: always
environment:
MYSQL_DATABASE: "${DB_DATABASE}"
MYSQL_USER: "${DB_USERNAME}"
MYSQL_PASSWORD: "${DB_PASSWORD}"
MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
app_storage:
```
### Environment Variables
| Variable | Required | Description |
|----------|----------|-------------|
| `APP_KEY` | Yes | Encryption key. Generate with: `echo "base64:$(openssl rand -base64 32)"` |
| `APP_URL` | Yes | Your domain (e.g., `https://meals.example.com`) |
| `DB_DATABASE` | Yes | Database name |
| `DB_USERNAME` | Yes | Database user |
| `DB_PASSWORD` | Yes | Database password |
| `DB_ROOT_PASSWORD` | Yes | MariaDB root password |
| `MAIL_HOST` | No | SMTP host for email notifications |
| `MAIL_PORT` | No | SMTP port (default: 587) |
| `MAIL_USERNAME` | No | SMTP username |
| `MAIL_PASSWORD` | No | SMTP password |
| `MAIL_FROM_ADDRESS` | No | From address for emails |
## 🔧 Development
### NixOS / Nix
```bash
git clone https://forge.lvl0.xyz/lvl0/dishplanner.git
cd dishplanner
nix-shell
```
The shell will display available commands and optionally start the containers for you.
#### Available Commands
| Command | Description |
|---------|-------------|
| `dev-up` | Start development environment |
| `dev-down` | Stop development environment |
| `dev-restart` | Restart containers |
| `dev-rebuild` | Full rebuild (removes volumes) |
| `dev-rebuild-quick` | Quick rebuild (keeps volumes) |
| `dev-logs [service]` | Follow logs |
| `dev-logs-db` | Tail database logs |
| `dev-shell` | Enter app container |
| `dev-artisan <cmd>` | Run artisan commands |
| `dev-test [path]` | Run the PHPUnit suite the CI way |
| `dev-fix-permissions` | Fix Docker-created file permissions |
#### Services
| Service | URL |
|---------|-----|
| App | http://localhost:8000 |
| Vite | http://localhost:5173 |
| Mailhog | http://localhost:8025 |
| MariaDB | localhost:3306 |
### Other Platforms
Contributions welcome for development setup instructions on other platforms.
## 🤝 Contributing
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for
the development setup, the checks that run in CI, and the commit conventions.
## 📄 License
This project is open-source software licensed under the [AGPL-3.0 license](LICENSE.md).
## 📞 Support
For issues and questions, please use [Forgejo Issues](https://forge.lvl0.xyz/lvl0/dishplanner/issues).

View file

@ -0,0 +1,84 @@
<?php
namespace App\Actions\User;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
class CreateUserAction
{
/**
* @throws Exception
*/
public function execute(array $data): User
{
try {
// Validate required fields first
if (! isset($data['name']) || empty($data['name'])) {
throw new InvalidArgumentException('Name is required');
}
if (! isset($data['planner_id']) || empty($data['planner_id'])) {
throw new InvalidArgumentException('Planner ID is required');
}
DB::beginTransaction();
Log::info('CreateUserAction: Starting user creation', [
'name' => $data['name'],
'planner_id' => $data['planner_id'],
]);
// Create the user
$user = User::create([
'name' => $data['name'],
'planner_id' => $data['planner_id'],
]);
if (! $user) {
throw new Exception('User creation returned null');
}
Log::info('CreateUserAction: User creation result', [
'user_id' => $user->id,
'name' => $user->name,
'planner_id' => $user->planner_id,
]);
// Verify the user was actually created
$createdUser = User::find($user->id);
if (! $createdUser) {
throw new Exception('User creation did not persist to database');
}
if ($createdUser->name !== $data['name']) {
throw new Exception('User creation data mismatch');
}
DB::commit();
Log::info('CreateUserAction: User successfully created', [
'user_id' => $user->id,
'name' => $user->name,
'planner_id' => $user->planner_id,
]);
return $user;
} catch (Exception $e) {
DB::rollBack();
Log::error('CreateUserAction: User creation failed', [
'name' => $data['name'] ?? 'N/A',
'planner_id' => $data['planner_id'] ?? 'N/A',
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace App\Actions\User;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class DeleteUserAction
{
/**
* @throws Exception
*/
public function execute(User $user): bool
{
try {
DB::beginTransaction();
Log::info('DeleteUserAction: Starting user deletion', [
'user_id' => $user->id,
'user_name' => $user->name,
'planner_id' => $user->planner_id,
]);
// Check for related data
$userDishCount = $user->userDishes()->count();
$dishCount = $user->dishes()->count();
Log::info('DeleteUserAction: User relationship counts', [
'user_id' => $user->id,
'user_dishes_count' => $userDishCount,
'dishes_count' => $dishCount,
]);
// Store user info before deletion for verification
$userId = $user->id;
$userName = $user->name;
// Delete the user (cascading deletes should handle related records)
$result = $user->delete();
Log::info('DeleteUserAction: Delete result', [
'result' => $result,
'user_id' => $userId,
]);
if (! $result) {
throw new Exception('User deletion returned false');
}
// Verify the deletion actually happened
$stillExists = User::find($userId);
if ($stillExists) {
throw new Exception('User deletion did not persist to database');
}
DB::commit();
Log::info('DeleteUserAction: User successfully deleted', [
'user_id' => $userId,
'user_name' => $userName,
]);
return true;
} catch (Exception $e) {
DB::rollBack();
Log::error('DeleteUserAction: User deletion failed', [
'user_id' => $user->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace App\Actions\User;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class EditUserAction
{
public function execute(User $user, array $data): bool
{
try {
DB::beginTransaction();
Log::info('EditUserAction: Starting user update', [
'user_id' => $user->id,
'old_name' => $user->name,
'new_name' => $data['name'],
'planner_id' => $user->planner_id,
]);
$result = $user->update([
'name' => $data['name'],
]);
Log::info('EditUserAction: Update result', [
'result' => $result,
'user_id' => $user->id,
]);
if (! $result) {
throw new \Exception('User update returned false');
}
// Verify the update actually happened
$user->refresh();
if ($user->name !== $data['name']) {
throw new \Exception('User update did not persist to database');
}
DB::commit();
Log::info('EditUserAction: User successfully updated', [
'user_id' => $user->id,
'updated_name' => $user->name,
]);
return true;
} catch (\Exception $e) {
DB::rollBack();
Log::error('EditUserAction: User update failed', [
'user_id' => $user->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
}

View file

@ -24,6 +24,7 @@ public function handle(): int
if ($planners->isEmpty()) {
$this->warn('No planners found. Aborting schedule generation.');
return self::FAILURE;
}

View file

@ -13,8 +13,7 @@ public function response(
?array $payload = null,
array|string|null $errors = null,
int $statusCode = 200,
): JsonResponse
{
): JsonResponse {
return response()->json(resolve(OutputService::class)->response($success, $payload, $errors), $statusCode);
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials, $request->boolean('remember'))) {
$request->session()->regenerate();
return redirect()->intended(route('dashboard'));
}
throw ValidationException::withMessages([
'email' => 'These credentials do not match our records.',
]);
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\Planner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
class RegisterController extends Controller
{
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:planners'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = Planner::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect(route('dashboard'));
}
}

View file

@ -10,7 +10,10 @@ class ForceJsonResponse
{
public function handle(Request $request, Closure $next): Response
{
$request->headers->set('Accept', 'application/json');
// Only force JSON for API routes
if ($request->is('api/*')) {
$request->headers->set('Accept', 'application/json');
}
return $next($request);
}

View file

@ -17,7 +17,7 @@ public function toArray(Request $request): array
'recurrences' => $this->recurrences->map(fn ($recurrence) => [
'id' => $recurrence->id,
'type' => $recurrence->recurrence_type,
'value' => $recurrence->getValue()
'value' => $recurrence->getValue(),
]),
];
}

View file

@ -0,0 +1,136 @@
<?php
namespace App\Livewire\Dishes;
use App\Models\Dish;
use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;
class DishesList extends Component
{
use WithPagination;
public $showCreateModal = false;
public $showEditModal = false;
public $showDeleteModal = false;
public $editingDish = null;
public $deletingDish = null;
// Form fields
public $name = '';
public $selectedUsers = [];
protected $rules = [
'name' => 'required|string|max:255',
'selectedUsers' => 'array',
];
public function render()
{
$dishes = Dish::with('users')
->orderBy('name')
->paginate(10);
$users = User::where('planner_id', auth()->id())
->orderBy('name')
->get();
return view('livewire.dishes.dishes-list', [
'dishes' => $dishes,
'users' => $users,
]);
}
public function create()
{
$this->reset(['name', 'selectedUsers']);
$this->resetValidation();
$this->showCreateModal = true;
}
public function store()
{
$this->validate();
$dish = Dish::create([
'name' => $this->name,
'planner_id' => auth()->id(),
]);
// Attach selected users
if (! empty($this->selectedUsers)) {
$dish->users()->attach($this->selectedUsers);
}
$this->showCreateModal = false;
$this->reset(['name', 'selectedUsers']);
session()->flash('success', 'Dish created successfully.');
}
public function edit(Dish $dish)
{
$this->editingDish = $dish;
$this->name = $dish->name;
$this->selectedUsers = $dish->users->pluck('id')->toArray();
$this->resetValidation();
$this->showEditModal = true;
}
public function update()
{
$this->validate();
$this->editingDish->update([
'name' => $this->name,
]);
// Sync users
$this->editingDish->users()->sync($this->selectedUsers);
$this->showEditModal = false;
$this->reset(['name', 'selectedUsers', 'editingDish']);
session()->flash('success', 'Dish updated successfully.');
}
public function confirmDelete(Dish $dish)
{
$this->deletingDish = $dish;
$this->showDeleteModal = true;
}
public function delete()
{
$this->deletingDish->users()->detach();
$this->deletingDish->delete();
$this->showDeleteModal = false;
$this->deletingDish = null;
session()->flash('success', 'Dish deleted successfully.');
}
public function cancel()
{
$this->showCreateModal = false;
$this->showEditModal = false;
$this->showDeleteModal = false;
$this->reset(['name', 'selectedUsers', 'editingDish', 'deletingDish']);
}
public function toggleAllUsers(): void
{
$users = User::where('planner_id', auth()->id())->get();
if (count($this->selectedUsers) === $users->count()) {
$this->selectedUsers = [];
} else {
$this->selectedUsers = $users->pluck('id')->map(fn ($id) => (string) $id)->toArray();
}
}
}

View file

@ -0,0 +1,462 @@
<?php
namespace App\Livewire\Schedule;
use App\Models\Dish;
use App\Models\Schedule;
use App\Models\ScheduledUserDish;
use App\Models\User;
use App\Models\UserDish;
use Carbon\Carbon;
use DishPlanner\Schedule\Services\ScheduleCalendarService;
use DishPlanner\ScheduledUserDish\Actions\DeleteScheduledUserDishForDateAction;
use DishPlanner\ScheduledUserDish\Actions\SkipScheduledUserDishForDateAction;
use Exception;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
class ScheduleCalendar extends Component
{
public $currentMonth;
public $currentYear;
public $calendarDays = [];
public $showRegenerateModal = false;
public $regenerateDate = null;
public $regenerateUserId = null;
// Edit dish modal
public $showEditDishModal = false;
public $editDate = null;
public $editUserId = null;
public $selectedDishId = null;
public $availableDishes = [];
// Add dish modal
public $showAddDishModal = false;
public $addDate = null;
public $addUserIds = [];
public $addSelectedDishId = null;
public $addAvailableUsers = [];
public $addAvailableDishes = [];
public function mount(): void
{
$this->currentMonth = now()->month;
$this->currentYear = now()->year;
$this->loadCalendar();
}
protected $listeners = ['schedule-generated' => 'refreshCalendar'];
public function render(): View
{
return view('livewire.schedule.schedule-calendar');
}
public function refreshCalendar(): void
{
$this->loadCalendar();
}
public function loadCalendar(): void
{
$service = new ScheduleCalendarService;
$this->calendarDays = $service->getCalendarDays(
auth()->user(),
$this->currentMonth,
$this->currentYear
);
}
public function previousMonth(): void
{
if ($this->currentMonth === 1) {
$this->currentMonth = 12;
$this->currentYear--;
} else {
$this->currentMonth--;
}
$this->loadCalendar();
}
public function nextMonth(): void
{
if ($this->currentMonth === 12) {
$this->currentMonth = 1;
$this->currentYear++;
} else {
$this->currentMonth++;
}
$this->loadCalendar();
}
public function regenerateForUserDate($date, $userId): void
{
if (! $this->authorizeUser($userId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
$this->regenerateDate = $date;
$this->regenerateUserId = $userId;
$this->showRegenerateModal = true;
}
public function confirmRegenerate(): void
{
try {
if (! $this->authorizeUser($this->regenerateUserId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
$action = new DeleteScheduledUserDishForDateAction;
$action->execute(
auth()->user(),
Carbon::parse($this->regenerateDate),
$this->regenerateUserId
);
$this->showRegenerateModal = false;
$this->loadCalendar();
session()->flash('success', 'Schedule regenerated for the selected date!');
} catch (Exception $e) {
Log::error('Schedule regeneration failed', ['exception' => $e, 'date' => $this->regenerateDate]);
session()->flash('error', 'Unable to regenerate schedule. Please try again.');
}
}
public function skipDay($date, $userId): void
{
try {
if (! $this->authorizeUser($userId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
$action = new SkipScheduledUserDishForDateAction;
$action->execute(
auth()->user(),
Carbon::parse($date),
$userId
);
$this->loadCalendar();
session()->flash('success', 'Day skipped successfully!');
} catch (Exception $e) {
Log::error('Skip day failed', ['exception' => $e, 'date' => $date, 'userId' => $userId]);
session()->flash('error', 'Unable to skip day. Please try again.');
}
}
private function authorizeUser(int $userId): bool
{
$user = User::find($userId);
return $user && $user->planner_id === auth()->id();
}
public function cancel(): void
{
$this->showRegenerateModal = false;
$this->regenerateDate = null;
$this->regenerateUserId = null;
$this->showEditDishModal = false;
$this->editDate = null;
$this->editUserId = null;
$this->selectedDishId = null;
$this->availableDishes = [];
$this->showAddDishModal = false;
$this->addDate = null;
$this->addUserIds = [];
$this->addSelectedDishId = null;
$this->addAvailableUsers = [];
$this->addAvailableDishes = [];
}
public function removeDish($date, $userId): void
{
try {
if (! $this->authorizeUser($userId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
$schedule = Schedule::where('planner_id', auth()->id())
->where('date', $date)
->first();
if ($schedule) {
ScheduledUserDish::where('schedule_id', $schedule->id)
->where('user_id', $userId)
->delete();
}
$this->loadCalendar();
session()->flash('success', 'Dish removed successfully!');
} catch (Exception $e) {
Log::error('Remove dish failed', ['exception' => $e, 'date' => $date, 'userId' => $userId]);
session()->flash('error', 'Unable to remove dish. Please try again.');
}
}
public function openAddDishModal($date): void
{
$this->addDate = $date;
// Load all users for this planner
$this->addAvailableUsers = User::where('planner_id', auth()->id())
->orderBy('name')
->get();
$this->addAvailableDishes = [];
$this->addUserIds = [];
$this->addSelectedDishId = null;
$this->showAddDishModal = true;
}
public function toggleAllUsers(): void
{
if (count($this->addUserIds) === count($this->addAvailableUsers)) {
$this->addUserIds = [];
} else {
$this->addUserIds = $this->addAvailableUsers->pluck('id')->map(fn ($id) => (string) $id)->toArray();
}
$this->updateAvailableDishes();
}
public function updatedAddUserIds(): void
{
$this->updateAvailableDishes();
}
private function updateAvailableDishes(): void
{
if (empty($this->addUserIds)) {
$this->addAvailableDishes = [];
} else {
// Load dishes that ALL selected users have in common
$selectedCount = count($this->addUserIds);
$this->addAvailableDishes = Dish::whereHas('users', function ($query) {
$query->whereIn('users.id', $this->addUserIds);
}, '=', $selectedCount)->orderBy('name')->get();
}
$this->addSelectedDishId = null;
}
public function saveAddDish(): void
{
try {
if (empty($this->addUserIds)) {
session()->flash('error', 'Please select at least one user.');
return;
}
if (! $this->addSelectedDishId) {
session()->flash('error', 'Please select a dish.');
return;
}
// Find or create the schedule for this date
$schedule = Schedule::firstOrCreate(
[
'planner_id' => auth()->id(),
'date' => $this->addDate,
],
['is_skipped' => false]
);
$addedCount = 0;
$skippedCount = 0;
foreach ($this->addUserIds as $userId) {
if (! $this->authorizeUser((int) $userId)) {
$skippedCount++;
continue;
}
// Check if user already has a dish scheduled for this date
$existing = ScheduledUserDish::where('schedule_id', $schedule->id)
->where('user_id', $userId)
->first();
if ($existing) {
$skippedCount++;
continue;
}
// Find the UserDish for this user and dish
$userDish = UserDish::where('user_id', $userId)
->where('dish_id', $this->addSelectedDishId)
->first();
if (! $userDish) {
$skippedCount++;
continue;
}
// Create the scheduled user dish
ScheduledUserDish::create([
'schedule_id' => $schedule->id,
'user_id' => $userId,
'user_dish_id' => $userDish->id,
'is_skipped' => false,
]);
$addedCount++;
}
$this->closeAddDishModal();
$this->loadCalendar();
if ($addedCount > 0 && $skippedCount > 0) {
session()->flash('success', "Dish added for {$addedCount} user(s). {$skippedCount} user(s) skipped (already scheduled).");
} elseif ($addedCount > 0) {
session()->flash('success', "Dish added for {$addedCount} user(s)!");
} else {
session()->flash('error', 'No users could be scheduled. They may already have dishes for this date.');
}
} catch (Exception $e) {
Log::error('Add dish failed', ['exception' => $e]);
session()->flash('error', 'Unable to add dish. Please try again.');
}
}
private function closeAddDishModal(): void
{
$this->showAddDishModal = false;
$this->addDate = null;
$this->addUserIds = [];
$this->addSelectedDishId = null;
$this->addAvailableUsers = [];
$this->addAvailableDishes = [];
}
public function editDish($date, $userId): void
{
if (! $this->authorizeUser($userId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
$this->editDate = $date;
$this->editUserId = $userId;
// Load dishes available for this user (via UserDish pivot)
$this->availableDishes = Dish::whereHas('users', function ($query) use ($userId) {
$query->where('users.id', $userId);
})->orderBy('name')->get();
// Get currently selected dish for this date/user if exists
$schedule = Schedule::where('planner_id', auth()->id())
->where('date', $date)
->first();
if ($schedule) {
$scheduledUserDish = ScheduledUserDish::where('schedule_id', $schedule->id)
->where('user_id', $userId)
->first();
if ($scheduledUserDish && $scheduledUserDish->userDish) {
$this->selectedDishId = $scheduledUserDish->userDish->dish_id;
}
}
$this->showEditDishModal = true;
}
public function saveDish(): void
{
try {
if (! $this->authorizeUser($this->editUserId)) {
session()->flash('error', 'Unauthorized action.');
return;
}
if (! $this->selectedDishId) {
session()->flash('error', 'Please select a dish.');
return;
}
// Find or create the schedule for this date
$schedule = Schedule::firstOrCreate(
[
'planner_id' => auth()->id(),
'date' => $this->editDate,
],
['is_skipped' => false]
);
// Find the UserDish for this user and dish
$userDish = UserDish::where('user_id', $this->editUserId)
->where('dish_id', $this->selectedDishId)
->first();
if (! $userDish) {
session()->flash('error', 'This dish is not assigned to this user.');
return;
}
// Update or create the scheduled user dish
ScheduledUserDish::updateOrCreate(
[
'schedule_id' => $schedule->id,
'user_id' => $this->editUserId,
],
[
'user_dish_id' => $userDish->id,
'is_skipped' => false,
]
);
$this->showEditDishModal = false;
$this->editDate = null;
$this->editUserId = null;
$this->selectedDishId = null;
$this->availableDishes = [];
$this->loadCalendar();
session()->flash('success', 'Dish updated successfully!');
} catch (Exception $e) {
Log::error('Save dish failed', ['exception' => $e]);
session()->flash('error', 'Unable to save dish. Please try again.');
}
}
public function getMonthNameProperty(): string
{
$service = new ScheduleCalendarService;
return $service->getMonthName($this->currentMonth, $this->currentYear);
}
}

View file

@ -0,0 +1,149 @@
<?php
namespace App\Livewire\Schedule;
use App\Models\User;
use Carbon\Carbon;
use DishPlanner\Schedule\Actions\ClearScheduleForMonthAction;
use DishPlanner\Schedule\Actions\GenerateScheduleForMonthAction;
use DishPlanner\Schedule\Actions\RegenerateScheduleForDateForUsersAction;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
class ScheduleGenerator extends Component
{
private const YEARS_IN_PAST = 1;
private const YEARS_IN_FUTURE = 5;
public $selectedMonth;
public $selectedYear;
public $selectedUsers = [];
public $clearExisting = true;
public $showAdvancedOptions = false;
public $isGenerating = false;
public function mount(): void
{
$this->selectedMonth = now()->month;
$this->selectedYear = now()->year;
$this->selectedUsers = User::where('planner_id', auth()->id())
->pluck('id')
->toArray();
}
public function render(): Factory|View
{
$users = User::where('planner_id', auth()->id())
->orderBy('name')
->get();
$years = range(now()->year - self::YEARS_IN_PAST, now()->year + self::YEARS_IN_FUTURE);
return view('livewire.schedule.schedule-generator', [
'users' => $users,
'months' => $this->getMonthNames(),
'years' => $years,
]);
}
public function generate(): void
{
$this->validate([
'selectedUsers' => 'required|array|min:1',
'selectedMonth' => 'required|integer|min:1|max:12',
'selectedYear' => 'required|integer|min:'.(now()->year - self::YEARS_IN_PAST).'|max:'.(now()->year + self::YEARS_IN_FUTURE),
]);
$this->isGenerating = true;
try {
$action = new GenerateScheduleForMonthAction;
$action->execute(
auth()->user(),
$this->selectedMonth,
$this->selectedYear,
$this->selectedUsers,
$this->clearExisting
);
$this->isGenerating = false;
$this->dispatch('schedule-generated');
session()->flash('success', 'Schedule generated successfully for '.
$this->getSelectedMonthName().' '.$this->selectedYear);
} catch (\Exception $e) {
$this->isGenerating = false;
Log::error('Schedule generation failed', ['exception' => $e]);
session()->flash('error', 'Unable to generate schedule. Please try again.');
}
}
public function regenerateForDate($date): void
{
try {
$action = new RegenerateScheduleForDateForUsersAction;
$action->execute(
auth()->user(),
Carbon::parse($date),
$this->selectedUsers
);
$this->dispatch('schedule-generated');
session()->flash('success', 'Schedule regenerated for '.Carbon::parse($date)->format('M d, Y'));
} catch (\Exception $e) {
Log::error('Schedule regeneration failed', ['exception' => $e, 'date' => $date]);
session()->flash('error', 'Unable to regenerate schedule. Please try again.');
}
}
public function clearMonth(): void
{
try {
$action = new ClearScheduleForMonthAction;
$action->execute(
auth()->user(),
$this->selectedMonth,
$this->selectedYear,
$this->selectedUsers
);
$this->dispatch('schedule-generated');
session()->flash('success', 'Schedule cleared for '.
$this->getSelectedMonthName().' '.$this->selectedYear);
} catch (\Exception $e) {
Log::error('Clear month failed', ['exception' => $e]);
session()->flash('error', 'Unable to clear schedule. Please try again.');
}
}
public function toggleAdvancedOptions()
{
$this->showAdvancedOptions = ! $this->showAdvancedOptions;
}
private function getMonthNames(): array
{
return [
1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December',
];
}
private function getSelectedMonthName(): string
{
return $this->getMonthNames()[$this->selectedMonth];
}
}

View file

@ -0,0 +1,129 @@
<?php
namespace App\Livewire\Users;
use App\Actions\User\CreateUserAction;
use App\Actions\User\DeleteUserAction;
use App\Actions\User\EditUserAction;
use App\Models\User;
use Exception;
use Illuminate\Contracts\View\View;
use Livewire\Component;
use Livewire\WithPagination;
class UsersList extends Component
{
use WithPagination;
public bool $showCreateModal = false;
public bool $showEditModal = false;
public bool $showDeleteModal = false;
public ?User $editingUser = null;
public ?User $deletingUser = null;
// Form fields
public string $name = '';
protected array $rules = [
'name' => 'required|string|max:255',
];
public function render(): View
{
$users = User::where('planner_id', auth()->id())
->orderBy('name')
->paginate(10);
return view('livewire.users.users-list', [
'users' => $users,
]);
}
public function create(): void
{
$this->reset(['name']);
$this->resetValidation();
$this->showCreateModal = true;
}
public function store(): void
{
$this->validate();
try {
(new CreateUserAction)->execute([
'name' => $this->name,
'planner_id' => auth()->id(),
]);
$this->showCreateModal = false;
$this->reset(['name']);
session()->flash('success', 'User created successfully.');
} catch (Exception $e) {
session()->flash('error', 'Failed to create user: '.$e->getMessage());
}
}
public function edit(User $user): void
{
$this->editingUser = $user;
$this->name = $user->name;
$this->resetValidation();
$this->showEditModal = true;
}
public function update(): void
{
$this->validate();
try {
(new EditUserAction)->execute($this->editingUser, ['name' => $this->name]);
$this->showEditModal = false;
$this->reset(['name', 'editingUser']);
session()->flash('success', 'User updated successfully.');
// Force component to re-render with fresh data
$this->resetPage();
} catch (Exception $e) {
session()->flash('error', 'Failed to update user: '.$e->getMessage());
}
}
public function confirmDelete(User $user): void
{
$this->deletingUser = $user;
$this->showDeleteModal = true;
}
public function delete(): void
{
try {
(new DeleteUserAction)->execute($this->deletingUser);
$this->showDeleteModal = false;
$this->deletingUser = null;
session()->flash('success', 'User deleted successfully.');
// Force component to re-render with fresh data
$this->resetPage();
} catch (Exception $e) {
session()->flash('error', 'Failed to delete user: '.$e->getMessage());
}
}
public function cancel(): void
{
$this->showCreateModal = false;
$this->showEditModal = false;
$this->showDeleteModal = false;
$this->reset(['name', 'editingUser', 'deletingUser']);
}
}

View file

@ -21,6 +21,7 @@
* @property Carbon $updated_at
* @property Collection<User> $users
* @property Collection<UserDish> $userDishes
*
* @method static create(array $data)
* @method static findOrFail(int $dish_id)
* @method static DishFactory factory($count = null, $state = [])

View file

@ -2,6 +2,7 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
@ -11,6 +12,10 @@
/**
* @property int $id
* @property static PlannerFactory factory($count = null, $state = [])
* @property Collection<User> $users
*
* @method static first()
* @method static create(array $array)
*/
class Planner extends Authenticatable
{
@ -24,8 +29,17 @@ class Planner extends Authenticatable
'password', 'remember_token',
];
protected $casts = [
'password' => 'hashed',
];
public function schedules(): HasMany
{
return $this->hasMany(Schedule::class);
}
public function users(): HasMany
{
return $this->hasMany(User::class);
}
}

View file

@ -22,11 +22,13 @@
* @property Dish $dish
* @property User $user
* @property Carbon $date
* @property boolean $is_skipped
* @property bool $is_skipped
* @property Collection<ScheduledUserDish> $scheduledUserDishes
*
* @method static create(array $array)
* @method static Builder where(array|Closure|Expression|string $column, mixed $operator = null, mixed $value = null, string $boolean = 'and')
* @method static ScheduleFactory factory($count = null, $state = [])
* @method static firstOrCreate(array $array, false[] $array1)
*/
class Schedule extends Model
{
@ -37,6 +39,8 @@ class Schedule extends Model
public $timestamps = false;
protected $dateFormat = 'Y-m-d';
protected $fillable = ['planner_id', 'date', 'is_skipped'];
protected $casts = [
@ -56,6 +60,6 @@ public function scheduledUserDishes(): HasMany
public function hasAllUsersScheduled(): bool
{
return $this->scheduledUserDishes->count() === User::all()->count();
return $this->scheduledUserDishes->count() === User::where('planner_id', $this->planner_id)->count();
}
}

View file

@ -12,17 +12,26 @@
* @property int $id
* @property int $schedule_id
* @property Schedule $schedule
* @property int $user_id
* @property User $user
* @property int $user_dish_id
* @property UserDish $userDish
* @property bool $is_skipped
*
* @method static create(array $array)
* @method static ScheduledUserDishFactory factory($count = null, $state = [])
* @method static firstOrCreate(array $array, array $array1)
*/
class ScheduledUserDish extends Model
{
use HasFactory;
protected $fillable = ['schedule_id', 'user_id', 'user_dish_id', 'is_skipped'];
protected $fillable = [
'schedule_id',
'user_id',
'user_dish_id',
'is_skipped',
];
protected $casts = [
'is_skipped' => 'boolean',

View file

@ -6,11 +6,10 @@
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
/**
* @property int $id
@ -18,24 +17,20 @@
* @property string $name
* @property Collection<Dish> $dishes
* @property Collection<UserDish> $userDishes
*
* @method static User findOrFail(int $user_id)
* @method static UserFactory factory($count = null, $state = [])
* @method static create(array $array)
* @method static where(string $string, int|string|null $id)
*/
class User extends Authenticatable
class User extends Model
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
use HasFactory;
protected $fillable = [
'planner_id',
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected static function booted(): void
@ -43,19 +38,6 @@ protected static function booted(): void
static::addGlobalScope(new BelongsToPlanner);
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
public function dishes(): BelongsToMany
{
return $this->belongsToMany(Dish::class, 'user_dishes', 'user_id', 'dish_id');

View file

@ -17,6 +17,7 @@
* @method static UserDish|null find(int|null $user_dish_id)
* @method static create(array $array)
* @method static where(string $string, int $id)
*
* @property int $id
* @property int $dish_id
* @property int $user_id

View file

@ -36,7 +36,7 @@ public function getValue(): int
return match ($this->recurrence_type) {
WeeklyRecurrence::class => $this->recurrence->weekday->value,
MinimumRecurrence::class => $this->recurrence->days,
default => throw new InvalidRecurrenceTypeException()
default => throw new InvalidRecurrenceTypeException
};
}
}

View file

@ -12,10 +12,11 @@
/**
* @property int $weekday
*
* @method static create(array $array)
* @method static WeeklyRecurrenceFactory factory($count = null, $state = [])
*/
class WeeklyRecurrence extends Model implements RecurrenceInterface, FixedRecurrenceInterface
class WeeklyRecurrence extends Model implements FixedRecurrenceInterface, RecurrenceInterface
{
/** @use HasFactory<WeeklyRecurrenceFactory> */
use HasFactory;

View file

@ -16,7 +16,6 @@
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Foundation\Exceptions\Handler as BaseHandler;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Throwable;
@ -25,7 +24,8 @@ class AppServiceProvider extends ServiceProvider
public function register(): void
{
$this->app->bind(ExceptionHandler::class, function ($app) {
return new class($app) extends BaseHandler {
return new class($app) extends BaseHandler
{
public function render($request, Throwable $e)
{
// Handle specific custom exception

View file

@ -2,7 +2,6 @@
namespace App\Services;
class OutputService
{
public function response(bool $success = true, ?array $payload = null, array|string|null $errors = null): array

View file

@ -1,71 +0,0 @@
APP_NAME=DishPlanner
APP_ENV=local
APP_KEY=base64:Z3WnYIG9I6xxft15P1EO31WHinj1R36eM/iN3ouyFBM=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8000
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
WWWGROUP=1000
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=dishplanner
DB_USERNAME=dpuser
DB_PASSWORD=dppass
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=file
CACHE_PREFIX=dishplanner
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

25
backend/.gitignore vendored
View file

@ -1,25 +0,0 @@
/composer.lock
/.composer
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
/auth.json
/.fleet
/.idea
/.nova
/.vscode
/.zed

View file

@ -1,35 +0,0 @@
# Use official PHP base with required extensions
FROM php:8.2-fpm
# Install system dependencies & PHP extensions
RUN apt-get update && apt-get install -y \
git unzip curl libzip-dev libpng-dev libonig-dev libxml2-dev zip \
&& docker-php-ext-install pdo pdo_mysql zip mbstring exif pcntl bcmath
# Install Composer globally
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
# Set working dir
WORKDIR /var/www
# Copy app files
COPY . .
# Install PHP dependencies
RUN composer install --no-dev --optimize-autoloader
# Laravel optimizations
RUN php artisan config:cache \
&& php artisan route:cache \
&& php artisan view:cache
# Set correct permissions
RUN chown -R www-data:www-data /var/www \
&& chmod -R 755 /var/www/storage
USER www-data
# Expose port 9000 (default for php-fpm)
EXPOSE 9000
CMD ["php-fpm"]

View file

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,14 +0,0 @@
# Dish Planner
Plan your future dishes
## Development
### Installation
This project uses Laravel Sail, so install all composer packages, get your docker up, and run
```shell
./vendor/bin/sail up -d
```

View file

@ -1,3 +0,0 @@
#!/bin/bash
docker build -t 192.168.178.152:50114/dishplanner-backend .
docker push 192.168.178.152:50114/dishplanner-backend

View file

@ -1,61 +0,0 @@
<?php
use App\Http\Middleware\ForceJsonResponse;
use App\Http\Middleware\HandleResourceNotFound;
use App\Services\OutputService;
use DishPlanner\Dish\Controllers\DishController;
use DishPlanner\Schedule\Console\Commands\GenerateScheduleCommand;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\HandleCors;
use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Validation\ValidationException;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->append(ForceJsonResponse::class);
$middleware->append(StartSession::class);
$middleware->append(HandleCors::class);
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
}
return $request->expectsJson();
});
/** @var OutputService $outputService */
$outputService = resolve(OutputService::class);
$exceptions->render(fn (ValidationException $e, Request $request) => $outputService
->response(false, null, [$e->getMessage()], 404)
);
$exceptions->render(fn (NotFoundHttpException $e, Request $request) => response()->json(
$outputService->response(false, null, ['MODEL_NOT_FOUND']),
404
));
$exceptions->render(fn (AccessDeniedHttpException $e, Request $request) => response()->json(
$outputService->response(false, null, [$e->getMessage()]),
403
));
})
->withCommands([
GenerateScheduleCommand::class,
])
->create();

View file

@ -1,5 +0,0 @@
<?php
return [
App\Providers\AppServiceProvider::class,
];

View file

@ -1,33 +0,0 @@
<?php
namespace Database\Seeders;
use App\Models\Dish;
use App\Models\Planner;
use App\Models\User;
use Illuminate\Database\Seeder;
class DishesSeeder extends Seeder
{
public function run(): void
{
$users = User::all();
$userOptions = collect([
[$users->first()],
[$users->last()],
[$users->first(), $users->last()],
]);
$planner = Planner::all()->first() ?? Planner::factory()->create();
collect([
'lasagne', 'pizza', 'burger', 'fries', 'salad', 'sushi', 'pancakes', 'ice cream', 'spaghetti', 'mac and cheese',
'steak', 'chicken', 'beef', 'pork', 'fish', 'chips', 'cake',
])->map(fn (string $name) => Dish::factory()
->create([
'planner_id' => $planner->id,
'name' => $name,
])
)->each(fn (Dish $dish) => $dish->users()->attach($userOptions->random()));
}
}

View file

@ -1,25 +0,0 @@
services:
backend:
volumes:
- '.:/var/www/html:Z'
mysql:
image: 'docker.io/library/mysql:8.0'
environment:
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
volumes:
- 'sail-mysql:/var/lib/mysql:Z'
frontend:
image: 'docker.io/library/node:22-alpine'
working_dir: /app
command: sh -c "npm install && npm run dev -- --host"
volumes:
- '../frontend:/app:Z'
ports:
- '5173:5173'
networks:
- sail
depends_on:
- backend

View file

@ -1,54 +0,0 @@
services:
backend:
build:
context: './vendor/laravel/sail/runtimes/8.4'
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: 'sail-8.4/app'
extra_hosts:
- 'host.docker.internal:host-gateway'
ports:
- '${APP_PORT:-80}:80'
- '${VITE_PORT:-5173}:${VITE_PORT:-5173}'
environment:
WWWUSER: '${WWWUSER}'
LARAVEL_SAIL: 1
XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
IGNITION_LOCAL_SITES_PATH: '${PWD}'
volumes:
- '.:/var/www/html:Z'
networks:
- sail
depends_on:
- mysql
mysql:
image: 'docker.io/mysql/mysql-server:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_ROOT_HOST: '%'
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'sail-mysql:/var/lib/mysql:Z'
networks:
- sail
healthcheck:
test:
- CMD
- mysqladmin
- ping
- '-p${DB_PASSWORD}'
retries: 3
timeout: 5s
networks:
sail:
driver: bridge
volumes:
sail-mysql:
driver: local

View file

@ -1,17 +0,0 @@
{
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"autoprefixer": "^10.4.20",
"axios": "^1.7.4",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^1.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13",
"vite": "^6.0"
}
}

View file

@ -1,3 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

File diff suppressed because one or more lines are too long

View file

@ -1,16 +0,0 @@
<?php
use Illuminate\Support\Facades\Route;
Route::group([
'as' => 'api.',
], function () {
require __DIR__ . '/api/auth.php';
Route::middleware('auth:sanctum')->group(function () {
require __DIR__ . '/api/users.php';
require __DIR__ . '/api/dishes.php';
require __DIR__ . '/api/schedule.php';
require __DIR__ . '/api/scheduledUserDishes.php';
});
});

View file

@ -1,7 +0,0 @@
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

View file

@ -1,20 +0,0 @@
import defaultTheme from 'tailwindcss/defaultTheme';
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/**/*.blade.php',
'./resources/**/*.js',
'./resources/**/*.vue',
],
theme: {
extend: {
fontFamily: {
sans: ['Figtree', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [],
};

View file

@ -1,98 +0,0 @@
<?php
namespace Tests\Feature;
use App\Models\Planner;
use App\Models\Schedule;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class PlannerLoginTest extends TestCase
{
use RefreshDatabase;
public function test_a_planner_can_log_in_with_correct_credentials(): void
{
$planner = Planner::factory()->create([
'email' => 'planner@example.com',
'password' => Hash::make('secret123'),
]);
$response = $this
->actingAs($planner)
->post(route('api.auth.login'), [
'email' => 'planner@example.com',
'password' => 'secret123',
]);
$response->assertOk();
$this->assertAuthenticatedAs($planner);
}
public function test_login_fails_with_invalid_credentials(): void
{
Planner::factory()->create([
'email' => 'planner@example.com',
'password' => Hash::make('secret123'),
]);
$response = $this->postJson(route('api.auth.login'), [
'email' => 'planner@example.com',
'password' => 'wrongpassword',
]);
$response->assertUnauthorized();
}
public function test_a_logged_in_planner_can_log_out(): void
{
$planner = Planner::factory()->create([
'password' => Hash::make('secret123'),
]);
$this->post(route('api.auth.login'), [
'email' => $planner->email,
'password' => 'secret123',
]);
$response = $this->post(route('api.auth.logout'));
$response->assertOk();
$this->assertGuest(); // nobody should be logged in after logout
}
public function test_planner_can_register(): void
{
$schedulesCount = Schedule::all()->count();
$response = $this->post(route('api.auth.register'), [
'name' => 'High Functioning Planner',
'email' => 'planner@example.com',
'password' => 'secret123',
'password_confirmation' => 'secret123',
]);
$response->assertCreated();
$this->assertDatabaseHas('planners', [
'email' => 'planner@example.com',
]);
$this->assertGreaterThan($schedulesCount, Schedule::all()->count());
}
public function test_it_returns_the_authenticated_planner(): void
{
$planner = Planner::factory()->create();
$this
->actingAs($planner)
->get(route('api.auth.me'))
->assertOk()
->assertJsonFragment([
'email' => $planner->email,
'name' => $planner->name,
]);
}
}

View file

@ -1,10 +0,0 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

View file

@ -1,20 +0,0 @@
<?php
namespace Tests\Traits;
use App\Models\Planner;
trait HasPlanner
{
protected Planner $planner;
public function setUp(): void
{
parent::setUp();
$planner = Planner::factory()->create();
$this->planner = $planner;
}
}

3
bin/build_and_push.sh Executable file
View file

@ -0,0 +1,3 @@
#!/bin/bash
docker build -t forge.lvl0.xyz/lvl0/dishplanner:latest .
docker push forge.lvl0.xyz/lvl0/dishplanner:latest

View file

@ -1,159 +0,0 @@
#!/usr/bin/env bash
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Get script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# Detect Docker or Podman
CONTAINER_CLI=""
# Check if docker is actually podman in disguise
if command -v docker &> /dev/null && docker --version 2>&1 | grep -q "podman"; then
CONTAINER_CLI="podman"
echo -e "${GREEN}Using Podman (via docker alias)${NC}"
elif command -v docker &> /dev/null && docker info &> /dev/null; then
CONTAINER_CLI="docker"
echo -e "${GREEN}Using Docker${NC}"
elif command -v podman &> /dev/null; then
CONTAINER_CLI="podman"
echo -e "${GREEN}Using Podman${NC}"
else
echo -e "${RED}✗ Neither Docker nor Podman found. Please install one of them first.${NC}"
echo -e "${YELLOW}Install Docker: https://docs.docker.com/get-docker/${NC}"
echo -e "${YELLOW}Install Podman: https://podman.io/getting-started/installation${NC}"
exit 1
fi
echo -e "${GREEN}=== Dish Planner Development Setup ===${NC}\n"
# Check if .env exists in backend
if [ ! -f "$PROJECT_ROOT/backend/.env" ]; then
echo -e "${YELLOW}Creating backend/.env from .env.example...${NC}"
cp "$PROJECT_ROOT/backend/.env.example" "$PROJECT_ROOT/backend/.env"
echo -e "${GREEN}✓ Created backend/.env${NC}\n"
fi
# Ensure APP_PORT is set for Podman (can't use privileged port 80)
if [ "$CONTAINER_CLI" = "podman" ] && ! grep -q "^APP_PORT=" "$PROJECT_ROOT/backend/.env"; then
echo -e "${YELLOW}Setting APP_PORT=8000 for Podman (non-privileged port)...${NC}"
echo "APP_PORT=8000" >> "$PROJECT_ROOT/backend/.env"
fi
# Backend setup
echo -e "${GREEN}=== Backend Setup ===${NC}"
cd "$PROJECT_ROOT/backend"
# Install dependencies if vendor doesn't exist
if [ ! -d "vendor" ]; then
echo -e "${YELLOW}No vendor directory found. Installing dependencies with Docker...${NC}"
# Use a standalone PHP/Composer Docker image to install dependencies
# This is the recommended Laravel approach for first-time setup
# Configure for Docker or Podman
VOLUME_OPTS="$PROJECT_ROOT/backend:/var/www/html"
USER_OPTS="-u $(id -u):$(id -g)"
EXTRA_OPTS=""
if [ "$CONTAINER_CLI" = "podman" ]; then
# Podman on SELinux systems needs :Z and --userns=keep-id to maintain user ID
VOLUME_OPTS="$VOLUME_OPTS:Z"
USER_OPTS=""
EXTRA_OPTS="--userns=keep-id"
fi
$CONTAINER_CLI run --rm \
$USER_OPTS \
$EXTRA_OPTS \
-v "$VOLUME_OPTS" \
-w /var/www/html \
docker.io/laravelsail/php84-composer:latest \
composer install --ignore-platform-reqs
echo -e "${GREEN}✓ Backend dependencies installed${NC}\n"
else
echo -e "${GREEN}✓ Backend dependencies already installed${NC}\n"
fi
# Check if database volume exists - if not, we're doing fresh initialization
FRESH_DB=false
if ! $CONTAINER_CLI volume inspect sail-mysql &>/dev/null && ! $CONTAINER_CLI volume inspect backend_sail-mysql &>/dev/null; then
FRESH_DB=true
echo -e "${YELLOW}Fresh database initialization detected${NC}"
fi
# Start containers using compose directly (docker-compose.override.yml is automatically used)
echo -e "${YELLOW}Starting backend containers...${NC}"
if $CONTAINER_CLI compose up -d 2>&1 | tee /tmp/compose-up.log; then
echo -e "${GREEN}✓ Containers started${NC}\n"
else
echo -e "${RED}✗ Failed to start containers. Check /tmp/compose-up.log for details${NC}"
exit 1
fi
# Wait for database to be ready
echo -e "${YELLOW}Waiting for database to be ready...${NC}"
MAX_ATTEMPTS=30
ATTEMPT=0
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
if $CONTAINER_CLI compose exec mysql mysqladmin ping -h localhost --silent 2>/dev/null; then
echo -e "${GREEN}✓ Database is ready${NC}"
break
fi
ATTEMPT=$((ATTEMPT + 1))
echo -e "${YELLOW}Waiting for database... (attempt $ATTEMPT/$MAX_ATTEMPTS)${NC}"
sleep 2
done
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
echo -e "${RED}✗ Database failed to become ready${NC}"
exit 1
fi
# Give MySQL extra time on fresh initialization to create users
if [ "$FRESH_DB" = true ]; then
echo -e "${YELLOW}Waiting for fresh database to complete initialization...${NC}"
sleep 10
else
sleep 3
fi
# Run migrations
echo -e "${YELLOW}Running database migrations...${NC}"
$CONTAINER_CLI compose exec backend php artisan migrate --force
# Check if database has data
echo -e "${YELLOW}Checking if database needs seeding...${NC}"
TABLE_COUNT=$($CONTAINER_CLI compose exec backend php artisan tinker --execute="echo \DB::table('users')->count();" 2>/dev/null | tail -1 | tr -d '[:space:]' || echo "0")
# Default to 0 if not a number
if ! [[ "$TABLE_COUNT" =~ ^[0-9]+$ ]]; then
TABLE_COUNT=0
fi
if [ "$TABLE_COUNT" -eq "0" ]; then
echo -e "${YELLOW}Database is empty. Run seeders? (y/n)${NC}"
read -r response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
$CONTAINER_CLI compose exec backend php artisan db:seed
echo -e "${GREEN}✓ Database seeded${NC}\n"
fi
fi
echo -e "${GREEN}✓ Backend setup complete${NC}"
echo -e "${GREEN}Backend API running at: http://localhost:8000${NC}\n"
# Display summary
echo -e "${GREEN}=== Development Environment Ready ===${NC}"
echo -e "${GREEN}Backend API:${NC} http://localhost:8000"
echo -e "${GREEN}Frontend:${NC} http://localhost:5173"
echo -e "${GREEN}Database:${NC} MySQL on localhost:3306"
echo -e ""
echo -e "${YELLOW}Note:${NC} Frontend container will install dependencies and start automatically."
echo -e "${YELLOW}To view frontend logs:${NC}"
echo -e " cd backend && $CONTAINER_CLI compose logs -f frontend"
echo -e ""
echo -e "${YELLOW}To stop all services:${NC}"
echo -e " cd backend && $CONTAINER_CLI compose down"

View file

@ -1,7 +1,7 @@
#!/bin/bash
set -e
echo "🔄 Pulling latest backend changes..."
echo "🔄 Pulling latest changes..."
git pull origin main
echo "📦 Installing PHP dependencies..."
@ -15,4 +15,4 @@ php artisan config:cache
php artisan route:cache
php artisan view:cache
echo "✅ Backend update complete!"
echo "✅ Update complete!"

63
bootstrap/app.php Normal file
View file

@ -0,0 +1,63 @@
<?php
use App\Http\Middleware\ForceJsonResponse;
use App\Services\OutputService;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Apply ForceJsonResponse only to API routes
$middleware->api(ForceJsonResponse::class);
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
}
return $request->expectsJson();
});
/** @var OutputService $outputService */
$outputService = resolve(OutputService::class);
$exceptions->render(function (ValidationException $e, Request $request) use ($outputService) {
if ($request->is('api/*') || $request->expectsJson()) {
return response()->json(
$outputService->response(false, null, [$e->getMessage()]),
404
);
}
});
$exceptions->render(function (NotFoundHttpException $e, Request $request) use ($outputService) {
if ($request->is('api/*') || $request->expectsJson()) {
return response()->json(
$outputService->response(false, null, ['MODEL_NOT_FOUND']),
404
);
}
});
$exceptions->render(function (AccessDeniedHttpException $e, Request $request) use ($outputService) {
if ($request->is('api/*') || $request->expectsJson()) {
return response()->json(
$outputService->response(false, null, [$e->getMessage()]),
403
);
}
});
})
->create();

0
backend/bootstrap/cache/.gitignore → bootstrap/cache/.gitignore vendored Normal file → Executable file
View file

7
bootstrap/providers.php Normal file
View file

@ -0,0 +1,7 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];

View file

@ -7,20 +7,24 @@
"laravel",
"framework"
],
"license": "MIT",
"license": "AGPL-3.0-only",
"require": {
"php": "^8.2",
"laravel/framework": "^12.9.2",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.9"
"laravel/tinker": "^2.9",
"livewire/livewire": "^3.7"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"larastan/larastan": "^3.10",
"laravel/dusk": "^8.3",
"laravel/pail": "^1.1",
"laravel/pint": "^1.13",
"laravel/sail": "^1.26",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.1",
"phpstan/phpstan-mockery": "^2.0",
"phpunit/phpunit": "^11.0.1"
},
"autoload": {
@ -55,6 +59,17 @@
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite"
],
"test": [
"@php artisan test"
],
"test:coverage": [
"Composer\\Config::disableProcessTimeout",
"@php -d xdebug.mode=coverage artisan test --coverage"
],
"test:coverage-html": [
"Composer\\Config::disableProcessTimeout",
"@php -d xdebug.mode=coverage vendor/bin/phpunit --coverage-html coverage --coverage-text"
]
},
"extra": {

8923
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,7 @@
|
*/
'name' => env('APP_NAME', 'Laravel'),
'name' => env('APP_NAME', 'Dish Planner'),
/*
|--------------------------------------------------------------------------

View file

@ -1,5 +1,7 @@
<?php
use App\Models\Planner;
return [
/*
@ -50,7 +52,7 @@
'providers' => [
'planners' => [
'driver' => 'eloquent',
'model' => App\Models\Planner::class,
'model' => Planner::class,
],
// 'users' => [

186
config/livewire.php Normal file
View file

@ -0,0 +1,186 @@
<?php
return [
/*
|---------------------------------------------------------------------------
| Class Namespace
|---------------------------------------------------------------------------
|
| This value sets the root class namespace for Livewire component classes in
| your application. This value will change where component auto-discovery
| finds components. It's also referenced by the file creation commands.
|
*/
'class_namespace' => 'App\\Livewire',
/*
|---------------------------------------------------------------------------
| View Path
|---------------------------------------------------------------------------
|
| This value is used to specify where Livewire component Blade templates are
| stored when running file creation commands like `artisan make:livewire`.
| It is also used if you choose to omit a component's render() method.
|
*/
'view_path' => resource_path('views/livewire'),
/*
|---------------------------------------------------------------------------
| Layout
|---------------------------------------------------------------------------
| The view that will be used as the layout when rendering a single component
| as an entire page via `Route::get('/post/create', CreatePost::class);`.
| In this case, the view returned by CreatePost will render into $slot.
|
*/
'layout' => 'components.layouts.app',
/*
|---------------------------------------------------------------------------
| Lazy Loading Placeholder
|---------------------------------------------------------------------------
| Livewire allows you to lazy load components that would otherwise slow down
| the initial page load. Every component can have a custom placeholder or
| you can define the default placeholder view for all components below.
|
*/
'lazy_placeholder' => null,
/*
|---------------------------------------------------------------------------
| Temporary File Uploads
|---------------------------------------------------------------------------
|
| Livewire handles file uploads by storing uploads in a temporary directory
| before the file is stored permanently. All file uploads are directed to
| a global endpoint for temporary storage. You may configure this below:
|
*/
'temporary_file_upload' => [
'disk' => null, // Example: 'local', 's3' | Default: 'default'
'rules' => null, // Example: ['file', 'mimes:png,jpg'] | Default: ['required', 'file', 'max:12288'] (12MB)
'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp'
'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1'
'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs...
'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
'mov', 'avi', 'wmv', 'mp3', 'm4a',
'jpg', 'jpeg', 'mpga', 'webp', 'wma',
],
'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
],
/*
|---------------------------------------------------------------------------
| Render On Redirect
|---------------------------------------------------------------------------
|
| This value determines if Livewire will run a component's `render()` method
| after a redirect has been triggered using something like `redirect(...)`
| Setting this to true will render the view once more before redirecting
|
*/
'render_on_redirect' => false,
/*
|---------------------------------------------------------------------------
| Eloquent Model Binding
|---------------------------------------------------------------------------
|
| Previous versions of Livewire supported binding directly to eloquent model
| properties using wire:model by default. However, this behavior has been
| deemed too "magical" and has therefore been put under a feature flag.
|
*/
'legacy_model_binding' => false,
/*
|---------------------------------------------------------------------------
| Auto-inject Frontend Assets
|---------------------------------------------------------------------------
|
| By default, Livewire automatically injects its JavaScript and CSS into the
| <head> and <body> of pages containing Livewire components. By disabling
| this behavior, you need to use @livewireStyles and @livewireScripts.
|
*/
'inject_assets' => true,
/*
|---------------------------------------------------------------------------
| Navigate (SPA mode)
|---------------------------------------------------------------------------
|
| By adding `wire:navigate` to links in your Livewire application, Livewire
| will prevent the default link handling and instead request those pages
| via AJAX, creating an SPA-like effect. Configure this behavior here.
|
*/
'navigate' => [
'show_progress_bar' => true,
'progress_bar_color' => '#2299dd',
],
/*
|---------------------------------------------------------------------------
| HTML Morph Markers
|---------------------------------------------------------------------------
|
| Livewire intelligently "morphs" existing HTML into the newly rendered HTML
| after each update. To make this process more reliable, Livewire injects
| "markers" into the rendered Blade surrounding @if, @class & @foreach.
|
*/
'inject_morph_markers' => true,
/*
|---------------------------------------------------------------------------
| Smart Wire Keys
|---------------------------------------------------------------------------
|
| Livewire uses loops and keys used within loops to generate smart keys that
| are applied to nested components that don't have them. This makes using
| nested components more reliable by ensuring that they all have keys.
|
*/
'smart_wire_keys' => false,
/*
|---------------------------------------------------------------------------
| Pagination Theme
|---------------------------------------------------------------------------
|
| When enabling Livewire's pagination feature by using the `WithPagination`
| trait, Livewire will use Tailwind templates to render pagination views
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
|
*/
'pagination_theme' => 'tailwind',
/*
|---------------------------------------------------------------------------
| Release Token
|---------------------------------------------------------------------------
|
| This token is stored client-side and sent along with each request to check
| a users session to see if a new release has invalidated it. If there is
| a mismatch it will throw an error and prompt for a browser refresh.
|
*/
'release_token' => 'a',
];

View file

@ -1,5 +1,8 @@
<?php
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Laravel\Sanctum\Sanctum;
return [
@ -75,9 +78,9 @@
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => ValidateCsrfToken::class,
],
];

View file

@ -3,8 +3,8 @@
namespace Database\Factories;
use App\Models\Dish;
use App\Models\UserDish;
use App\Models\User;
use App\Models\UserDish;
use Illuminate\Database\Eloquent\Factories\Factory;
/**

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