28 Commits
Author SHA1 Message Date
Daniel-Garmig 3db7d0577a Generate Nightly Build - 202405132319
Publish_on_Tag / Build and Push (push) Successful in 14m14s
2024-05-13 23:19:31 +02:00
Daniel-Garmig ca160d1543 Fix setup endpoint -Setup conditions where invalid.
CI / Docker Lint (push) Successful in 30s
2024-05-13 23:18:35 +02:00
Daniel-Garmig 236cfe44e9 Generate Nightly Build - 202405132248
Publish_on_Tag / Build and Push (push) Successful in 14m25s
2024-05-13 22:47:54 +02:00
Daniel-Garmig 2fae2fb37f Setup - Create new setup endpoint to init DB and instance config.
CI / Docker Lint (push) Successful in 30s
2024-05-13 22:43:19 +02:00
Daniel-Garmig 901454df3c Docs - Add deploy docs. 2024-05-13 22:37:39 +02:00
Daniel-Garmig 4abe778657 Generate Nightly Build - 202405131843
Publish_on_Tag / Build and Push (push) Successful in 14m51s
2024-05-13 18:43:29 +02:00
Daniel-Garmig d6ad52c044 Update .gitea/workflows/pub-on-tag.yaml
CI / Docker Lint (push) Successful in 22s
Fix error on variable "repository_owner" being uppercase for docker image tag.
2024-05-13 18:40:37 +02:00
Daniel-Garmig 72a9f69799 Generate Nightly Build - 202405131822
Publish_on_Tag / Build and Push (push) Failing after 1m17s
2024-05-13 18:22:21 +02:00
Daniel-Garmig faea267b1f Add Gitea Actions Support.
CI / Docker Lint (push) Successful in 17s
2024-05-13 18:14:32 +02:00
Daniel-Garmig e8bfcd9c6b Room Availability - Edit + bulk edit 2024-05-11 00:45:35 +02:00
Daniel-Garmig ed4ba9d82f Booking Creation - Finish initial implement.
- Check and update availability.
- Set prices.
- Generate booking refNumber.
2024-05-10 21:31:24 +02:00
Daniel-Garmig 528d1a39ab Booking API - "api/booking/create"
- New endpoint to create bookings.
2024-05-08 23:29:19 +02:00
Daniel-Garmig 4f451c2f75 Bookings - Easyadmin support. 2024-05-08 20:38:03 +02:00
Daniel-Garmig 86abb7222e Bookings - Create model:
- Booking model.
- BookingCustomer model.
- BookingRoom
2024-05-08 20:02:18 +02:00
Daniel-Garmig 7b6d1408f8 API response adjustments. 2024-05-07 22:50:09 +02:00
Daniel-Garmig a4ec188cff Add nelmio/cors-bundle - Add CORS support for Front-end requests. 2024-05-04 01:44:22 +02:00
Daniel-Garmig 15a884fafa PriceService + XDEBUG.
- Arreglados problemas que impedian el funcionamiento de xdebug para hacer debug.
- Correción errores PriceService.
2024-05-01 20:21:14 +02:00
Daniel-Garmig 9c8759e24d FareTable y RoomFares
- Implementación modelo tarifarios y tarifas.
- Implementación inicial servicio precios.
2024-05-01 18:07:49 +02:00
Daniel-Garmig 7ec989a76a FareTables and RoomFares - Implementación inicial
Creación del modelo y pantallas base para administración.
2024-04-29 23:14:28 +02:00
Daniel-Garmig 8e7bad7771 RoomAvailability - Initial implementation 2024-04-28 03:19:19 +02:00
Daniel-Garmig 7a56158563 Config Variables - Model & Easyadmin. 2024-04-27 18:46:35 +02:00
Daniel-Garmig 84d9c81afd User management - Login and user password hash. 2024-04-26 21:37:39 +02:00
Daniel-Garmig 30773d7af4 Admin Panel - User management 2024-04-26 19:52:35 +02:00
Daniel-Garmig 34ecf58097 EasyAdmin - Implemetanción inicial.
Añadido menú para gestionar las Categorias.
2024-04-22 20:15:44 +02:00
Daniel-Garmig fcfe2f9250 New API - RoomCategory 2024-04-22 18:10:16 +02:00
Daniel-Garmig 2079188760 Added Doctrine ORM and dependencies. 2024-04-20 23:34:21 +02:00
Daniel-Garmig d826067e32 Basic proyect generation 2024-04-17 23:33:50 +02:00
Daniel-Garmig 29de33a83f Repo Init. 2024-04-17 23:20:02 +02:00
107 changed files with 11593 additions and 234 deletions
+34
View File
@@ -0,0 +1,34 @@
**/*.log
**/*.md
**/*.php~
**/*.dist.php
**/*.dist
**/*.cache
**/._*
**/.dockerignore
**/.DS_Store
**/.git/
**/.gitattributes
**/.gitignore
**/.gitmodules
**/compose.*.yaml
**/compose.*.yml
**/compose.yaml
**/compose.yml
**/docker-compose.*.yaml
**/docker-compose.*.yml
**/docker-compose.yaml
**/docker-compose.yml
**/Dockerfile
**/Thumbs.db
.github/
docs/
public/bundles/
tests/
var/
vendor/
.editorconfig
.env.*.local
.env.local
.env.local.php
.env.test
+58
View File
@@ -0,0 +1,58 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 4
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{js,html,ts,tsx}]
indent_size = 2
[*.json]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[*.sh]
indent_style = tab
[*.xml{,.dist}]
indent_style = space
indent_size = 4
[*.{yaml,yml}]
trim_trailing_whitespace = false
[.github/workflows/*.yml]
indent_size = 2
[.gitmodules]
indent_style = tab
[.php_cs{,.dist}]
indent_style = space
indent_size = 4
[composer.json]
indent_size = 4
[{,docker-}compose{,.*}.{yaml,yml}]
indent_style = space
indent_size = 2
[{,*.*}Dockerfile]
indent_style = tab
[{,*.*}Caddyfile]
indent_style = tab
+34
View File
@@ -0,0 +1,34 @@
# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
# * .env contains default values for the environment variables needed by the app
# * .env.local uncommitted file with local overrides
# * .env.$APP_ENV committed environment-specific defaults
# * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=d130654a5d6a8ab5945b20b22dfeee74
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://app:[email protected]:3306/app?serverVersion=8.0.32&charset=utf8mb4"
# DATABASE_URL="mysql://app:[email protected]:3306/app?serverVersion=10.11.2-MariaDB&charset=utf8mb4"
DATABASE_URL="postgresql://app:[email protected]:54195/app?serverVersion=16&charset=utf8"
###< doctrine/doctrine-bundle ###
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###
+17
View File
@@ -0,0 +1,17 @@
* text=auto eol=lf
*.conf text eol=lf
*.html text eol=lf
*.ini text eol=lf
*.js text eol=lf
*.json text eol=lf
*.md text eol=lf
*.php text eol=lf
*.sh text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
bin/console text eol=lf
composer.lock text eol=lf merge=ours
*.ico binary
*.png binary
+23
View File
@@ -0,0 +1,23 @@
name: CI
on:
push:
branches:
- main
pull_request: ~
workflow_dispatch: ~
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
lint:
name: Docker Lint
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Lint Dockerfile
uses: hadolint/[email protected]
+45
View File
@@ -0,0 +1,45 @@
name: Publish_on_Tag
on:
push:
tags:
- devbuild_*
workflow_dispatch: ~
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
name: Build and Push
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to local registry
uses: docker/login-action@v3
with:
registry: ${{vars.REGISTRY_INSTANCE}}
username: ${{gitea.repository_owner}}
password: ${{secrets.REGISTRY_TOKEN}} # It should be a user/org token with package perms.
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{vars.REGISTRY_INSTANCE}}/somnia/somniarooms:devbuild
target: frankenphp_prod
platforms: linux/amd64,linux/arm64
secrets: |
GIT_AUTH_TOKEN=${{secrets.REGISTRY_TOKEN}}
+10
View File
@@ -0,0 +1,10 @@
###> symfony/framework-bundle ###
/.env.local
/.env.local.php
/.env.*.local
/config/secrets/prod/prod.decrypt.private.php
/public/bundles/
/var/
/vendor/
###< symfony/framework-bundle ###
+51
View File
@@ -0,0 +1,51 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003,
"pathMappings": {
"/app" : "${workspaceFolder}"
}
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
},
{
"name": "Launch Built-in web server",
"type": "php",
"request": "launch",
"runtimeArgs": [
"-dxdebug.mode=debug",
"-dxdebug.start_with_request=yes",
"-S",
"localhost:0"
],
"program": "",
"cwd": "${workspaceRoot}",
"port": 9003,
"serverReadyAction": {
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
}
}
]
}
+94
View File
@@ -0,0 +1,94 @@
#syntax=docker/dockerfile:1.4
# Versions
FROM dunglas/frankenphp:1-php8.3 AS frankenphp_upstream
# The different stages of this Dockerfile are meant to be built into separate images
# https://docs.docker.com/develop/develop-images/multistage-build/#stop-at-a-specific-build-stage
# https://docs.docker.com/compose/compose-file/#target
# Base FrankenPHP image
FROM frankenphp_upstream AS frankenphp_base
WORKDIR /app
# persistent / runtime deps
# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
acl \
file \
gettext \
git \
&& rm -rf /var/lib/apt/lists/*
RUN set -eux; \
install-php-extensions \
@composer \
apcu \
intl \
opcache \
zip \
;
# https://getcomposer.org/doc/03-cli.md#composer-allow-superuser
ENV COMPOSER_ALLOW_SUPERUSER=1
###> recipes ###
###> doctrine/doctrine-bundle ###
RUN install-php-extensions pdo_pgsql
###< doctrine/doctrine-bundle ###
###< recipes ###
COPY --link frankenphp/conf.d/app.ini $PHP_INI_DIR/conf.d/
COPY --link --chmod=755 frankenphp/docker-entrypoint.sh /usr/local/bin/docker-entrypoint
COPY --link frankenphp/Caddyfile /etc/caddy/Caddyfile
ENTRYPOINT ["docker-entrypoint"]
HEALTHCHECK --start-period=60s CMD curl -f http://localhost:2019/metrics || exit 1
CMD [ "frankenphp", "run", "--config", "/etc/caddy/Caddyfile" ]
# Dev FrankenPHP image
FROM frankenphp_base AS frankenphp_dev
ENV APP_ENV=dev XDEBUG_MODE=off
VOLUME /app/var/
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
RUN set -eux; \
install-php-extensions \
xdebug \
;
COPY --link frankenphp/conf.d/app.dev.ini $PHP_INI_DIR/conf.d/
CMD [ "frankenphp", "run", "--config", "/etc/caddy/Caddyfile", "--watch" ]
# Prod FrankenPHP image
FROM frankenphp_base AS frankenphp_prod
ENV APP_ENV=prod
ENV FRANKENPHP_CONFIG="import worker.Caddyfile"
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY --link frankenphp/conf.d/app.prod.ini $PHP_INI_DIR/conf.d/
COPY --link frankenphp/worker.Caddyfile /etc/caddy/worker.Caddyfile
# prevent the reinstallation of vendors at every changes in the source code
COPY --link composer.* symfony.* ./
RUN set -eux; \
composer install --no-cache --prefer-dist --no-dev --no-autoloader --no-scripts --no-progress
# copy sources
COPY --link . ./
RUN rm -Rf frankenphp/
RUN set -eux; \
mkdir -p var/cache var/log; \
composer dump-autoload --classmap-authoritative --no-dev; \
composer dump-env prod; \
composer run-script --no-dev post-install-cmd; \
chmod +x bin/console; sync;
+19 -232
View File
@@ -1,232 +1,19 @@
GNU GENERAL PUBLIC LICENSE Copyright (c) Fabien Potencier
Version 3, 29 June 2007
Permission is hereby granted, free of charge, to any person obtaining a copy
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/> of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
Preamble to do so, subject to the following conditions:
The GNU General Public License is a free, copyleft license for software and other kinds of works. The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the 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 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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
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. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
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. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
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. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
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.
InstantRooms
Copyright (C) 2024 Daniel-Garmig
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:
InstantRooms Copyright (C) 2024 Daniel-Garmig
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/philosophy/why-not-lgpl.html>.
+38 -2
View File
@@ -1,3 +1,39 @@
# InstantRooms # SomniaRooms
Hotel Room booking system A Hotel Room booking system.
Powered by:
- PHP Symfony.
- Easyadmin.
## Commands:
Build containers:
```
docker compose build --no-cache
```
Start Containers:
```
docker compose up --pull always -d --wait
docker compose --env-file .\.env.local up -d --wait
```
Stop containers
```
docker compose down --remove-orphans
```
### Prod:
You can use docker compose for prod or build and deploy a prod image.
**Build Prod image**
```
docker build -t somniarooms:prod --target frankenphp_prod .
```
**Deploy prod image**
```
docker run -d -it -p 80:80 -p 443:443 --name somniarooms --env-file ./env.prod.local somniarooms:prod
```
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env php
<?php
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
if (!is_dir(dirname(__DIR__).'/vendor')) {
throw new LogicException('Dependencies are missing. Try running "composer install".');
}
if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) {
throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".');
}
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
$kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
return new Application($kernel);
};
+30
View File
@@ -0,0 +1,30 @@
# Development environment override
services:
php:
build:
context: .
target: frankenphp_dev
volumes:
- ./:/app
- ./frankenphp/Caddyfile:/etc/caddy/Caddyfile:ro
- ./frankenphp/conf.d/app.dev.ini:/usr/local/etc/php/conf.d/app.dev.ini:ro
# If you develop on Mac or Windows you can remove the vendor/ directory
# from the bind-mount for better performance by enabling the next line:
- /app/vendor
environment:
MERCURE_EXTRA_DIRECTIVES: demo
# See https://xdebug.org/docs/all_settings#mode
XDEBUG_MODE: "${XDEBUG_MODE:-off}"
extra_hosts:
# Ensure that host.docker.internal is correctly defined on Linux
- host.docker.internal:host-gateway
tty: true
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database:
ports:
- 54195:5432
###< doctrine/doctrine-bundle ###
+10
View File
@@ -0,0 +1,10 @@
# Production environment override
services:
php:
build:
context: .
target: frankenphp_prod
environment:
APP_SECRET: ${APP_SECRET}
MERCURE_PUBLISHER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET}
MERCURE_SUBSCRIBER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET}
+68
View File
@@ -0,0 +1,68 @@
services:
php:
image: ${IMAGES_PREFIX:-}app-php
restart: unless-stopped
environment:
SERVER_NAME: ${SERVER_NAME:-localhost}, php:80
MERCURE_PUBLISHER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
MERCURE_SUBSCRIBER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
TRUSTED_PROXIES: ${TRUSTED_PROXIES:-127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
TRUSTED_HOSTS: ^${SERVER_NAME:-example\.com|localhost}|php$$
# Run "composer require symfony/orm-pack" to install and configure Doctrine ORM
DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-!ChangeMe!}@database:5432/${POSTGRES_DB:-app}?serverVersion=${POSTGRES_VERSION:-15}&charset=${POSTGRES_CHARSET:-utf8}
# Run "composer require symfony/mercure-bundle" to install and configure the Mercure integration
MERCURE_URL: ${CADDY_MERCURE_URL:-http://php/.well-known/mercure}
MERCURE_PUBLIC_URL: https://${SERVER_NAME:-localhost}/.well-known/mercure
MERCURE_JWT_SECRET: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
# The two next lines can be removed after initial installation
SYMFONY_VERSION: ${SYMFONY_VERSION:-}
STABILITY: ${STABILITY:-stable}
volumes:
- caddy_data:/data
- caddy_config:/config
ports:
# HTTP
- target: 80
published: ${HTTP_PORT:-80}
protocol: tcp
# HTTPS
- target: 443
published: ${HTTPS_PORT:-443}
protocol: tcp
# HTTP/3
- target: 443
published: ${HTTP3_PORT:-443}
protocol: udp
# Mercure is installed as a Caddy module, prevent the Flex recipe from installing another service
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database:
image: postgres:${POSTGRES_VERSION:-16}-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB:-app}
# You should definitely change the password in production
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-!ChangeMe!}
POSTGRES_USER: ${POSTGRES_USER:-app}
healthcheck:
test: ["CMD", "pg_isready"]
timeout: 5s
retries: 5
start_period: 60s
volumes:
- database_data:/var/lib/postgresql/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
# - ./docker/db/data:/var/lib/postgresql/data:rw
###< doctrine/doctrine-bundle ###
volumes:
caddy_data:
caddy_config:
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database_data:
###< doctrine/doctrine-bundle ###
+88
View File
@@ -0,0 +1,88 @@
{
"name": "dgm/somnia-rooms",
"type": "project",
"license": "GPL-3.0",
"description": "A FOSS Hotel room booking system.",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.3.6",
"ext-ctype": "*",
"ext-iconv": "*",
"doctrine/dbal": "^3",
"doctrine/doctrine-bundle": "^2.12",
"doctrine/doctrine-migrations-bundle": "^3.3",
"doctrine/orm": "^3.1",
"easycorp/easyadmin-bundle": "^4.10",
"nelmio/cors-bundle": "^2.4",
"phpdocumentor/reflection-docblock": "^5.4",
"phpstan/phpdoc-parser": "^1.28",
"runtime/frankenphp-symfony": "^0.2.0",
"symfony/console": "7.0.*",
"symfony/dotenv": "7.0.*",
"symfony/flex": "^2",
"symfony/form": "7.0.*",
"symfony/framework-bundle": "7.0.*",
"symfony/property-access": "7.0.*",
"symfony/property-info": "7.0.*",
"symfony/runtime": "7.0.*",
"symfony/security-bundle": "7.0.*",
"symfony/serializer": "7.0.*",
"symfony/yaml": "7.0.*"
},
"config": {
"allow-plugins": {
"php-http/discovery": true,
"symfony/flex": true,
"symfony/runtime": true
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php73": "*",
"symfony/polyfill-php74": "*",
"symfony/polyfill-php80": "*",
"symfony/polyfill-php81": "*",
"symfony/polyfill-php82": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "7.0.*",
"docker": true
}
},
"require-dev": {
"symfony/maker-bundle": "^1.58",
"symfony/stopwatch": "7.0.*",
"symfony/web-profiler-bundle": "7.0.*"
}
}
Generated
+6473
View File
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
<?php
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle::class => ['all' => true],
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
];
+19
View File
@@ -0,0 +1,19 @@
framework:
cache:
# Unique name of your app: used to compute stable namespaces for cache keys.
#prefix_seed: your_vendor_name/app_name
# The "app" cache stores to the filesystem by default.
# The data in this cache should persist between deploys.
# Other options include:
# Redis
#app: cache.adapter.redis
#default_redis_provider: redis://localhost
# APCu (not recommended with heavy random-write workloads as memory fragmentation can cause perf issues)
#app: cache.adapter.apcu
# Namespaced pools use the above "app" backend by default
#pools:
#my.dedicated.cache: null
+52
View File
@@ -0,0 +1,52 @@
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
# IMPORTANT: You MUST configure your server version,
# either here or in the DATABASE_URL env var (see .env file)
#server_version: '16'
profiling_collect_backtrace: '%kernel.debug%'
use_savepoints: true
orm:
auto_generate_proxy_classes: true
enable_lazy_ghost_objects: true
report_fields_where_declared: true
validate_xml_mapping: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
mappings:
App:
type: attribute
is_bundle: false
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
controller_resolver:
auto_mapping: true
when@test:
doctrine:
dbal:
# "TEST_TOKEN" is typically set by ParaTest
dbname_suffix: '_test%env(default::TEST_TOKEN)%'
when@prod:
doctrine:
orm:
auto_generate_proxy_classes: false
proxy_dir: '%kernel.build_dir%/doctrine/orm/Proxies'
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool
framework:
cache:
pools:
doctrine.result_cache_pool:
adapter: cache.app
doctrine.system_cache_pool:
adapter: cache.system
+6
View File
@@ -0,0 +1,6 @@
doctrine_migrations:
migrations_paths:
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
'DoctrineMigrations': '%kernel.project_dir%/migrations'
enable_profiler: false
+16
View File
@@ -0,0 +1,16 @@
# see https://symfony.com/doc/current/reference/configuration/framework.html
framework:
secret: '%env(APP_SECRET)%'
#csrf_protection: true
# Note that the session will be started ONLY if you read or write from it.
session: true
#esi: true
#fragments: true
when@test:
framework:
test: true
session:
storage_factory_id: session.storage.factory.mock_file
+15
View File
@@ -0,0 +1,15 @@
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/api/':
allow_origin: ['*']
allow_headers: ['*']
allow_methods: ['POST', 'GET']
max_age: 3600
'^/': null
+10
View File
@@ -0,0 +1,10 @@
framework:
router:
# Configure how to generate URLs in non-HTTP contexts, such as CLI commands.
# See https://symfony.com/doc/current/routing.html#generating-urls-in-commands
#default_uri: http://localhost
when@prod:
framework:
router:
strict_requirements: null
+51
View File
@@ -0,0 +1,51 @@
security:
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
+7
View File
@@ -0,0 +1,7 @@
framework:
default_locale: en
translator:
default_path: '%kernel.project_dir%/translations'
fallbacks:
- en
providers:
+6
View File
@@ -0,0 +1,6 @@
twig:
file_name_pattern: '*.twig'
when@test:
twig:
strict_variables: true
+11
View File
@@ -0,0 +1,11 @@
framework:
validation:
# Enables validator auto-mapping support.
# For instance, basic validation constraints will be inferred from Doctrine's metadata.
#auto_mapping:
# App\Entity\: []
when@test:
framework:
validation:
not_compromised_password: false
+17
View File
@@ -0,0 +1,17 @@
when@dev:
web_profiler:
toolbar: true
intercept_redirects: false
framework:
profiler:
only_exceptions: false
collect_serializer_data: true
when@test:
web_profiler:
toolbar: false
intercept_redirects: false
framework:
profiler: { collect: false }
+5
View File
@@ -0,0 +1,5 @@
<?php
if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}
+5
View File
@@ -0,0 +1,5 @@
controllers:
resource:
path: ../src/Controller/
namespace: App\Controller
type: attribute
+4
View File
@@ -0,0 +1,4 @@
when@dev:
_errors:
resource: '@FrameworkBundle/Resources/config/routing/errors.xml'
prefix: /_error
+3
View File
@@ -0,0 +1,3 @@
_security_logout:
resource: security.route_loader.logout
type: service
+8
View File
@@ -0,0 +1,8 @@
when@dev:
web_profiler_wdt:
resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
prefix: /_wdt
web_profiler_profiler:
resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
prefix: /_profiler
+24
View File
@@ -0,0 +1,24 @@
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
+86
View File
@@ -0,0 +1,86 @@
# SomniaRooms - API Endpoints and Objects
En este documento se indican los endpoints disponibles en la API de SomniaRooms, así como los mensajes de petición y respuesta en cada caso. (Vamos, un Swagger pero escrito a mano.)
## Config (`api/config`)
Permite al cliente obtener las variables de configuración del sistema. Ver más sobre las [variables de configuración](config-vars.md) en la documentación.
**TODO**
## Room Category (`api/room/category`)
Estos endpoints permiten obtener la información de las categorias del sistema.
**TODO**
## Search (`api/search`)
Conjunto de Endpoints para consultar el estado de las habitaciones.
## Reservas (`api/booking`)
Endpoint para la gestión y consulta de las reservas.
### `api/booking/details`
Permite obtener el detalle de una reserva.
Es necesario enviar la información de la reserva a consultar.
**Request (JSON):**
```json
{
"refNumber": "2024001",
"email": "[email protected]"
}
```
Se debe incluir el número de referencia de la reserva y el correo electrónico asociado.
**Response (JSON):**
TODO
### `api/booking/create`
Endpoint para crear nuevas reservas.
Se enviarán los datos de la reserva con el siguiente formato:
**Request (JSON)_**
```json
{
"arrivalDate": "20240510",
"departureDate": "20240514",
"customerDetails": {
"name": "Juan",
"surname": "Perez",
"email": "[email protected]",
"phoneNumber": "12345678"
},
"rooms": [
{
"roomCategory": 1,
"guestNumber": 2,
"amount": 1
},
{
"roomCategory": 1,
"guestNumber": 3,
"amount": 1
}
]
}
```
Si la reserva es correcta se devolverá el número de referencia de la reserva:
```json
{
"refNumber": "2024001",
"email": "[email protected]",
}
```
+54
View File
@@ -0,0 +1,54 @@
# SomniaRooms - App Configuration Variables.
This document contains a list of all config variables of SomniaRooms. Variables are stored in DB (table _`config_variable`_) and can be configured from admin panel.
Variables are divided in sections. Some sections are ony accesible from SomniaRoom, but others can be retrieved by anyone using config endpoint (_`/config`_).
## List of sections:
WIP
TODO -> Add default table with basic information to all sections.
### **Company**
Variables in this section contains information about the Hotel.
- SectionName -> company
- Availability -> public
- Nº variables -> X
**Variable list:**
- Name - Name of hotel.
### **Price Management**
Configure how backend services calculates prices for bookings.
- SectionName -> price_mng
- Availability -> internal
- Nº variables -> X
**Variable list:**
WIP
#### FinalPriceCalculation.
Establece cómo se deben tratar los precios de cada día para generar el precio final de la estancia.
Algunos algoritmos para estos serán:
- Precio más alto.
- Precio más bajo.
- Suma de precios. --> Por defecto.
- Media de precios.
#### MultipleRoomFareValid
Estrategia de selección de tarifa en caso de que haya varias válidas (mientras no exista un sistema de prioridad de tarifas...)
Posibles algoritmos:
- Precio más alto.
- Precio más bajo.
- Media.
+198
View File
@@ -0,0 +1,198 @@
# SomniaRooms - How to deploy.
SomniaRooms is designed to be easy to deploy and use.
Production images for Docker Containers are available from Gitea Registry.
Documentation on how to deploy them as containers can be found at [Readme](../README.md).
## Docker compose examples.
Here are some deploy examples using docker compose:
SomniaRooms back-end and front-end can run on the same machine, but some config is needed to work.
### Deploy back-end and front-end on different servers (different ip address).
If your servers have different IP addresses everything is a little bit easier. You can set-up subdomains for each one.
Use the following docker compose files for back-end and front-end.
Back-end:
```yml
services:
somniarooms-back:
image: gitea.uberelectronnetwork.cc/somnia/somniarooms:devbuild
restart: unless-stopped
environment:
SERVER_NAME: https://api.somnia.dev # <-- Your hostname here!
DATABASE_URL: postgresql://somnia:ChangeMe!@database/somniarooms?serverVersion=16&ch> MERCURE_PUBLISHER_JWT_KEY: ChangeThisMercureHubJWTSecretKey!
MERCURE_SUBSCRIBER_JWT_KEY: ChangeThisMercureHubJWTSecretKey!
APP_SECRET: ChangeMySecret
FRANKENPHP_CONFIG: "" # <-- Dont touch this line unless you know what are doing.
volumes:
- caddy_data:/data
- caddy_config:/config
ports:
# HTTP
- target: 80
published: 80
protocol: tcp
# HTTPS
- target: 443
published: 443
protocol: tcp
# HTTP/3
- target: 443
published: 443
protocol: udp
depends_on:
- database
database:
image: postgres:16-alpine
environment:
POSTGRES_DB: somniarooms
# You should definitely change the password in production
POSTGRES_PASSWORD: ChangeMe!
POSTGRES_USER: somnia
healthcheck:
test: ["CMD", "pg_isready"]
timeout: 5s
retries: 5
start_period: 60s
volumes:
- database_data:/var/lib/postgresql/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to acciden> # - ./docker/db/data:/var/lib/postgresql/data:rw
volumes:
caddy_data:
caddy_config:
database_data:
```
Config details
- SERVER_NAME -> if set to https a SSL cert will be obtained. If you set http, SSL will be disabled. (Read more about this [here](https://caddyserver.com/docs/automatic-https))
Front-end:
```yml
services:
somniarooms-front:
image: gitea.uberelectronnetwork.cc/somnia/somniaroomsapp:devbuild
restart: unless-stopped
environment:
# You should set your public IP/hostname to back-end.
SOMNIAROOMS_BACKEND_HOST: https://api.somnia.dev # <-- Your back-end hostname here!
SOMNIAROOMS_BACKEND_PORT: 443 # <-- Your back-end port here! (443 if using https)
ports:
# HTTP
- target: 80
published: 80
# HTTPS
- target: 443
published: 443
```
### Deploy on the same server.
Right now, it's quite difficult to set back-end app on a port different from 80/443. Back-end uses Caddy as webserver and automatically try to get SSL certs from let's encrypt.
My go-to option will be using some reverse-proxy to redirect requests to back or front by domain name.
This is an example of deployment using Traefik.
```yml
services:
reverse-proxy:
# The official v3 Traefik docker image
image: traefik:v3.0
restart: unless-stopped
# Enables the web UI and tells Traefik to listen to docker
command:
- --api.insecure=true
- --providers.docker
- --entrypoints.web.address=:80
- --entrypoints.websecure.address=:443
- --entrypoints.web.http.redirections.entryPoint.to=websecure
- --entrypoints.web.http.redirections.entryPoint.scheme=https
- --certificatesresolvers.lets-encrypt.acme.tlschallenge=true
- --certificatesresolvers.lets-encrypt.acme.email=your_email # <-- Your email here!
- --certificatesresolvers.lets-encrypt.acme.storage=/letsencrypt/acme.json
ports:
# The HTTP port
- "80:80"
# The HTTPS port
- "443:443"
# The Web UI (enabled by --api.insecure=true)
- "8080:8080"
volumes:
# So that Traefik can listen to the Docker events
- /var/run/docker.sock:/var/run/docker.sock
# acme.json should be created on host instance
- .certs/:/letsencrypt/
somniarooms-back:
image: gitea.uberelectronnetwork.cc/somnia/somniarooms:devbuild
restart: unless-stopped
environment:
SERVER_NAME: https://api.somnia.dev # <-- Your hostname here!
DATABASE_URL: postgresql://somnia:ChangeMe!@database/somniarooms?serverVersion=16&charset=utf8
MERCURE_PUBLISHER_JWT_KEY: ChangeThisMercureHubJWTSecretKey!
MERCURE_SUBSCRIBER_JWT_KEY: ChangeThisMercureHubJWTSecretKey!
APP_SECRET: ChangeMySecret
FRANKENPHP_CONFIG: "" # <-- Dont touch this line unless you know what are doing.
volumes:
- caddy_data:/data
- caddy_config:/config
depends_on:
- database
labels:
# HTTPS YOUR APP
- "traefik.enable=true"
- "traefik.http.routers.somniarooms-back.rule=Host(`api.somnia.dev`)" # <-- Your back-end hostname here!
- "traefik.http.routers.somniarooms-back.entrypoints=websecure"
- "traefik.http.routers.somniarooms-back.tls=true"
- "traefik.http.routers.somniarooms-back.tls.certresolver=lets-encrypt"
somniarooms-front:
image: gitea.uberelectronnetwork.cc/somnia/somniaroomsapp:devbuild
restart: unless-stopped
environment:
# You should set your public IP/hostname to back-end.
SOMNIAROOMS_BACKEND_HOST: https://api.somnia.dev # <-- Your back-end hostname here!
SOMNIAROOMS_BACKEND_PORT: 443 # <-- Your back-end port here! (443 if using https)
depends_on:
- somniarooms-back
labels:
- "traefik.http.routers.somniarooms-front.rule=Host(`app.somnia.dev`)" # <-- Your front-end hostname here!
database:
image: postgres:16-alpine
environment:
POSTGRES_DB: somniarooms
# You should definitely change the password in production
POSTGRES_PASSWORD: ChangeMe!
POSTGRES_USER: somnia
healthcheck:
test: ["CMD", "pg_isready"]
timeout: 5s
retries: 5
start_period: 60s
volumes:
- database_data:/var/lib/postgresql/data:rw
# You may use a bind-mounted host directory instead, so that it is harder to acciden> # - ./docker/db/data:/var/lib/postgresql/data:rw
volumes:
caddy_data:
caddy_config:
database_data:
```
## What's next?
Remember you can run your docker compose files using:
```
docker compose up -d --wait
```
+55
View File
@@ -0,0 +1,55 @@
{
{$CADDY_GLOBAL_OPTIONS}
frankenphp {
{$FRANKENPHP_CONFIG}
}
# https://caddyserver.com/docs/caddyfile/directives#sorting-algorithm
order mercure after encode
order vulcain after reverse_proxy
order php_server before file_server
}
{$CADDY_EXTRA_CONFIG}
{$SERVER_NAME:localhost} {
log {
# Redact the authorization query parameter that can be set by Mercure
format filter {
wrap console
fields {
uri query {
replace authorization REDACTED
}
}
}
}
root * /app/public
encode zstd br gzip
mercure {
# Transport to use (default to Bolt)
transport_url {$MERCURE_TRANSPORT_URL:bolt:///data/mercure.db}
# Publisher JWT key
publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
# Subscriber JWT key
subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
# Allow anonymous subscribers (double-check that it's what you want)
anonymous
# Enable the subscription API (double-check that it's what you want)
subscriptions
# Extra directives
{$MERCURE_EXTRA_DIRECTIVES}
}
vulcain
{$CADDY_SERVER_EXTRA_DIRECTIVES}
# Disable Topics tracking if not enabled explicitly: https://github.com/jkarlin/topics
header ?Permissions-Policy "browsing-topics=()"
php_server
}
+10
View File
@@ -0,0 +1,10 @@
; See https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
; See https://github.com/docker/for-linux/issues/264
; The `client_host` below may optionally be replaced with `discover_client_host=yes`
; Add `start_with_request=yes` to start debug session on each request
xdebug.client_host=host.docker.internal
xdebug.start_with_request=yes
;xdebug.mode=debug
xdebug.discover_client_host=1
xdebug.idekey=docker
;xdebug.log=/dev/stdout
+13
View File
@@ -0,0 +1,13 @@
expose_php = 0
date.timezone = UTC
apc.enable_cli = 1
session.use_strict_mode = 1
zend.detect_unicode = 0
; https://symfony.com/doc/current/performance.html
realpath_cache_size = 4096K
realpath_cache_ttl = 600
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.memory_consumption = 256
opcache.enable_file_override = 1
+2
View File
@@ -0,0 +1,2 @@
opcache.preload_user = root
opcache.preload = /app/config/preload.php
+60
View File
@@ -0,0 +1,60 @@
#!/bin/sh
set -e
if [ "$1" = 'frankenphp' ] || [ "$1" = 'php' ] || [ "$1" = 'bin/console' ]; then
# Install the project the first time PHP is started
# After the installation, the following block can be deleted
if [ ! -f composer.json ]; then
rm -Rf tmp/
composer create-project "symfony/skeleton $SYMFONY_VERSION" tmp --stability="$STABILITY" --prefer-dist --no-progress --no-interaction --no-install
cd tmp
cp -Rp . ..
cd -
rm -Rf tmp/
composer require "php:>=$PHP_VERSION" runtime/frankenphp-symfony
composer config --json extra.symfony.docker 'true'
if grep -q ^DATABASE_URL= .env; then
echo "To finish the installation please press Ctrl+C to stop Docker Compose and run: docker compose up --build -d --wait"
sleep infinity
fi
fi
if [ -z "$(ls -A 'vendor/' 2>/dev/null)" ]; then
composer install --prefer-dist --no-progress --no-interaction
fi
if grep -q ^DATABASE_URL= .env; then
echo "Waiting for database to be ready..."
ATTEMPTS_LEFT_TO_REACH_DATABASE=60
until [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ] || DATABASE_ERROR=$(php bin/console dbal:run-sql -q "SELECT 1" 2>&1); do
if [ $? -eq 255 ]; then
# If the Doctrine command exits with 255, an unrecoverable error occurred
ATTEMPTS_LEFT_TO_REACH_DATABASE=0
break
fi
sleep 1
ATTEMPTS_LEFT_TO_REACH_DATABASE=$((ATTEMPTS_LEFT_TO_REACH_DATABASE - 1))
echo "Still waiting for database to be ready... Or maybe the database is not reachable. $ATTEMPTS_LEFT_TO_REACH_DATABASE attempts left."
done
if [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ]; then
echo "The database is not up or not reachable:"
echo "$DATABASE_ERROR"
exit 1
else
echo "The database is now ready and reachable"
fi
if [ "$( find ./migrations -iname '*.php' -print -quit )" ]; then
php bin/console doctrine:migrations:migrate --no-interaction
fi
fi
setfacl -R -m u:www-data:rwX -m u:"$(whoami)":rwX var
setfacl -dR -m u:www-data:rwX -m u:"$(whoami)":rwX var
fi
exec docker-php-entrypoint "$@"
+4
View File
@@ -0,0 +1,4 @@
worker {
file ./public/index.php
env APP_RUNTIME Runtime\FrankenPhpSymfony\Runtime
}
View File
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240420232815 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE room_category_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE room_category_details_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE room_category_photo_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE room_category (id INT NOT NULL, name VARCHAR(64) NOT NULL, description TEXT DEFAULT NULL, bed_type VARCHAR(64) DEFAULT NULL, max_guest_num INT NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE TABLE room_category_details (id INT NOT NULL, room_category_id INT NOT NULL, details_section VARCHAR(255) NOT NULL, detail_value VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_3735FABB67333DD ON room_category_details (room_category_id)');
$this->addSql('CREATE TABLE room_category_photo (id INT NOT NULL, room_category_id INT NOT NULL, path VARCHAR(255) NOT NULL, alt_text VARCHAR(255) DEFAULT NULL, kind VARCHAR(30) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_B5843CAC67333DD ON room_category_photo (room_category_id)');
$this->addSql('ALTER TABLE room_category_details ADD CONSTRAINT FK_3735FABB67333DD FOREIGN KEY (room_category_id) REFERENCES room_category (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE room_category_photo ADD CONSTRAINT FK_B5843CAC67333DD FOREIGN KEY (room_category_id) REFERENCES room_category (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE room_category_id_seq CASCADE');
$this->addSql('DROP SEQUENCE room_category_details_id_seq CASCADE');
$this->addSql('DROP SEQUENCE room_category_photo_id_seq CASCADE');
$this->addSql('ALTER TABLE room_category_details DROP CONSTRAINT FK_3735FABB67333DD');
$this->addSql('ALTER TABLE room_category_photo DROP CONSTRAINT FK_B5843CAC67333DD');
$this->addSql('DROP TABLE room_category');
$this->addSql('DROP TABLE room_category_details');
$this->addSql('DROP TABLE room_category_photo');
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240422163212 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, username VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_USERNAME ON "user" (username)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
$this->addSql('DROP TABLE "user"');
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240427153125 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE config_variable_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE config_variable (id INT NOT NULL, key VARCHAR(32) NOT NULL, value VARCHAR(255) NOT NULL, section VARCHAR(64) DEFAULT NULL, PRIMARY KEY(id))');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE config_variable_id_seq CASCADE');
$this->addSql('DROP TABLE config_variable');
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240427171934 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE room_availability (day DATE NOT NULL, room_category_id INT NOT NULL, num_available INT NOT NULL, PRIMARY KEY(day, room_category_id))');
$this->addSql('CREATE INDEX IDX_89C5BA2C67333DD ON room_availability (room_category_id)');
$this->addSql('ALTER TABLE room_availability ADD CONSTRAINT FK_89C5BA2C67333DD FOREIGN KEY (room_category_id) REFERENCES room_category (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE UNIQUE INDEX UNIQ_718569538A90ABA9 ON config_variable (key)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE room_availability DROP CONSTRAINT FK_89C5BA2C67333DD');
$this->addSql('DROP TABLE room_availability');
$this->addSql('DROP INDEX UNIQ_718569538A90ABA9');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240429200025 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE fare_table_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE room_fare_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE fare_table (id INT NOT NULL, room_category_id INT NOT NULL, start_date TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, end_date TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, comment VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_8E43BE7067333DD ON fare_table (room_category_id)');
$this->addSql('CREATE TABLE room_fare (id INT NOT NULL, fare_table_id INT NOT NULL, guest_number INT NOT NULL, fare_amount INT NOT NULL, day_type VARCHAR(2) DEFAULT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_35C9B213A7233EF2 ON room_fare (fare_table_id)');
$this->addSql('ALTER TABLE fare_table ADD CONSTRAINT FK_8E43BE7067333DD FOREIGN KEY (room_category_id) REFERENCES room_category (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE room_fare ADD CONSTRAINT FK_35C9B213A7233EF2 FOREIGN KEY (fare_table_id) REFERENCES fare_table (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE room_availability ALTER day TYPE VARCHAR(255)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE fare_table_id_seq CASCADE');
$this->addSql('DROP SEQUENCE room_fare_id_seq CASCADE');
$this->addSql('ALTER TABLE fare_table DROP CONSTRAINT FK_8E43BE7067333DD');
$this->addSql('ALTER TABLE room_fare DROP CONSTRAINT FK_35C9B213A7233EF2');
$this->addSql('DROP TABLE fare_table');
$this->addSql('DROP TABLE room_fare');
$this->addSql('ALTER TABLE room_availability ALTER day TYPE DATE');
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240508180113 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE booking_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE booking_customer_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE booking_room_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE booking (id INT NOT NULL, arrival_date DATE NOT NULL, departure_date DATE NOT NULL, booking_time TIMESTAMP(0) WITH TIME ZONE NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE TABLE booking_customer (id INT NOT NULL, booking_id INT NOT NULL, name VARCHAR(64) NOT NULL, surname VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, phone_number VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE UNIQUE INDEX UNIQ_BA0D10843301C60 ON booking_customer (booking_id)');
$this->addSql('CREATE TABLE booking_room (id INT NOT NULL, booking_id INT NOT NULL, room_category_id INT NOT NULL, guest_number INT NOT NULL, room_price INT NOT NULL, amount INT NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_6A0E73D53301C60 ON booking_room (booking_id)');
$this->addSql('CREATE INDEX IDX_6A0E73D567333DD ON booking_room (room_category_id)');
$this->addSql('ALTER TABLE booking_customer ADD CONSTRAINT FK_BA0D10843301C60 FOREIGN KEY (booking_id) REFERENCES booking (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE booking_room ADD CONSTRAINT FK_6A0E73D53301C60 FOREIGN KEY (booking_id) REFERENCES booking (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE booking_room ADD CONSTRAINT FK_6A0E73D567333DD FOREIGN KEY (room_category_id) REFERENCES room_category (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE booking_id_seq CASCADE');
$this->addSql('DROP SEQUENCE booking_customer_id_seq CASCADE');
$this->addSql('DROP SEQUENCE booking_room_id_seq CASCADE');
$this->addSql('ALTER TABLE booking_customer DROP CONSTRAINT FK_BA0D10843301C60');
$this->addSql('ALTER TABLE booking_room DROP CONSTRAINT FK_6A0E73D53301C60');
$this->addSql('ALTER TABLE booking_room DROP CONSTRAINT FK_6A0E73D567333DD');
$this->addSql('DROP TABLE booking');
$this->addSql('DROP TABLE booking_customer');
$this->addSql('DROP TABLE booking_room');
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240508180617 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE booking ADD ref_number VARCHAR(20) NOT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE booking DROP ref_number');
}
}
View File
+9
View File
@@ -0,0 +1,9 @@
<?php
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Controller\Admin;
use App\Controller\Admin\BookingCustomerCrudController;
use App\Entity\Booking;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
class BookingCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Booking::class;
}
public function configureFields(string $pageName): iterable
{
$fieldRefNumber = TextField::new ('refNumber');
$fieldBookingTime = DateTimeField::new ('BookingTime');
if ($pageName == Crud::PAGE_EDIT) {
$fieldRefNumber->setDisabled(true);
$fieldBookingTime->setDisabled(true);
}
yield FormField::addFieldset('Booking details');
yield $fieldRefNumber;
yield $fieldBookingTime;
yield DateField::new ('ArrivalDate');
yield DateField::new ('DepartureDate');
yield AssociationField::new ('bookingCustomer')->renderAsEmbeddedForm(BookingCustomerCrudController::class);
yield CollectionField::new ('bookingRooms')->useEntryCrudForm();
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Controller\Admin;
use App\Entity\BookingCustomer;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
class BookingCustomerCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return BookingCustomer::class;
}
public function configureFields(string $pageName): iterable
{
yield TextField::new('Name');
yield TextField::new('Surname');
yield TextField::new('Email');
yield TextField::new('PhoneNumber');
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Controller\Admin;
use App\Controller\Admin\RoomCategoryCrudController;
use App\Entity\BookingRoom;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
class BookingRoomCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return BookingRoom::class;
}
public function configureFields(string $pageName): iterable
{
yield AssociationField::new ('RoomCategory')->setCrudController(RoomCategoryCrudController::class);
yield NumberField::new ('GuestNumber');
yield MoneyField::new ('RoomPrice')->setCurrency("EUR");
yield NumberField::new ('Amount');
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Controller\Admin;
use App\Entity\ConfigVariable;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
class ConfigVariableCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return ConfigVariable::class;
}
public function configureFields(string $pageName): iterable
{
yield TextField::new('section');
yield TextField::new('key');
yield TextField::new('value');
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Controller\Admin;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\{AssociationField, TextField, DateField};
use App\Entity\FareTable;
use App\Entity\RoomCategory;
use App\Controller\Admin\RoomCategoryCrudController;
class FareTableCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return FareTable::class;
}
public function configureFields(string $pageName): iterable
{
//$catRepo = $this->entityManager->getRepository(SomeEntity::class);
yield TextField::new('comment')->setLabel('Name');
yield AssociationField::new('roomCategory');
yield DateField::new('startDate');
yield DateField::new('endDate');
}
}
@@ -0,0 +1,147 @@
<?php
namespace App\Controller\Admin;
use App\Entity\RoomAvailability;
use App\Entity\RoomCategory;
use App\Repository\RoomAvailabilityRepository;
use App\Repository\RoomCategoryRepository;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted("ROLE_ADMIN")]
class RoomAvailabilityAdminController extends AbstractController
{
private $adminUrlGenerator;
private EntityManagerInterface $entityManager;
public function __construct(AdminUrlGenerator $adminUrlGenerator, EntityManagerInterface $em)
{
$this->adminUrlGenerator = $adminUrlGenerator;
$this->entityManager = $em;
}
#[Route('/admin/roomAvailability', name: 'admin_roomAvailability')]
public function index(RoomAvailabilityRepository $repo, RoomCategoryRepository $catRepo): Response
{
$categoryList = $catRepo->findAll();
return $this->render('admin/room_availability/index.html.twig', [
'roomCategoryList' => $categoryList,
]);
}
// List RoomAvailability items from category.
#[Route('/admin/roomAvailability/{categoryId}', name: 'admin_roomAvailability_category')]
public function categoryAvailability(RoomAvailabilityRepository $repo, RoomCategoryRepository $catRepo, string $categoryId): Response
{
$category = $catRepo->find($categoryId);
$availabilityList = $repo->findByRoomCategory($categoryId);
return $this->render('admin/room_availability/category_view.html.twig', [
'categoryData' => $category,
'availabilityList' => $availabilityList,
]);
}
// Edit a RoomAvailability numAvailable.
#[Route('/admin/roomAvailability/edit/{categoryId}/{day}', name: 'admin_roomAvailability_category_update')]
public function updateCategoryAvailability(Request $request, RoomAvailabilityRepository $repo, string $categoryId, string $day): Response
{
$availabilityItem = $repo->find(["day" => $day, "roomCategory" => $categoryId]);
if ($availabilityItem == null) {
//TODOME: Aquí deberíamos llevar a una página de error o algo.
$url = $this->adminUrlGenerator->setRoute('admin_roomAvailability_category', [
'categoryId' => $item->getId(),
])->generateUrl();
return $this->redirect($url);
}
$form = $this->createFormBuilder($availabilityItem)
->add('numAvailable', NumberType::class, ['label' => 'Num Available'])
->add('save', SubmitType::class, ['label' => 'Update value'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
// but, the original `$availabilityItem` variable has also been updated
$this->entityManager->flush();
$url = $this->adminUrlGenerator->setRoute('admin_roomAvailability_category', [
'categoryId' => $categoryId,
])->generateUrl();
return $this->redirect($url);
}
return $this->render('admin/room_availability/availability_day_edit.html.twig', [
'form' => $form,
'availabilityData' => $availabilityItem,
]);
}
// Bulk edit all roomAvailability of a category on period.
#[Route('/admin/roomAvailability/{categoryId}/bulkedit', name: 'admin_roomAvailability_category_bulkupdate')]
public function bulkUpdateCategoryAvailability(Request $request, RoomAvailabilityRepository $repo, string $categoryId): Response
{
$form = $this->createFormBuilder()
->add('startDate', DateType::class, [
'widget' => 'single_text',
])
->add('endDate', DateType::class, [
'widget' => 'single_text',
])
->add('numAvailable', NumberType::class, [
'label' => 'Num Available',
])
->add('save', SubmitType::class, ['label' => 'Update value'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
$data = $form->getData();
$categoryItem = $this->entityManager->find(RoomCategory::class, $categoryId);
$repo->bulkEditRoomAvailabilityForCategoryOnPeriod($categoryItem, $data['startDate'], $data['endDate'], $data['numAvailable']);
$url = $this->adminUrlGenerator->setRoute('admin_roomAvailability')->generateUrl();
return $this->redirect($url);
}
return $this->render('admin/room_availability/availability_bulk_edit.html.twig', [
'form' => $form,
'categoryId' => $categoryId,
]);
}
#[Route('/admin/roomAvailabilityTEST/', name: 'admin_roomAvailability_test')]
public function availabilityTest(EntityManagerInterface $entityManager): Response
{
$avl = new RoomAvailability();
$avl->setDay(new \DateTime("2024-04-24"));
$avl->setRoomCategory($entityManager->find(RoomCategory::class, 4));
$avl->setNumAvailable(2);
$entityManager->persist($avl);
$entityManager->flush();
return $this->json($avl);
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Controller\Admin;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use App\Entity\RoomCategory;
class RoomCategoryCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return RoomCategory::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud;
}
public function configureFields(string $pageName): iterable
{
return [
//IdField::new('id'),
TextField::new('name'),
TextField::new('description'),
TextField::new('bedType'),
IntegerField::new('maxGuestNum'),
CollectionField::new('roomCategoryDetails')->useEntryCrudForm(),
CollectionField::new('roomCategoryPhotos')->useEntryCrudForm()
];
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Controller\Admin;
use App\Entity\RoomCategoryDetails;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
class RoomCategoryDetailsCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return RoomCategoryDetails::class;
}
public function configureFields(string $pageName): iterable
{
return [
TextField::new('detailsSection'),
TextField::new('detailValue'),
];
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Controller\Admin;
use App\Entity\RoomCategoryPhoto;
use App\Entity\RoomCategoryPhotoKinds;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\{TextField, ChoiceField};
class RoomCategoryPhotoCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return RoomCategoryPhoto::class;
}
public function configureFields(string $pageName): iterable
{
yield TextField::new('path');
yield TextField::new('altText');
yield ChoiceField::new('kind')->setChoices(['Main' => 'main', 'Bathroom' => 'bathroom', 'Other' => 'other']);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Controller\Admin;
use App\Entity\RoomFare;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
class RoomFareCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return RoomFare::class;
}
public function configureFields(string $pageName): iterable
{
$fieldFareTable = AssociationField::new ('fareTable')->setRequired(true);
if ($pageName == Crud::PAGE_EDIT) {
$fieldFareTable->setDisabled(true);
}
yield $fieldFareTable;
yield NumberField::new ('guestNumber');
yield MoneyField::new ('fareAmount')->setCurrency('EUR');
$dayTypeList = ["MONDAY" => 1, "TUESDAY" => 2, "WEDNESDAY" => 3, "THURSDAY" => 4, "FRIDAY" => 5, "SATURDAY" => 6, "SUNDAY" => 0];
yield ChoiceField::new('dayType')->setChoices($dayTypeList);
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Controller\Admin;
use App\Entity\Booking;
use App\Entity\ConfigVariable;
use App\Entity\FareTable;
use App\Entity\RoomCategory;
use App\Entity\RoomFare;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class SomniaDashboardController extends AbstractDashboardController
{
#[Route('/admin', name: 'admin')]
public function index(): Response
{
return $this->render('admin/somniaDashboard.html.twig');
}
public function configureDashboard(): Dashboard
{
return Dashboard::new ()
->setTitle('SomniaRooms');
}
public function configureMenuItems(): iterable
{
yield MenuItem::linkToDashboard('Dashboard', 'fa fa-home');
yield MenuItem::Section('Booking Management');
yield MenuItem::linkToCrud('Bookings', 'fas fa-book', Booking::class);
yield MenuItem::Section('Room Management');
yield MenuItem::linkToCrud('Category', 'fas fa-layer-group', RoomCategory::class);
yield MenuItem::linkToRoute('Room Availability', 'fas fa-calendar-check', 'admin_roomAvailability');
yield MenuItem::linkToCrud('Fare Tables', 'fas fa-table', FareTable::class);
yield MenuItem::linkToCrud('Room Fares', 'fas fa-tag', RoomFare::class);
yield MenuItem::Section('App Management');
yield MenuItem::linkToCrud('Config Vars', 'fas fa-gear', ConfigVariable::class);
yield MenuItem::linkToCrud('Users', 'fas fa-user', User::class)
->setPermission("ROLE_SUPERADMIN");
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Controller\Admin;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserCrudController extends AbstractCrudController
{
public function __construct(
public UserPasswordHasherInterface $userPasswordHasher
) {}
public static function getEntityFqcn(): string
{
return User::class;
}
public function configureFields(string $pageName): iterable
{
yield TextField::new ('username');
yield TextField::new ('username')->onlyWhenUpdating()->setDisabled(true);
$availableRoles = ['User' => 'ROLE_USER', 'Admin' => 'ROLE_ADMIN', 'Test' => 'ROLE_TEST', 'SuperAdmin' => 'ROLE_SUPERADMIN'];
yield ChoiceField::new ('roles')
->setChoices($availableRoles)
->allowMultipleChoices(true);
yield FormField::addPanel('Set password')->setIcon('fa fa-key');
$fieldPassword = Field::new ('plainPassword', 'New password')
->hideOnIndex()
->setRequired(false)
->setFormType(RepeatedType::class)
->setFormTypeOptions([
'type' => PasswordType::class,
'first_options' => ['label' => 'New password'],
'second_options' => ['label' => 'Repeat password'],
'error_bubbling' => true,
'invalid_message' => 'The password fields do not match.',
]);
if($pageName == Crud::PAGE_NEW) {
$fieldPassword->setRequired(true);
}
yield $fieldPassword;
}
/**
* @param User $entityInstance
*/
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
//Hash password on creation.
$plaintextPassword = $entityInstance->getPlainPassword();
$hashedPassword = $this->userPasswordHasher->hashPassword($entityInstance, $plaintextPassword);
$entityInstance->setPassword($hashedPassword);
parent::updateEntity($entityManager, $entityInstance);
}
/**
* @param User $entityInstance
*/
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$plaintextPassword = $entityInstance->getPlainPassword();
if($plaintextPassword && $plaintextPassword != "") {
//New password set. Hash password.
$hashedPassword = $this->userPasswordHasher->hashPassword($entityInstance, $plaintextPassword);
$entityInstance->setPassword($hashedPassword);
}
parent::updateEntity($entityManager, $entityInstance);
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
namespace App\Controller;
use App\Entity\Booking;
use App\Entity\BookingCustomer;
use App\Entity\BookingRoom;
use App\Repository\BookingRepository;
use App\Repository\RoomCategoryRepository;
use App\Repository\RoomAvailabilityRepository;
use App\Service\PricesService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Attribute\Route;
class BookingController extends AbstractController
{
#[Route('/api/booking/details', name: 'app_booking_details')]
public function getBookingDetails(Request $request, BookingRepository $repoBooking): JsonResponse
{
$payload = $request->toArray();
if (\is_null($payload)) {
throw new \Exception('Invalid Payload', 400);
}
$refNumber = $payload["refNumber"];
$customerEmail = $payload["email"];
$bookingList = $repoBooking->findBy(["refNumber" => $refNumber]);
if (\is_null($bookingList) || \count($bookingList) == 0) {
throw new HttpException(404, 'Invalid Booking');
}
$customerBooking = $bookingList[0];
if ($customerBooking->getBookingCustomer()->getEmail() != $customerEmail) {
throw new HttpException(404, 'Invalid Booking');
}
return $this->json($customerBooking);
}
#[Route('/api/booking/create', name: 'app_booking_create')]
public function newBooking(Request $request, BookingRepository $repoBooking, EntityManagerInterface $entityManager,
RoomCategoryRepository $repoCat, RoomAvailabilityRepository $repoAvailability,
PricesService $priceSrv): JsonResponse
{
$payload = $request->toArray();
if (\is_null($payload)) {
throw new \Exception('Invalid Payload', 400);
}
$booking = new Booking();
try {
$reqArrivalDate = $payload["arrivalDate"];
$reqDepartureDate = $payload["departureDate"];
$arrivalDate = new \DateTime($reqArrivalDate);
$departureDate = new \DateTime($reqDepartureDate);
if ($arrivalDate >= $departureDate) {
throw new HttpException(400, "Arrival cant be before departure");
}
$entityManager->beginTransaction();
$currentTime = new \DateTime();
// Create booking from request data.
$booking->setBookingTime($currentTime);
$booking->setArrivalDate($arrivalDate);
$booking->setDepartureDate($departureDate);
$highest_id = $entityManager->createQueryBuilder()
->select('MAX(e.id)')
->from('App\Entity\Booking', 'e')
->getQuery()
->getSingleScalarResult();
$booking->setRefNumber($currentTime->format("Y") . $highest_id + 1);
$entityManager->persist($booking);
// Create booking customer.
$reqCustomer = $payload["customerDetails"];
$bookingCustomer = new BookingCustomer();
$bookingCustomer->setName($reqCustomer["name"]);
$bookingCustomer->setSurname($reqCustomer["surname"]);
$bookingCustomer->setEmail($reqCustomer["email"]);
$bookingCustomer->setPhoneNumber($reqCustomer["phoneNumber"]);
$bookingCustomer->setBooking($booking);
$entityManager->persist($bookingCustomer);
$reqRoomList = $payload["rooms"];
if (\count($reqRoomList) == 0) {
throw new HttpException(400, "Se debe indicar al menos una habitación");
}
// Create each room.
foreach ($reqRoomList as $roomItem) {
$room = new BookingRoom();
$room->setBooking($booking);
//Get Room category.
$roomCategory = $repoCat->find($roomItem["roomCategory"]);
if ($roomCategory == null) {
throw new HttpException(400, "La RoomCategory no es válida.");
}
//Check room availability.
$amountAvailable = $repoAvailability->getAvailabilityForCategoryInPeriod($roomCategory, $arrivalDate, $departureDate);
$selectedAmount = $roomItem['amount'];
$selectedGuestAmount = $roomItem["guestNumber"];
if($amountAvailable == null || $selectedAmount > $amountAvailable) {
throw new HttpException(400, "No se pueden reservar más habitaciones de las disponibles.");
}
$room->setRoomCategory($roomCategory);
$room->setGuestNumber($selectedGuestAmount);
$room->setAmount($selectedAmount);
//Get Price for period.
$priceList = $priceSrv->getFinalPricesForSearch($roomCategory, $arrivalDate, $departureDate);
$priceFound = false;
foreach ($priceList as $key => $value) {
if($key == $selectedGuestAmount) {
$room->setRoomPrice($value);
$priceFound = true;
break;
}
}
if(!$priceFound) {
throw new HttpException(500,
"No se puedo obtener el precio para la categoría: " . $roommCategory->getId() . " , guests: " . $selecctedGuestAmount);
}
$entityManager->persist($room);
//If booking is nice, let's update current availability.
$repoAvailability->updateAvailabilityForRoomCategoryOnPeriod($roomCategory, $arrivalDate, $departureDate, $selectedAmount, true); //Update using "diff" mode.
}
$entityManager->commit();
$entityManager->flush();
} catch (\Throwable $th) {
$entityManager->rollback();
throw $th;
}
$results = ["refNumber" => $booking->getRefNumber()];
return $this->json($results);
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use App\Repository\ConfigVariableRepository;
class ConfigVariableController extends AbstractController
{
#[Route('/api/config', name: 'app_config_variable')]
public function getAllVariables(ConfigVariableRepository $repo): Response
{
$varList = $repo->findAllVariables();
return $this->json(['results' => $varList]);
}
#[Route('/api/config/section', name: 'app_config_sections')]
public function getSections(ConfigVariableRepository $repo): Response
{
$sectionList = $repo->getAllSections();
$returnList = [];
foreach ($sectionList as $section) {
$sectionValue = $section["section"];
$returnList[] = $sectionValue;
}
return $this->json(['results' => $returnList]);
}
#[Route('/api/config/section/{section}', name: 'app_config_variableBySection')]
public function getVariablesBySection(ConfigVariableRepository $repo, string $section): Response
{
if(\is_null($section) || $section == '') {
return new Response("Invalid section value", 404);
}
$varList = $repo->findAllBySection($section);
return $this->json(['results' => $varList]);
}
#[Route('/api/config/var/{key}', name: 'app_config_variable')]
public function getByKey(ConfigVariableRepository $repo, string $key): Response
{
$var = $repo->findVariableByKey($key);
return $this->json($var);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\RoomCategoryRepository;
use App\Entity\RoomCategory;
use App\Entity\RoomCategoryDetails;
use App\Entity\RoomCategoryPhoto;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;
class RoomCategoryController extends AbstractController
{
#[Route('/api/room/category', name: 'app_room_AllCategories')]
public function getAll(RoomCategoryRepository $catRepo): Response
{
$catList = $catRepo->findAll();
return $this->json(["results" => $catList]);
}
#[Route('/api/room/category/{id}', name: 'app_room_category')]
public function getById(RoomCategory $category): Response
{
return $this->json($category);
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace App\Controller;
use App\Repository\FareTableRepository;
use App\Repository\RoomAvailabilityRepository;
use App\Repository\RoomCategoryRepository;
use App\Service\PricesService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class SearchRoomsController extends AbstractController
{
#[Route('/api/search/availability', name: 'app_search_availability')]
public function getAvailabilityForPeriod(Request $request, RoomAvailabilityRepository $repoAvailability): Response
{
$payload = $request->toArray();
if (\is_null($payload)) {
throw new \Exception('Invalid Payload', 400);
}
$filter = $payload["filter"];
$startDate = new \DateTime($filter["startDate"]);
$endDate = new \DateTime($filter["endDate"]);
$rs = $repoAvailability->getAvailabilityForPeriod($startDate, $endDate);
return $this->json(["results" => $rs]);
}
#[Route('/api/search/availabilityDetails', name: 'app_search_availabilityDetails')]
public function getAvailabilityForPeriodDetails(Request $request, RoomAvailabilityRepository $repoAvailability): Response
{
$payload = $request->toArray();
if (\is_null($payload)) {
throw new \Exception('Invalid Payload', 400);
}
$filter = $payload["filter"];
$startDate = new \DateTime($filter["startDate"]);
$endDate = new \DateTime($filter["endDate"]);
$rs = $repoAvailability->getAvailabilityForPeriodDetails($startDate, $endDate);
return $this->json($rs);
}
#[Route('/api/search/fares', name: 'app_search_faresForCategory')]
public function getFaresForCategoryOnPeriod(Request $request, RoomCategoryRepository $repoCat, PricesService $priceService): Response
{
$payload = $request->toArray();
if (\is_null($payload)) {
throw new \Exception('Invalid Payload', 400);
}
$filter = $payload["filter"];
$catId = $filter["roomCategory"];
$roomCategory = $repoCat->find($catId);
if ($roomCategory === null) {
throw new \Exception('Invalid Category', 400);
}
$startDate = new \DateTime($filter["startDate"]);
$endDate = new \DateTime($filter["endDate"]);
$daysDiff = $startDate->diff($endDate)->days;
if (!$daysDiff || $startDate > $endDate) {
throw new \Exception('Invalid time interval', 400);
}
$fareList = $priceService->getFinalPricesForSearch($roomCategory, $startDate, $endDate);
$rs = [];
foreach ($fareList as $key => $value) {
$rs[] = [ "guestNumber" => $key, "price" => $value];
}
return $this->json(["results" => $rs]);
}
#[Route('/search/debug', name: 'app_search_faresDebug')]
public function faresDebug(Request $request, PricesService $priceService, FareTableRepository $repoFareTable, RoomCategoryRepository $repoCat): Response
{
$fareTable[] = $repoFareTable->find(1);
$fareTable[] = $repoFareTable->find(2);
$cat = $repoCat->find(4);
$startDate = new \DateTime("2024-04-27");
$endDate = new \DateTime("2024-05-02");
$rs = $priceService->getFinalPricesForSearch($cat, $startDate, $endDate);
return $this->json($rs);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\ConfigVariable;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route(path: '/setup', name: 'app_security_addAdmin')]
public function addAdmin(UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager): Response
{
$configRepo = $entityManager->getRepository(ConfigVariable::class);
$setupStatus = $configRepo->findBy(["key" => "SETUP_STATUS"]);
if($setupStatus != null && $setupStatus[0] != null && $setupStatus[0]->getValue() != 1) {
return new Response("Setup was already done");
}
$entityManager->beginTransaction();
try {
//Create system variables.
$var_setup = new ConfigVariable();
$var_setup->setKey("SETUP_STATUS");
$var_setup->setValue("1");
$var_setup->setSection("SYSTEM");
$entityManager->persist($var_setup);
//Create user Admin.
$user = new User();
$user->setUsername("admin");
$user->setRoles(["ROLE_USER", "ROLE_ADMIN", "ROLE_SUPERADMIN"]);
$plaintextPassword = "admin";
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
$entityManager->persist($user);
$entityManager->flush();
$entityManager->commit();
} catch (\Throwable $th) {
$entityManager->rollback();
throw $th;
}
return new Response("Setup completed :)");
}
}
View File
+149
View File
@@ -0,0 +1,149 @@
<?php
namespace App\Entity;
use App\Repository\BookingRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: BookingRepository::class)]
class Booking
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: Types::DATE_MUTABLE)]
private ?\DateTimeInterface $ArrivalDate = null;
#[ORM\Column(type : Types::DATE_MUTABLE)]
private ?\DateTimeInterface $DepartureDate = null;
#[ORM\Column(type : Types::DATETIMETZ_MUTABLE)]
private ?\DateTimeInterface $BookingTime = null;
#[ORM\OneToOne(mappedBy : 'Booking', cascade: ['persist', 'remove'])]
private ?BookingCustomer $bookingCustomer = null;
/**
* @var Collection<int, BookingRoom>
*/
#[ORM\OneToMany(targetEntity: BookingRoom::class, mappedBy: 'Booking', orphanRemoval: true, cascade: ['persist'])]
private Collection $bookingRooms;
#[ORM\Column(length: 20)]
private ?string $refNumber = null;
public function __construct()
{
$this->bookingRooms = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getArrivalDate(): ?\DateTimeInterface
{
return $this->ArrivalDate;
}
public function setArrivalDate(\DateTimeInterface $ArrivalDate): static
{
$this->ArrivalDate = $ArrivalDate;
return $this;
}
public function getDepartureDate(): ?\DateTimeInterface
{
return $this->DepartureDate;
}
public function setDepartureDate(\DateTimeInterface $DepartureDate): static
{
$this->DepartureDate = $DepartureDate;
return $this;
}
public function getBookingTime(): ?\DateTimeInterface
{
return $this->BookingTime;
}
public function setBookingTime(\DateTimeInterface $BookingTime): static
{
$this->BookingTime = $BookingTime;
return $this;
}
public function getBookingCustomer(): ?BookingCustomer
{
return $this->bookingCustomer;
}
public function setBookingCustomer(BookingCustomer $bookingCustomer): static
{
// set the owning side of the relation if necessary
if ($bookingCustomer->getBooking() !== $this) {
$bookingCustomer->setBooking($this);
}
$this->bookingCustomer = $bookingCustomer;
return $this;
}
/**
* @return Collection<int, BookingRoom>
*/
public function getBookingRooms(): Collection
{
return $this->bookingRooms;
}
public function addBookingRoom(BookingRoom $bookingRoom): static
{
if (!$this->bookingRooms->contains($bookingRoom)) {
$this->bookingRooms->add($bookingRoom);
$bookingRoom->setBooking($this);
}
return $this;
}
public function removeBookingRoom(BookingRoom $bookingRoom): static
{
if ($this->bookingRooms->removeElement($bookingRoom)) {
// set the owning side to null (unless already changed)
if ($bookingRoom->getBooking() === $this) {
$bookingRoom->setBooking(null);
}
}
return $this;
}
public function getRefNumber(): ?string
{
return $this->refNumber;
}
public function setRefNumber(string $refNumber): static
{
$this->refNumber = $refNumber;
return $this;
}
function __toString(): string
{
return $this->getRefNumber();
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Entity;
use App\Repository\BookingCustomerRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Ignore;
#[ORM\Entity(repositoryClass: BookingCustomerRepository::class)]
class BookingCustomer
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\OneToOne(inversedBy: 'bookingCustomer', cascade: ['persist', 'remove'])]
#[ORM\JoinColumn(nullable: false, onDelete: "CASCADE")]
#[Ignore]
private ?Booking $Booking = null;
#[ORM\Column(length: 64)]
private ?string $Name = null;
#[ORM\Column(length: 255)]
private ?string $Surname = null;
#[ORM\Column(length: 255)]
private ?string $Email = null;
#[ORM\Column(length: 255)]
private ?string $PhoneNumber = null;
public function getId(): ?int
{
return $this->id;
}
#[Ignore]
public function getBooking(): ?Booking
{
return $this->Booking;
}
#[Ignore]
public function setBooking(Booking $Booking): static
{
$this->Booking = $Booking;
return $this;
}
public function getName(): ?string
{
return $this->Name;
}
public function setName(string $Name): static
{
$this->Name = $Name;
return $this;
}
public function getSurname(): ?string
{
return $this->Surname;
}
public function setSurname(string $Surname): static
{
$this->Surname = $Surname;
return $this;
}
public function getEmail(): ?string
{
return $this->Email;
}
public function setEmail(string $Email): static
{
$this->Email = $Email;
return $this;
}
public function getPhoneNumber(): ?string
{
return $this->PhoneNumber;
}
public function setPhoneNumber(string $PhoneNumber): static
{
$this->PhoneNumber = $PhoneNumber;
return $this;
}
function __toString(): string
{
return $this->getName() . " " . $this->getSurname();
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Entity;
use App\Repository\BookingRoomRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Ignore;
#[ORM\Entity(repositoryClass: BookingRoomRepository::class)]
class BookingRoom
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'bookingRooms')]
#[ORM\JoinColumn(nullable: false, onDelete: "CASCADE")]
#[Ignore]
private ?Booking $Booking = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false)]
#[Ignore]
private ?RoomCategory $RoomCategory = null;
#[ORM\Column]
private ?int $GuestNumber = null;
#[ORM\Column]
private ?int $RoomPrice = null;
#[ORM\Column]
private ?int $Amount = null;
public function getId(): ?int
{
return $this->id;
}
#[Ignore]
public function getBooking(): ?Booking
{
return $this->Booking;
}
#[Ignore]
public function setBooking(?Booking $Booking): static
{
$this->Booking = $Booking;
return $this;
}
#[Ignore]
public function getRoomCategory(): ?RoomCategory
{
return $this->RoomCategory;
}
#[Ignore]
public function setRoomCategory(?RoomCategory $RoomCategory): static
{
$this->RoomCategory = $RoomCategory;
return $this;
}
public function getRoomCategoryId(): int
{
return $this->getRoomCategory()->getId();
}
public function getGuestNumber(): ?int
{
return $this->GuestNumber;
}
public function setGuestNumber(int $GuestNumber): static
{
$this->GuestNumber = $GuestNumber;
return $this;
}
public function getRoomPrice(): ?int
{
return $this->RoomPrice;
}
public function setRoomPrice(int $RoomPrice): static
{
$this->RoomPrice = $RoomPrice;
return $this;
}
public function getAmount(): ?int
{
return $this->Amount;
}
public function setAmount(int $Amount): static
{
$this->Amount = $Amount;
return $this;
}
function __toString(): string
{
return $this->getAmount() . " " . $this->getRoomCategory()->getName() . " - " . $this->getGuestNumber() . " Guests";
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Entity;
use App\Repository\ConfigVariableRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ConfigVariableRepository::class)]
class ConfigVariable
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 32, unique: true)]
private ?string $key = null;
#[ORM\Column(length: 255)]
private ?string $value = null;
#[ORM\Column(length: 64, nullable: true)]
private ?string $section = null;
public function getId(): ?int
{
return $this->id;
}
public function getKey(): ?string
{
return $this->key;
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getValue(): ?string
{
return $this->value;
}
public function setValue(string $value): static
{
$this->value = $value;
return $this;
}
public function getSection(): ?string
{
return $this->section;
}
public function setSection(?string $section): static
{
$this->section = $section;
return $this;
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace App\Entity;
use App\Repository\FareTableRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: FareTableRepository::class)]
class FareTable
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false, onDelete: "CASCADE")]
private ?RoomCategory $roomCategory = null;
#[ORM\Column(type: Types::DATETIME_MUTABLE)]
private ?\DateTimeInterface $startDate = null;
#[ORM\Column(type : Types::DATETIME_MUTABLE, nullable: true)]
private ?\DateTimeInterface $endDate = null;
#[ORM\Column(length : 255, nullable: true)]
private ?string $comment = null;
/**
* @var Collection<int, RoomFare>
*/
#[ORM\OneToMany(targetEntity: RoomFare::class, mappedBy: 'fareTable', orphanRemoval: true)]
private Collection $roomFares;
public function __construct()
{
$this->roomFares = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoomCategory(): ?RoomCategory
{
return $this->roomCategory;
}
public function setRoomCategory(?RoomCategory $roomCategory): static
{
$this->roomCategory = $roomCategory;
return $this;
}
public function getStartDate(): ?\DateTimeInterface
{
return $this->startDate;
}
public function setStartDate(\DateTimeInterface $startDate): static
{
$this->startDate = $startDate;
return $this;
}
public function getEndDate(): ?\DateTimeInterface
{
return $this->endDate;
}
public function setEndDate(?\DateTimeInterface $endDate): static
{
$this->endDate = $endDate;
return $this;
}
public function getComment(): ?string
{
return $this->comment;
}
public function setComment(?string $comment): static
{
$this->comment = $comment;
return $this;
}
/**
* @return Collection<int, RoomFare>
*/
public function getRoomFares(): Collection
{
return $this->roomFares;
}
public function addRoomFare(RoomFare $roomFare): static
{
if (!$this->roomFares->contains($roomFare)) {
$this->roomFares->add($roomFare);
$roomFare->setFareTable($this);
}
return $this;
}
public function removeRoomFare(RoomFare $roomFare): static
{
if ($this->roomFares->removeElement($roomFare)) {
// set the owning side to null (unless already changed)
if ($roomFare->getFareTable() === $this) {
$roomFare->setFareTable(null);
}
}
return $this;
}
public function __toString(): string
{
if (!\is_null($this->comment)) {
return $this->comment;
}
return $this->id;
}
/**
* Get max guest number for current roomFares.
*/
public function getMaxGuestNumber(): int
{
$maxGuests = $this->getRoomFares()->reduce(function (int $acc, RoomFare $value): int {
return \max($acc, $value->getGuestNumber());
}, -1);
return $maxGuests;
}
/**
* Get min guest number for current roomFares.
*/
public function getMinGuestNumber(): int
{
$firstGuestNum = $this->getRoomFares()->first()->getGuestNumber() ?? 999;
$maxGuests = $this->getRoomFares()->reduce(function (int $acc, RoomFare $value): int {
return \min($acc, $value->getGuestNumber());
}, $firstGuestNum);
return $maxGuests;
}
/**
* Obtiene las tarifas que aplican al GuestNumber indicado.
* @param int $guestNumber GuestNumber para búsqueda.
* @return RoomFare[] Lista de tarifas.
*/
public function getRoomFaresByGuestNumber(int $guestNumber)
{
$roomFareList = $this->getRoomFares()->filter(function (RoomFare $element) use ($guestNumber) {
return $element->getGuestNumber() == $guestNumber;
});
return $roomFareList;
}
public function isActiveOnDate(\DateTimeInterface $date): bool
{
$active = ($this->startDate <= $date && $this->endDate > $date);
return $active;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Entity;
use App\Repository\RoomAvailabilityRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoomAvailabilityRepository::class)]
class RoomAvailability
{
#[ORM\Id]
#[ORM\Column]
private ?string $day = null;
#[ORM\Id]
#[ORM\ManyToOne(targetEntity: RoomCategory::class)]
#[ORM\JoinColumn(nullable: false, onDelete: "CASCADE")]
private ?RoomCategory $roomCategory = null;
#[ORM\Column]
private ?int $numAvailable = null;
public function getDay(): ?\DateTimeInterface
{
return new \DateTime($this->day);
}
public function setDay(\DateTimeInterface $day): static
{
$this->day = $day->format("Y-m-d");
return $this;
}
public function getRoomCategory(): ?RoomCategory
{
return $this->roomCategory;
}
public function setRoomCategory(?RoomCategory $roomCategory): static
{
$this->roomCategory = $roomCategory;
return $this;
}
public function getNumAvailable(): ?int
{
return $this->numAvailable;
}
public function setNumAvailable(int $numAvailable): static
{
$this->numAvailable = $numAvailable;
return $this;
}
public function modNumAvailable(int $diffAmount):void {
$this->numAvailable -= $diffAmount;
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace App\Entity;
use App\Repository\RoomCategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoomCategoryRepository::class)]
class RoomCategory
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 64)]
private ?string $name = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(length: 64, nullable: true)]
private ?string $bedType = null;
#[ORM\Column]
private ?int $maxGuestNum = null;
/**
* @var Collection<int, RoomCategoryPhoto>
*/
#[ORM\OneToMany(targetEntity: RoomCategoryPhoto::class, mappedBy: 'roomCategory', orphanRemoval: true, cascade: ['persist'])]
private Collection $roomCategoryPhotos;
/**
* @var Collection<int, RoomCategoryDetails>
*/
#[ORM\OneToMany(targetEntity: RoomCategoryDetails::class, mappedBy: 'roomCategory', orphanRemoval: true, cascade: ['persist'])]
private Collection $roomCategoryDetails;
public function __construct()
{
$this->roomCategoryPhotos = new ArrayCollection();
$this->roomCategoryDetails = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): static
{
$this->description = $description;
return $this;
}
public function getBedType(): ?string
{
return $this->bedType;
}
public function setBedType(?string $bedType): static
{
$this->bedType = $bedType;
return $this;
}
public function getMaxGuestNum(): ?int
{
return $this->maxGuestNum;
}
public function setMaxGuestNum(int $maxGuestNum): static
{
$this->maxGuestNum = $maxGuestNum;
return $this;
}
/**
* @return Collection<int, RoomCategoryPhoto>
*/
public function getRoomCategoryPhotos(): Collection
{
return $this->roomCategoryPhotos;
}
public function addRoomCategoryPhoto(RoomCategoryPhoto $roomCategoryPhoto): static
{
if (!$this->roomCategoryPhotos->contains($roomCategoryPhoto)) {
$this->roomCategoryPhotos->add($roomCategoryPhoto);
$roomCategoryPhoto->setRoomCategory($this);
}
return $this;
}
public function removeRoomCategoryPhoto(RoomCategoryPhoto $roomCategoryPhoto): static
{
if ($this->roomCategoryPhotos->removeElement($roomCategoryPhoto)) {
// set the owning side to null (unless already changed)
if ($roomCategoryPhoto->getRoomCategory() === $this) {
$roomCategoryPhoto->setRoomCategory(null);
}
}
return $this;
}
/**
* @return Collection<int, RoomCategoryDetails>
*/
public function getRoomCategoryDetails(): Collection
{
return $this->roomCategoryDetails;
}
public function addRoomCategoryDetail(RoomCategoryDetails $roomCategoryDetail): static
{
if (!$this->roomCategoryDetails->contains($roomCategoryDetail)) {
$this->roomCategoryDetails->add($roomCategoryDetail);
$roomCategoryDetail->setRoomCategory($this);
}
return $this;
}
public function removeRoomCategoryDetail(RoomCategoryDetails $roomCategoryDetail): static
{
if ($this->roomCategoryDetails->removeElement($roomCategoryDetail)) {
// set the owning side to null (unless already changed)
if ($roomCategoryDetail->getRoomCategory() === $this) {
$roomCategoryDetail->setRoomCategory(null);
}
}
return $this;
}
public function __toString()
{
return $this->name;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Entity;
use App\Repository\RoomCategoryDetailsRepository;
use Symfony\Component\Serializer\Annotation\Ignore;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoomCategoryDetailsRepository::class)]
class RoomCategoryDetails
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $detailsSection = null;
#[ORM\Column(length: 255)]
private ?string $detailValue = null;
#[ORM\ManyToOne(inversedBy: 'roomCategoryDetails')]
#[ORM\JoinColumn(nullable: false)]
#[Ignore]
private ?RoomCategory $roomCategory = null;
public function getId(): ?int
{
return $this->id;
}
public function getDetailsSection(): ?string
{
return $this->detailsSection;
}
public function setDetailsSection(string $detailsSection): static
{
$this->detailsSection = $detailsSection;
return $this;
}
public function getDetailValue(): ?string
{
return $this->detailValue;
}
public function setDetailValue(string $detailValue): static
{
$this->detailValue = $detailValue;
return $this;
}
#[Ignore]
public function getRoomCategory(): ?RoomCategory
{
return $this->roomCategory;
}
#[Ignore]
public function setRoomCategory(?RoomCategory $roomCategory): static
{
$this->roomCategory = $roomCategory;
return $this;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Entity;
use App\Repository\RoomCategoryPhotoRepository;
use Symfony\Component\Serializer\Annotation\Ignore;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoomCategoryPhotoRepository::class)]
class RoomCategoryPhoto
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $path = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $altText = null;
#[ORM\Column(length: 30)]
private ?string $kind = null;
#[ORM\ManyToOne(inversedBy: 'roomCategoryPhotos')]
#[ORM\JoinColumn(nullable: false)]
#[Ignore]
private ?RoomCategory $roomCategory = null;
public function getId(): ?int
{
return $this->id;
}
public function getPath(): ?string
{
return $this->path;
}
public function setPath(string $path): static
{
$this->path = $path;
return $this;
}
public function getAltText(): ?string
{
return $this->altText;
}
public function setAltText(?string $altText): static
{
$this->altText = $altText;
return $this;
}
public function getKind(): ?string
{
return $this->kind;
}
public function setKind(string $kind): static
{
$this->kind = $kind;
return $this;
}
#[Ignore]
public function getRoomCategory(): ?RoomCategory
{
return $this->roomCategory;
}
#[Ignore]
public function setRoomCategory(?RoomCategory $roomCategory): static
{
$this->roomCategory = $roomCategory;
return $this;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Entity;
use App\Repository\RoomFareRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: RoomFareRepository::class)]
class RoomFare
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'roomFares')]
#[ORM\JoinColumn(nullable: false)]
private ?FareTable $fareTable = null;
#[ORM\Column]
private ?int $guestNumber = null;
#[ORM\Column]
private ?int $fareAmount = null;
#[ORM\Column(length: 2, nullable: true)]
private ?string $dayType = null;
public function getId(): ?int
{
return $this->id;
}
public function getFareTable(): ?FareTable
{
return $this->fareTable;
}
public function setFareTable(?FareTable $fareTable): static
{
$this->fareTable = $fareTable;
return $this;
}
public function getGuestNumber(): ?int
{
return $this->guestNumber;
}
public function setGuestNumber(int $guestNumber): static
{
$this->guestNumber = $guestNumber;
return $this;
}
public function getFareAmount(): ?int
{
return $this->fareAmount;
}
public function setFareAmount(int $fareAmount): static
{
$this->fareAmount = $fareAmount;
return $this;
}
public function getDayType(): ?string
{
return $this->dayType;
}
public function setDayType(?string $dayType): static
{
$this->dayType = $dayType;
return $this;
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_USERNAME', fields: ['username'])]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180)]
private ?string $username = null;
/**
* @var list<string> The user roles
*/
#[ORM\Column]
private array $roles = [];
/**
* @var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
/**
* @var string Store unhashed user password on user creation/edit.
*/
private ?string $plainPassword = null;
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): static
{
$this->username = $username;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->username;
}
/**
* @see UserInterface
*
* @return list<string>
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
/**
* @param list<string> $roles
*/
public function setRoles(array $roles): static
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(string $plainPassword): static
{
$this->plainPassword = $plainPassword;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\BookingCustomer;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<BookingCustomer>
*
* @method BookingCustomer|null find($id, $lockMode = null, $lockVersion = null)
* @method BookingCustomer|null findOneBy(array $criteria, array $orderBy = null)
* @method BookingCustomer[] findAll()
* @method BookingCustomer[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class BookingCustomerRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, BookingCustomer::class);
}
// /**
// * @return BookingCustomer[] Returns an array of BookingCustomer objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('b.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?BookingCustomer
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\Booking;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Booking>
*
* @method Booking|null find($id, $lockMode = null, $lockVersion = null)
* @method Booking|null findOneBy(array $criteria, array $orderBy = null)
* @method Booking[] findAll()
* @method Booking[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class BookingRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Booking::class);
}
// /**
// * @return Booking[] Returns an array of Booking objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('b.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Booking
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\BookingRoom;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<BookingRoom>
*
* @method BookingRoom|null find($id, $lockMode = null, $lockVersion = null)
* @method BookingRoom|null findOneBy(array $criteria, array $orderBy = null)
* @method BookingRoom[] findAll()
* @method BookingRoom[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class BookingRoomRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, BookingRoom::class);
}
// /**
// * @return BookingRoom[] Returns an array of BookingRoom objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('b.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?BookingRoom
// {
// return $this->createQueryBuilder('b')
// ->andWhere('b.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
@@ -0,0 +1,76 @@
<?php
namespace App\Repository;
use App\Entity\ConfigVariable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ConfigVariable>
*
* @method ConfigVariable|null find($id, $lockMode = null, $lockVersion = null)
* @method ConfigVariable|null findOneBy(array $criteria, array $orderBy = null)
* @method ConfigVariable[] findAll()
* @method ConfigVariable[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ConfigVariableRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ConfigVariable::class);
}
/**
* Get all config variables for API.
*/
public function findAllVariables(): array
{
return $this->createQueryBuilder('c')
->select('c.key, c.value, c.section')
->getQuery()
->getResult();
}
/**
* @param string Config section.
* @return ConfigVariable[] Returns an array of ConfigVariable objects
*/
public function findAllBySection(string $section): array
{
return $this->createQueryBuilder('c')
->select('c.key, c.value')
->andWhere('c.section = :val')
->setParameter('val', $section)
->getQuery()
->getResult();
}
/**
* Get Config Variable by it's key.
* @param string Variable Key
* @return ConfigVariable|null Config Variable.
*/
public function findVariableByKey($varKey)
{
return $this->createQueryBuilder('c')
->select('c.key, c.value, c.section')
->andWhere('c.key = :val')
->setParameter('val', $varKey)
->getQuery()
->getOneOrNullResult();
}
/**
* Get all section names that contains config variables.
* @return string[] Returns an array of strings.
*/
public function getAllSections(): array
{
return $this->createQueryBuilder('c')
->select('c.section')
->distinct()
->getQuery()
->getResult();
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Repository;
use App\Entity\FareTable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<FareTable>
*
* @method FareTable|null find($id, $lockMode = null, $lockVersion = null)
* @method FareTable|null findOneBy(array $criteria, array $orderBy = null)
* @method FareTable[] findAll()
* @method FareTable[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class FareTableRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, FareTable::class);
}
/**
* Gets all fareTables for time period.
* @param integer|string ID Categoria.
* @param DateTimeInterface Period start date
* @param DateTimeInterface Period end date
* @return array Array with all faretables active in given period.
*/
public function findFareTable(int $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate): array
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
return $this->createQueryBuilder('f')
->andWhere('f.roomCategory = :category')
->andWhere('f.startDate < :endDate')
->andWhere('f.endDate >= :startDate')
->setParameter('category', $roomCategory)
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->getResult();
}
/**
* Obtiene una lista con los números de huéspedes permitidos por todos los tarifarios pasados.
* @param FareTable[] $fareTableList Lista con los FareTable a consultar.
* @return int[] Lista con los números de huéspedes permitidos.
*/
public function getAllowedGuestNumberOnFareTableList(array $fareTableList): array
{
$fareTableCount = count($fareTableList);
if($fareTableCount == 0) {
return [];
}
$fareTableIdList = \array_map(function (FareTable $element) {
return $element->getId();
}, $fareTableList);
$strIdList = \implode(",", $fareTableIdList);
//Subquery -> Obtiene los números de huéspedes de las tarifas de un tarifario.
//Query -> Cuenta en cuantos tarifarios aparece cada número de huéspedes y queda con aquellos que aparecen en todos (having).
$sql = "SELECT guest_number
FROM (SELECT DISTINCT fare_table_id, guest_number FROM room_fare WHERE fare_table_id IN ($strIdList))
GROUP BY guest_number
HAVING COUNT(fare_table_id) = $fareTableCount";
$conn = $this->getEntityManager()->getConnection();
$rs = $conn->executeQuery($sql);
$allowedGuestNumbers = [];
while (true) {
$value = $rs->fetchOne();
if (!$value) {
break;
}
$allowedGuestNumbers[] = $value;
}
return $allowedGuestNumbers;
}
}
@@ -0,0 +1,177 @@
<?php
namespace App\Repository;
use App\Entity\RoomAvailability;
use App\Entity\RoomCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<RoomAvailability>
*
* @method RoomAvailability|null find($id, $lockMode = null, $lockVersion = null)
* @method RoomAvailability|null findOneBy(array $criteria, array $orderBy = null)
* @method RoomAvailability[] findAll()
* @method RoomAvailability[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomAvailabilityRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, RoomAvailability::class);
}
/**
* @return RoomAvailability[] Returns an array of RoomAvailability objects
*/
public function findByRoomCategory($categoryId): array
{
return $this->createQueryBuilder('a')
->andWhere('a.roomCategory = :val')
->setParameter('val', $categoryId)
->orderBy('a.day', 'ASC')
->getQuery()
->getResult();
}
/**
* @param \DateTimeInterface Period start (included in range).
* @param \DateTimeInterface Period end (not included in range).
* @return RoomAvailability[] Returns an array of RoomAvailability objects
*/
public function getAvailabilityForPeriod(\DateTimeInterface $startDate, \DateTimeInterface $endDate): array
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
return $this->createQueryBuilder('ra')
->select('IDENTITY(ra.roomCategory) as roomCategory, MIN(ra.numAvailable) as availability')
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->groupBy('ra.roomCategory')
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->getArrayResult();
}
/**
* @param \DateTimeInterface Period start (included in range).
* @param \DateTimeInterface Period end (not included in range).
* @return int Returns number of available room of that category on selected period.
*/
public function getAvailabilityForCategoryInPeriod(RoomCategory $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate): int | null
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
$roomCatId = $roomCategory->getId();
return $this->createQueryBuilder('ra')
->select('MIN(ra.numAvailable) as availability')
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->andWhere('ra.roomCategory = :roomCategory')
->setParameter('roomCategory', $roomCatId)
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->getSingleScalarResult();
}
public function getAvailabilityForPeriodDetails(\DateTimeInterface $startDate, \DateTimeInterface $endDate): array
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
return $this->createQueryBuilder('ra')
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->getArrayResult();
}
/**
* Updates All Availability of selected roomCategory during period. It can operate in 2 modes, normal and diff mode.
* - Normal mode -> Sets value.
* - Diff mode -> apply value as sum ( currentAvailability += diff )
* NOTE: A Flush is needed after this operation.
*/
public function updateAvailabilityForRoomCategoryOnPeriod(RoomCategory $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate, int $amount, bool $isDiff = false): void
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
$roomCatId = $roomCategory->getId();
$availabilityItemList = $this->createQueryBuilder('ra')
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->andWhere('ra.roomCategory = :roomCategory')
->setParameter('roomCategory', $roomCatId)
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->getResult();
$em = $this->getEntityManager();
foreach ($availabilityItemList as $item) {
if ($isDiff) {
$item->modNumAvailable($amount);
} else {
$item->setNumAvailable($amount);
}
}
}
/**
* For a given RoomCategory, sets its availability for all days on a period with the given amount.
*/
public function bulkEditRoomAvailabilityForCategoryOnPeriod(RoomCategory $roomCategory, \DateTimeInterface $startDate, \DateTimeInterface $endDate, int $amount): void
{
$strStartDate = $startDate->format('Y-m-d');
$strEndDate = $endDate->format('Y-m-d');
$roomCatId = $roomCategory->getId();
$entityManager = $this->getEntityManager();
$entityManager->beginTransaction();
try {
//First, delete old data.
$this->createQueryBuilder('ra')
->delete()
->andWhere('ra.day >= :startDate')
->andWhere('ra.day < :endDate')
->andWhere('ra.roomCategory = :roomCategory')
->setParameter('roomCategory', $roomCatId)
->setParameter('startDate', $strStartDate)
->setParameter('endDate', $strEndDate)
->getQuery()
->execute();
$entityManager->flush();
//For each day, create item and persist it.
$daterange = new \DatePeriod($startDate, new \DateInterval('P1D'), $endDate);
foreach ($daterange as $date) {
$item = new RoomAvailability();
$item->setRoomCategory($roomCategory);
$item->setDay($date);
$item->setNumAvailable($amount);
$entityManager->persist($item);
}
$entityManager->flush();
$entityManager->commit();
} catch (\Throwable $th) {
$entityManager->rollback();
throw $th;
}
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\RoomCategoryDetails;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<RoomCategoryDetails>
*
* @method RoomCategoryDetails|null find($id, $lockMode = null, $lockVersion = null)
* @method RoomCategoryDetails|null findOneBy(array $criteria, array $orderBy = null)
* @method RoomCategoryDetails[] findAll()
* @method RoomCategoryDetails[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomCategoryDetailsRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, RoomCategoryDetails::class);
}
// /**
// * @return RoomCategoryDetails[] Returns an array of RoomCategoryDetails objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('r.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?RoomCategoryDetails
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\RoomCategoryPhoto;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<RoomCategoryPhoto>
*
* @method RoomCategoryPhoto|null find($id, $lockMode = null, $lockVersion = null)
* @method RoomCategoryPhoto|null findOneBy(array $criteria, array $orderBy = null)
* @method RoomCategoryPhoto[] findAll()
* @method RoomCategoryPhoto[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomCategoryPhotoRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, RoomCategoryPhoto::class);
}
// /**
// * @return RoomCategoryPhoto[] Returns an array of RoomCategoryPhoto objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('r.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?RoomCategoryPhoto
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\RoomCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<RoomCategory>
*
* @method RoomCategory|null find($id, $lockMode = null, $lockVersion = null)
* @method RoomCategory|null findOneBy(array $criteria, array $orderBy = null)
* @method RoomCategory[] findAll()
* @method RoomCategory[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomCategoryRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, RoomCategory::class);
}
// /**
// * @return RoomCategory[] Returns an array of RoomCategory objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('r.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?RoomCategory
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Repository;
use App\Entity\RoomFare;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<RoomFare>
*
* @method RoomFare|null find($id, $lockMode = null, $lockVersion = null)
* @method RoomFare|null findOneBy(array $criteria, array $orderBy = null)
* @method RoomFare[] findAll()
* @method RoomFare[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class RoomFareRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, RoomFare::class);
}
// /**
// * @return RoomFare[] Returns an array of RoomFare objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('r.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?RoomFare
// {
// return $this->createQueryBuilder('r')
// ->andWhere('r.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
/**
* @extends ServiceEntityRepository<User>
*
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[] findAll()
* @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
}
$user->setPassword($newHashedPassword);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
}
// /**
// * @return User[] Returns an array of User objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('u.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?User
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
+157
View File
@@ -0,0 +1,157 @@
<?php
namespace App\Service;
use App\Entity\FareTable;
use App\Entity\RoomCategory;
use App\Repository\FareTableRepository;
use App\Repository\RoomFareRepository;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Servicio para calcular los precios de las estancias.
* En un futuro este servicio deberá admitir múltiples estrategias de cálculo de precios finales.
*/
class PricesService
{
public function __construct(
private FareTableRepository $repoFareTable,
private RoomFareRepository $repoRoomFares
) {
}
/**
* Calcula los precios de la estancia para la categoría y periodo indicados.
* Devolverá para cada numero de personas, el precio final de la estancia.
*
* e. g. --> [ 2 => 120€, 3 => 180€ ]
*
* @return array Contiene los precios en función del número de personas.
*/
public function getFinalPricesForSearch(RoomCategory $category, \DateTimeInterface $startDate, \DateTimeInterface $endDate): array
{
$daysDiff = $startDate->diff($endDate)->days;
if (!$daysDiff) {
return "Invalid date period :( ";
}
$fareTablesForPeriod = $this->repoFareTable->findFareTable($category->getId(), $startDate, $endDate);
//Obtenemos el número de personas permitido por todos los tarifarios activos.
$allowedGuestNumbers = $this->repoFareTable->getAllowedGuestNumberOnFareTableList($fareTablesForPeriod);
$rs = [];
//Calculamos los precios para cada GuestNumber permitido.
foreach ($allowedGuestNumbers as $currentGuestNumber) {
//Calculamos el precio de cada día.
// e.g. --> [ "2024-04-30" => 20, "2024-05-01" => 28, "2024-05-02" => 20, ...].
$dailyPrices = $this->getDailyPricesForSearch($startDate, $endDate, $currentGuestNumber, $fareTablesForPeriod);
$rs[$currentGuestNumber] = $dailyPrices;
}
//Aplicamos la estrategia de precios configurada para calcular el precio final de la estancia.
// TODOME: Crear y configurar diversas estrategias de precios -> Por el momento utilizamos "Suma del precio de cada día".
$finalResult = [];
foreach ($rs as $guestNum => $priceArray) {
$finalAmount = \array_reduce($priceArray, function ($acc, $element) {
return $acc + $element;
});
$finalResult[$guestNum] = $finalAmount;
}
return $finalResult;
}
/**
* Dado un número de huéspedes, calcula el precio de cada día del periodo indicado.
* @param \DateTimeInterface $startDate Fecha de inicio del periodo.
* @param \DateTimeInterface $endDate Fecha fin del periodo.
* @param int $guestNumber Número de huéspedes para los que calcular los precios.
* @param array $fareTableList Array con los tarifarios que aplican en el periodo indicado.
* @return array Devuelve un array con los precios: e.g. --> [ "2024-04-30" => 2500, "2024-05-01" => 3500, "2024-05-02" => 3000, ...].
*/
public function getDailyPricesForSearch(\DateTimeInterface $startDate, \DateTimeInterface $endDate, int $guestNumber, array $fareTableList): array
{
$daysDiff = $startDate->diff($endDate)->days;
$dailyPrices = [];
$currentDate = new \DateTime($startDate->format("Y-m-d")); //TODOME: Comprobar si es tipo referencia y está cambiando.
for ($i = 0; $i < $daysDiff; $i++) {
$strCurrentDate = $currentDate->format("Y-m-d");
//Obtenemos el tarifario que aplica --> TODOME: Buscar si se puede cachear esto, para no recarlcularlo para cada GuestNumber.
$currentFareTableList = \array_filter($fareTableList, function (FareTable $element) use ($currentDate) {
return $element->isActiveOnDate($currentDate);
});
if (count($currentFareTableList) != 1) {
$dailyPrices[$strCurrentDate] = "ERROR - Number of FareTable found: " . count($currentFareTableList);
continue;
}
$currentFareTable = array_values($currentFareTableList)[0];
//TODOME: -> Obtener precio específico (RoomPrices).
//Si no hay precio, calcular mediante tarifarios.
$roomFares = $currentFareTable->getRoomFaresByGuestNumber($guestNumber);
if (count($roomFares) < 1) {
$dailyPrices[$strCurrentDate] = "ERROR - Invalid RoomFares found";
continue;
}
//Si sólo hay 1 tarifa, aplico esa, sino calculo la apropiada según condiciones.
$fareAmount = null;
if (count($roomFares) == 1) {
$fareAmount = $roomFares->first()->getFareAmount();
} else {
$fareAmount = $this->calculateFareApplyingConditions($roomFares, $currentDate);
}
$dailyPrices[$strCurrentDate] = $fareAmount;
//Add 1 day to current date.
$currentDate->add(new \DateInterval("P1D"));
}
return $dailyPrices;
}
/**
* Calcula el precio a aplicar según las condiciones de las tarifas.
* @param RoomFare[] $roomFareList Lista con las posibles tarifas.
* @param DateTimeInterface $fareCondDate Fecha utilizada para las condiciones.
*
*/
public function calculateFareApplyingConditions(ArrayCollection $roomFareList, \DateTimeInterface $fareCondDate): int
{
$currentDayOfWeek = $fareCondDate->format("w");
//Comprobamos si a alguna de las tarifas se la aplica la condición de "DayType" y coincide con el actual.
// Si es así, devolvemos su valor.
foreach ($roomFareList as $roomFare) {
$dayType = $roomFare->getDayType();
if ($dayType == null || $dayType == "") {
continue;
}
if($dayType == $currentDayOfWeek) {
return $roomFare->getFareAmount();
}
}
//TODOME: Si existen múltiples tarifas posibles, debería haber una estrategia para elegir una u otra. Variable de configuración para esto.
$faresWithoutConditions = $roomFareList->filter(function ($element) {
return $element->getDayType() == null;
});
return $faresWithoutConditions->first()->getFareAmount();
}
}
+188
View File
@@ -0,0 +1,188 @@
{
"doctrine/doctrine-bundle": {
"version": "2.12",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "2.12",
"ref": "32f890075233ac4a1176e848a0f8e932ac6536d6"
},
"files": [
"./config/packages/doctrine.yaml",
"./src/Entity/.gitignore",
"./src/Repository/.gitignore"
]
},
"doctrine/doctrine-migrations-bundle": {
"version": "3.3",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "3.1",
"ref": "1d01ec03c6ecbd67c3375c5478c9a423ae5d6a33"
},
"files": [
"./config/packages/doctrine_migrations.yaml",
"./migrations/.gitignore"
]
},
"easycorp/easyadmin-bundle": {
"version": "4.10",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "3.0",
"ref": "b131e6cbfe1b898a508987851963fff485986285"
}
},
"nelmio/cors-bundle": {
"version": "2.4",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "1.5",
"ref": "6bea22e6c564fba3a1391615cada1437d0bde39c"
},
"files": [
"./config/packages/nelmio_cors.yaml"
]
},
"symfony/console": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "5.3",
"ref": "1781ff40d8a17d87cf53f8d4cf0c8346ed2bb461"
},
"files": [
"bin/console"
]
},
"symfony/flex": {
"version": "2.4",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "1.0",
"ref": "146251ae39e06a95be0fe3d13c807bcf3938b172"
},
"files": [
".env"
]
},
"symfony/framework-bundle": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "7.0",
"ref": "6356c19b9ae08e7763e4ba2d9ae63043efc75db5"
},
"files": [
"config/packages/cache.yaml",
"config/packages/framework.yaml",
"config/preload.php",
"config/routes/framework.yaml",
"config/services.yaml",
"public/index.php",
"src/Controller/.gitignore",
"src/Kernel.php"
]
},
"symfony/maker-bundle": {
"version": "1.58",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "1.0",
"ref": "fadbfe33303a76e25cb63401050439aa9b1a9c7f"
}
},
"symfony/routing": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "7.0",
"ref": "21b72649d5622d8f7da329ffb5afb232a023619d"
},
"files": [
"config/packages/routing.yaml",
"config/routes.yaml"
]
},
"symfony/security-bundle": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "6.4",
"ref": "2ae08430db28c8eb4476605894296c82a642028f"
},
"files": [
"./config/packages/security.yaml",
"./config/routes/security.yaml"
]
},
"symfony/translation": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "6.3",
"ref": "e28e27f53663cc34f0be2837aba18e3a1bef8e7b"
},
"files": [
"./config/packages/translation.yaml",
"./translations/.gitignore"
]
},
"symfony/twig-bundle": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "6.4",
"ref": "cab5fd2a13a45c266d45a7d9337e28dee6272877"
},
"files": [
"./config/packages/twig.yaml",
"./templates/base.html.twig"
]
},
"symfony/uid": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "7.0",
"ref": "0df5844274d871b37fc3816c57a768ffc60a43a5"
}
},
"symfony/validator": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "7.0",
"ref": "8c1c4e28d26a124b0bb273f537ca8ce443472bfd"
},
"files": [
"./config/packages/validator.yaml"
]
},
"symfony/web-profiler-bundle": {
"version": "7.0",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "6.1",
"ref": "e42b3f0177df239add25373083a564e5ead4e13a"
},
"files": [
"./config/packages/web_profiler.yaml",
"./config/routes/web_profiler.yaml"
]
}
}
@@ -0,0 +1,10 @@
{# templates/admin/room_availability/availability_day_edit.html.twig #}
{% extends '@EasyAdmin/page/content.html.twig' %}
{% block content_title 'Category - Room Availability - Edit' %}
{% block main %}
<div>
<h3>{{categoryId}}</h3>
</div>
{{ form(form) }}
{% endblock %}

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