Compare commits
238 Commits
feature/re
...
tenant/ont
| Author | SHA1 | Date | |
|---|---|---|---|
| fc04992ebb | |||
| 7d27d77629 | |||
| b2ffa7bb6b | |||
| 3465352218 | |||
| 8adbfecc35 | |||
| 1f35a6d709 | |||
| 32f86d14d6 | |||
| 49eaf0ad65 | |||
| db97de6711 | |||
| c876b2b171 | |||
| f6ff91ff3b | |||
| acac2858c3 | |||
| cd1c99f487 | |||
| 607892173d | |||
| 52f7b98162 | |||
| a06f8146e5 | |||
| fd60880812 | |||
| e0b1f27b97 | |||
| e7d24607a6 | |||
| 865893b96b | |||
| 14bda25c56 | |||
| 6997550767 | |||
| 657ef1d89f | |||
| 018b1d8ec7 | |||
| 93a9ca7e5c | |||
| 6ce734b2c2 | |||
| 7f4aa81d4b | |||
| 6927da6342 | |||
| 2f98fd6234 | |||
| de5c533d85 | |||
| 90a0ac3e36 | |||
| de10de2376 | |||
| 4923010afb | |||
| f87f7f55a9 | |||
| 17dbf52181 | |||
| a7e1d8995f | |||
| b5fae81795 | |||
| 8664c86915 | |||
| 9e72ec0c60 | |||
| e9aae7a4c3 | |||
| 6545be498f | |||
| 8c15ad7cc1 | |||
| f859eba8a8 | |||
| 8ba34c6c7a | |||
| d7c015e71e | |||
| d8d608c435 | |||
| 985316d3b4 | |||
| d601cc1984 | |||
| 70d47ac310 | |||
| 5d1d7086c7 | |||
| 9a6ec3d1f2 | |||
| 38ba5f4195 | |||
| 4bd74d95cb | |||
| 6f87aae939 | |||
| 71ef09b413 | |||
| 1d54cb1c48 | |||
| 7d52e11bca | |||
| ebae063a0f | |||
| f0c1e74c1b | |||
| 709859e731 | |||
| e95a7612c2 | |||
| 8bc0e165c7 | |||
| 158b28ec1a | |||
| 8c22485d49 | |||
| 2462f25f2f | |||
| 63b01f366a | |||
| ddd0b1b56d | |||
| 2cad0c39b4 | |||
| 3089873232 | |||
| 3fa0235163 | |||
| 0910d90363 | |||
| f3d446d012 | |||
| 71c462aaba | |||
| 481eb30795 | |||
| afebc7f639 | |||
| 1ec48f7e21 | |||
| 07972760fc | |||
| 848c3b280f | |||
| c387a01d62 | |||
| 5d9adc0494 | |||
| 593580d648 | |||
| eb524c7d99 | |||
| 65e8436ae1 | |||
| 07500f699d | |||
| 4997665da6 | |||
| dbfadf417a | |||
| dddb086cd8 | |||
| a825b3693b | |||
| 679342ec8d | |||
| a5420e6a42 | |||
| 91b8788c91 | |||
| b6a52ceb8c | |||
| 51d051733c | |||
| f62cd08807 | |||
| d61b1e4b0a | |||
| 1bffefece3 | |||
| b0d2cd05bc | |||
| 520397baa5 | |||
| 591f53c102 | |||
| 85529f40f2 | |||
| 4a952af784 | |||
| b1d4c4d13d | |||
| 8861e42fff | |||
| 7fbdd3844f | |||
| f2c1542e46 | |||
| def86405dc | |||
| 870de3ca6e | |||
| d8d489e846 | |||
| 4183d6386d | |||
| 8089298383 | |||
| d51db00247 | |||
| 88c3a08a23 | |||
| 21e89805d0 | |||
| 195ac73aed | |||
| c24a8b946d | |||
| 70060f65ec | |||
| 02ff829c06 | |||
| 69c836a578 | |||
| 87cc430f05 | |||
| 3e9e35c681 | |||
| 0bd6dc3b22 | |||
| f056c32f49 | |||
| 11df4dbe72 | |||
| 9b69a1d387 | |||
| 4251ca8a8a | |||
| b14f34d3e8 | |||
| d636b2b82b | |||
| cfa1091116 | |||
| d0b1607ff4 | |||
| 92546a28c0 | |||
| ce26fb5d1a | |||
| 38a57adf55 | |||
| e1d9590905 | |||
| 00a01e1a8e | |||
| 56e011bc7a | |||
| 5c6a03b10d | |||
| cc446433f6 | |||
| 2d0664a7c7 | |||
| 2192eea09f | |||
| 8659708e1a | |||
| dce54ceb67 | |||
| cab33d4842 | |||
| f318f614af | |||
| 581696ffab | |||
| 53cee7ecdd | |||
| 757f362918 | |||
| a8e73af806 | |||
| 61789d9238 | |||
| dd2082f40e | |||
| 755d6a9903 | |||
| c486131905 | |||
| 9ba2041f7b | |||
| 92ad7340fe | |||
| 6b2f8de210 | |||
| 69f3569ccf | |||
| 9937c1b484 | |||
| 43e497cf97 | |||
| 207c979f71 | |||
| 30bfd9eff8 | |||
| 3f8b5bf206 | |||
| d92b5a7623 | |||
| e4670491c7 | |||
| 1b94b2ca13 | |||
| 46dcb84985 | |||
| f7983b109f | |||
| 8ff9ed216c | |||
| f80d146012 | |||
| 1cb2cf3d54 | |||
| 97250d10b7 | |||
| 15979874ce | |||
| 0defe75adb | |||
| 34afb5142d | |||
| 8eba15155e | |||
| 85c31579e2 | |||
| 159ec36cb2 | |||
| 32b1eb5639 | |||
| 0f9d3e79d4 | |||
| b97753f825 | |||
| f1b724ed63 | |||
| 571cae0f98 | |||
| 30b8527c9a | |||
| 0e5f6dceb0 | |||
| cd0a6e9b5e | |||
| 1bbb3d0914 | |||
| e4157a4005 | |||
| c9f8a1c4a6 | |||
| 308af52ad5 | |||
| ae6728998d | |||
| f1b829264f | |||
| fccb7676bf | |||
| 3adc04b68d | |||
| 12e2870d40 | |||
| 0b53253461 | |||
| 6cc0fcd9c0 | |||
| dc6668df72 | |||
| f428a88ba8 | |||
| e21c5e9e9f | |||
| f7a8b42892 | |||
| 9f8e42c30b | |||
| d45199a0ef | |||
| c1da31711f | |||
| cf61611d76 | |||
| 2c4d22f0b9 | |||
| caa1fddcc1 | |||
| 5f0c99c395 | |||
| 832fad19bc | |||
| 28ed5d71b2 | |||
| 23a5ac32cc | |||
| 1b19d36e26 | |||
| 86533b9ab4 | |||
| 369cfb0a40 | |||
| 7b0c9831f1 | |||
| ede2173a5a | |||
| 5d760bfd80 | |||
| e3599a48e4 | |||
| 5d629e27b1 | |||
| 563e4634d1 | |||
| c75787a59c | |||
| f6f3a997f7 | |||
| 019c9df23b | |||
| 9ea85b7924 | |||
| 0769bb8683 | |||
| c645feba80 | |||
| 56f602d876 | |||
| d6bab24e1d | |||
| dd828d9a4e | |||
| 7c2a098696 | |||
| 1977df6765 | |||
| c6ac974459 | |||
| 8d88e1bb13 | |||
| 78970573a8 | |||
| f289e9e2e4 | |||
| 2487546a75 | |||
| cc884e3cc0 | |||
| ffb586c348 | |||
| ec18aaf0c5 | |||
| 941cb5c73c | |||
| 934bd07105 |
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@@ -7,7 +7,7 @@
|
|||||||
"type": "chrome",
|
"type": "chrome",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"preLaunchTask": "npm: start",
|
"preLaunchTask": "npm: start",
|
||||||
"url": "http://localhost:4200/"
|
"url": "http://localhost:4300/"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "ng test",
|
"name": "ng test",
|
||||||
|
|||||||
34
angular.json
34
angular.json
@@ -34,7 +34,12 @@
|
|||||||
"server": "src/main.server.ts",
|
"server": "src/main.server.ts",
|
||||||
"outputMode": "server",
|
"outputMode": "server",
|
||||||
"security": {
|
"security": {
|
||||||
"allowedHosts": ["localhost", "127.0.0.1"]
|
"allowedHosts": [
|
||||||
|
"localhost",
|
||||||
|
"localhost:4300",
|
||||||
|
"127.0.0.1",
|
||||||
|
"127.0.0.1:4300"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"ssr": {
|
"ssr": {
|
||||||
"entry": "src/server.ts"
|
"entry": "src/server.ts"
|
||||||
@@ -42,6 +47,9 @@
|
|||||||
},
|
},
|
||||||
"configurations": {
|
"configurations": {
|
||||||
"production": {
|
"production": {
|
||||||
|
"optimization": true,
|
||||||
|
"extractLicenses": true,
|
||||||
|
"sourceMap": false,
|
||||||
"budgets": [
|
"budgets": [
|
||||||
{
|
{
|
||||||
"type": "initial",
|
"type": "initial",
|
||||||
@@ -54,7 +62,13 @@
|
|||||||
"maximumError": "8kB"
|
"maximumError": "8kB"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputHashing": "all"
|
"outputHashing": "all",
|
||||||
|
"fileReplacements": [
|
||||||
|
{
|
||||||
|
"replace": "src/environments/environment.ts",
|
||||||
|
"with": "src/environments/environment.production.ts"
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"development": {
|
"development": {
|
||||||
"optimization": true,
|
"optimization": true,
|
||||||
@@ -64,9 +78,18 @@
|
|||||||
"local": {
|
"local": {
|
||||||
"optimization": false,
|
"optimization": false,
|
||||||
"extractLicenses": false,
|
"extractLicenses": false,
|
||||||
"sourceMap": true
|
"sourceMap": true,
|
||||||
|
"fileReplacements": [
|
||||||
|
{
|
||||||
|
"replace": "src/environments/environment.ts",
|
||||||
|
"with": "src/environments/environment.local.ts"
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"homo": {
|
"homo": {
|
||||||
|
"optimization": true,
|
||||||
|
"extractLicenses": true,
|
||||||
|
"sourceMap": false,
|
||||||
"fileReplacements": [
|
"fileReplacements": [
|
||||||
{
|
{
|
||||||
"replace": "src/environments/environment.ts",
|
"replace": "src/environments/environment.ts",
|
||||||
@@ -79,6 +102,9 @@
|
|||||||
},
|
},
|
||||||
"serve": {
|
"serve": {
|
||||||
"builder": "@angular/build:dev-server",
|
"builder": "@angular/build:dev-server",
|
||||||
|
"options": {
|
||||||
|
"port": 4300
|
||||||
|
},
|
||||||
"configurations": {
|
"configurations": {
|
||||||
"production": {
|
"production": {
|
||||||
"buildTarget": "shopit-front:build:production"
|
"buildTarget": "shopit-front:build:production"
|
||||||
@@ -93,7 +119,7 @@
|
|||||||
"buildTarget": "shopit-front:build:homo"
|
"buildTarget": "shopit-front:build:homo"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"defaultConfiguration": "development"
|
"defaultConfiguration": "local"
|
||||||
},
|
},
|
||||||
"test": {
|
"test": {
|
||||||
"builder": "@angular/build:unit-test"
|
"builder": "@angular/build:unit-test"
|
||||||
|
|||||||
BIN
public/fonts/KaushanScript/KaushanScript-Regular.ttf
Normal file
BIN
public/fonts/KaushanScript/KaushanScript-Regular.ttf
Normal file
Binary file not shown.
95
public/fonts/KaushanScript/OFL.txt
Normal file
95
public/fonts/KaushanScript/OFL.txt
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
Copyright (c) 2011, Pablo Impallari (www.impallari.com|impallari@gmail.com),
|
||||||
|
Copyright (c) 2011, Igino Marini. (www.ikern.com|mail@iginomarini.com),
|
||||||
|
with Reserved Font Name Kaushan Script.
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
93
public/fonts/Smooch/OFL.txt
Normal file
93
public/fonts/Smooch/OFL.txt
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright 2017 The Smooch Project Authors (https://github.com/googlefonts/smooch)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
BIN
public/fonts/Smooch/Smooch-Regular.ttf
Normal file
BIN
public/fonts/Smooch/Smooch-Regular.ttf
Normal file
Binary file not shown.
BIN
public/images/ticket-selector-entrada-pasarela.png
Normal file
BIN
public/images/ticket-selector-entrada-pasarela.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 333 KiB |
@@ -1,3 +1,11 @@
|
|||||||
|
@font-face {
|
||||||
|
font-family: 'Smooch';
|
||||||
|
src: url('/fonts/Smooch/Smooch-Regular.ttf') format('truetype');
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "Gotham";
|
font-family: "Gotham";
|
||||||
src: url("/fonts/Gotham/Gotham Thin.otf") format("opentype");
|
src: url("/fonts/Gotham/Gotham Thin.otf") format("opentype");
|
||||||
@@ -30,6 +38,14 @@
|
|||||||
font-display: swap;
|
font-display: swap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: "Gotham Book";
|
||||||
|
src: url("/fonts/Gotham/Gotham Book.otf") format("opentype");
|
||||||
|
font-weight: 400;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "Gotham";
|
font-family: "Gotham";
|
||||||
src: url("/fonts/Gotham/Gotham Italic.otf") format("opentype");
|
src: url("/fonts/Gotham/Gotham Italic.otf") format("opentype");
|
||||||
|
|||||||
27
src/app/app.config.spec.ts
Normal file
27
src/app/app.config.spec.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { HttpRequest } from '@angular/common/http';
|
||||||
|
|
||||||
|
import { isStoreCatalogRequest } from './app.config';
|
||||||
|
|
||||||
|
describe('isStoreCatalogRequest', () => {
|
||||||
|
it.each([
|
||||||
|
'http://localhost:8000/api/tenants/demo/catalog',
|
||||||
|
'http://localhost:8000/api/tenants/demo/catalog?currency=ARS',
|
||||||
|
'http://localhost:8000/api/tenants/demo/catalog/featured-groups/7/items?page=2',
|
||||||
|
'http://localhost:8000/api/tenants/demo/catalog-items?q=remera&page=1',
|
||||||
|
'http://localhost:8000/api/tenants/demo/catalog-items/42?variant_id=3',
|
||||||
|
])('includes GET %s in the hydration transfer cache', (url) => {
|
||||||
|
expect(isStoreCatalogRequest(new HttpRequest('GET', url))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['GET', 'http://localhost:8000/api/tenants/demo/productos'],
|
||||||
|
['GET', 'http://localhost:8000/api/tenants/demo/categories/7'],
|
||||||
|
['GET', 'http://localhost:8000/api/tenants/demo/catalog-items/42/variant-options'],
|
||||||
|
['GET', 'http://localhost:8000/api/tenants/demo/catalogue'],
|
||||||
|
])('excludes %s %s from the hydration transfer cache', (method, url) => {
|
||||||
|
const request =
|
||||||
|
method === 'GET' ? new HttpRequest('GET', url) : new HttpRequest('POST', url, null);
|
||||||
|
|
||||||
|
expect(isStoreCatalogRequest(request)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import {
|
|||||||
provideAppInitializer,
|
provideAppInitializer,
|
||||||
provideBrowserGlobalErrorListeners,
|
provideBrowserGlobalErrorListeners,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter, UrlSerializer } from '@angular/router';
|
||||||
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
|
||||||
|
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -12,11 +12,14 @@ import { authBootstrap } from './core/services/auth/auth-bootstrap';
|
|||||||
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
import { authInterceptor } from './core/services/auth/auth.interceptor';
|
||||||
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
import { globalLoadingInterceptor } from './core/services/global-loading/global-loading.interceptor';
|
||||||
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
import { tenantBootstrap } from './core/services/tenant-bootstrap';
|
||||||
|
import { TenantUrlSerializer } from './core/services/tenant-url.serializer';
|
||||||
|
|
||||||
function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
export function isStoreCatalogRequest(request: HttpRequest<unknown>): boolean {
|
||||||
return (
|
return (
|
||||||
request.method === 'GET' &&
|
request.method === 'GET' &&
|
||||||
/\/api\/tenants\/[^/]+\/productos(?:\/\d+)?(?:\?|$)/.test(request.urlWithParams)
|
/\/api\/tenants\/[^/?#]+\/(?:catalog(?:\/featured-groups\/\d+\/items)?|catalog-items(?:\/\d+)?|events(?:\/\d+)?)\/?(?:[?#]|$)/.test(
|
||||||
|
request.urlWithParams,
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,6 +27,7 @@ export const appConfig: ApplicationConfig = {
|
|||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
|
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||||
provideClientHydration(
|
provideClientHydration(
|
||||||
withHttpTransferCacheOptions({
|
withHttpTransferCacheOptions({
|
||||||
includeRequestsWithAuthHeaders: true,
|
includeRequestsWithAuthHeaders: true,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { of } from 'rxjs';
|
|||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { AuthService } from './core/services/auth/auth.service';
|
import { AuthService } from './core/services/auth/auth.service';
|
||||||
import { CartService } from './core/services/cart/cart.service';
|
import { CartService } from './core/services/cart/cart.service';
|
||||||
|
import { CheckoutService } from './core/services/checkout.service';
|
||||||
import { Tenant } from './core/services/tenant.interface';
|
import { Tenant } from './core/services/tenant.interface';
|
||||||
import { TenantService } from './core/services/tenant.service';
|
import { TenantService } from './core/services/tenant.service';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
@@ -97,6 +98,21 @@ async function renderAppAt(
|
|||||||
{
|
{
|
||||||
provide: AuthService,
|
provide: AuthService,
|
||||||
useValue: authService
|
useValue: authService
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: CheckoutService,
|
||||||
|
useValue: {
|
||||||
|
withCustomLoading() {
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
getPurchase: vi.fn().mockResolvedValue({
|
||||||
|
id: 25,
|
||||||
|
status: 'created',
|
||||||
|
items: [],
|
||||||
|
subtotal: '0.00',
|
||||||
|
total: '0.00'
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
@@ -233,15 +249,46 @@ describe('app routes', () => {
|
|||||||
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('redirects unauthenticated users from /checkout to /login', async () => {
|
it('renders the tenant not found screen at / without redirecting to itself', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(false));
|
const { fixture, router } = await renderAppAt(
|
||||||
|
'/',
|
||||||
|
createTenantServiceStub('not-found', null),
|
||||||
|
createAuthServiceStub()
|
||||||
|
);
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
expect(router.url).toBe('/login?returnUrl=%2Fcheckout');
|
expect(router.url).toBe('/');
|
||||||
|
expect(compiled.querySelector('.tenant-status')).not.toBeNull();
|
||||||
|
expect(compiled.textContent).toContain('No encontramos una tienda para este dominio');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows authenticated users to access /checkout', async () => {
|
it('redirects unauthenticated users from /checkout/:id to /login', async () => {
|
||||||
const { router } = await renderAppAt('/checkout', createTenantServiceStub(), createAuthServiceStub(true));
|
const { router } = await renderAppAt('/checkout/25', createTenantServiceStub(), createAuthServiceStub(false));
|
||||||
|
|
||||||
expect(router.url).toBe('/checkout');
|
expect(router.url).toBe('/login?returnUrl=%2Fcheckout%2F25');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows authenticated users to access /checkout/:id', async () => {
|
||||||
|
const checkoutTenant = {
|
||||||
|
...tenant,
|
||||||
|
menues: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
code: 'checkout',
|
||||||
|
label: 'Checkout',
|
||||||
|
parent_menu_code: null,
|
||||||
|
content_type: 'dynamic' as const,
|
||||||
|
route: '/checkout',
|
||||||
|
submenues: []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
const { router } = await renderAppAt(
|
||||||
|
'/checkout/25',
|
||||||
|
createTenantServiceStub('ready', checkoutTenant),
|
||||||
|
createAuthServiceStub(true)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(router.url).toBe('/checkout/25');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,5 +14,12 @@ export const routes: Routes = [
|
|||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
loadChildren: () => import('./features/store/store.routes').then((m) => m.routes)
|
loadChildren: () => import('./features/store/store.routes').then((m) => m.routes)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '**',
|
||||||
|
loadComponent: () =>
|
||||||
|
import('./shared/pages/route-not-found-page.component').then(
|
||||||
|
(m) => m.RouteNotFoundPageComponent,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
.tenant-status__card {
|
.tenant-status__card {
|
||||||
width: min(100%, 34rem);
|
width: min(100%, 34rem);
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
border: 1px solid rgba(32, 32, 32, 0.1);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 1.5rem;
|
border-radius: 1.5rem;
|
||||||
background-color: rgba(255, 255, 255, 0.92);
|
background-color: rgba(255, 255, 255, 0.92);
|
||||||
box-shadow: 0 1.25rem 3rem rgba(0, 0, 0, 0.1);
|
box-shadow: 0 1.25rem 3rem rgba(0, 0, 0, 0.1);
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
.tenant-status__spinner {
|
.tenant-status__spinner {
|
||||||
width: 3rem;
|
width: 3rem;
|
||||||
height: 3rem;
|
height: 3rem;
|
||||||
border: 0.25rem solid rgba(32, 32, 32, 0.08);
|
border: 0.25rem solid var(--border-color);
|
||||||
border-top-color: var(--tenant-primary);
|
border-top-color: var(--tenant-primary);
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
animation: tenant-status-spin 0.8s linear infinite;
|
animation: tenant-status-spin 0.8s linear infinite;
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import '@angular/compiler';
|
import '@angular/compiler';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||||
import {
|
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
|
||||||
BrowserTestingModule,
|
|
||||||
platformBrowserTesting
|
|
||||||
} from '@angular/platform-browser/testing';
|
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
@@ -17,6 +14,8 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
site_title: 'Test Store',
|
||||||
|
favicon: 'https://example.com/favicon.png',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -25,7 +24,7 @@ const tenant: Tenant = {
|
|||||||
footer_bg_color: '#313131',
|
footer_bg_color: '#313131',
|
||||||
header_logo: 'https://example.com/header.png',
|
header_logo: 'https://example.com/header.png',
|
||||||
footer_logo: 'https://example.com/footer.png',
|
footer_logo: 'https://example.com/footer.png',
|
||||||
categories: []
|
categories: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: Tenant | null) {
|
function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: Tenant | null) {
|
||||||
@@ -36,17 +35,14 @@ function createTenantServiceStub(status: 'ready' | 'not-found', currentTenant: T
|
|||||||
tenant: tenantState.asReadonly(),
|
tenant: tenantState.asReadonly(),
|
||||||
status: statusState.asReadonly(),
|
status: statusState.asReadonly(),
|
||||||
getTenant: () => tenantState(),
|
getTenant: () => tenantState(),
|
||||||
bootstrap: vi.fn().mockResolvedValue(undefined)
|
bootstrap: vi.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('App', () => {
|
describe('App', () => {
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
try {
|
try {
|
||||||
getTestBed().initTestEnvironment(
|
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting());
|
||||||
BrowserTestingModule,
|
|
||||||
platformBrowserTesting()
|
|
||||||
);
|
|
||||||
} catch {
|
} catch {
|
||||||
// Test environment may already be initialized by another setup entrypoint.
|
// Test environment may already be initialized by another setup entrypoint.
|
||||||
}
|
}
|
||||||
@@ -63,9 +59,9 @@ describe('App', () => {
|
|||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: createTenantServiceStub('ready', tenant)
|
useValue: createTenantServiceStub('ready', tenant),
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
@@ -73,23 +69,32 @@ describe('App', () => {
|
|||||||
|
|
||||||
expect(fixture.componentInstance).toBeTruthy();
|
expect(fixture.componentInstance).toBeTruthy();
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary')).toBe(
|
||||||
tenant.primary_color
|
tenant.primary_color,
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary')).toBe(
|
||||||
tenant.secondary_color
|
tenant.secondary_color,
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger')).toBe(
|
||||||
tenant.danger_color
|
tenant.danger_color,
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-primary-rgb')).toBe(
|
||||||
'99, 118, 243'
|
'99, 118, 243',
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-secondary-rgb')).toBe(
|
||||||
'160, 160, 160'
|
'160, 160, 160',
|
||||||
);
|
);
|
||||||
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger-rgb')).toBe(
|
expect(fixture.nativeElement.style.getPropertyValue('--tenant-danger-rgb')).toBe(
|
||||||
'255, 136, 136'
|
'255, 136, 136',
|
||||||
);
|
);
|
||||||
|
expect(document.title).toBe(tenant.site_title);
|
||||||
|
expect(
|
||||||
|
document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'),
|
||||||
|
).toBe(tenant.favicon);
|
||||||
|
expect(
|
||||||
|
document.head
|
||||||
|
.querySelector<HTMLLinkElement>('link[rel~="icon"]')
|
||||||
|
?.getAttribute('fetchpriority'),
|
||||||
|
).toBe('high');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the tenant not found screen when the tenant is missing', async () => {
|
it('renders the tenant not found screen when the tenant is missing', async () => {
|
||||||
@@ -99,14 +104,25 @@ describe('App', () => {
|
|||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: createTenantServiceStub('not-found', null)
|
useValue: createTenantServiceStub('not-found', null),
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('No encontramos una tienda para este dominio');
|
expect(fixture.nativeElement.textContent).toContain(
|
||||||
|
'No encontramos una tienda para este dominio',
|
||||||
|
);
|
||||||
|
expect(document.title).toBe('ShopitFront');
|
||||||
|
expect(
|
||||||
|
document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.getAttribute('href'),
|
||||||
|
).toBe("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E");
|
||||||
|
expect(
|
||||||
|
document.head
|
||||||
|
.querySelector<HTMLLinkElement>('link[rel~="icon"]')
|
||||||
|
?.getAttribute('fetchpriority'),
|
||||||
|
).toBe('high');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Component, computed, inject } from '@angular/core';
|
import { DOCUMENT } from '@angular/common';
|
||||||
|
import { Component, computed, effect, inject } from '@angular/core';
|
||||||
|
import { Title } from '@angular/platform-browser';
|
||||||
import { RouterOutlet } from '@angular/router';
|
import { RouterOutlet } from '@angular/router';
|
||||||
|
|
||||||
import { TenantService } from './core/services/tenant.service';
|
import { TenantService } from './core/services/tenant.service';
|
||||||
@@ -7,9 +9,13 @@ import { GlobalLoadingComponent } from './shared/components/global-loading/globa
|
|||||||
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
import { ModalHostComponent } from './shared/components/modal-host/modal-host.component';
|
||||||
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
import { ToastContainerComponent } from './shared/components/toast-container/toast-container.component';
|
||||||
|
|
||||||
|
const EMPTY_FAVICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";
|
||||||
|
|
||||||
function hexToRgb(hex: string): string {
|
function hexToRgb(hex: string): string {
|
||||||
const cleanHex = hex.replace('#', '').trim();
|
const cleanHex = hex.replace('#', '').trim();
|
||||||
let r = 0, g = 0, b = 0;
|
let r = 0,
|
||||||
|
g = 0,
|
||||||
|
b = 0;
|
||||||
if (cleanHex.length === 3) {
|
if (cleanHex.length === 3) {
|
||||||
r = parseInt(cleanHex[0] + cleanHex[0], 16);
|
r = parseInt(cleanHex[0] + cleanHex[0], 16);
|
||||||
g = parseInt(cleanHex[1] + cleanHex[1], 16);
|
g = parseInt(cleanHex[1] + cleanHex[1], 16);
|
||||||
@@ -24,12 +30,7 @@ function hexToRgb(hex: string): string {
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
imports: [
|
imports: [RouterOutlet, ToastContainerComponent, ModalHostComponent, GlobalLoadingComponent],
|
||||||
RouterOutlet,
|
|
||||||
ToastContainerComponent,
|
|
||||||
ModalHostComponent,
|
|
||||||
GlobalLoadingComponent
|
|
||||||
],
|
|
||||||
templateUrl: './app.html',
|
templateUrl: './app.html',
|
||||||
styleUrl: './app.scss',
|
styleUrl: './app.scss',
|
||||||
host: {
|
host: {
|
||||||
@@ -52,46 +53,59 @@ function hexToRgb(hex: string): string {
|
|||||||
'[style.--tenant-header-bg]': 'tenantHeaderBgColor()',
|
'[style.--tenant-header-bg]': 'tenantHeaderBgColor()',
|
||||||
'[style.--tenant-footer-bg]': 'tenantFooterBgColor()',
|
'[style.--tenant-footer-bg]': 'tenantFooterBgColor()',
|
||||||
'[style.--color-header-bg]': 'tenantHeaderBgColor()',
|
'[style.--color-header-bg]': 'tenantHeaderBgColor()',
|
||||||
'[style.--color-footer-bg]': 'tenantFooterBgColor()'
|
'[style.--color-footer-bg]': 'tenantFooterBgColor()',
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
export class App {
|
export class App {
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
private readonly document = inject(DOCUMENT);
|
||||||
|
private readonly title = inject(Title);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const tenant = this.tenantService.tenant();
|
||||||
|
const siteTitle = tenant?.site_title?.trim() || 'ShopitFront';
|
||||||
|
const faviconHref = tenant?.favicon || EMPTY_FAVICON;
|
||||||
|
|
||||||
|
this.title.setTitle(siteTitle);
|
||||||
|
|
||||||
|
let favicon = this.document.head.querySelector<HTMLLinkElement>('link[rel~="icon"]');
|
||||||
|
|
||||||
|
if (!favicon) {
|
||||||
|
favicon = this.document.createElement('link');
|
||||||
|
favicon.setAttribute('rel', 'icon');
|
||||||
|
this.document.head.appendChild(favicon);
|
||||||
|
}
|
||||||
|
|
||||||
|
favicon.setAttribute('href', faviconHref);
|
||||||
|
favicon.setAttribute('fetchpriority', 'high');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected readonly status = this.tenantService.status;
|
protected readonly status = this.tenantService.status;
|
||||||
|
|
||||||
protected readonly tenantPrimaryColor = computed(
|
protected readonly tenantPrimaryColor = computed(
|
||||||
() => this.tenantService.tenant()?.primary_color ?? DEFAULT_TENANT_BRANDING.primaryColor
|
() => this.tenantService.tenant()?.primary_color ?? DEFAULT_TENANT_BRANDING.primaryColor,
|
||||||
);
|
);
|
||||||
protected readonly tenantSecondaryColor = computed(
|
protected readonly tenantSecondaryColor = computed(
|
||||||
() => this.tenantService.tenant()?.secondary_color ?? DEFAULT_TENANT_BRANDING.secondaryColor
|
() => this.tenantService.tenant()?.secondary_color ?? DEFAULT_TENANT_BRANDING.secondaryColor,
|
||||||
);
|
);
|
||||||
protected readonly tenantDangerColor = computed(
|
protected readonly tenantDangerColor = computed(
|
||||||
() => this.tenantService.tenant()?.danger_color ?? DEFAULT_TENANT_BRANDING.dangerColor
|
() => this.tenantService.tenant()?.danger_color ?? DEFAULT_TENANT_BRANDING.dangerColor,
|
||||||
);
|
);
|
||||||
protected readonly tenantSuccessColor = computed(
|
protected readonly tenantSuccessColor = computed(
|
||||||
() => this.tenantService.tenant()?.success_color ?? DEFAULT_TENANT_BRANDING.successColor
|
() => this.tenantService.tenant()?.success_color ?? DEFAULT_TENANT_BRANDING.successColor,
|
||||||
);
|
|
||||||
protected readonly tenantPrimaryColorRgb = computed(() =>
|
|
||||||
hexToRgb(this.tenantPrimaryColor())
|
|
||||||
);
|
);
|
||||||
|
protected readonly tenantPrimaryColorRgb = computed(() => hexToRgb(this.tenantPrimaryColor()));
|
||||||
protected readonly tenantSecondaryColorRgb = computed(() =>
|
protected readonly tenantSecondaryColorRgb = computed(() =>
|
||||||
hexToRgb(this.tenantSecondaryColor())
|
hexToRgb(this.tenantSecondaryColor()),
|
||||||
);
|
|
||||||
protected readonly tenantDangerColorRgb = computed(() =>
|
|
||||||
hexToRgb(this.tenantDangerColor())
|
|
||||||
);
|
|
||||||
protected readonly tenantSuccessColorRgb = computed(() =>
|
|
||||||
hexToRgb(this.tenantSuccessColor())
|
|
||||||
);
|
);
|
||||||
|
protected readonly tenantDangerColorRgb = computed(() => hexToRgb(this.tenantDangerColor()));
|
||||||
|
protected readonly tenantSuccessColorRgb = computed(() => hexToRgb(this.tenantSuccessColor()));
|
||||||
protected readonly tenantHeaderBgColor = computed(
|
protected readonly tenantHeaderBgColor = computed(
|
||||||
() =>
|
() => this.tenantService.tenant()?.header_bg_color ?? DEFAULT_TENANT_BRANDING.headerBgColor,
|
||||||
this.tenantService.tenant()?.header_bg_color ??
|
|
||||||
DEFAULT_TENANT_BRANDING.headerBgColor
|
|
||||||
);
|
);
|
||||||
protected readonly tenantFooterBgColor = computed(
|
protected readonly tenantFooterBgColor = computed(
|
||||||
() =>
|
() => this.tenantService.tenant()?.footer_bg_color ?? DEFAULT_TENANT_BRANDING.footerBgColor,
|
||||||
this.tenantService.tenant()?.footer_bg_color ??
|
|
||||||
DEFAULT_TENANT_BRANDING.footerBgColor
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
90
src/app/core/guards/menu.guard.spec.ts
Normal file
90
src/app/core/guards/menu.guard.spec.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter, Router, UrlSerializer, UrlTree } from '@angular/router';
|
||||||
|
|
||||||
|
import { Tenant } from '../services/tenant.interface';
|
||||||
|
import { TenantService } from '../services/tenant.service';
|
||||||
|
import { TenantUrlSerializer } from '../services/tenant-url.serializer';
|
||||||
|
import { hasMenuGuard } from './menu.guard';
|
||||||
|
|
||||||
|
const tenant: Tenant = {
|
||||||
|
id: 1,
|
||||||
|
codigo: 'test',
|
||||||
|
nombre: 'Test Tenant',
|
||||||
|
dominio: 'localhost',
|
||||||
|
primary_color: '#6376F3',
|
||||||
|
secondary_color: '#A0A0A0',
|
||||||
|
danger_color: '#FF8888',
|
||||||
|
success_color: '#198754',
|
||||||
|
header_bg_color: '#313131',
|
||||||
|
footer_bg_color: '#313131',
|
||||||
|
header_logo: 'https://example.com/header.png',
|
||||||
|
footer_logo: 'https://example.com/footer.png',
|
||||||
|
categories: [],
|
||||||
|
menues: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
code: 'index',
|
||||||
|
label: 'Inicio',
|
||||||
|
parent_menu_code: null,
|
||||||
|
content_type: 'dynamic',
|
||||||
|
route: '/',
|
||||||
|
submenues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
function runGuard(menuCode: string, url: string, currentTenant: Tenant | null) {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: { tenant: () => currentTenant, getTenant: () => currentTenant },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return TestBed.runInInjectionContext(() =>
|
||||||
|
hasMenuGuard(menuCode)(null as never, { url } as never),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('hasMenuGuard', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows a route exposed by the tenant menu', () => {
|
||||||
|
expect(runGuard('index', '/', tenant)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels navigation when the tenant is missing', () => {
|
||||||
|
expect(runGuard('index', '/', null)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('redirects a missing menu route to the store root', () => {
|
||||||
|
const result = runGuard('checkout', '/checkout/25', tenant);
|
||||||
|
|
||||||
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows the store root when its menu is missing to avoid a self-redirect', () => {
|
||||||
|
const tenantWithoutMenus = { ...tenant, menues: [] };
|
||||||
|
|
||||||
|
expect(runGuard('index', '/', tenantWithoutMenus)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows a tenant base path as the store root when its menu is missing', () => {
|
||||||
|
const tenantWithoutMenus = { ...tenant, base_path: '/onticket', menues: [] };
|
||||||
|
|
||||||
|
expect(runGuard('index', '/onticket', tenantWithoutMenus)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows a tenant base path with query parameters as the store root', () => {
|
||||||
|
const tenantWithoutMenus = { ...tenant, base_path: '/onticket', menues: [] };
|
||||||
|
|
||||||
|
expect(runGuard('index', '/onticket?ref=home', tenantWithoutMenus)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,22 +1,24 @@
|
|||||||
import { inject } from '@angular/core';
|
import { inject } from '@angular/core';
|
||||||
import { CanActivateFn, Router } from '@angular/router';
|
import { CanActivateFn, PRIMARY_OUTLET, Router } from '@angular/router';
|
||||||
import { findMenu } from '../services/menu.utils';
|
import { findMenu } from '../services/menu.utils';
|
||||||
import { TenantService } from '../services/tenant.service';
|
import { TenantService } from '../services/tenant.service';
|
||||||
|
|
||||||
export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
export const hasMenuGuard = (menuCode: string): CanActivateFn => {
|
||||||
return () => {
|
return (_route, state) => {
|
||||||
const tenantService = inject(TenantService);
|
const tenantService = inject(TenantService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
|
|
||||||
const tenant = tenantService.tenant();
|
const tenant = tenantService.tenant();
|
||||||
|
|
||||||
if (!tenant) {
|
if (!tenant) {
|
||||||
return router.createUrlTree(['/']);
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
const hasMenu = findMenu(tenant.menues ?? [], menuCode) !== undefined;
|
||||||
|
|
||||||
if (hasMenu) {
|
const primarySegments = router.parseUrl(state.url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
||||||
|
|
||||||
|
if (hasMenu || primarySegments.length === 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
<footer class="store-layout__footer mt-auto text-light">
|
<footer
|
||||||
|
class="store-layout__footer mt-auto text-light"
|
||||||
|
[style.background-image]="backgroundImageUrl ? 'url(' + backgroundImageUrl + ')' : null"
|
||||||
|
>
|
||||||
<div class="container-xl px-3 px-md-4 py-4 py-md-5 store-layout__footer-content">
|
<div class="container-xl px-3 px-md-4 py-4 py-md-5 store-layout__footer-content">
|
||||||
<div class="row g-4 store-layout__footer-grid">
|
<div class="row g-4 store-layout__footer-grid">
|
||||||
<div class="col-12 store-layout__brand-column">
|
<div class="col-12 store-layout__brand-column">
|
||||||
@@ -19,14 +22,18 @@
|
|||||||
|
|
||||||
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
<div class="col-12 col-md-6 col-xl-5 d-grid gap-3 align-content-start store-layout__contact">
|
||||||
<div class="d-grid gap-2 store-layout__contact-details">
|
<div class="d-grid gap-2 store-layout__contact-details">
|
||||||
<div class="d-flex align-items-center gap-2">
|
@if (address) {
|
||||||
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
<div class="d-flex align-items-center gap-2">
|
||||||
<span>Av. San Lorenzo 1542, Rosario</span>
|
<i class="fa-solid fa-location-dot" aria-hidden="true"></i>
|
||||||
</div>
|
<span>{{ address }}</span>
|
||||||
<div class="d-flex align-items-center gap-2">
|
</div>
|
||||||
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
}
|
||||||
<span>54 9 (0341) 6658247</span>
|
@if (phone) {
|
||||||
</div>
|
<div class="d-flex align-items-center gap-2">
|
||||||
|
<i class="fa-solid fa-phone" aria-hidden="true"></i>
|
||||||
|
<span>{{ phone }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
<p class="mb-0 small store-layout__muted-text store-layout__copyright">
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
.store-layout__footer {
|
.store-layout__footer {
|
||||||
background-color: var(--tenant-footer-bg);
|
background-color: var(--tenant-footer-bg);
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: center;
|
||||||
|
background-size: cover;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__mobile-divider {
|
.store-layout__mobile-divider {
|
||||||
@@ -7,21 +10,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
.store-layout__brand-slot {
|
||||||
width: min(100%, 12rem);
|
width: min(100%, 230px);
|
||||||
min-width: 10rem;
|
min-width: 10rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-logo-shell {
|
.store-layout__brand-logo-shell {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: min(100%, 12rem);
|
width: min(100%, 230px);
|
||||||
height: 2.75rem;
|
height: 65px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-logo {
|
.store-layout__brand-logo {
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: auto;
|
||||||
height: 100%;
|
height: auto;
|
||||||
max-height: 2.75rem;
|
max-width: 130px;
|
||||||
|
max-height: 65px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
object-position: left center;
|
object-position: left center;
|
||||||
}
|
}
|
||||||
@@ -46,7 +50,7 @@
|
|||||||
place-items: center;
|
place-items: center;
|
||||||
width: 2.75rem;
|
width: 2.75rem;
|
||||||
height: 2.75rem;
|
height: 2.75rem;
|
||||||
border: 1px dashed rgba(255, 255, 255, 0.35);
|
border: 1px dashed var(--border-color);
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
font-size: 1.05rem;
|
font-size: 1.05rem;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
@@ -67,7 +71,7 @@
|
|||||||
|
|
||||||
.store-layout__footer-link {
|
.store-layout__footer-link {
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
color: rgba(255, 255, 255, 0.72);
|
color: #ffffff;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
|
|
||||||
&:hover,
|
&:hover,
|
||||||
@@ -98,6 +102,7 @@
|
|||||||
@media (max-width: 767.98px) {
|
@media (max-width: 767.98px) {
|
||||||
.store-layout__footer-content {
|
.store-layout__footer-content {
|
||||||
padding: 1.45rem 2.5rem 1.8rem !important;
|
padding: 1.45rem 2.5rem 1.8rem !important;
|
||||||
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__footer-grid {
|
.store-layout__footer-grid {
|
||||||
@@ -117,7 +122,6 @@
|
|||||||
order: 1;
|
order: 1;
|
||||||
width: auto;
|
width: auto;
|
||||||
padding-bottom: 1.65rem;
|
padding-bottom: 1.65rem;
|
||||||
font-size: 0.72rem;
|
|
||||||
line-height: 1.25;
|
line-height: 1.25;
|
||||||
|
|
||||||
&:nth-of-type(even) {
|
&:nth-of-type(even) {
|
||||||
@@ -133,8 +137,8 @@
|
|||||||
display: block;
|
display: block;
|
||||||
order: 2;
|
order: 2;
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
width: 100vw;
|
width: 100%;
|
||||||
border-top: 1px solid rgba(255, 255, 255, 0.3);
|
border-top: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-column,
|
.store-layout__brand-column,
|
||||||
@@ -145,21 +149,21 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
.store-layout__brand-slot {
|
||||||
width: min(100%, 7.75rem);
|
width: min(100%, 150px);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-logo {
|
.store-layout__brand-logo {
|
||||||
max-height: 2.5rem;
|
max-height: 55px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-logo-shell {
|
.store-layout__brand-logo-shell {
|
||||||
width: min(100%, 7.75rem);
|
width: min(100%, 150px);
|
||||||
height: 2.5rem;
|
height: 55px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-text {
|
.store-layout__brand-text {
|
||||||
font-size: 1.45rem;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__social-column {
|
.store-layout__social-column {
|
||||||
@@ -183,11 +187,10 @@
|
|||||||
.store-layout__contact-details {
|
.store-layout__contact-details {
|
||||||
justify-items: center;
|
justify-items: center;
|
||||||
gap: 0.4rem !important;
|
gap: 0.4rem !important;
|
||||||
font-size: 0.7rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__copyright {
|
.store-layout__copyright {
|
||||||
font-size: 0.6rem;
|
font-size: 11px;
|
||||||
line-height: 1.3;
|
line-height: 1.3;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ export class StoreFooterComponent {
|
|||||||
@Input({ required: true }) footerSections: StoreFooterSection[] = [];
|
@Input({ required: true }) footerSections: StoreFooterSection[] = [];
|
||||||
@Input({ required: true }) socialMedia: SocialMedia[] = [];
|
@Input({ required: true }) socialMedia: SocialMedia[] = [];
|
||||||
@Input() logoUrl: string | null = null;
|
@Input() logoUrl: string | null = null;
|
||||||
|
@Input() backgroundImageUrl: string | null = null;
|
||||||
@Input() storeName: string | null = null;
|
@Input() storeName: string | null = null;
|
||||||
|
@Input() address: string | null = null;
|
||||||
|
@Input() phone: string | null = null;
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
<header class="immersive-header" [class.immersive-header--compact]="!showHero()">
|
||||||
|
<div class="immersive-header__backdrop">
|
||||||
|
@if (showHero() && backgroundImageUrl(); as backgroundImage) {
|
||||||
|
<img
|
||||||
|
class="immersive-header__backdrop-image"
|
||||||
|
[src]="backgroundImage"
|
||||||
|
alt=""
|
||||||
|
loading="eager"
|
||||||
|
fetchpriority="high"
|
||||||
|
decoding="async"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="immersive-header__content">
|
||||||
|
<nav
|
||||||
|
class="immersive-header__nav container-xl px-3 px-md-4"
|
||||||
|
aria-label="Navegación de la tienda"
|
||||||
|
>
|
||||||
|
<a routerLink="/" class="immersive-header__brand" aria-label="Ir al inicio">
|
||||||
|
@if (logoUrl()) {
|
||||||
|
<img
|
||||||
|
[src]="logoUrl()"
|
||||||
|
alt="Logo del comercio"
|
||||||
|
loading="eager"
|
||||||
|
fetchpriority="high"
|
||||||
|
decoding="async"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<div class="immersive-header__actions">
|
||||||
|
@if (displaySearchBar()) {
|
||||||
|
<form class="immersive-header__search" role="search" (submit)="submitSearch($event)">
|
||||||
|
<label class="visually-hidden" for="immersive-search-input">Buscar productos</label>
|
||||||
|
<app-input
|
||||||
|
id="immersive-search-input"
|
||||||
|
placeholder="Buscar"
|
||||||
|
type="search"
|
||||||
|
[(value)]="searchTerm"
|
||||||
|
[invalid]="showSearchError()"
|
||||||
|
(valueChange)="showSearchError.set(false)"
|
||||||
|
/>
|
||||||
|
@if (showSearchError()) {
|
||||||
|
<span id="immersive-search-error" class="immersive-header__search-error" role="alert"
|
||||||
|
>Ingresá al menos 3 caracteres.</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (ticketsMenu(); as menu) {
|
||||||
|
<app-button
|
||||||
|
variant="secondary"
|
||||||
|
hostClass="immersive-header__tickets"
|
||||||
|
(click)="ticketsClick.emit()"
|
||||||
|
>
|
||||||
|
{{ menu.label }}
|
||||||
|
</app-button>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (displayCart()) {
|
||||||
|
<app-cart-icon
|
||||||
|
[quantity]="cartDisabled() ? null : cartQuantity()"
|
||||||
|
[disabled]="cartDisabled()"
|
||||||
|
[ariaLabel]="
|
||||||
|
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
||||||
|
"
|
||||||
|
(click)="onCartClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="immersive-header__account">
|
||||||
|
<app-icon-button
|
||||||
|
variant="user"
|
||||||
|
ariaLabel="Mi cuenta"
|
||||||
|
ariaControls="immersive-user-dropdown"
|
||||||
|
[ariaExpanded]="isUserDropdownOpen()"
|
||||||
|
(clicked)="toggleUserDropdown()"
|
||||||
|
/>
|
||||||
|
@if (isUserDropdownOpen()) {
|
||||||
|
<app-user-dropdown
|
||||||
|
id="immersive-user-dropdown"
|
||||||
|
[user]="user()"
|
||||||
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
|
(logoutClick)="onLogoutClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
@if (checkoutRemainingTime(); as remainingTime) {
|
||||||
|
<div
|
||||||
|
class="immersive-header__timer container-xl px-3 px-md-4"
|
||||||
|
role="timer"
|
||||||
|
aria-label="Tiempo restante de compra"
|
||||||
|
>
|
||||||
|
Tiempo restante de compra: <strong>{{ remainingTime }}</strong>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (showHero()) {
|
||||||
|
@if (heroContent(); as content) {
|
||||||
|
<div class="immersive-header__copy">
|
||||||
|
<p class="immersive-header__eyebrow">{{ content.eyebrow }}</p>
|
||||||
|
<h1 class="immersive-header__title">{{ content.title }}</h1>
|
||||||
|
<p class="immersive-header__description">{{ content.description }}</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (carouselImages().length) {
|
||||||
|
<app-continuous-image-carousel
|
||||||
|
[images]="carouselImages()"
|
||||||
|
ariaLabel="Imágenes del evento"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header {
|
||||||
|
position: relative;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
isolation: isolate;
|
||||||
|
min-height: 640px;
|
||||||
|
color: #fff;
|
||||||
|
background: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__content {
|
||||||
|
grid-area: 1 / 1;
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
min-width: 0;
|
||||||
|
padding-top: clamp(1.75rem, 4vw, 2.5rem);
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__backdrop {
|
||||||
|
grid-area: 1 / 1;
|
||||||
|
position: relative;
|
||||||
|
z-index: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
background-color: #101010;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__backdrop-image {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 0;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
object-position: center 42%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__backdrop::before,
|
||||||
|
.immersive-header__backdrop::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__backdrop::before {
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__backdrop::after {
|
||||||
|
background: linear-gradient(180deg, rgba(0, 0, 0, 0.48) 0%, rgba(0, 0, 0, 0.4) 47%, #f5f5f5 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__nav {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1.5rem;
|
||||||
|
min-height: 2.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__brand {
|
||||||
|
display: inline-flex;
|
||||||
|
flex: none;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.immersive-header__brand img {
|
||||||
|
display: block;
|
||||||
|
width: clamp(105px, 13vw, 145px);
|
||||||
|
max-height: 2.25rem;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
.immersive-header__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: clamp(0.35rem, 1vw, 1rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__search {
|
||||||
|
position: relative;
|
||||||
|
width: clamp(115px, 17vw, 205px);
|
||||||
|
}
|
||||||
|
.immersive-header__search-error {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 0.25rem);
|
||||||
|
right: 0;
|
||||||
|
width: max-content;
|
||||||
|
color: var(--tenant-danger, #dc3545);
|
||||||
|
font-size: 0.7rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host ::ng-deep .immersive-header__tickets {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
.immersive-header__account {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
.immersive-header__account app-user-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
right: 0;
|
||||||
|
z-index: 20;
|
||||||
|
color: #222;
|
||||||
|
}
|
||||||
|
:host ::ng-deep .immersive-header__actions .icon-btn,
|
||||||
|
:host ::ng-deep .immersive-header__actions .cart-icon {
|
||||||
|
color: var(--tenant-primary, #ff7006);
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header__copy {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
margin: clamp(2.1rem, 5vw, 3.25rem) auto 0;
|
||||||
|
padding-inline: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.immersive-header__eyebrow,
|
||||||
|
.immersive-header__title {
|
||||||
|
font-family: 'Smooch', cursive;
|
||||||
|
font-weight: 400;
|
||||||
|
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.55);
|
||||||
|
}
|
||||||
|
.immersive-header__eyebrow {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 50px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.immersive-header__title {
|
||||||
|
margin: -0.15rem 0 0;
|
||||||
|
font-size: 140px;
|
||||||
|
line-height: 1.05;
|
||||||
|
}
|
||||||
|
.immersive-header__description {
|
||||||
|
margin: 1.15rem 0 0;
|
||||||
|
font-size: clamp(0.75rem, 1.4vw, 0.95rem);
|
||||||
|
text-shadow: 0 1px 5px rgba(0, 0, 0, 0.6);
|
||||||
|
}
|
||||||
|
.immersive-header__timer {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
text-align: right;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.immersive-header app-continuous-image-carousel {
|
||||||
|
display: block;
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
margin-top: clamp(3.25rem, 7vw, 5rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-header--compact {
|
||||||
|
min-height: 0;
|
||||||
|
padding-bottom: 1.5rem;
|
||||||
|
color: #666666;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.immersive-header--compact .immersive-header__backdrop {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host ::ng-deep .immersive-header--compact .immersive-header__actions .icon-btn,
|
||||||
|
:host ::ng-deep .immersive-header--compact .immersive-header__actions .cart-icon {
|
||||||
|
color: #666666;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.immersive-header__nav {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
.immersive-header__actions {
|
||||||
|
flex: 1;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
.immersive-header__search {
|
||||||
|
width: clamp(105px, 38vw, 180px);
|
||||||
|
}
|
||||||
|
.immersive-header__copy {
|
||||||
|
margin-top: 3rem;
|
||||||
|
}
|
||||||
|
.immersive-header__eyebrow {
|
||||||
|
font-size: clamp(2rem, 8vw, 50px);
|
||||||
|
}
|
||||||
|
.immersive-header__title {
|
||||||
|
font-size: clamp(3rem, 12vw, 5rem);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import {
|
||||||
|
Component,
|
||||||
|
ElementRef,
|
||||||
|
HostListener,
|
||||||
|
computed,
|
||||||
|
inject,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
signal,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
|
import { Menu, WebsiteExtras } from '../../../services/tenant.interface';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||||
|
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
||||||
|
import { InputComponent } from '../../../../shared/components/input/input.component';
|
||||||
|
import { ContinuousImageCarouselComponent } from '../../../../shared/components/continuous-image-carousel/continuous-image-carousel.component';
|
||||||
|
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-immersive-store-header',
|
||||||
|
imports: [
|
||||||
|
RouterLink,
|
||||||
|
ButtonComponent,
|
||||||
|
CartIconComponent,
|
||||||
|
IconButtonComponent,
|
||||||
|
InputComponent,
|
||||||
|
ContinuousImageCarouselComponent,
|
||||||
|
UserDropdownComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './immersive-store-header.component.html',
|
||||||
|
styleUrl: './immersive-store-header.component.scss',
|
||||||
|
})
|
||||||
|
export class ImmersiveStoreHeaderComponent {
|
||||||
|
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||||
|
|
||||||
|
readonly logoUrl = input<string | null>(null);
|
||||||
|
readonly backgroundImageUrl = input<string | null>(null);
|
||||||
|
readonly heroContent = input<WebsiteExtras['immersiveHero']>(undefined);
|
||||||
|
readonly carouselImages = input<readonly string[]>([]);
|
||||||
|
readonly showHero = input(true);
|
||||||
|
readonly cartQuantity = input(0);
|
||||||
|
readonly user = input<AuthUser | null>(null);
|
||||||
|
readonly isAuthenticated = input(false);
|
||||||
|
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
||||||
|
readonly ticketsMenu = input<Menu | null>(null);
|
||||||
|
readonly displaySearchBar = input(true);
|
||||||
|
readonly displayCart = input(true);
|
||||||
|
readonly cartDisabled = input(false);
|
||||||
|
readonly checkoutRemainingSeconds = input<number | null>(null);
|
||||||
|
|
||||||
|
readonly cartClick = output<void>();
|
||||||
|
readonly ticketsClick = output<void>();
|
||||||
|
readonly loginClick = output<void>();
|
||||||
|
readonly logoutClick = output<void>();
|
||||||
|
readonly searchSubmit = output<string>();
|
||||||
|
|
||||||
|
protected searchTerm = '';
|
||||||
|
protected readonly showSearchError = signal(false);
|
||||||
|
protected readonly isUserDropdownOpen = signal(false);
|
||||||
|
protected readonly checkoutRemainingTime = computed(() => {
|
||||||
|
const seconds = this.checkoutRemainingSeconds();
|
||||||
|
if (seconds === null) return null;
|
||||||
|
|
||||||
|
return `${Math.floor(seconds / 60)
|
||||||
|
.toString()
|
||||||
|
.padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
protected submitSearch(event?: Event): void {
|
||||||
|
event?.preventDefault();
|
||||||
|
const term = this.searchTerm.trim();
|
||||||
|
if (term.length < 3) {
|
||||||
|
this.showSearchError.set(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.showSearchError.set(false);
|
||||||
|
this.searchSubmit.emit(term);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleUserDropdown(): void {
|
||||||
|
if (!this.isAuthenticated()) {
|
||||||
|
this.loginClick.emit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.isUserDropdownOpen.update((open) => !open);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onCartClick(): void {
|
||||||
|
if (!this.cartDisabled()) this.cartClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onLogoutClick(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.logoutClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:click', ['$event'])
|
||||||
|
protected onDocumentClick(event: MouseEvent): void {
|
||||||
|
if (event.target instanceof Node && !this.host.nativeElement.contains(event.target)) {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:keydown.escape')
|
||||||
|
protected onEscapeKey(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
<header
|
||||||
|
class="store-layout__header"
|
||||||
|
[style.background-image]="backgroundImageUrl() ? 'url(' + backgroundImageUrl() + ')' : null"
|
||||||
|
>
|
||||||
|
<div class="store-layout__header-main">
|
||||||
|
<div class="container-xl px-3 px-md-4 py-3 py-lg-4">
|
||||||
|
<div class="row align-items-center gy-3 gy-md-0">
|
||||||
|
<div class="col-auto col-md-auto order-1 store-layout__brand-column">
|
||||||
|
<a
|
||||||
|
routerLink="/"
|
||||||
|
class="store-layout__brand-slot d-inline-flex align-items-center gap-3 text-decoration-none"
|
||||||
|
data-testid="store-header-brand-slot"
|
||||||
|
aria-label="Logo del comercio"
|
||||||
|
>
|
||||||
|
@if (logoUrl()) {
|
||||||
|
<img
|
||||||
|
class="store-layout__brand-logo"
|
||||||
|
[src]="logoUrl()"
|
||||||
|
alt="Logo del comercio"
|
||||||
|
loading="eager"
|
||||||
|
fetchpriority="high"
|
||||||
|
decoding="async"
|
||||||
|
/>
|
||||||
|
} @else {
|
||||||
|
<div class="store-layout__brand-logo-shell" aria-hidden="true">
|
||||||
|
<span class="store-layout__brand-logo-skeleton"></span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (displaySeachBar()) {
|
||||||
|
<div class="col-12 px-0 d-md-none order-3">
|
||||||
|
<hr class="store-layout__mobile-separator" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-12 col-md order-4 order-md-2">
|
||||||
|
<div class="store-layout__search-wrapper ms-md-auto">
|
||||||
|
<div class="input-group store-layout__search" role="search">
|
||||||
|
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
||||||
|
<input
|
||||||
|
id="store-search-input"
|
||||||
|
type="search"
|
||||||
|
class="form-control store-layout__search-input border-end-0 rounded-start"
|
||||||
|
placeholder="Buscar productos"
|
||||||
|
autocomplete="off"
|
||||||
|
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
||||||
|
[attr.aria-invalid]="showSearchError()"
|
||||||
|
[minlength]="minSearchLength"
|
||||||
|
[formControl]="searchControl"
|
||||||
|
(input)="clearSearchError()"
|
||||||
|
(keydown.enter)="submitSearch($event)"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
||||||
|
aria-label="Buscar"
|
||||||
|
(click)="submitSearch()"
|
||||||
|
>
|
||||||
|
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if (showSearchError()) {
|
||||||
|
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
||||||
|
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3"
|
||||||
|
>
|
||||||
|
@if (ticketsMenu(); as menu) {
|
||||||
|
<app-button
|
||||||
|
variant="primary"
|
||||||
|
hostClass="store-layout__tickets-btn-host"
|
||||||
|
data-testid="store-header-tickets"
|
||||||
|
(click)="ticketsClick.emit()"
|
||||||
|
>
|
||||||
|
{{ menu.label }}
|
||||||
|
</app-button>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (displayCart()) {
|
||||||
|
<app-cart-icon
|
||||||
|
[quantity]="cartDisabled() ? null : cartQuantity()"
|
||||||
|
[disabled]="cartDisabled()"
|
||||||
|
[ariaLabel]="
|
||||||
|
cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito de compras'
|
||||||
|
"
|
||||||
|
[title]="cartDisabled() ? 'Carrito no disponible durante el checkout' : 'Carrito'"
|
||||||
|
(click)="onCartClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="store-layout__user-menu d-none d-md-inline-flex position-relative">
|
||||||
|
<app-icon-button
|
||||||
|
variant="user"
|
||||||
|
ariaLabel="Mi cuenta"
|
||||||
|
ariaControls="store-user-dropdown"
|
||||||
|
[ariaExpanded]="isUserDropdownOpen()"
|
||||||
|
title="Mi cuenta"
|
||||||
|
(clicked)="toggleUserDropdown()"
|
||||||
|
/>
|
||||||
|
|
||||||
|
@if (isUserDropdownOpen()) {
|
||||||
|
<app-user-dropdown
|
||||||
|
id="store-user-dropdown"
|
||||||
|
[user]="user()"
|
||||||
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
|
(logoutClick)="onLogoutClick()"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="store-layout__mobile-menu d-inline-flex d-md-none position-relative">
|
||||||
|
<app-icon-button
|
||||||
|
variant="bars"
|
||||||
|
ariaLabel="Menu"
|
||||||
|
ariaControls="store-mobile-menu"
|
||||||
|
[ariaExpanded]="isMobileMenuOpen()"
|
||||||
|
title="Menu"
|
||||||
|
(clicked)="toggleMobileMenu()"
|
||||||
|
/>
|
||||||
|
|
||||||
|
@if (isMobileMenuOpen()) {
|
||||||
|
<div
|
||||||
|
id="store-mobile-menu"
|
||||||
|
class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu"
|
||||||
|
>
|
||||||
|
<a
|
||||||
|
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||||
|
(click)="onMobileAccountClick()"
|
||||||
|
>
|
||||||
|
<i class="fa-regular fa-circle-user fa-lg"></i>
|
||||||
|
<span class="fw-medium">Mi cuenta</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
@if (displayCategories()) {
|
||||||
|
<hr class="my-1 border-secondary opacity-25" />
|
||||||
|
|
||||||
|
@for (category of categories(); track category.id) {
|
||||||
|
<a
|
||||||
|
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
||||||
|
(click)="onCategorySelect(category)"
|
||||||
|
>
|
||||||
|
<span class="fw-medium">{{ category.nombre }}</span>
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="store-layout__categories d-none d-md-block">
|
||||||
|
<div class="container-xl h-100 px-3 px-md-4 d-flex align-items-center">
|
||||||
|
@if (displayCategories()) {
|
||||||
|
<div class="store-layout__category-menu">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-3 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
||||||
|
aria-label="Categorias"
|
||||||
|
aria-controls="store-category-dropdown"
|
||||||
|
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
||||||
|
(click)="toggleCategoryDropdown()"
|
||||||
|
>
|
||||||
|
<span>Categorias</span>
|
||||||
|
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<app-category-dropdown
|
||||||
|
id="store-category-dropdown"
|
||||||
|
[categories]="categories()"
|
||||||
|
[open]="isCategoryDropdownOpen()"
|
||||||
|
(categorySelect)="onCategorySelect($event)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (checkoutRemainingTime(); as remainingTime) {
|
||||||
|
<div
|
||||||
|
class="store-layout__checkout-timer ms-auto d-none d-md-flex align-items-baseline gap-3"
|
||||||
|
role="timer"
|
||||||
|
aria-label="Tiempo restante de compra"
|
||||||
|
>
|
||||||
|
<span class="store-layout__checkout-timer-label">Tiempo restante de compra:</span>
|
||||||
|
<span class="store-layout__checkout-timer-value">{{ remainingTime }}</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
.store-layout__header {
|
||||||
|
color: #ffffff;
|
||||||
|
background-color: var(--tenant-header-bg);
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: center;
|
||||||
|
background-size: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__header-main {
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__categories {
|
||||||
|
height: 3.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer {
|
||||||
|
color: var(--tenant-primary);
|
||||||
|
font-weight: 700;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer-label {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__checkout-timer-value {
|
||||||
|
font-size: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
min-width: 150px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-column {
|
||||||
|
max-width: 12rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-logo-shell {
|
||||||
|
position: relative;
|
||||||
|
width: min(100%, 12rem);
|
||||||
|
height: 2.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-logo {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-logo-skeleton {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
rgba(255, 255, 255, 0.12) 0%,
|
||||||
|
rgba(255, 255, 255, 0.22) 50%,
|
||||||
|
rgba(255, 255, 255, 0.12) 100%
|
||||||
|
);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: store-header-logo-skeleton 1.2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-wrapper {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.store-layout__search-wrapper {
|
||||||
|
width: min(100%, 260px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host {
|
||||||
|
flex: 0 0 clamp(8rem, 15vw, 13.5rem);
|
||||||
|
width: clamp(8rem, 15vw, 13.5rem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-error {
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.2;
|
||||||
|
color: var(--tenant-danger, #dc3545);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-input {
|
||||||
|
color: #666666;
|
||||||
|
border-color: var(--border-color);
|
||||||
|
background-color: rgba(255, 255, 255, 0.96);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-input::placeholder {
|
||||||
|
color: #666666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-input:focus {
|
||||||
|
border-color: var(--border-color);
|
||||||
|
box-shadow: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-button {
|
||||||
|
color: #a0a0a0;
|
||||||
|
border-color: var(--border-color);
|
||||||
|
background-color: rgba(255, 255, 255, 0.96);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__search-button:hover,
|
||||||
|
.store-layout__search-button:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
border-color: var(--border-color);
|
||||||
|
background-color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__action-button {
|
||||||
|
color: #a0a0a0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__action-button:hover,
|
||||||
|
.store-layout__action-button:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__user-menu {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-trigger {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
color: #a0a0a0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-trigger:hover,
|
||||||
|
.store-layout__category-trigger:focus-visible {
|
||||||
|
color: #8a8a8a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-menu {
|
||||||
|
position: relative;
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__category-menu app-category-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 1050;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes store-header-logo-skeleton {
|
||||||
|
from {
|
||||||
|
background-position: 200% 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
background-position: -200% 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 150px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host {
|
||||||
|
flex: 1 1 0;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 50vw;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-separator {
|
||||||
|
border-color: var(--border-color);
|
||||||
|
opacity: 1;
|
||||||
|
margin: 0 -1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 399.98px) {
|
||||||
|
.store-layout__brand-column {
|
||||||
|
flex: 1 1 0;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: none;
|
||||||
|
padding-right: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__brand-slot {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 6.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__actions-column {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
margin-left: 0 !important;
|
||||||
|
padding-left: 0.25rem;
|
||||||
|
gap: 0.25rem !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .store-layout__tickets-btn-host .btn {
|
||||||
|
padding-inline: 0.75rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-dropdown-menu {
|
||||||
|
top: 100%;
|
||||||
|
min-width: 220px;
|
||||||
|
z-index: 1050;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-layout__mobile-dropdown-item {
|
||||||
|
cursor: pointer;
|
||||||
|
color: #8a8a8a;
|
||||||
|
|
||||||
|
&:hover,
|
||||||
|
&:focus-visible {
|
||||||
|
color: #666666;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import {
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
ElementRef,
|
||||||
|
HostListener,
|
||||||
|
inject,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
signal,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { Router, RouterLink } from '@angular/router';
|
||||||
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
|
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
||||||
|
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
||||||
|
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
||||||
|
import { Menu } from '../../../services/tenant.interface';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
||||||
|
import { ReactiveFormsModule, FormControl } from '@angular/forms';
|
||||||
|
import { Category } from '../../../services/tenant.interface';
|
||||||
|
import { CategoryDropdownComponent } from './category-dropdown/category-dropdown.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-standard-store-header',
|
||||||
|
imports: [
|
||||||
|
ButtonComponent,
|
||||||
|
CartIconComponent,
|
||||||
|
IconButtonComponent,
|
||||||
|
RouterLink,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
UserDropdownComponent,
|
||||||
|
CategoryDropdownComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './standard-store-header.component.html',
|
||||||
|
styleUrl: './standard-store-header.component.scss',
|
||||||
|
})
|
||||||
|
export class StandardStoreHeaderComponent {
|
||||||
|
private readonly elementRef = inject(ElementRef<HTMLElement>);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
|
||||||
|
readonly logoUrl = input<string | null>(null);
|
||||||
|
readonly backgroundImageUrl = input<string | null>(null);
|
||||||
|
readonly cartQuantity = input<number>(0);
|
||||||
|
readonly user = input<AuthUser | null>(null);
|
||||||
|
readonly isAuthenticated = input<boolean>(false);
|
||||||
|
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
||||||
|
readonly ticketsMenu = input<Menu | null>(null);
|
||||||
|
readonly categories = input<readonly Category[]>([]);
|
||||||
|
readonly displayCategories = input(true);
|
||||||
|
readonly displaySeachBar = input(true);
|
||||||
|
readonly displayCart = input(true);
|
||||||
|
readonly cartDisabled = input(false);
|
||||||
|
readonly checkoutRemainingSeconds = input<number | null>(null);
|
||||||
|
readonly cartClick = output<void>();
|
||||||
|
readonly ticketsClick = output<void>();
|
||||||
|
readonly loginClick = output<void>();
|
||||||
|
readonly logoutClick = output<void>();
|
||||||
|
readonly searchSubmit = output<string>();
|
||||||
|
readonly categorySelect = output<Category>();
|
||||||
|
|
||||||
|
protected readonly isUserDropdownOpen = signal(false);
|
||||||
|
protected readonly isCategoryDropdownOpen = signal(false);
|
||||||
|
protected readonly isMobileMenuOpen = signal(false);
|
||||||
|
protected readonly minSearchLength = 3;
|
||||||
|
protected readonly showSearchError = signal(false);
|
||||||
|
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
||||||
|
protected readonly checkoutRemainingTime = computed(() => {
|
||||||
|
const remainingSeconds = this.checkoutRemainingSeconds();
|
||||||
|
|
||||||
|
if (remainingSeconds === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const minutes = Math.floor(remainingSeconds / 60);
|
||||||
|
const seconds = remainingSeconds % 60;
|
||||||
|
|
||||||
|
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
protected onCartClick(): void {
|
||||||
|
if (this.cartDisabled()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cartClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:click', ['$event'])
|
||||||
|
protected onDocumentClick(event: MouseEvent): void {
|
||||||
|
if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = event.target;
|
||||||
|
if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@HostListener('document:keydown.escape')
|
||||||
|
protected onEscapeKey(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleUserDropdown(): void {
|
||||||
|
if (!this.isAuthenticated()) {
|
||||||
|
this.loginClick.emit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isUserDropdownOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onLoginClick(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.loginClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onLogoutClick(): void {
|
||||||
|
this.isUserDropdownOpen.set(false);
|
||||||
|
this.logoutClick.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected submitSearch(event?: Event): void {
|
||||||
|
event?.preventDefault();
|
||||||
|
|
||||||
|
const term = this.searchControl.value.trim();
|
||||||
|
|
||||||
|
if (term.length < this.minSearchLength) {
|
||||||
|
this.showSearchError.set(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.showSearchError.set(false);
|
||||||
|
this.searchSubmit.emit(term);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected clearSearchError(): void {
|
||||||
|
this.showSearchError.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleCategoryDropdown(): void {
|
||||||
|
this.isCategoryDropdownOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onCategorySelect(category: Category): void {
|
||||||
|
this.isCategoryDropdownOpen.set(false);
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
this.categorySelect.emit(category);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toggleMobileMenu(): void {
|
||||||
|
this.isMobileMenuOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected onMobileAccountClick(): void {
|
||||||
|
this.isMobileMenuOpen.set(false);
|
||||||
|
if (!this.isAuthenticated()) {
|
||||||
|
this.loginClick.emit();
|
||||||
|
} else {
|
||||||
|
const menus = this.accountNavigationMenus();
|
||||||
|
if (menus.length > 0) {
|
||||||
|
this.router.navigate([menus[0].route]);
|
||||||
|
} else {
|
||||||
|
this.router.navigate(['/cuenta']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,162 +1,68 @@
|
|||||||
<header class="store-layout__header">
|
@switch (headerType()) {
|
||||||
<div class="store-layout__header-main">
|
@case ('immersive') {
|
||||||
<div class="container-xl px-3 px-md-4 py-3 py-lg-4">
|
<app-immersive-store-header
|
||||||
<div class="row align-items-center gy-3 gy-md-0">
|
[logoUrl]="logoUrl()"
|
||||||
<div class="col-auto col-md-auto order-1 store-layout__brand-column">
|
[backgroundImageUrl]="backgroundImageUrl()"
|
||||||
<a
|
[heroContent]="heroContent()"
|
||||||
routerLink="/"
|
[carouselImages]="carouselImages()"
|
||||||
class="store-layout__brand-slot d-inline-flex align-items-center gap-3 text-decoration-none"
|
[showHero]="showHero()"
|
||||||
data-testid="store-header-brand-slot"
|
[cartQuantity]="cartQuantity()"
|
||||||
aria-label="Logo del comercio"
|
[user]="user()"
|
||||||
>
|
[isAuthenticated]="isAuthenticated()"
|
||||||
@if (logoUrl()) {
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
<img class="store-layout__brand-logo" [src]="logoUrl()" alt="Logo del comercio" />
|
[ticketsMenu]="ticketsMenu()"
|
||||||
} @else {
|
[displaySearchBar]="displaySeachBar()"
|
||||||
<div class="store-layout__brand-logo-shell" aria-hidden="true">
|
[displayCart]="displayCart()"
|
||||||
<span class="store-layout__brand-logo-skeleton"></span>
|
[cartDisabled]="cartDisabled()"
|
||||||
</div>
|
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
||||||
}
|
(cartClick)="cartClick.emit()"
|
||||||
</a>
|
(ticketsClick)="ticketsClick.emit()"
|
||||||
</div>
|
(loginClick)="loginClick.emit()"
|
||||||
|
(logoutClick)="logoutClick.emit()"
|
||||||
|
(searchSubmit)="searchSubmit.emit($event)"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
@default {
|
||||||
|
<ng-container *ngTemplateOutlet="standardHeader" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
<div class="col-12 px-0 d-md-none order-3">
|
<ng-template #standardHeader>
|
||||||
<hr class="store-layout__mobile-separator">
|
<app-standard-store-header
|
||||||
</div>
|
[logoUrl]="logoUrl()"
|
||||||
|
[backgroundImageUrl]="backgroundImageUrl()"
|
||||||
|
[cartQuantity]="cartQuantity()"
|
||||||
|
[user]="user()"
|
||||||
|
[isAuthenticated]="isAuthenticated()"
|
||||||
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
|
[ticketsMenu]="ticketsMenu()"
|
||||||
|
[categories]="categories()"
|
||||||
|
[displayCategories]="displayCategories()"
|
||||||
|
[displaySeachBar]="displaySeachBar()"
|
||||||
|
[displayCart]="displayCart()"
|
||||||
|
[cartDisabled]="cartDisabled()"
|
||||||
|
[checkoutRemainingSeconds]="checkoutRemainingSeconds()"
|
||||||
|
(cartClick)="cartClick.emit()"
|
||||||
|
(ticketsClick)="ticketsClick.emit()"
|
||||||
|
(loginClick)="loginClick.emit()"
|
||||||
|
(logoutClick)="logoutClick.emit()"
|
||||||
|
(searchSubmit)="searchSubmit.emit($event)"
|
||||||
|
(categorySelect)="categorySelect.emit($event)"
|
||||||
|
/>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
<div class="col-12 col-md order-4 order-md-2">
|
@if (headerType() === 'immersive' && displayCategories() && categories().length) {
|
||||||
<div class="store-layout__search-wrapper ms-md-auto">
|
<nav class="immersive-categories" aria-label="Categorías">
|
||||||
<div class="input-group store-layout__search" role="search">
|
<div class="immersive-categories__list">
|
||||||
<label class="visually-hidden" for="store-search-input">Buscar productos</label>
|
@for (category of categories(); track category.id) {
|
||||||
<input
|
|
||||||
id="store-search-input"
|
|
||||||
type="search"
|
|
||||||
class="form-control store-layout__search-input border-end-0 rounded-start"
|
|
||||||
placeholder="Buscar productos"
|
|
||||||
autocomplete="off"
|
|
||||||
[attr.aria-describedby]="showSearchError() ? 'store-search-error' : null"
|
|
||||||
[attr.aria-invalid]="showSearchError()"
|
|
||||||
[minlength]="minSearchLength"
|
|
||||||
[formControl]="searchControl"
|
|
||||||
(input)="clearSearchError()"
|
|
||||||
(keydown.enter)="submitSearch($event)"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn store-layout__search-button border-start-0 rounded-end px-3"
|
|
||||||
aria-label="Buscar"
|
|
||||||
(click)="submitSearch()"
|
|
||||||
>
|
|
||||||
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (showSearchError()) {
|
|
||||||
<p id="store-search-error" class="store-layout__search-error mb-0" role="alert">
|
|
||||||
Ingresá al menos {{ minSearchLength }} caracteres para buscar.
|
|
||||||
</p>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-layout__actions-column col-auto col-md-auto order-2 order-md-3 ms-auto d-flex flex-row align-items-center justify-content-end gap-2 gap-md-3">
|
|
||||||
@if (ticketsMenu(); as menu) {
|
|
||||||
<app-button
|
|
||||||
variant="primary"
|
|
||||||
hostClass="store-layout__tickets-btn-host"
|
|
||||||
data-testid="store-header-tickets"
|
|
||||||
(click)="ticketsClick.emit()"
|
|
||||||
>
|
|
||||||
{{ menu.label }}
|
|
||||||
</app-button>
|
|
||||||
}
|
|
||||||
|
|
||||||
<app-cart-icon
|
|
||||||
[quantity]="cartQuantity()"
|
|
||||||
ariaLabel="Carrito de compras"
|
|
||||||
title="Carrito"
|
|
||||||
(click)="cartClick.emit()"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div class="store-layout__user-menu d-none d-md-inline-flex position-relative">
|
|
||||||
<app-icon-button
|
|
||||||
variant="user"
|
|
||||||
ariaLabel="Mi cuenta"
|
|
||||||
ariaControls="store-user-dropdown"
|
|
||||||
[ariaExpanded]="isUserDropdownOpen()"
|
|
||||||
title="Mi cuenta"
|
|
||||||
(clicked)="toggleUserDropdown()"
|
|
||||||
/>
|
|
||||||
|
|
||||||
@if (isUserDropdownOpen()) {
|
|
||||||
<app-user-dropdown
|
|
||||||
id="store-user-dropdown"
|
|
||||||
[user]="user()"
|
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
|
||||||
(logoutClick)="onLogoutClick()"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-layout__mobile-menu d-inline-flex d-md-none position-relative">
|
|
||||||
<app-icon-button
|
|
||||||
variant="bars"
|
|
||||||
ariaLabel="Menu"
|
|
||||||
ariaControls="store-mobile-menu"
|
|
||||||
[ariaExpanded]="isMobileMenuOpen()"
|
|
||||||
title="Menu"
|
|
||||||
(clicked)="toggleMobileMenu()"
|
|
||||||
/>
|
|
||||||
|
|
||||||
@if (isMobileMenuOpen()) {
|
|
||||||
<div id="store-mobile-menu" class="position-absolute end-0 bg-white rounded shadow mt-2 py-2 store-layout__mobile-dropdown-menu">
|
|
||||||
<a
|
|
||||||
class="dropdown-item d-flex align-items-center gap-2 px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
|
||||||
(click)="onMobileAccountClick()"
|
|
||||||
>
|
|
||||||
<i class="fa-regular fa-circle-user fa-lg"></i>
|
|
||||||
<span class="fw-medium">Mi cuenta</span>
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<hr class="my-1 border-secondary opacity-25">
|
|
||||||
|
|
||||||
@for (category of categories(); track category.id) {
|
|
||||||
<a
|
|
||||||
class="dropdown-item px-3 py-2 text-decoration-none store-layout__mobile-dropdown-item"
|
|
||||||
(click)="onCategorySelect(category)"
|
|
||||||
>
|
|
||||||
<span class="fw-medium">{{ category.nombre }}</span>
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="store-layout__categories d-none d-md-block">
|
|
||||||
<div class="container-xl px-3 px-md-4">
|
|
||||||
<div class="store-layout__category-menu">
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="btn btn-link d-inline-flex align-items-center gap-2 px-0 py-2 text-uppercase fw-bold text-decoration-none store-layout__category-trigger"
|
class="immersive-categories__item"
|
||||||
aria-label="Categorias"
|
(click)="categorySelect.emit(category)"
|
||||||
aria-controls="store-category-dropdown"
|
|
||||||
[attr.aria-expanded]="isCategoryDropdownOpen()"
|
|
||||||
(click)="toggleCategoryDropdown()"
|
|
||||||
>
|
>
|
||||||
<span>Categorias</span>
|
{{ category.nombre | uppercase }}
|
||||||
<i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
|
|
||||||
</button>
|
</button>
|
||||||
|
}
|
||||||
<app-category-dropdown
|
|
||||||
id="store-category-dropdown"
|
|
||||||
[categories]="categories()"
|
|
||||||
[open]="isCategoryDropdownOpen()"
|
|
||||||
(categorySelect)="onCategorySelect($event)"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</nav>
|
||||||
</header>
|
}
|
||||||
|
|||||||
@@ -1,210 +1,48 @@
|
|||||||
.store-layout__header {
|
:host {
|
||||||
color: #ffffff;
|
|
||||||
background-color: var(--tenant-header-bg);
|
|
||||||
box-shadow: inset 0 -1px 0 rgba(255, 255, 255, 0.08);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__header-main {
|
|
||||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
min-width: 150px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-column {
|
|
||||||
max-width: 12rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-logo-shell {
|
|
||||||
position: relative;
|
|
||||||
width: min(100%, 12rem);
|
|
||||||
height: 2.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-logo {
|
|
||||||
display: block;
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.immersive-shell--compact) {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
background-position: center 42%;
|
||||||
|
background-size: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
:host(.immersive-shell--compact) .immersive-categories {
|
||||||
|
border-top: 1px solid rgba(255, 255, 255, 0.6);
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.immersive-categories {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
overflow-x: auto;
|
||||||
object-fit: contain;
|
background: #f5f5f5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__brand-logo-skeleton {
|
.immersive-categories__list {
|
||||||
display: block;
|
display: flex;
|
||||||
width: 100%;
|
align-items: center;
|
||||||
height: 100%;
|
justify-content: center;
|
||||||
border-radius: 0.75rem;
|
gap: clamp(1rem, 3vw, 2.5rem);
|
||||||
background: linear-gradient(
|
width: max-content;
|
||||||
90deg,
|
min-width: 100%;
|
||||||
rgba(255, 255, 255, 0.12) 0%,
|
min-height: 3.5rem;
|
||||||
rgba(255, 255, 255, 0.22) 50%,
|
padding: 0.75rem 1rem;
|
||||||
rgba(255, 255, 255, 0.12) 100%
|
|
||||||
);
|
|
||||||
background-size: 200% 100%;
|
|
||||||
animation: store-header-logo-skeleton 1.2s ease-in-out infinite;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__search-wrapper {
|
.immersive-categories__item {
|
||||||
width: 100%;
|
flex: none;
|
||||||
min-width: 0;
|
border: 0;
|
||||||
}
|
padding: 0;
|
||||||
|
background: transparent;
|
||||||
@media (min-width: 768px) {
|
|
||||||
.store-layout__search-wrapper {
|
|
||||||
width: min(100%, 260px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__actions-column {
|
|
||||||
padding-left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .store-layout__tickets-btn-host {
|
|
||||||
flex: 0 0 clamp(8rem, 15vw, 13.5rem);
|
|
||||||
width: clamp(8rem, 15vw, 13.5rem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-error {
|
|
||||||
margin-top: 0.25rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
line-height: 1.2;
|
|
||||||
color: var(--tenant-danger, #dc3545);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-input {
|
|
||||||
color: #666666;
|
color: #666666;
|
||||||
border-color: #cccccc;
|
font-size: 15px;
|
||||||
background-color: rgba(255, 255, 255, 0.96);
|
font-weight: 700;
|
||||||
}
|
white-space: nowrap;
|
||||||
|
|
||||||
.store-layout__search-input::placeholder {
|
|
||||||
color: #666666;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-input:focus {
|
|
||||||
border-color: #cccccc;
|
|
||||||
box-shadow: none;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-button {
|
|
||||||
color: #a0a0a0;
|
|
||||||
border-color: #cccccc;
|
|
||||||
background-color: rgba(255, 255, 255, 0.96);
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__search-button:hover,
|
|
||||||
.store-layout__search-button:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
border-color: #cccccc;
|
|
||||||
background-color: #ffffff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__action-button {
|
|
||||||
color: #a0a0a0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__action-button:hover,
|
|
||||||
.store-layout__action-button:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__user-menu {
|
|
||||||
position: relative;
|
|
||||||
display: inline-flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-trigger {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
color: #a0a0a0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-trigger:hover,
|
|
||||||
.store-layout__category-trigger:focus-visible {
|
|
||||||
color: #8a8a8a;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-menu {
|
|
||||||
position: relative;
|
|
||||||
display: inline-flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__category-menu app-category-dropdown {
|
|
||||||
position: absolute;
|
|
||||||
z-index: 1050;
|
|
||||||
top: 100%;
|
|
||||||
left: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes store-header-logo-skeleton {
|
|
||||||
from {
|
|
||||||
background-position: 200% 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
to {
|
|
||||||
background-position: -200% 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 767.98px) {
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
min-width: 0;
|
|
||||||
max-width: 150px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-separator {
|
|
||||||
border-color: #DDDDDD;
|
|
||||||
opacity: 1;
|
|
||||||
margin: 0 -1rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 399.98px) {
|
|
||||||
.store-layout__brand-column {
|
|
||||||
flex: 1 1 0;
|
|
||||||
width: auto;
|
|
||||||
min-width: 0;
|
|
||||||
max-width: none;
|
|
||||||
padding-right: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__brand-slot {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 6.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__actions-column {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
width: auto;
|
|
||||||
margin-left: 0 !important;
|
|
||||||
padding-left: 0.25rem;
|
|
||||||
gap: 0.25rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .store-layout__tickets-btn-host .btn {
|
|
||||||
padding-inline: 0.75rem;
|
|
||||||
font-size: 0.875rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-dropdown-menu {
|
|
||||||
top: 100%;
|
|
||||||
min-width: 220px;
|
|
||||||
z-index: 1050;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-layout__mobile-dropdown-item {
|
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
color: #8a8a8a;
|
}
|
||||||
|
|
||||||
&:hover,
|
.immersive-categories__item:hover,
|
||||||
&:focus-visible {
|
.immersive-categories__item:focus-visible {
|
||||||
color: #666666;
|
text-decoration: underline;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,137 +1,56 @@
|
|||||||
import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
|
import { NgTemplateOutlet, UpperCasePipe } from '@angular/common';
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Component, computed, input, output } from '@angular/core';
|
||||||
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../../services/auth/auth.interfaces';
|
||||||
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
|
import { Category, Menu, WebsiteExtras } from '../../../services/tenant.interface';
|
||||||
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
|
import { ImmersiveStoreHeaderComponent } from './immersive-store-header.component';
|
||||||
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
|
import { StandardStoreHeaderComponent } from './standard-store-header.component';
|
||||||
import { Menu } from '../../../services/tenant.interface';
|
|
||||||
import { ButtonComponent } from '../../../../shared/components/button/button.component';
|
export type StoreHeaderType = 'standard' | 'immersive';
|
||||||
import { ReactiveFormsModule, FormControl } from '@angular/forms';
|
|
||||||
import { Category } from '../../../services/tenant.interface';
|
|
||||||
import { CategoryDropdownComponent } from './category-dropdown/category-dropdown.component';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-header',
|
selector: 'app-store-header',
|
||||||
imports: [
|
imports: [NgTemplateOutlet, UpperCasePipe, StandardStoreHeaderComponent, ImmersiveStoreHeaderComponent],
|
||||||
ButtonComponent,
|
|
||||||
CartIconComponent,
|
|
||||||
IconButtonComponent,
|
|
||||||
RouterLink,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
UserDropdownComponent,
|
|
||||||
CategoryDropdownComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './store-header.component.html',
|
templateUrl: './store-header.component.html',
|
||||||
styleUrl: './store-header.component.scss',
|
styleUrl: './store-header.component.scss',
|
||||||
|
host: {
|
||||||
|
'[class.immersive-shell--compact]': 'isCompactImmersive()',
|
||||||
|
'[style.background-image]': 'compactBackground()',
|
||||||
|
},
|
||||||
})
|
})
|
||||||
export class StoreHeaderComponent {
|
export class StoreHeaderComponent {
|
||||||
private readonly elementRef = inject(ElementRef<HTMLElement>);
|
readonly headerType = input<StoreHeaderType>('standard');
|
||||||
private readonly router = inject(Router);
|
|
||||||
|
|
||||||
readonly logoUrl = input<string | null>(null);
|
readonly logoUrl = input<string | null>(null);
|
||||||
|
readonly backgroundImageUrl = input<string | null>(null);
|
||||||
|
readonly heroContent = input<WebsiteExtras['immersiveHero']>(undefined);
|
||||||
|
readonly carouselImages = input<readonly string[]>([]);
|
||||||
|
readonly showHero = input(true);
|
||||||
|
protected readonly isCompactImmersive = computed(
|
||||||
|
() => this.headerType() === 'immersive' && !this.showHero(),
|
||||||
|
);
|
||||||
|
protected readonly compactBackground = computed(() => {
|
||||||
|
if (!this.isCompactImmersive()) return null;
|
||||||
|
|
||||||
|
const gradient =
|
||||||
|
'linear-gradient(180deg, rgba(245, 245, 245, 0.72) 0%, rgba(245, 245, 245, 0.88) 58%, #f5f5f5 100%)';
|
||||||
|
const image = this.backgroundImageUrl();
|
||||||
|
return image ? `${gradient}, url(${JSON.stringify(image)})` : gradient;
|
||||||
|
});
|
||||||
readonly cartQuantity = input<number>(0);
|
readonly cartQuantity = input<number>(0);
|
||||||
readonly user = input<AuthUser | null>(null);
|
readonly user = input<AuthUser | null>(null);
|
||||||
readonly isAuthenticated = input<boolean>(false);
|
readonly isAuthenticated = input<boolean>(false);
|
||||||
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
readonly accountNavigationMenus = input<readonly Menu[]>([]);
|
||||||
readonly ticketsMenu = input<Menu | null>(null);
|
readonly ticketsMenu = input<Menu | null>(null);
|
||||||
readonly categories = input<readonly Category[]>([]);
|
readonly categories = input<readonly Category[]>([]);
|
||||||
|
readonly displayCategories = input(true);
|
||||||
|
readonly displaySeachBar = input(true);
|
||||||
|
readonly displayCart = input(true);
|
||||||
|
readonly cartDisabled = input(false);
|
||||||
|
readonly checkoutRemainingSeconds = input<number | null>(null);
|
||||||
|
|
||||||
readonly cartClick = output<void>();
|
readonly cartClick = output<void>();
|
||||||
readonly ticketsClick = output<void>();
|
readonly ticketsClick = output<void>();
|
||||||
readonly loginClick = output<void>();
|
readonly loginClick = output<void>();
|
||||||
readonly logoutClick = output<void>();
|
readonly logoutClick = output<void>();
|
||||||
readonly searchSubmit = output<string>();
|
readonly searchSubmit = output<string>();
|
||||||
readonly categorySelect = output<Category>();
|
readonly categorySelect = output<Category>();
|
||||||
|
|
||||||
protected readonly isUserDropdownOpen = signal(false);
|
|
||||||
protected readonly isCategoryDropdownOpen = signal(false);
|
|
||||||
protected readonly isMobileMenuOpen = signal(false);
|
|
||||||
protected readonly minSearchLength = 3;
|
|
||||||
protected readonly showSearchError = signal(false);
|
|
||||||
protected readonly searchControl = new FormControl('', { nonNullable: true });
|
|
||||||
|
|
||||||
@HostListener('document:click', ['$event'])
|
|
||||||
protected onDocumentClick(event: MouseEvent): void {
|
|
||||||
if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = event.target;
|
|
||||||
if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:keydown.escape')
|
|
||||||
protected onEscapeKey(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleUserDropdown(): void {
|
|
||||||
if (!this.isAuthenticated()) {
|
|
||||||
this.loginClick.emit();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.isUserDropdownOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLoginClick(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.loginClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onLogoutClick(): void {
|
|
||||||
this.isUserDropdownOpen.set(false);
|
|
||||||
this.logoutClick.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected submitSearch(event?: Event): void {
|
|
||||||
event?.preventDefault();
|
|
||||||
|
|
||||||
const term = this.searchControl.value.trim();
|
|
||||||
|
|
||||||
if (term.length < this.minSearchLength) {
|
|
||||||
this.showSearchError.set(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.showSearchError.set(false);
|
|
||||||
this.searchSubmit.emit(term);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected clearSearchError(): void {
|
|
||||||
this.showSearchError.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleCategoryDropdown(): void {
|
|
||||||
this.isCategoryDropdownOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onCategorySelect(category: Category): void {
|
|
||||||
this.isCategoryDropdownOpen.set(false);
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
this.categorySelect.emit(category);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected toggleMobileMenu(): void {
|
|
||||||
this.isMobileMenuOpen.update((isOpen) => !isOpen);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected onMobileAccountClick(): void {
|
|
||||||
this.isMobileMenuOpen.set(false);
|
|
||||||
if (!this.isAuthenticated()) {
|
|
||||||
this.loginClick.emit();
|
|
||||||
} else {
|
|
||||||
const menus = this.accountNavigationMenus();
|
|
||||||
if (menus.length > 0) {
|
|
||||||
this.router.navigate([menus[0].route]);
|
|
||||||
} else {
|
|
||||||
this.router.navigate(['/cuenta']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
.user-dropdown {
|
.user-dropdown {
|
||||||
display: grid;
|
display: grid;
|
||||||
background: #ffffff;
|
background: #ffffff;
|
||||||
border: 1px solid rgba(32, 32, 32, 0.1);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.16);
|
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.16);
|
||||||
padding: 0.75rem;
|
padding: 0.75rem;
|
||||||
|
|||||||
@@ -1,13 +1,24 @@
|
|||||||
<div class="store-layout d-flex flex-column flex-grow-1">
|
<div class="store-layout d-flex flex-column flex-grow-1">
|
||||||
<app-store-header
|
<app-store-header
|
||||||
|
ngSkipHydration
|
||||||
|
[headerType]="tenant()?.header_type ?? 'standard'"
|
||||||
|
[heroContent]="tenant()?.extras?.immersiveHero"
|
||||||
|
[carouselImages]="tenant()?.extras?.immersiveHeroCarousel ?? []"
|
||||||
|
[showHero]="isHomeRoute()"
|
||||||
[cartQuantity]="cartQuantity()"
|
[cartQuantity]="cartQuantity()"
|
||||||
[logoUrl]="tenant()?.header_logo ?? null"
|
[logoUrl]="tenant()?.header_logo ?? null"
|
||||||
|
[backgroundImageUrl]="tenant()?.header_bg_image ?? null"
|
||||||
[user]="user()"
|
[user]="user()"
|
||||||
[isAuthenticated]="isAuthenticated()"
|
[isAuthenticated]="isAuthenticated()"
|
||||||
[accountNavigationMenus]="accountNavigationMenus()"
|
[accountNavigationMenus]="accountNavigationMenus()"
|
||||||
[ticketsMenu]="ticketsMenu() ?? null"
|
[ticketsMenu]="ticketsMenu() ?? null"
|
||||||
[categories]="tenant()?.categories ?? []"
|
[categories]="navigationCategories()"
|
||||||
(cartClick)="isCartOpen.set(!isCartOpen())"
|
[displayCategories]="displayCategories()"
|
||||||
|
[displaySeachBar]="tenant()?.display_seach_bar ?? true"
|
||||||
|
[displayCart]="displayCart()"
|
||||||
|
[cartDisabled]="isCheckoutRoute()"
|
||||||
|
[checkoutRemainingSeconds]="headerCheckoutRemainingSeconds()"
|
||||||
|
(cartClick)="onCartClick()"
|
||||||
(ticketsClick)="onTicketsClick()"
|
(ticketsClick)="onTicketsClick()"
|
||||||
(loginClick)="onLoginClick()"
|
(loginClick)="onLoginClick()"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
@@ -15,11 +26,8 @@
|
|||||||
(categorySelect)="onCategorySelect($event)"
|
(categorySelect)="onCategorySelect($event)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@if (isCartOpen()) {
|
@if (displayCart() && !isCheckoutRoute() && isCartOpen()) {
|
||||||
<div
|
<div class="store-layout__cart-overlay" (click)="isCartOpen.set(false)"></div>
|
||||||
class="store-layout__cart-overlay"
|
|
||||||
(click)="isCartOpen.set(false)"
|
|
||||||
></div>
|
|
||||||
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
<div class="store-layout__cart-dropdown card border-0 shadow-lg">
|
||||||
<app-cart
|
<app-cart
|
||||||
[showClose]="true"
|
[showClose]="true"
|
||||||
@@ -27,13 +35,15 @@
|
|||||||
[subtotal]="cartSubtotal()"
|
[subtotal]="cartSubtotal()"
|
||||||
[discount]="cartDiscount()"
|
[discount]="cartDiscount()"
|
||||||
[total]="cartTotal()"
|
[total]="cartTotal()"
|
||||||
|
[readonly]="!canModifyCart()"
|
||||||
|
[allowModify]="canModifyCart()"
|
||||||
|
[allowUpdateQuantity]="canUpdateCartQuantity()"
|
||||||
|
[allowUpdateVariant]="canUpdateCartVariant()"
|
||||||
|
[allowDelete]="canDeleteCartItems()"
|
||||||
[backgroundColor]="'#ffffff'"
|
[backgroundColor]="'#ffffff'"
|
||||||
(closed)="isCartOpen.set(false)"
|
(closed)="isCartOpen.set(false)"
|
||||||
>
|
>
|
||||||
<app-button
|
<app-button variant="secondary" class="flex-grow-1" (click)="isCartOpen.set(false)"
|
||||||
variant="secondary"
|
|
||||||
class="flex-grow-1"
|
|
||||||
(click)="isCartOpen.set(false)"
|
|
||||||
>Seguir comprando</app-button
|
>Seguir comprando</app-button
|
||||||
>
|
>
|
||||||
<app-button
|
<app-button
|
||||||
@@ -61,7 +71,10 @@
|
|||||||
[footerSections]="footerSections()"
|
[footerSections]="footerSections()"
|
||||||
[socialMedia]="tenant()?.social_media ?? []"
|
[socialMedia]="tenant()?.social_media ?? []"
|
||||||
[logoUrl]="tenant()?.footer_logo ?? null"
|
[logoUrl]="tenant()?.footer_logo ?? null"
|
||||||
|
[backgroundImageUrl]="tenant()?.footer_bg_image ?? null"
|
||||||
[storeName]="tenant()?.nombre ?? null"
|
[storeName]="tenant()?.nombre ?? null"
|
||||||
|
[address]="tenant()?.address ?? null"
|
||||||
|
[phone]="tenant()?.phone ?? null"
|
||||||
(logoutClick)="onLogoutClick()"
|
(logoutClick)="onLogoutClick()"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
:host {
|
:host {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
min-height: 100dvh;
|
min-height: 100dvh;
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
color: #202020;
|
color: #202020;
|
||||||
@@ -7,6 +9,8 @@
|
|||||||
|
|
||||||
.store-layout {
|
.store-layout {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-layout__cart-overlay {
|
.store-layout__cart-overlay {
|
||||||
@@ -21,18 +25,25 @@
|
|||||||
|
|
||||||
.store-layout__cart-dropdown {
|
.store-layout__cart-dropdown {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 76px;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
top: 100px;
|
||||||
right: calc((100% - 1320px) / 2 + 1.5rem);
|
right: calc((100% - 1320px) / 2 + 1.5rem);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
max-height: calc(100vh - 120px);
|
max-height: calc(100vh - 120px);
|
||||||
z-index: 1050;
|
z-index: 1050;
|
||||||
background-color: #ffffff;
|
background-color: #ffffff;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
border: 1px solid var(--border-color);
|
||||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
|
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
animation: store-layout-slide-down 0.2s ease-out;
|
animation: store-layout-slide-down 0.2s ease-out;
|
||||||
|
|
||||||
|
> app-cart {
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 1400px) {
|
@media (max-width: 1400px) {
|
||||||
right: 1.5rem;
|
right: 1.5rem;
|
||||||
}
|
}
|
||||||
@@ -40,6 +51,7 @@
|
|||||||
right: 1rem;
|
right: 1rem;
|
||||||
left: 1rem;
|
left: 1rem;
|
||||||
width: auto;
|
width: auto;
|
||||||
|
max-width: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { signal } from '@angular/core';
|
import { signal } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
convertToParamMap,
|
||||||
|
ParamMap,
|
||||||
|
provideRouter,
|
||||||
|
Router,
|
||||||
|
UrlSerializer,
|
||||||
|
} from '@angular/router';
|
||||||
|
|
||||||
import { of } from 'rxjs';
|
import { BehaviorSubject, of, throwError } from 'rxjs';
|
||||||
|
|
||||||
import { Tenant } from '../../services/tenant.interface';
|
import { Tenant } from '../../services/tenant.interface';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
@@ -15,13 +23,19 @@ import { AuthService } from '../../services/auth/auth.service';
|
|||||||
import { AuthUser } from '../../services/auth/auth.interfaces';
|
import { AuthUser } from '../../services/auth/auth.interfaces';
|
||||||
import { StoreLayoutComponent } from './store-layout.component';
|
import { StoreLayoutComponent } from './store-layout.component';
|
||||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||||
|
import { StandardStoreHeaderComponent } from './store-header/standard-store-header.component';
|
||||||
import { CheckoutService } from '../../services/checkout.service';
|
import { CheckoutService } from '../../services/checkout.service';
|
||||||
|
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
||||||
|
import { TenantUrlSerializer } from '../../services/tenant-url.serializer';
|
||||||
|
import { EventDateNoticeService } from '../../services/event-date-notice.service';
|
||||||
|
|
||||||
const tenant: Tenant = {
|
const tenant: Tenant = {
|
||||||
id: 1,
|
id: 1,
|
||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
address: 'Calle Test 123, Rosario',
|
||||||
|
phone: '+54 341 555 1234',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -30,6 +44,15 @@ const tenant: Tenant = {
|
|||||||
footer_bg_color: '#313131',
|
footer_bg_color: '#313131',
|
||||||
header_logo: 'https://example.com/header.png',
|
header_logo: 'https://example.com/header.png',
|
||||||
footer_logo: 'https://example.com/footer.png',
|
footer_logo: 'https://example.com/footer.png',
|
||||||
|
header_bg_image: 'https://example.com/header-background.png',
|
||||||
|
footer_bg_image: 'https://example.com/footer-background.png',
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
categories: [],
|
categories: [],
|
||||||
menues: [
|
menues: [
|
||||||
{
|
{
|
||||||
@@ -130,12 +153,16 @@ describe('StoreLayoutComponent', () => {
|
|||||||
let tenantState = signal<Tenant | null>(tenant);
|
let tenantState = signal<Tenant | null>(tenant);
|
||||||
let cartState = signal<Cart | null>(null);
|
let cartState = signal<Cart | null>(null);
|
||||||
let authUserState = signal<AuthUser | null>(null);
|
let authUserState = signal<AuthUser | null>(null);
|
||||||
|
let checkoutRemainingSecondsState = signal<number | null>(null);
|
||||||
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
let checkoutServiceStub: { startCheckout: ReturnType<typeof vi.fn> };
|
||||||
|
let queryParamMapState: BehaviorSubject<ParamMap>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tenantState = signal<Tenant | null>(tenant);
|
tenantState = signal<Tenant | null>(tenant);
|
||||||
cartState = signal<Cart | null>(null);
|
cartState = signal<Cart | null>(null);
|
||||||
authUserState = signal<AuthUser | null>(null);
|
authUserState = signal<AuthUser | null>(null);
|
||||||
|
checkoutRemainingSecondsState = signal<number | null>(null);
|
||||||
|
queryParamMapState = new BehaviorSubject(convertToParamMap({}));
|
||||||
const isAuthenticatedState = signal(false);
|
const isAuthenticatedState = signal(false);
|
||||||
checkoutServiceStub = {
|
checkoutServiceStub = {
|
||||||
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
startCheckout: vi.fn().mockResolvedValue({ id: 55 }),
|
||||||
@@ -145,6 +172,11 @@ describe('StoreLayoutComponent', () => {
|
|||||||
imports: [StoreLayoutComponent],
|
imports: [StoreLayoutComponent],
|
||||||
providers: [
|
providers: [
|
||||||
provideRouter([]),
|
provideRouter([]),
|
||||||
|
{ provide: UrlSerializer, useClass: TenantUrlSerializer },
|
||||||
|
{
|
||||||
|
provide: ActivatedRoute,
|
||||||
|
useValue: { queryParamMap: queryParamMapState.asObservable() },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
provide: TenantService,
|
provide: TenantService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -181,13 +213,25 @@ describe('StoreLayoutComponent', () => {
|
|||||||
useValue: {
|
useValue: {
|
||||||
user: authUserState,
|
user: authUserState,
|
||||||
isAuthenticated: isAuthenticatedState,
|
isAuthenticated: isAuthenticatedState,
|
||||||
logout: vi.fn().mockReturnValue(of(void 0)),
|
logout: vi.fn().mockReturnValue(of({ message: 'Sesión cerrada correctamente.' })),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: CheckoutService,
|
provide: CheckoutService,
|
||||||
useValue: checkoutServiceStub,
|
useValue: checkoutServiceStub,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: CheckoutCountdownService,
|
||||||
|
useValue: {
|
||||||
|
remainingSeconds: checkoutRemainingSecondsState.asReadonly(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: EventDateNoticeService,
|
||||||
|
useValue: {
|
||||||
|
claim: vi.fn().mockReturnValue(of({ data: [] })),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
@@ -204,6 +248,254 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
expect(compiled.querySelector('app-store-footer .store-layout__footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders the immersive header with configured copy and carousel images', () => {
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
|
expect(header.componentInstance.headerType()).toBe('standard');
|
||||||
|
expect(element.querySelector('app-standard-store-header')).not.toBeNull();
|
||||||
|
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
header_type: 'immersive',
|
||||||
|
extras: {
|
||||||
|
immersiveHero: {
|
||||||
|
eyebrow: 'Encendé tu',
|
||||||
|
title: 'experiencia',
|
||||||
|
description: 'Reservá tu entrada',
|
||||||
|
},
|
||||||
|
immersiveHeroCarousel: ['/first.jpg', '/second.jpg'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(header.componentInstance.headerType()).toBe('immersive');
|
||||||
|
expect(element.querySelector('app-standard-store-header')).toBeNull();
|
||||||
|
expect(element.querySelector('app-immersive-store-header')).not.toBeNull();
|
||||||
|
expect(element.querySelector('.immersive-header__eyebrow')?.textContent).toContain(
|
||||||
|
'Encendé tu',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('.immersive-header__title')?.textContent).toContain('experiencia');
|
||||||
|
expect(element.querySelector('.immersive-header__description')?.textContent).toContain(
|
||||||
|
'Reservá tu entrada',
|
||||||
|
);
|
||||||
|
const backdropImage = element.querySelector<HTMLImageElement>(
|
||||||
|
'.immersive-header__backdrop-image',
|
||||||
|
);
|
||||||
|
expect(backdropImage?.getAttribute('src')).toBe(tenant.header_bg_image);
|
||||||
|
expect(backdropImage?.getAttribute('loading')).toBe('eager');
|
||||||
|
expect(backdropImage?.getAttribute('fetchpriority')).toBe('high');
|
||||||
|
expect(backdropImage?.getAttribute('decoding')).toBe('async');
|
||||||
|
const headerLogo = element.querySelector<HTMLImageElement>('.immersive-header__brand img');
|
||||||
|
expect(headerLogo?.getAttribute('loading')).toBe('eager');
|
||||||
|
expect(headerLogo?.getAttribute('fetchpriority')).toBe('high');
|
||||||
|
expect(headerLogo?.getAttribute('decoding')).toBe('async');
|
||||||
|
expect(element.querySelectorAll('.continuous-carousel__set')).toHaveLength(2);
|
||||||
|
const carouselImages = element.querySelectorAll<HTMLImageElement>(
|
||||||
|
'.continuous-carousel__image',
|
||||||
|
);
|
||||||
|
expect(carouselImages[0]?.getAttribute('src')).toBe('/first.jpg');
|
||||||
|
expect(carouselImages[0]?.getAttribute('loading')).toBe('eager');
|
||||||
|
expect(carouselImages[0]?.getAttribute('fetchpriority')).toBe('low');
|
||||||
|
expect(carouselImages[1]?.getAttribute('fetchpriority')).toBe('low');
|
||||||
|
expect(carouselImages[5]?.getAttribute('loading')).toBe('lazy');
|
||||||
|
expect(carouselImages[5]?.getAttribute('fetchpriority')).toBe('low');
|
||||||
|
expect(element.querySelector('app-cart-icon')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows immersive categories below the header and navigates on selection', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
header_type: 'immersive',
|
||||||
|
display_categories: true,
|
||||||
|
categories: [{ id: 11, nombre: 'Música', subcategories: [] }],
|
||||||
|
menues: [
|
||||||
|
...(tenant.menues ?? []),
|
||||||
|
{
|
||||||
|
id: 20,
|
||||||
|
code: 'product.category',
|
||||||
|
label: 'Categoría de productos',
|
||||||
|
parent_menu_code: null,
|
||||||
|
content_type: 'dynamic',
|
||||||
|
route: '/categoria/:id',
|
||||||
|
submenues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const header = element.querySelector('app-immersive-store-header header');
|
||||||
|
const categories = element.querySelector('app-store-header .immersive-categories');
|
||||||
|
const categoryButton = categories?.querySelector<HTMLButtonElement>('button');
|
||||||
|
|
||||||
|
expect(header).not.toBeNull();
|
||||||
|
expect(categories).not.toBeNull();
|
||||||
|
expect(header?.contains(categories)).toBe(false);
|
||||||
|
expect(categoryButton?.textContent?.trim()).toBe('MÚSICA');
|
||||||
|
|
||||||
|
const navigate = vi.spyOn(TestBed.inject(Router), 'navigate');
|
||||||
|
categoryButton?.click();
|
||||||
|
expect(navigate).toHaveBeenCalledWith(['/categoria', 11], { queryParams: { page: 1 } });
|
||||||
|
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
header_type: 'immersive',
|
||||||
|
display_categories: false,
|
||||||
|
categories: [{ id: 11, nombre: 'Música', subcategories: [] }],
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(element.querySelector('.immersive-categories')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses event categories and their dedicated route for multi-event storefronts', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
storefront_website_type_code: 'onticket_multi_event',
|
||||||
|
header_type: 'immersive',
|
||||||
|
display_categories: true,
|
||||||
|
categories: [],
|
||||||
|
event_categories: [{ id: 12, nombre: 'Teatro', subcategories: [] }],
|
||||||
|
menues: [
|
||||||
|
...(tenant.menues ?? []),
|
||||||
|
{
|
||||||
|
id: 21,
|
||||||
|
code: 'event.category',
|
||||||
|
label: 'Categoría de eventos',
|
||||||
|
parent_menu_code: null,
|
||||||
|
content_type: 'dynamic',
|
||||||
|
route: '/eventos/categoria/:id',
|
||||||
|
submenues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const categoryButton = (fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>(
|
||||||
|
'.immersive-categories button',
|
||||||
|
);
|
||||||
|
const navigate = vi.spyOn(TestBed.inject(Router), 'navigate');
|
||||||
|
|
||||||
|
expect(categoryButton?.textContent?.trim()).toBe('TEATRO');
|
||||||
|
categoryButton?.click();
|
||||||
|
expect(navigate).toHaveBeenCalledWith(['/eventos/categoria', 12], {
|
||||||
|
queryParams: { page: 1 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens the cart when requested through the openCart query parameter', () => {
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(true);
|
||||||
|
expect((fixture.nativeElement as HTMLElement).querySelector('app-cart')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables the cart icon and prevents opening the popup during checkout with a tenant base path', () => {
|
||||||
|
tenantState.set({ ...tenant, base_path: 'fiesta' });
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/fiesta/checkout/25');
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const cartButton = element.querySelector<HTMLButtonElement>('app-cart-icon button');
|
||||||
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
|
|
||||||
|
expect(cartButton?.disabled).toBe(true);
|
||||||
|
expect(cartButton?.getAttribute('aria-label')).toBe(
|
||||||
|
'Carrito no disponible durante el checkout',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('[data-testid="cart-badge"]')).toBeNull();
|
||||||
|
|
||||||
|
header.componentInstance.cartClick.emit();
|
||||||
|
queryParamMapState.next(convertToParamMap({ openCart: 'true' }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
|
expect(element.querySelector('app-cart')).toBeNull();
|
||||||
|
expect(element.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the synchronized countdown in the header whenever one is active', () => {
|
||||||
|
checkoutRemainingSecondsState.set(587);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
expect(element.querySelector('.store-layout__checkout-timer-label')?.textContent).toContain(
|
||||||
|
'Tiempo restante de compra:',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('.store-layout__checkout-timer-value')?.textContent?.trim()).toBe(
|
||||||
|
'09:47',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves the countdown out of the header on multi-event checkout', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
storefront_website_type_code: 'onticket_multi_event',
|
||||||
|
checkout_summary_type: 'event',
|
||||||
|
});
|
||||||
|
checkoutRemainingSecondsState.set(587);
|
||||||
|
const router = TestBed.inject(Router);
|
||||||
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const element = fixture.nativeElement as HTMLElement;
|
||||||
|
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
||||||
|
|
||||||
|
expect(header.componentInstance.checkoutRemainingSeconds()).toBeNull();
|
||||||
|
expect(element.querySelector('.store-layout__checkout-timer')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides the configured header elements when the tenant disables them', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
categories: [{ id: 1, nombre: 'Remeras', subcategories: [] }],
|
||||||
|
display_categories: false,
|
||||||
|
display_seach_bar: false,
|
||||||
|
display_cart: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const compiled = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
expect(compiled.querySelector('#store-search-input')).toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__category-trigger')).toBeNull();
|
||||||
|
expect(compiled.querySelector('app-cart-icon')).toBeNull();
|
||||||
|
|
||||||
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(compiled.querySelector('app-cart')).toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__cart-overlay')).toBeNull();
|
||||||
|
|
||||||
|
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
||||||
|
(header.componentInstance as any).toggleMobileMenu();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(compiled.querySelectorAll('.store-layout__mobile-dropdown-item')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('renders the tenant branding and action icons', () => {
|
it('renders the tenant branding and action icons', () => {
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -212,22 +504,36 @@ describe('StoreLayoutComponent', () => {
|
|||||||
|
|
||||||
expect(compiled.querySelector('[data-testid="store-header-brand-slot"]')).not.toBeNull();
|
expect(compiled.querySelector('[data-testid="store-header-brand-slot"]')).not.toBeNull();
|
||||||
expect(compiled.querySelector('[data-testid="store-footer-brand-slot"]')).not.toBeNull();
|
expect(compiled.querySelector('[data-testid="store-footer-brand-slot"]')).not.toBeNull();
|
||||||
expect(
|
const headerLogo = compiled.querySelector<HTMLImageElement>(
|
||||||
compiled.querySelector(
|
`app-store-header img.store-layout__brand-logo[src="${tenant.header_logo}"]`,
|
||||||
`app-store-header img.store-layout__brand-logo[src="${tenant.header_logo}"]`,
|
);
|
||||||
),
|
expect(headerLogo).not.toBeNull();
|
||||||
).not.toBeNull();
|
expect(headerLogo?.getAttribute('loading')).toBe('eager');
|
||||||
|
expect(headerLogo?.getAttribute('fetchpriority')).toBe('high');
|
||||||
|
expect(headerLogo?.getAttribute('decoding')).toBe('async');
|
||||||
expect(
|
expect(
|
||||||
compiled.querySelector(
|
compiled.querySelector(
|
||||||
`app-store-footer img.store-layout__brand-logo[src="${tenant.footer_logo}"]`,
|
`app-store-footer img.store-layout__brand-logo[src="${tenant.footer_logo}"]`,
|
||||||
),
|
),
|
||||||
).not.toBeNull();
|
).not.toBeNull();
|
||||||
|
expect(
|
||||||
|
(compiled.querySelector('.store-layout__header') as HTMLElement).style.backgroundImage,
|
||||||
|
).toContain(tenant.header_bg_image!);
|
||||||
|
expect(
|
||||||
|
(compiled.querySelector('.store-layout__footer') as HTMLElement).style.backgroundImage,
|
||||||
|
).toContain(tenant.footer_bg_image!);
|
||||||
expect(compiled.querySelector('.fa-cart-shopping')).not.toBeNull();
|
expect(compiled.querySelector('.fa-cart-shopping')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-circle-user')).not.toBeNull();
|
expect(compiled.querySelector('.fa-circle-user')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-instagram')).not.toBeNull();
|
expect(compiled.querySelector('.fa-instagram')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
expect(compiled.querySelector('.fa-whatsapp')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
expect(compiled.querySelector('.fa-facebook')).not.toBeNull();
|
||||||
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
expect(compiled.querySelector('.fa-linkedin-in')).not.toBeNull();
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.address,
|
||||||
|
);
|
||||||
|
expect(compiled.querySelector('.store-layout__contact-details')?.textContent).toContain(
|
||||||
|
tenant.phone,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates to search results when the search button is clicked', () => {
|
it('navigates to search results when the search button is clicked', () => {
|
||||||
@@ -236,7 +542,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
||||||
const searchButton = header.query(By.css('.store-layout__search-button'));
|
const searchButton = header.query(By.css('.store-layout__search-button'));
|
||||||
|
|
||||||
(header.componentInstance as any).searchControl.setValue(' zapatillas ');
|
(header.componentInstance as any).searchControl.setValue(' zapatillas ');
|
||||||
@@ -254,7 +560,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
||||||
const input = header.query(By.css('#store-search-input'));
|
const input = header.query(By.css('#store-search-input'));
|
||||||
const keyboardEvent = {
|
const keyboardEvent = {
|
||||||
preventDefault: vi.fn(),
|
preventDefault: vi.fn(),
|
||||||
@@ -275,7 +581,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|
||||||
const header = fixture.debugElement.query(By.directive(StoreHeaderComponent));
|
const header = fixture.debugElement.query(By.directive(StandardStoreHeaderComponent));
|
||||||
const input = header.query(By.css('#store-search-input'));
|
const input = header.query(By.css('#store-search-input'));
|
||||||
const searchButton = header.query(By.css('.store-layout__search-button'));
|
const searchButton = header.query(By.css('.store-layout__search-button'));
|
||||||
|
|
||||||
@@ -439,6 +745,20 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(authService.logout).toHaveBeenCalled();
|
expect(authService.logout).toHaveBeenCalled();
|
||||||
expect(cartService.clearCart).toHaveBeenCalled();
|
expect(cartService.clearCart).toHaveBeenCalled();
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||||
|
expect(TestBed.inject(ToastService).info).toHaveBeenCalledWith('Sesión cerrada correctamente.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a danger toast when logout fails', async () => {
|
||||||
|
const authService = TestBed.inject(AuthService);
|
||||||
|
const message = 'La sesión no pudo cerrarse en el servidor.';
|
||||||
|
(authService.logout as any).mockReturnValue(throwError(() => ({ error: { message } })));
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
await (fixture.componentInstance as any).onLogoutClick();
|
||||||
|
|
||||||
|
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('provides account actions from the footer', () => {
|
it('provides account actions from the footer', () => {
|
||||||
@@ -478,7 +798,7 @@ describe('StoreLayoutComponent', () => {
|
|||||||
const authService = TestBed.inject(AuthService);
|
const authService = TestBed.inject(AuthService);
|
||||||
const cartService = TestBed.inject(CartService);
|
const cartService = TestBed.inject(CartService);
|
||||||
const router = TestBed.inject(Router);
|
const router = TestBed.inject(Router);
|
||||||
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout?purchase=25');
|
vi.spyOn(router, 'url', 'get').mockReturnValue('/checkout/25');
|
||||||
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||||
|
|
||||||
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
@@ -532,10 +852,9 @@ describe('StoreLayoutComponent', () => {
|
|||||||
precio_unitario: '100.00',
|
precio_unitario: '100.00',
|
||||||
catalog_item_id: 1,
|
catalog_item_id: 1,
|
||||||
variant_id: null,
|
variant_id: null,
|
||||||
product: {
|
nombre: 'Producto',
|
||||||
nombre: 'Producto',
|
imagen: null,
|
||||||
imagen: null,
|
variant: null,
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -566,12 +885,44 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
expect(checkoutServiceStub.startCheckout).toHaveBeenCalledWith('test', {
|
||||||
cart_id: 1,
|
cart_id: 1,
|
||||||
});
|
});
|
||||||
expect(router.navigate).toHaveBeenCalledWith(['/checkout'], {
|
expect(router.navigate).toHaveBeenCalledWith(['/checkout', 55]);
|
||||||
queryParams: { purchase: 55 },
|
|
||||||
});
|
|
||||||
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
expect((fixture.componentInstance as any).isCartOpen()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows the backend message and refreshes the cart when its reservation expired', async () => {
|
||||||
|
const message = 'La reserva de stock venció. Usá el carrito activo para continuar.';
|
||||||
|
checkoutServiceStub.startCheckout.mockRejectedValue(
|
||||||
|
new HttpErrorResponse({
|
||||||
|
status: 422,
|
||||||
|
error: { code: 'stock_reservation.expired', message },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
cartState.set({
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [],
|
||||||
|
});
|
||||||
|
authUserState.set({
|
||||||
|
id: 7,
|
||||||
|
nombre_apellido: 'Juan Perez',
|
||||||
|
email: 'juan@example.com',
|
||||||
|
dni: '12345678',
|
||||||
|
telefono: '3415555555',
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
const loadCart = vi.spyOn(TestBed.inject(CartService), 'loadCart');
|
||||||
|
fixture.detectChanges();
|
||||||
|
loadCart.mockClear();
|
||||||
|
|
||||||
|
await (fixture.componentInstance as any).onCheckoutClick();
|
||||||
|
|
||||||
|
expect(TestBed.inject(ToastService).danger).toHaveBeenCalledWith(message);
|
||||||
|
expect(loadCart).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
it('allows modifying quantities directly in the regular cart without a toggle', () => {
|
||||||
cartState.set({
|
cartState.set({
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -585,10 +936,9 @@ describe('StoreLayoutComponent', () => {
|
|||||||
precio_unitario: '100.00',
|
precio_unitario: '100.00',
|
||||||
catalog_item_id: 1,
|
catalog_item_id: 1,
|
||||||
variant_id: null,
|
variant_id: null,
|
||||||
product: {
|
nombre: 'Producto',
|
||||||
nombre: 'Producto',
|
imagen: null,
|
||||||
imagen: null,
|
variant: null,
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -608,4 +958,102 @@ describe('StoreLayoutComponent', () => {
|
|||||||
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
|
expect(cartItem.componentInstance.quantityDisabled()).toBe(false);
|
||||||
expect(buyButton).toBeDefined();
|
expect(buyButton).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('hides quantity selectors when the tenant disables cart editing', () => {
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'disabled',
|
||||||
|
allow_modify: false,
|
||||||
|
allow_delete: false,
|
||||||
|
allow_update_quantity: false,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cartState.set({
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
cantidad: 1,
|
||||||
|
precio_unitario: '100.00',
|
||||||
|
catalog_item_id: 1,
|
||||||
|
variant_id: null,
|
||||||
|
nombre: 'Producto',
|
||||||
|
imagen: null,
|
||||||
|
variant: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const cartItem = fixture.debugElement.query(By.css('app-cart-item'));
|
||||||
|
expect(cartItem.componentInstance.readonly()).toBe(true);
|
||||||
|
expect(cartItem.nativeElement.querySelector('app-quantity-selector')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows variant selectors only for the full cart editing policy', () => {
|
||||||
|
const variantCart: Cart = {
|
||||||
|
id: 1,
|
||||||
|
tenant_codigo: tenant.codigo,
|
||||||
|
status: 'active',
|
||||||
|
subtotal: '100.00',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
cantidad: 1,
|
||||||
|
precio_unitario: '100.00',
|
||||||
|
catalog_item_id: 1,
|
||||||
|
variant_id: 10,
|
||||||
|
nombre: 'Producto',
|
||||||
|
imagen: null,
|
||||||
|
variant: { id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||||
|
variants: [
|
||||||
|
{ id: 10, precio: '100.00', stock_tecnico: 5, values: { talle: 'M' } },
|
||||||
|
{ id: 11, precio: '100.00', stock_tecnico: 5, values: { talle: 'L' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'quantity_and_remove',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
cartState.set(variantCart);
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(StoreLayoutComponent);
|
||||||
|
fixture.detectChanges();
|
||||||
|
(fixture.componentInstance as any).isCartOpen.set(true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('app-variant-selector')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('app-quantity-selector')).not.toBeNull();
|
||||||
|
|
||||||
|
tenantState.set({
|
||||||
|
...tenant,
|
||||||
|
cart_editing_policy: {
|
||||||
|
code: 'full',
|
||||||
|
allow_modify: true,
|
||||||
|
allow_delete: true,
|
||||||
|
allow_update_quantity: true,
|
||||||
|
allow_update_variant: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(fixture.nativeElement.querySelector('app-variant-selector')).not.toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,17 +1,43 @@
|
|||||||
import { Component, computed, inject, OnInit, signal } from '@angular/core';
|
import { isPlatformBrowser } from '@angular/common';
|
||||||
import { Router, RouterOutlet } from '@angular/router';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import {
|
||||||
|
Component,
|
||||||
|
computed,
|
||||||
|
DestroyRef,
|
||||||
|
effect,
|
||||||
|
inject,
|
||||||
|
OnInit,
|
||||||
|
PLATFORM_ID,
|
||||||
|
signal,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import {
|
||||||
|
ActivatedRoute,
|
||||||
|
NavigationEnd,
|
||||||
|
PRIMARY_OUTLET,
|
||||||
|
Router,
|
||||||
|
RouterOutlet,
|
||||||
|
} from '@angular/router';
|
||||||
|
import { filter, firstValueFrom } from 'rxjs';
|
||||||
import { TenantService } from '../../services/tenant.service';
|
import { TenantService } from '../../services/tenant.service';
|
||||||
import { CartService } from '../../services/cart/cart.service';
|
import { CartService } from '../../services/cart/cart.service';
|
||||||
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
import { StoreFooterComponent, StoreFooterSection } from './store-footer/store-footer.component';
|
||||||
import { StoreHeaderComponent } from './store-header/store-header.component';
|
import { StoreHeaderComponent } from './store-header/store-header.component';
|
||||||
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
|
import { CartComponent, CartItemMock } from '../../../shared/components/cart/cart.component';
|
||||||
import { ButtonComponent } from '../../../shared/components/button/button.component';
|
import { ButtonComponent } from '../../../shared/components/button/button.component';
|
||||||
import { CartItem } from '../../services/cart/cart.interface';
|
import { CartItem, CartItemVariantValue } from '../../services/cart/cart.interface';
|
||||||
import { AuthService } from '../../services/auth/auth.service';
|
import { AuthService } from '../../services/auth/auth.service';
|
||||||
import { findMenu } from '../../services/menu.utils';
|
import { findMenu } from '../../services/menu.utils';
|
||||||
import { CheckoutService } from '../../services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
isExpiredStockReservationResponse,
|
||||||
|
} from '../../services/checkout.service';
|
||||||
import { ToastService } from '../../services/toast.service';
|
import { ToastService } from '../../services/toast.service';
|
||||||
import { Category } from '../../services/tenant.interface';
|
import { Category } from '../../services/tenant.interface';
|
||||||
|
import { CheckoutCountdownService } from '../../services/checkout-countdown.service';
|
||||||
|
import { EventDateNotice, EventDateNoticeService } from '../../services/event-date-notice.service';
|
||||||
|
import { ModalService } from '../../services/modal.service';
|
||||||
|
import { EventDateNoticeModalComponent } from '../../../shared/components/event-date-notice-modal/event-date-notice-modal.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-store-layout',
|
selector: 'app-store-layout',
|
||||||
@@ -30,11 +56,78 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
private readonly cartService = inject(CartService);
|
private readonly cartService = inject(CartService);
|
||||||
private readonly authService = inject(AuthService);
|
private readonly authService = inject(AuthService);
|
||||||
private readonly checkoutService = inject(CheckoutService);
|
private readonly checkoutService = inject(CheckoutService);
|
||||||
|
private readonly checkoutCountdownService = inject(CheckoutCountdownService);
|
||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
|
private readonly eventDateNoticeService = inject(EventDateNoticeService);
|
||||||
|
private readonly modalService = inject(ModalService);
|
||||||
|
private claimedNoticeUserId: number | null = null;
|
||||||
|
|
||||||
protected readonly isCartOpen = signal(false);
|
protected readonly isCartOpen = signal(false);
|
||||||
|
protected readonly isCheckoutRoute = signal(this.isCheckoutUrl(this.router.url));
|
||||||
|
protected readonly isHomeRoute = signal(this.isHomeUrl(this.router.url));
|
||||||
|
protected readonly checkoutRemainingSeconds = this.checkoutCountdownService.remainingSeconds;
|
||||||
protected readonly isCreatingPurchase = signal(false);
|
protected readonly isCreatingPurchase = signal(false);
|
||||||
|
private readonly isMultiEventStorefront = computed(
|
||||||
|
() => this.tenant()?.storefront_website_type_code === 'onticket_multi_event',
|
||||||
|
);
|
||||||
|
protected readonly headerCheckoutRemainingSeconds = computed(() =>
|
||||||
|
this.isCheckoutRoute() && this.tenant()?.checkout_summary_type === 'event'
|
||||||
|
? null
|
||||||
|
: this.checkoutRemainingSeconds(),
|
||||||
|
);
|
||||||
|
protected readonly navigationCategories = computed(() =>
|
||||||
|
this.isMultiEventStorefront()
|
||||||
|
? (this.tenant()?.event_categories ?? [])
|
||||||
|
: (this.tenant()?.categories ?? []),
|
||||||
|
);
|
||||||
|
private readonly categoryMenu = computed(() =>
|
||||||
|
findMenu(
|
||||||
|
this.tenant()?.menues ?? [],
|
||||||
|
this.isMultiEventStorefront() ? 'event.category' : 'product.category',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
protected readonly displayCategories = computed(
|
||||||
|
() => (this.tenant()?.display_categories ?? true) && this.categoryMenu() !== undefined,
|
||||||
|
);
|
||||||
|
protected readonly displayCart = computed(() => this.tenant()?.display_cart ?? true);
|
||||||
|
protected readonly cartEditingPolicy = computed(() => this.tenant()?.cart_editing_policy ?? null);
|
||||||
|
protected readonly canModifyCart = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_modify ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canDeleteCartItems = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_delete ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartQuantity = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_update_quantity ?? false,
|
||||||
|
);
|
||||||
|
protected readonly canUpdateCartVariant = computed(
|
||||||
|
() => this.cartEditingPolicy()?.allow_update_variant ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const user = this.authService.user();
|
||||||
|
|
||||||
|
if (!isPlatformBrowser(this.platformId) || !user) {
|
||||||
|
this.claimedNoticeUserId = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.claimedNoticeUserId === user.id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.claimedNoticeUserId = user.id;
|
||||||
|
this.eventDateNoticeService.claim().subscribe({
|
||||||
|
next: ({ data }) => void this.showEventDateNotices(data, user.id),
|
||||||
|
error: (error) => console.error('Error loading event date notices', error),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected readonly cartSubtotal = computed(() => {
|
protected readonly cartSubtotal = computed(() => {
|
||||||
const cart = this.cartService.cart();
|
const cart = this.cartService.cart();
|
||||||
@@ -52,7 +145,7 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
private mapCartItemToMock(item: CartItem): CartItemMock {
|
private mapCartItemToMock(item: CartItem): CartItemMock {
|
||||||
const fullName = item.product?.nombre ?? '';
|
const fullName = item.nombre ?? '';
|
||||||
let product = fullName;
|
let product = fullName;
|
||||||
let attributes: { label: string; value: string }[] = [];
|
let attributes: { label: string; value: string }[] = [];
|
||||||
|
|
||||||
@@ -69,18 +162,39 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectedVariant = item.variant;
|
||||||
|
|
||||||
|
if (selectedVariant) {
|
||||||
|
attributes = Object.entries(selectedVariant.values).map(([label, value]) => ({
|
||||||
|
label: this.formatAttributeLabel(label),
|
||||||
|
value: this.formatAttributeValue(value),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cartItemId: item.id,
|
cartItemId: item.id,
|
||||||
imageUrl: item.product?.imagen ?? null,
|
imageUrl: item.imagen,
|
||||||
product,
|
product,
|
||||||
originalPrice: null,
|
originalPrice: null,
|
||||||
discountedPrice: parseFloat(item.precio_unitario),
|
discountedPrice: parseFloat(item.precio_unitario),
|
||||||
discountPercentage: null,
|
discountPercentage: null,
|
||||||
attributes,
|
attributes,
|
||||||
quantity: item.cantidad,
|
quantity: item.cantidad,
|
||||||
|
variantId: item.variant_id,
|
||||||
|
variants: item.variants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private formatAttributeLabel(value: string): string {
|
||||||
|
const label = value.replace(/[_-]+/g, ' ');
|
||||||
|
return label.charAt(0).toUpperCase() + label.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatAttributeValue(value: CartItemVariantValue): string {
|
||||||
|
const values = Array.isArray(value) ? value : [value];
|
||||||
|
return values.map((item) => (typeof item === 'string' ? item : item.label)).join(', ');
|
||||||
|
}
|
||||||
|
|
||||||
protected readonly currentYear = new Date().getFullYear();
|
protected readonly currentYear = new Date().getFullYear();
|
||||||
protected readonly tenant = this.tenantService.tenant;
|
protected readonly tenant = this.tenantService.tenant;
|
||||||
protected readonly user = this.authService.user;
|
protected readonly user = this.authService.user;
|
||||||
@@ -111,15 +225,77 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.router.events
|
||||||
|
.pipe(
|
||||||
|
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
)
|
||||||
|
.subscribe((event) => {
|
||||||
|
const isCheckoutRoute = this.isCheckoutUrl(event.urlAfterRedirects);
|
||||||
|
this.isCheckoutRoute.set(isCheckoutRoute);
|
||||||
|
this.isHomeRoute.set(this.isHomeUrl(event.urlAfterRedirects));
|
||||||
|
|
||||||
|
if (isCheckoutRoute) {
|
||||||
|
this.isCartOpen.set(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.route.queryParamMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
|
||||||
|
if (params.get('openCart') === 'true' && !this.isCheckoutRoute()) {
|
||||||
|
this.isCartOpen.set(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
this.cartService.loadCart().subscribe({
|
this.cartService.loadCart().subscribe({
|
||||||
error: (err) => console.error('Error loading cart', err),
|
error: (err) => console.error('Error loading cart', err),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private isCheckoutUrl(url: string): boolean {
|
||||||
|
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
||||||
|
|
||||||
|
return primarySegments[0]?.path === 'checkout';
|
||||||
|
}
|
||||||
|
|
||||||
|
private isHomeUrl(url: string): boolean {
|
||||||
|
const primarySegments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments ?? [];
|
||||||
|
return primarySegments.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
protected onLoginClick(): void {
|
protected onLoginClick(): void {
|
||||||
void this.router.navigate(['/login']);
|
void this.router.navigate(['/login']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected onCartClick(): void {
|
||||||
|
if (this.isCheckoutRoute()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isCartOpen.update((isOpen) => !isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showEventDateNotices(notices: EventDateNotice[], userId: number): Promise<void> {
|
||||||
|
for (const notice of notices) {
|
||||||
|
if (this.authService.user()?.id !== userId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const modalRef = this.modalService.open<EventDateNoticeModalComponent, void, EventDateNotice>(
|
||||||
|
EventDateNoticeModalComponent,
|
||||||
|
{
|
||||||
|
size: 'sm',
|
||||||
|
data: notice,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await firstValueFrom(modalRef.afterClosed$);
|
||||||
|
|
||||||
|
if (modalRef.dismissReason() === 'replaced') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected onSearch(term: string): void {
|
protected onSearch(term: string): void {
|
||||||
void this.router.navigate(['/buscar'], {
|
void this.router.navigate(['/buscar'], {
|
||||||
queryParams: { q: term, page: 1 },
|
queryParams: { q: term, page: 1 },
|
||||||
@@ -127,7 +303,9 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected onCategorySelect(category: Category): void {
|
protected onCategorySelect(category: Category): void {
|
||||||
void this.router.navigate(['/categoria', category.id], {
|
const route = this.isMultiEventStorefront() ? '/eventos/categoria' : '/categoria';
|
||||||
|
|
||||||
|
void this.router.navigate([route, category.id], {
|
||||||
queryParams: { page: 1 },
|
queryParams: { page: 1 },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -143,29 +321,45 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
protected async onLogoutClick(): Promise<void> {
|
protected async onLogoutClick(): Promise<void> {
|
||||||
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
const isLeavingCheckout = this.router.url.startsWith('/checkout');
|
||||||
|
|
||||||
// Checkout must be left while the authenticated session is still valid so
|
// Leave checkout before closing the authenticated session so its component
|
||||||
// its CanDeactivate guard can cancel the pending purchase.
|
// can stop payment polling cleanly. The checkout itself remains pending.
|
||||||
if (isLeavingCheckout) {
|
if (isLeavingCheckout) {
|
||||||
const navigationSucceeded = await this.router.navigate(['/']);
|
const navigationSucceeded = await this.router.navigate(['/']);
|
||||||
|
|
||||||
if (!navigationSucceeded) {
|
if (!navigationSucceeded) {
|
||||||
|
this.toastService.danger('No se pudo cerrar la sesión. Intentá nuevamente.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.authService.logout().subscribe({
|
this.authService.logout().subscribe({
|
||||||
next: () => {
|
next: ({ message }) => {
|
||||||
this.cartService.clearCart();
|
this.cartService.clearCart();
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
|
this.toastService.info(message || 'Sesión cerrada correctamente.');
|
||||||
|
|
||||||
if (!isLeavingCheckout) {
|
if (!isLeavingCheckout) {
|
||||||
void this.router.navigate(['/']);
|
void this.router.navigate(['/']);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: (err) => console.error('Error logging out', err),
|
error: (error: unknown) => {
|
||||||
|
this.toastService.danger(this.resolveLogoutErrorMessage(error));
|
||||||
|
console.error('Error logging out', error);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private resolveLogoutErrorMessage(error: unknown): string {
|
||||||
|
const payload =
|
||||||
|
typeof error === 'object' && error !== null && 'error' in error
|
||||||
|
? (error as { error?: { message?: unknown } }).error
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return typeof payload?.message === 'string' && payload.message.trim()
|
||||||
|
? payload.message
|
||||||
|
: 'No se pudo cerrar la sesión. Intentá nuevamente.';
|
||||||
|
}
|
||||||
|
|
||||||
protected async onCheckoutClick(): Promise<void> {
|
protected async onCheckoutClick(): Promise<void> {
|
||||||
if (this.isCreatingPurchase()) {
|
if (this.isCreatingPurchase()) {
|
||||||
return;
|
return;
|
||||||
@@ -192,14 +386,21 @@ export class StoreLayoutComponent implements OnInit {
|
|||||||
cart_id: cart.id,
|
cart_id: cart.id,
|
||||||
});
|
});
|
||||||
|
|
||||||
this.cartService.clearCart();
|
|
||||||
this.isCartOpen.set(false);
|
this.isCartOpen.set(false);
|
||||||
await this.router.navigate(['/checkout'], {
|
await this.router.navigate(['/checkout', purchase.id]);
|
||||||
queryParams: { purchase: purchase.id },
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create cart purchase:', error);
|
console.error('Failed to create cart purchase:', error);
|
||||||
this.toastService.danger('No se pudo iniciar la compra.');
|
const message =
|
||||||
|
error instanceof HttpErrorResponse && typeof error.error?.message === 'string'
|
||||||
|
? error.error.message
|
||||||
|
: 'No se pudo iniciar la compra.';
|
||||||
|
this.toastService.danger(message);
|
||||||
|
|
||||||
|
if (error instanceof HttpErrorResponse && isExpiredStockReservationResponse(error.error)) {
|
||||||
|
this.cartService.loadCart(true).subscribe({
|
||||||
|
error: (refreshError) => console.error('Error refreshing expired cart', refreshError),
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
this.isCreatingPurchase.set(false);
|
this.isCreatingPurchase.set(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,12 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout?mode=direct' } as never),
|
authGuard(null as never, { url: '/checkout/25' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result instanceof UrlTree).toBe(true);
|
expect(result instanceof UrlTree).toBe(true);
|
||||||
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe(
|
||||||
'/login?returnUrl=%2Fcheckout%3Fmode%3Ddirect',
|
'/login?returnUrl=%2Fcheckout%2F25',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ describe('auth guards', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const result = TestBed.runInInjectionContext(() =>
|
const result = TestBed.runInInjectionContext(() =>
|
||||||
authGuard(null as never, { url: '/checkout' } as never),
|
authGuard(null as never, { url: '/checkout/25' } as never),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ export interface LoginResponse {
|
|||||||
user: AuthUser;
|
user: AuthUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LogoutResponse {
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface RegisterResponse {
|
export interface RegisterResponse {
|
||||||
message: string;
|
message: string;
|
||||||
data: AuthUser;
|
data: AuthUser;
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, TransferState } from '@angular/core';
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TimeoutError } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../../environments/environment';
|
import { environment } from '../../../../environments/environment';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from '../bootstrap-request-timeout';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { CookieService } from '../cookie/cookie.service';
|
import { CookieService } from '../cookie/cookie.service';
|
||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
@@ -72,13 +74,13 @@ describe('AuthService', () => {
|
|||||||
expect(service.token()).toBe('plain-text-token');
|
expect(service.token()).toBe('plain-text-token');
|
||||||
expect(service.user()?.email).toBe('ada@example.com');
|
expect(service.user()?.email).toBe('ada@example.com');
|
||||||
expect(service.isAuthenticated()).toBe(true);
|
expect(service.isAuthenticated()).toBe(true);
|
||||||
expect(cookieStore['shopit.auth.token']).toBe('plain-text-token');
|
expect(cookieStore['shopit.front.auth.token']).toBe('plain-text-token');
|
||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hydrates token from cookies and loads the current user during bootstrap', async () => {
|
it('hydrates token from cookies and loads the current user during bootstrap', async () => {
|
||||||
cookieStore['shopit.auth.token'] = 'persisted-token';
|
cookieStore['shopit.front.auth.token'] = 'persisted-token';
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
@@ -152,7 +154,7 @@ describe('AuthService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('clears an expired session when /me returns 401', async () => {
|
it('clears an expired session when /me returns 401', async () => {
|
||||||
cookieStore['shopit.auth.token'] = 'expired-token';
|
cookieStore['shopit.front.auth.token'] = 'expired-token';
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
@@ -176,11 +178,48 @@ describe('AuthService', () => {
|
|||||||
expect(service.user()).toBeNull();
|
expect(service.user()).toBeNull();
|
||||||
expect(service.token()).toBeNull();
|
expect(service.token()).toBeNull();
|
||||||
expect(service.isAuthenticated()).toBe(false);
|
expect(service.isAuthenticated()).toBe(false);
|
||||||
expect(cookieStore['shopit.auth.token']).toBeUndefined();
|
expect(cookieStore['shopit.front.auth.token']).toBeUndefined();
|
||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('propagates a /me timeout without clearing the local session', async () => {
|
||||||
|
cookieStore['shopit.front.auth.token'] = 'valid-token';
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
AuthService,
|
||||||
|
{ provide: CookieService, useValue: createCookieServiceStub() },
|
||||||
|
{ provide: BOOTSTRAP_REQUEST_TIMEOUT_MS, useValue: 25 },
|
||||||
|
TransferState,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(AuthService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
const bootstrapPromise = service.bootstrap();
|
||||||
|
const rejection = expect(bootstrapPromise).rejects.toBeInstanceOf(TimeoutError);
|
||||||
|
const request = httpController.expectOne(`${environment.url}me`);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(25);
|
||||||
|
await rejection;
|
||||||
|
|
||||||
|
expect(request.cancelled).toBe(true);
|
||||||
|
expect(service.user()).toBeNull();
|
||||||
|
expect(service.token()).toBe('valid-token');
|
||||||
|
expect(cookieStore['shopit.front.auth.token']).toBe('valid-token');
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('registers without creating a session', () => {
|
it('registers without creating a session', () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
@@ -384,7 +423,7 @@ describe('AuthService', () => {
|
|||||||
|
|
||||||
expect(service.token()).toBe('plain-text-token');
|
expect(service.token()).toBe('plain-text-token');
|
||||||
expect(service.user()?.email).toBe('ada@example.com');
|
expect(service.user()?.email).toBe('ada@example.com');
|
||||||
expect(cookieStore['shopit.auth.token']).toBe('plain-text-token');
|
expect(cookieStore['shopit.front.auth.token']).toBe('plain-text-token');
|
||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { DOCUMENT } from '@angular/common';
|
|||||||
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
||||||
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||||
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
import { computed, inject, Injectable, PLATFORM_ID, signal, TransferState, makeStateKey } from '@angular/core';
|
||||||
import { firstValueFrom, map, Observable, of, tap } from 'rxjs';
|
import { firstValueFrom, map, Observable, of, tap, timeout } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../../environments/environment';
|
import { environment } from '../../../../environments/environment';
|
||||||
import { BaseApiService } from '../base-api.service';
|
import { BaseApiService } from '../base-api.service';
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
AuthUser,
|
AuthUser,
|
||||||
LoginPayload,
|
LoginPayload,
|
||||||
LoginResponse,
|
LoginResponse,
|
||||||
|
LogoutResponse,
|
||||||
RegisterPayload,
|
RegisterPayload,
|
||||||
RegisterResponse,
|
RegisterResponse,
|
||||||
ResetPasswordPayload,
|
ResetPasswordPayload,
|
||||||
@@ -20,8 +21,9 @@ import {
|
|||||||
} from './auth.interfaces';
|
} from './auth.interfaces';
|
||||||
import { CookieService } from '../cookie/cookie.service';
|
import { CookieService } from '../cookie/cookie.service';
|
||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from '../bootstrap-request-timeout';
|
||||||
|
|
||||||
const AUTH_TOKEN_COOKIE_KEY = 'shopit.auth.token';
|
const AUTH_TOKEN_COOKIE_KEY = 'shopit.front.auth.token';
|
||||||
const AUTH_USER_SSR_STATE_KEY = makeStateKey<AuthUser>('shopit.auth.user');
|
const AUTH_USER_SSR_STATE_KEY = makeStateKey<AuthUser>('shopit.auth.user');
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
@@ -33,6 +35,7 @@ export class AuthService extends BaseApiService {
|
|||||||
private readonly cookieService = inject(CookieService);
|
private readonly cookieService = inject(CookieService);
|
||||||
private readonly transferState = inject(TransferState);
|
private readonly transferState = inject(TransferState);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
private readonly bootstrapRequestTimeoutMs = inject(BOOTSTRAP_REQUEST_TIMEOUT_MS);
|
||||||
|
|
||||||
private readonly userState = signal<AuthUser | null>(null);
|
private readonly userState = signal<AuthUser | null>(null);
|
||||||
private readonly tokenState = signal<string | null>(null);
|
private readonly tokenState = signal<string | null>(null);
|
||||||
@@ -117,8 +120,12 @@ export class AuthService extends BaseApiService {
|
|||||||
|
|
||||||
const apiUrl = new URL(environment.url);
|
const apiUrl = new URL(environment.url);
|
||||||
const authorizationUrl = new URL('/auth/google/redirect', apiUrl.origin);
|
const authorizationUrl = new URL('/auth/google/redirect', apiUrl.origin);
|
||||||
|
const basePath = tenant.base_path && tenant.base_path !== '/' ? tenant.base_path : '';
|
||||||
authorizationUrl.searchParams.set('tenant', tenant.codigo);
|
authorizationUrl.searchParams.set('tenant', tenant.codigo);
|
||||||
authorizationUrl.searchParams.set('return_url', this.document.location.origin);
|
authorizationUrl.searchParams.set(
|
||||||
|
'return_url',
|
||||||
|
`${this.document.location.origin}${basePath}`,
|
||||||
|
);
|
||||||
|
|
||||||
this.document.location.assign(authorizationUrl.toString());
|
this.document.location.assign(authorizationUrl.toString());
|
||||||
}
|
}
|
||||||
@@ -149,14 +156,14 @@ export class AuthService extends BaseApiService {
|
|||||||
.pipe(tap((user) => this.userState.set(user)));
|
.pipe(tap((user) => this.userState.set(user)));
|
||||||
}
|
}
|
||||||
|
|
||||||
logout(): Observable<void> {
|
logout(): Observable<LogoutResponse> {
|
||||||
if (!this.tokenState()) {
|
if (!this.tokenState()) {
|
||||||
this.clearSession();
|
this.clearSession();
|
||||||
return of(void 0);
|
return of({ message: 'Sesión cerrada correctamente.' });
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.http
|
return this.http
|
||||||
.post<void>(`${environment.url}logout`, {})
|
.post<LogoutResponse>(`${environment.url}logout`, {})
|
||||||
.pipe(tap(() => this.clearSession()));
|
.pipe(tap(() => this.clearSession()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +182,9 @@ export class AuthService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const user = await firstValueFrom(this.loadCurrentUser());
|
const user = await firstValueFrom(
|
||||||
|
this.loadCurrentUser().pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||||
|
);
|
||||||
|
|
||||||
if (isPlatformServer(this.platformId)) {
|
if (isPlatformServer(this.platformId)) {
|
||||||
this.transferState.set(AUTH_USER_SSR_STATE_KEY, user);
|
this.transferState.set(AUTH_USER_SSR_STATE_KEY, user);
|
||||||
|
|||||||
9
src/app/core/services/bootstrap-request-timeout.ts
Normal file
9
src/app/core/services/bootstrap-request-timeout.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { InjectionToken } from '@angular/core';
|
||||||
|
|
||||||
|
export const BOOTSTRAP_REQUEST_TIMEOUT_MS = new InjectionToken<number>(
|
||||||
|
'BOOTSTRAP_REQUEST_TIMEOUT_MS',
|
||||||
|
{
|
||||||
|
providedIn: 'root',
|
||||||
|
factory: () => 10_000,
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -1,6 +1,18 @@
|
|||||||
export interface CartItemProduct {
|
export interface CartItemVariantOption {
|
||||||
nombre: string;
|
value: string;
|
||||||
imagen: string | null;
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CartItemVariantValue =
|
||||||
|
| string
|
||||||
|
| CartItemVariantOption
|
||||||
|
| Array<string | CartItemVariantOption>;
|
||||||
|
|
||||||
|
export interface CartItemVariant {
|
||||||
|
id: number;
|
||||||
|
precio: string;
|
||||||
|
stock_tecnico: number | null;
|
||||||
|
values: Record<string, CartItemVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CartItem {
|
export interface CartItem {
|
||||||
@@ -9,7 +21,10 @@ export interface CartItem {
|
|||||||
precio_unitario: string;
|
precio_unitario: string;
|
||||||
catalog_item_id: number;
|
catalog_item_id: number;
|
||||||
variant_id: number | null;
|
variant_id: number | null;
|
||||||
product: CartItemProduct | null;
|
nombre: string | null;
|
||||||
|
imagen: string | null;
|
||||||
|
variant: CartItemVariant | null;
|
||||||
|
variants?: CartItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Cart {
|
export interface Cart {
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ import { CartService } from './cart.service';
|
|||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
import { Cart } from './cart.interface';
|
import { Cart } from './cart.interface';
|
||||||
import { LOADING_MODE } from '../global-loading/loading-mode';
|
import { LOADING_MODE } from '../global-loading/loading-mode';
|
||||||
|
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
|
||||||
|
|
||||||
describe('CartService', () => {
|
describe('CartService', () => {
|
||||||
let service: CartService;
|
let service: CartService;
|
||||||
let httpMock: HttpTestingController;
|
let httpMock: HttpTestingController;
|
||||||
let tenantServiceMock: any;
|
let tenantServiceMock: any;
|
||||||
|
let catalogAvailabilityService: CatalogAvailabilityService;
|
||||||
|
|
||||||
const mockCart: Cart = {
|
const mockCart: Cart = {
|
||||||
id: 123,
|
id: 123,
|
||||||
@@ -24,9 +26,13 @@ describe('CartService', () => {
|
|||||||
precio_unitario: '10.00',
|
precio_unitario: '10.00',
|
||||||
catalog_item_id: 5,
|
catalog_item_id: 5,
|
||||||
variant_id: 10,
|
variant_id: 10,
|
||||||
product: {
|
nombre: 'Test Product (Size: M)',
|
||||||
nombre: 'Test Product (Size: M)',
|
imagen: null,
|
||||||
imagen: null,
|
variant: {
|
||||||
|
id: 10,
|
||||||
|
precio: '10.00',
|
||||||
|
stock_tecnico: 1,
|
||||||
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -49,6 +55,7 @@ describe('CartService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(CartService);
|
service = TestBed.inject(CartService);
|
||||||
|
catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||||
httpMock = TestBed.inject(HttpTestingController);
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -76,6 +83,20 @@ describe('CartService', () => {
|
|||||||
req.flush({ data: mockCart });
|
req.flush({ data: mockCart });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refreshes catalog availability only after the expired cart has been reloaded', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
|
service.loadCart(true).subscribe();
|
||||||
|
|
||||||
|
expect(availabilityChanged).not.toHaveBeenCalled();
|
||||||
|
const req = httpMock.expectOne('http://api.test/tenants/acme/cart');
|
||||||
|
req.flush({ data: mockCart });
|
||||||
|
|
||||||
|
expect(service.cart()).toEqual(mockCart);
|
||||||
|
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
it('propagates a custom loading mode to the request context', () => {
|
it('propagates a custom loading mode to the request context', () => {
|
||||||
service.withCustomLoading().loadCart().subscribe();
|
service.withCustomLoading().loadCart().subscribe();
|
||||||
|
|
||||||
@@ -97,6 +118,9 @@ describe('CartService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should add item and update signal', () => {
|
it('should add item and update signal', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
service.addItem(5, 10, 2).subscribe((res) => {
|
service.addItem(5, 10, 2).subscribe((res) => {
|
||||||
expect(res.data).toEqual(mockCart);
|
expect(res.data).toEqual(mockCart);
|
||||||
expect(service.cart()).toEqual(mockCart);
|
expect(service.cart()).toEqual(mockCart);
|
||||||
@@ -111,9 +135,13 @@ describe('CartService', () => {
|
|||||||
});
|
});
|
||||||
expect(req.request.withCredentials).toBe(true);
|
expect(req.request.withCredentials).toBe(true);
|
||||||
req.flush({ data: mockCart });
|
req.flush({ data: mockCart });
|
||||||
|
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should update item quantity and update signal', () => {
|
it('should update item quantity and update signal', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
const updatedCart = { ...mockCart, subtotal: '30.00' };
|
const updatedCart = { ...mockCart, subtotal: '30.00' };
|
||||||
updatedCart.items[0].cantidad = 3;
|
updatedCart.items[0].cantidad = 3;
|
||||||
|
|
||||||
@@ -127,9 +155,13 @@ describe('CartService', () => {
|
|||||||
expect(req.request.body).toEqual({ cantidad: 3 });
|
expect(req.request.body).toEqual({ cantidad: 3 });
|
||||||
expect(req.request.withCredentials).toBe(true);
|
expect(req.request.withCredentials).toBe(true);
|
||||||
req.flush({ data: updatedCart });
|
req.flush({ data: updatedCart });
|
||||||
|
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should remove item and update signal', () => {
|
it('should remove item and update signal', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
const emptyCart: Cart = {
|
const emptyCart: Cart = {
|
||||||
id: 123,
|
id: 123,
|
||||||
tenant_codigo: 'acme',
|
tenant_codigo: 'acme',
|
||||||
@@ -147,5 +179,18 @@ describe('CartService', () => {
|
|||||||
expect(req.request.method).toBe('DELETE');
|
expect(req.request.method).toBe('DELETE');
|
||||||
expect(req.request.withCredentials).toBe(true);
|
expect(req.request.withCredentials).toBe(true);
|
||||||
req.flush({ data: emptyCart });
|
req.flush({ data: emptyCart });
|
||||||
|
expect(availabilityChanged).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not notify an availability change when a cart mutation fails', () => {
|
||||||
|
const availabilityChanged = vi.fn();
|
||||||
|
catalogAvailabilityService.availabilityChanged$.subscribe(availabilityChanged);
|
||||||
|
|
||||||
|
service.removeItem(10).subscribe({ error: vi.fn() });
|
||||||
|
|
||||||
|
const req = httpMock.expectOne('http://api.test/tenants/acme/cart/items/10');
|
||||||
|
req.flush({ message: 'Error' }, { status: 500, statusText: 'Server Error' });
|
||||||
|
|
||||||
|
expect(availabilityChanged).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { catchError, map, Observable, tap } from 'rxjs';
|
|||||||
|
|
||||||
import { ApiResponse } from '../api-response.interface';
|
import { ApiResponse } from '../api-response.interface';
|
||||||
import { BaseApiService } from '../base-api.service';
|
import { BaseApiService } from '../base-api.service';
|
||||||
|
import { CatalogAvailabilityService } from '../catalog/catalog-availability.service';
|
||||||
import { TenantService } from '../tenant.service';
|
import { TenantService } from '../tenant.service';
|
||||||
import { Cart } from './cart.interface';
|
import { Cart } from './cart.interface';
|
||||||
|
|
||||||
@@ -10,6 +11,7 @@ import { Cart } from './cart.interface';
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CartService extends BaseApiService {
|
export class CartService extends BaseApiService {
|
||||||
|
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
|
||||||
private readonly cartState = signal<Cart | null>(null);
|
private readonly cartState = signal<Cart | null>(null);
|
||||||
@@ -32,14 +34,19 @@ export class CartService extends BaseApiService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadCart(): Observable<Cart> {
|
loadCart(refreshCatalogAvailability = false): Observable<Cart> {
|
||||||
return this.http
|
return this.http
|
||||||
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
.get<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart`, {
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
map((response) => response.data),
|
map((response) => response.data),
|
||||||
tap((cart) => this.cartState.set(cart)),
|
tap((cart) => {
|
||||||
|
this.cartState.set(cart);
|
||||||
|
if (refreshCatalogAvailability) {
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
|
}
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,9 +57,7 @@ export class CartService extends BaseApiService {
|
|||||||
): Observable<ApiResponse<Cart>> {
|
): Observable<ApiResponse<Cart>> {
|
||||||
this.isUpdatingState.set(true);
|
this.isUpdatingState.set(true);
|
||||||
return this.http
|
return this.http
|
||||||
.post<
|
.post<ApiResponse<Cart>>(
|
||||||
ApiResponse<Cart>
|
|
||||||
>(
|
|
||||||
`${this.tenantApiUrl}/cart/items`,
|
`${this.tenantApiUrl}/cart/items`,
|
||||||
{ catalog_item_id: catalogItemId, variant_id: variantId, cantidad },
|
{ catalog_item_id: catalogItemId, variant_id: variantId, cantidad },
|
||||||
{
|
{
|
||||||
@@ -62,6 +67,7 @@ export class CartService extends BaseApiService {
|
|||||||
.pipe(
|
.pipe(
|
||||||
tap((response) => {
|
tap((response) => {
|
||||||
this.cartState.set(response.data);
|
this.cartState.set(response.data);
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
this.isUpdatingState.set(false);
|
this.isUpdatingState.set(false);
|
||||||
}),
|
}),
|
||||||
catchError((error) => {
|
catchError((error) => {
|
||||||
@@ -71,24 +77,31 @@ export class CartService extends BaseApiService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateItemQuantity(
|
updateItemQuantity(cartItemId: number, cantidad: number): Observable<ApiResponse<Cart>> {
|
||||||
|
return this.updateItem(cartItemId, { cantidad });
|
||||||
|
}
|
||||||
|
|
||||||
|
updateItemVariant(
|
||||||
cartItemId: number,
|
cartItemId: number,
|
||||||
cantidad: number,
|
cantidad: number,
|
||||||
|
variantId: number,
|
||||||
|
): Observable<ApiResponse<Cart>> {
|
||||||
|
return this.updateItem(cartItemId, { cantidad, variant_id: variantId });
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateItem(
|
||||||
|
cartItemId: number,
|
||||||
|
payload: { cantidad: number; variant_id?: number },
|
||||||
): Observable<ApiResponse<Cart>> {
|
): Observable<ApiResponse<Cart>> {
|
||||||
this.isUpdatingState.set(true);
|
this.isUpdatingState.set(true);
|
||||||
return this.http
|
return this.http
|
||||||
.patch<
|
.patch<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, payload, {
|
||||||
ApiResponse<Cart>
|
withCredentials: true,
|
||||||
>(
|
})
|
||||||
`${this.tenantApiUrl}/cart/items/${cartItemId}`,
|
|
||||||
{ cantidad },
|
|
||||||
{
|
|
||||||
withCredentials: true,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.pipe(
|
.pipe(
|
||||||
tap((response) => {
|
tap((response) => {
|
||||||
this.cartState.set(response.data);
|
this.cartState.set(response.data);
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
this.isUpdatingState.set(false);
|
this.isUpdatingState.set(false);
|
||||||
}),
|
}),
|
||||||
catchError((error) => {
|
catchError((error) => {
|
||||||
@@ -101,14 +114,13 @@ export class CartService extends BaseApiService {
|
|||||||
removeItem(cartItemId: number): Observable<ApiResponse<Cart>> {
|
removeItem(cartItemId: number): Observable<ApiResponse<Cart>> {
|
||||||
this.isUpdatingState.set(true);
|
this.isUpdatingState.set(true);
|
||||||
return this.http
|
return this.http
|
||||||
.delete<
|
.delete<ApiResponse<Cart>>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, {
|
||||||
ApiResponse<Cart>
|
|
||||||
>(`${this.tenantApiUrl}/cart/items/${cartItemId}`, {
|
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(
|
||||||
tap((response) => {
|
tap((response) => {
|
||||||
this.cartState.set(response.data);
|
this.cartState.set(response.data);
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
this.isUpdatingState.set(false);
|
this.isUpdatingState.set(false);
|
||||||
}),
|
}),
|
||||||
catchError((error) => {
|
catchError((error) => {
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { Observable, Subject } from 'rxjs';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class CatalogAvailabilityService {
|
||||||
|
private readonly availabilityChangedSubject = new Subject<void>();
|
||||||
|
|
||||||
|
readonly availabilityChanged$: Observable<void> = this.availabilityChangedSubject.asObservable();
|
||||||
|
|
||||||
|
notifyAvailabilityChanged(): void {
|
||||||
|
this.availabilityChangedSubject.next();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
|
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
|
||||||
|
|
||||||
|
export type CatalogItemType = 'product' | 'bundle';
|
||||||
|
|
||||||
export interface Product {
|
export interface Product {
|
||||||
id: number;
|
id: number;
|
||||||
|
type: CatalogItemType;
|
||||||
category_id: number;
|
category_id: number;
|
||||||
brand_id: number | null;
|
brand_id: number | null;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -15,32 +18,61 @@ export interface Product {
|
|||||||
|
|
||||||
export interface ProductAttributeOption {
|
export interface ProductAttributeOption {
|
||||||
id: number;
|
id: number;
|
||||||
|
validity_time_id?: number | null;
|
||||||
value: string;
|
value: string;
|
||||||
label: string;
|
label: string;
|
||||||
sort_order: number;
|
sort_order: number;
|
||||||
metadata: Record<string, unknown> | null;
|
metadata: Record<string, unknown> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ProductAttributeType =
|
||||||
|
| 'string'
|
||||||
|
| 'number'
|
||||||
|
| 'boolean'
|
||||||
|
| 'select'
|
||||||
|
| 'multiselect'
|
||||||
|
| 'color'
|
||||||
|
| 'image'
|
||||||
|
| 'event_date';
|
||||||
|
|
||||||
export interface ProductAttribute {
|
export interface ProductAttribute {
|
||||||
id: number;
|
id: number;
|
||||||
codigo: string;
|
codigo: string;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
is_required: boolean;
|
is_required: boolean;
|
||||||
|
allow_multi_select?: boolean;
|
||||||
|
show_in_selector?: boolean;
|
||||||
metadata_schema: Record<string, unknown> | null;
|
metadata_schema: Record<string, unknown> | null;
|
||||||
type: string;
|
type: ProductAttributeType;
|
||||||
options: ProductAttributeOption[];
|
options: ProductAttributeOption[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InventoryPolicy = 'tracked' | 'unlimited';
|
export type InventoryPolicy = 'tracked' | 'unlimited';
|
||||||
|
|
||||||
|
export interface CatalogVariantOption {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CatalogVariantValue =
|
||||||
|
| string
|
||||||
|
| CatalogVariantOption
|
||||||
|
| Array<string | CatalogVariantOption>;
|
||||||
|
|
||||||
export interface CatalogItemVariant {
|
export interface CatalogItemVariant {
|
||||||
id: number;
|
id: number;
|
||||||
stock_tecnico: number | null;
|
descripcion?: string | null;
|
||||||
|
precio?: string;
|
||||||
|
event_date_id?: number | null;
|
||||||
|
event_date_ids?: number[];
|
||||||
|
event_dates?: string[];
|
||||||
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
minimum_use_date?: string | null;
|
minimum_use_date?: string | null;
|
||||||
maximum_use_date?: string | null;
|
maximum_use_date?: string | null;
|
||||||
effective_minimum_use_date?: string | null;
|
effective_minimum_use_date?: string | null;
|
||||||
effective_maximum_use_date?: string | null;
|
effective_maximum_use_date?: string | null;
|
||||||
values: Record<string, string>;
|
values: Record<string, CatalogVariantValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
||||||
@@ -49,6 +81,8 @@ export interface SelectedCatalogItemVariant extends CatalogItemVariant {
|
|||||||
|
|
||||||
export interface CatalogItemDetail {
|
export interface CatalogItemDetail {
|
||||||
id: number;
|
id: number;
|
||||||
|
type: CatalogItemType;
|
||||||
|
purpose?: 'product' | 'entry';
|
||||||
category_id: number | null;
|
category_id: number | null;
|
||||||
brand_id: number | null;
|
brand_id: number | null;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -58,32 +92,63 @@ export interface CatalogItemDetail {
|
|||||||
category: string | null;
|
category: string | null;
|
||||||
brand: string | null;
|
brand: string | null;
|
||||||
inventory_policy: InventoryPolicy;
|
inventory_policy: InventoryPolicy;
|
||||||
|
max_units_per_user?: number | null;
|
||||||
has_tickets: boolean;
|
has_tickets: boolean;
|
||||||
minimum_use_date: string | null;
|
minimum_use_date: string | null;
|
||||||
maximum_use_date: string | null;
|
maximum_use_date: string | null;
|
||||||
attributes: ProductAttribute[];
|
attributes: ProductAttribute[];
|
||||||
variants: CatalogItemVariant[];
|
variants: CatalogItemVariant[];
|
||||||
selected_variant?: SelectedCatalogItemVariant;
|
selected_variant?: SelectedCatalogItemVariant;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
images?: string[];
|
images?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CatalogProductLayout = 'row' | 'column_with_image' | 'column_with_cart';
|
export type CatalogProductLayout =
|
||||||
export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'carousel';
|
| 'row'
|
||||||
|
| 'column_with_image'
|
||||||
|
| 'column_with_cart'
|
||||||
|
| 'ticket_selector';
|
||||||
|
export type CatalogGroupLayout = 'paginated' | 'simple' | 'simple_vertical' | 'carousel' | 'single';
|
||||||
|
|
||||||
export interface CatalogFeaturedItemVariant {
|
export interface CatalogFeaturedItemVariant {
|
||||||
id: number;
|
id: number;
|
||||||
stock_tecnico: number | null;
|
descripcion?: string | null;
|
||||||
values: Record<string, string>;
|
precio?: string;
|
||||||
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
|
values: Record<string, CatalogVariantValue>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CatalogVariantOptionsResponse {
|
||||||
|
variants: CatalogFeaturedItemVariant[];
|
||||||
|
selectors: CatalogVariantSelector[];
|
||||||
|
selected_values: Record<string, string | string[]>;
|
||||||
|
resolved_variant: CatalogFeaturedItemVariant | null;
|
||||||
|
valid: boolean;
|
||||||
|
available_variant_count: number;
|
||||||
|
matching_variant_count: number;
|
||||||
|
price_range: {
|
||||||
|
minimum: string;
|
||||||
|
maximum: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CatalogVariantSelector {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
options: CatalogVariantValue[];
|
||||||
|
enabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CatalogFeaturedItem {
|
export interface CatalogFeaturedItem {
|
||||||
id: number;
|
id: number;
|
||||||
|
type: CatalogItemType;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
descripcion?: string | null;
|
descripcion?: string | null;
|
||||||
precio: number | string;
|
precio: number | string;
|
||||||
image?: string | null;
|
image?: string | null;
|
||||||
stock_tecnico?: number | null;
|
maximum_addable_quantity?: number | null;
|
||||||
|
unavailable_message?: string | null;
|
||||||
variants?: CatalogFeaturedItemVariant[];
|
variants?: CatalogFeaturedItemVariant[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +158,7 @@ export type CatalogFeaturedItems =
|
|||||||
|
|
||||||
export interface CatalogFeaturedGroup {
|
export interface CatalogFeaturedGroup {
|
||||||
id: number;
|
id: number;
|
||||||
|
code: string;
|
||||||
title: string;
|
title: string;
|
||||||
layout: CatalogProductLayout;
|
layout: CatalogProductLayout;
|
||||||
group_layout: CatalogGroupLayout;
|
group_layout: CatalogGroupLayout;
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ import {
|
|||||||
CatalogFeaturedItem,
|
CatalogFeaturedItem,
|
||||||
CatalogFeaturedItems,
|
CatalogFeaturedItems,
|
||||||
CatalogItemDetail,
|
CatalogItemDetail,
|
||||||
|
CatalogVariantOptionsResponse,
|
||||||
CategoryItemsResponse,
|
CategoryItemsResponse,
|
||||||
Product,
|
|
||||||
} from './catalog.interface';
|
} from './catalog.interface';
|
||||||
|
|
||||||
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
type HttpParamValue = string | number | boolean | readonly (string | number | boolean)[];
|
||||||
@@ -32,12 +32,6 @@ export class CatalogService extends BaseApiService {
|
|||||||
return this.tenantService.getTenantApiUrl();
|
return this.tenantService.getTenantApiUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
getProductos(params?: ApiPaginationQueryParams): Observable<ApiPaginatedResponse<Product[]>> {
|
|
||||||
return this.http.get<ApiPaginatedResponse<Product[]>>(`${this.tenantApiUrl}/productos`, {
|
|
||||||
params: this.buildHttpParams(params),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
getCatalog(): Observable<CatalogFeaturedGroup[]> {
|
||||||
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
return this.http.get<CatalogFeaturedGroup[]>(`${this.tenantApiUrl}/catalog`);
|
||||||
}
|
}
|
||||||
@@ -74,10 +68,7 @@ export class CatalogService extends BaseApiService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getCatalogItem(
|
getCatalogItem(id: number, variantId?: number): Observable<CatalogItemDetail> {
|
||||||
id: number,
|
|
||||||
variantId?: number,
|
|
||||||
): Observable<CatalogItemDetail> {
|
|
||||||
let params = new HttpParams();
|
let params = new HttpParams();
|
||||||
if (variantId) {
|
if (variantId) {
|
||||||
params = params.set('variant_id', variantId);
|
params = params.set('variant_id', variantId);
|
||||||
@@ -90,6 +81,20 @@ export class CatalogService extends BaseApiService {
|
|||||||
.pipe(map((response) => response.data));
|
.pipe(map((response) => response.data));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getVariantOptions(
|
||||||
|
catalogItemId: number,
|
||||||
|
payload: {
|
||||||
|
selected_values: Record<string, string | string[]>;
|
||||||
|
cart_item_id?: number | null;
|
||||||
|
},
|
||||||
|
): Observable<CatalogVariantOptionsResponse> {
|
||||||
|
return this.http
|
||||||
|
.post<
|
||||||
|
ApiResponse<CatalogVariantOptionsResponse>
|
||||||
|
>(`${this.tenantApiUrl}/catalog-items/${catalogItemId}/variant-options`, payload, { withCredentials: true })
|
||||||
|
.pipe(map((response) => response.data));
|
||||||
|
}
|
||||||
|
|
||||||
private buildHttpParams(params?: ApiPaginationQueryParams): HttpParams {
|
private buildHttpParams(params?: ApiPaginationQueryParams): HttpParams {
|
||||||
if (!params) {
|
if (!params) {
|
||||||
return new HttpParams();
|
return new HttpParams();
|
||||||
|
|||||||
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
69
src/app/core/services/checkout-countdown.service.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { CheckoutCountdownService } from './checkout-countdown.service';
|
||||||
|
|
||||||
|
describe('CheckoutCountdownService', () => {
|
||||||
|
let service: CheckoutCountdownService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(new Date('2026-08-27T12:00:00.000Z'));
|
||||||
|
TestBed.configureTestingModule({ providers: [CheckoutCountdownService] });
|
||||||
|
service = TestBed.inject(CheckoutCountdownService);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
service.clear();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts down from the checkout server timing without depending on the client clock', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: '2026-08-27T15:10:00.000Z',
|
||||||
|
expires_in_seconds: 600,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(600);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(1_000);
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(599);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recalculates against the deadline after a delayed browser interval', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: 10,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.setSystemTime(new Date('2026-08-27T12:00:07.000Z'));
|
||||||
|
vi.advanceTimersByTime(1_000);
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears the countdown when checkout has no expiration', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: null,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the active countdown when a partial checkout response omits timing fields', () => {
|
||||||
|
service.synchronize({
|
||||||
|
expires_at: null,
|
||||||
|
expires_in_seconds: 10,
|
||||||
|
server_time: '2026-08-27T15:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
service.synchronize({});
|
||||||
|
|
||||||
|
expect(service.remainingSeconds()).toBe(10);
|
||||||
|
});
|
||||||
|
});
|
||||||
97
src/app/core/services/checkout-countdown.service.ts
Normal file
97
src/app/core/services/checkout-countdown.service.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import { Injectable, OnDestroy, signal } from '@angular/core';
|
||||||
|
|
||||||
|
export interface CheckoutTiming {
|
||||||
|
expires_at: string | null;
|
||||||
|
expires_in_seconds: number | null;
|
||||||
|
server_time: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root',
|
||||||
|
})
|
||||||
|
export class CheckoutCountdownService implements OnDestroy {
|
||||||
|
private readonly remainingSecondsState = signal<number | null>(null);
|
||||||
|
private deadlineMs: number | null = null;
|
||||||
|
private intervalId: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
readonly remainingSeconds = this.remainingSecondsState.asReadonly();
|
||||||
|
|
||||||
|
synchronize(timing: Partial<CheckoutTiming>): void {
|
||||||
|
const remainingSeconds = this.resolveRemainingSeconds(timing);
|
||||||
|
|
||||||
|
if (remainingSeconds === undefined) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainingSeconds === null) {
|
||||||
|
this.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.stopInterval();
|
||||||
|
this.deadlineMs = Date.now() + remainingSeconds * 1_000;
|
||||||
|
this.updateRemainingSeconds();
|
||||||
|
|
||||||
|
if (remainingSeconds > 0) {
|
||||||
|
this.intervalId = setInterval(() => this.updateRemainingSeconds(), 1_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.stopInterval();
|
||||||
|
this.deadlineMs = null;
|
||||||
|
this.remainingSecondsState.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveRemainingSeconds(timing: Partial<CheckoutTiming>): number | null | undefined {
|
||||||
|
if (timing.expires_at === null && timing.expires_in_seconds === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expiresAt =
|
||||||
|
typeof timing.expires_at === 'string' ? Date.parse(timing.expires_at) : Number.NaN;
|
||||||
|
const serverTime =
|
||||||
|
typeof timing.server_time === 'string' ? Date.parse(timing.server_time) : Number.NaN;
|
||||||
|
|
||||||
|
if (Number.isFinite(expiresAt) && Number.isFinite(serverTime)) {
|
||||||
|
return Math.max(0, Math.ceil((expiresAt - serverTime) / 1_000));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof timing.expires_in_seconds === 'number' &&
|
||||||
|
Number.isFinite(timing.expires_in_seconds)
|
||||||
|
) {
|
||||||
|
return Math.max(0, Math.ceil(timing.expires_in_seconds));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number.isFinite(expiresAt)) {
|
||||||
|
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1_000));
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateRemainingSeconds(): void {
|
||||||
|
if (this.deadlineMs === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingSeconds = Math.max(0, Math.ceil((this.deadlineMs - Date.now()) / 1_000));
|
||||||
|
this.remainingSecondsState.set(remainingSeconds);
|
||||||
|
|
||||||
|
if (remainingSeconds === 0) {
|
||||||
|
this.stopInterval();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private stopInterval(): void {
|
||||||
|
if (this.intervalId !== null) {
|
||||||
|
clearInterval(this.intervalId);
|
||||||
|
this.intervalId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
97
src/app/core/services/checkout.service.spec.ts
Normal file
97
src/app/core/services/checkout.service.spec.ts
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||||
|
import { CheckoutService } from './checkout.service';
|
||||||
|
|
||||||
|
describe('CheckoutService', () => {
|
||||||
|
let service: CheckoutService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [CheckoutService, provideHttpClient(), provideHttpClientTesting()],
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(CheckoutService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('starts one direct checkout with all selected variants', async () => {
|
||||||
|
const payload = {
|
||||||
|
direct_items: [
|
||||||
|
{ catalog_item_id: 10, variant_id: 101, cantidad: 1 },
|
||||||
|
{ catalog_item_id: 10, variant_id: 102, cantidad: 1 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const purchasePromise = service.startCheckout('desfile', payload);
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||||
|
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
expect(request.request.body).toEqual(payload);
|
||||||
|
|
||||||
|
request.flush({ data: { id: 55 } });
|
||||||
|
|
||||||
|
await expect(purchasePromise).resolves.toMatchObject({ id: 55 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refreshes catalog availability when starting checkout fails', async () => {
|
||||||
|
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||||
|
const notifyAvailabilityChanged = vi.spyOn(
|
||||||
|
catalogAvailabilityService,
|
||||||
|
'notifyAvailabilityChanged',
|
||||||
|
);
|
||||||
|
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||||
|
|
||||||
|
request.flush(
|
||||||
|
{ message: 'No hay stock disponible.' },
|
||||||
|
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(purchasePromise).rejects.toBeTruthy();
|
||||||
|
expect(notifyAvailabilityChanged).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits for the expired cart refresh before refreshing catalog availability', async () => {
|
||||||
|
const catalogAvailabilityService = TestBed.inject(CatalogAvailabilityService);
|
||||||
|
const notifyAvailabilityChanged = vi.spyOn(
|
||||||
|
catalogAvailabilityService,
|
||||||
|
'notifyAvailabilityChanged',
|
||||||
|
);
|
||||||
|
const purchasePromise = service.startCheckout('desfile', { cart_id: 12 });
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/start-checkout`);
|
||||||
|
|
||||||
|
request.flush(
|
||||||
|
{
|
||||||
|
code: 'stock_reservation.expired',
|
||||||
|
message: 'La reserva de stock venció.',
|
||||||
|
},
|
||||||
|
{ status: 422, statusText: 'Unprocessable Entity' },
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(purchasePromise).rejects.toBeTruthy();
|
||||||
|
expect(notifyAvailabilityChanged).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves checkout timing fields when completing a purchase', async () => {
|
||||||
|
const purchasePromise = service.completePurchase('desfile', 55);
|
||||||
|
const request = httpMock.expectOne(`${environment.url}tenants/desfile/compras/55/complete`);
|
||||||
|
const response = {
|
||||||
|
status: 'pending_payment',
|
||||||
|
expires_at: '2026-08-26T20:00:00.000Z',
|
||||||
|
expires_in_seconds: 900,
|
||||||
|
server_time: '2026-08-26T19:45:00.000Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
request.flush({ data: response });
|
||||||
|
|
||||||
|
await expect(purchasePromise).resolves.toEqual(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
import { Injectable } from '@angular/core';
|
import { inject, Injectable } from '@angular/core';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { ApiPaginatedResponse } from './api-paginated-response.interface';
|
||||||
|
import { ApiPaginationQueryParams } from './api-pagination-query-params.interface';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { CatalogAvailabilityService } from './catalog/catalog-availability.service';
|
||||||
|
|
||||||
export interface UpdatePurchaseCustomerPayload {
|
export interface UpdatePurchaseCustomerPayload {
|
||||||
dni: string;
|
dni: string;
|
||||||
@@ -11,20 +14,89 @@ export interface UpdatePurchaseCustomerPayload {
|
|||||||
email: string;
|
email: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DirectCheckoutItem {
|
||||||
|
catalog_item_id: number;
|
||||||
|
variant_id: number | null;
|
||||||
|
cantidad: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnavailableCheckoutItem {
|
||||||
|
index: number;
|
||||||
|
catalog_item_id: number;
|
||||||
|
variant_id: number | null;
|
||||||
|
requested_quantity: number;
|
||||||
|
available_quantity: number;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InsufficientStockResponse {
|
||||||
|
code: 'purchase.insufficient_stock';
|
||||||
|
message: string;
|
||||||
|
errors: Record<string, string[]>;
|
||||||
|
unavailable_items: UnavailableCheckoutItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isInsufficientStockResponse(value: unknown): value is InsufficientStockResponse {
|
||||||
|
if (typeof value !== 'object' || value === null) return false;
|
||||||
|
|
||||||
|
const response = value as Partial<InsufficientStockResponse>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
response.code === 'purchase.insufficient_stock' && Array.isArray(response.unavailable_items)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExpiredStockReservationResponse {
|
||||||
|
code: 'stock_reservation.expired';
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isExpiredStockReservationResponse(
|
||||||
|
value: unknown,
|
||||||
|
): value is ExpiredStockReservationResponse {
|
||||||
|
return (
|
||||||
|
typeof value === 'object' &&
|
||||||
|
value !== null &&
|
||||||
|
(value as Partial<ExpiredStockReservationResponse>).code === 'stock_reservation.expired'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export type StartCheckoutPayload =
|
export type StartCheckoutPayload =
|
||||||
| {
|
| {
|
||||||
cart_id: number;
|
cart_id: number;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
direct_item: {
|
direct_items: DirectCheckoutItem[];
|
||||||
catalog_item_id: number;
|
|
||||||
variant_id: number | null;
|
|
||||||
cantidad: number;
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface PurchaseStatusResponse {
|
export interface PurchaseStatusResponse {
|
||||||
status: string | null;
|
status: string | null;
|
||||||
|
expires_at: string | null;
|
||||||
|
expires_in_seconds: number | null;
|
||||||
|
server_time: string;
|
||||||
|
payment_verification?: PurchasePaymentVerificationResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PurchasePaymentCandidateReason =
|
||||||
|
| 'ambiguous_exact_match'
|
||||||
|
| 'exact_dni_near_amount'
|
||||||
|
| 'exact_amount_near_dni';
|
||||||
|
|
||||||
|
export interface PurchasePaymentCandidatePrimaryResponse {
|
||||||
|
reason: PurchasePaymentCandidateReason;
|
||||||
|
dni_distance: number | null;
|
||||||
|
payment_amount: string;
|
||||||
|
purchase_amount: string;
|
||||||
|
amount_difference: string;
|
||||||
|
confidence: 'exact' | 'high' | 'medium';
|
||||||
|
detected_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchasePaymentVerificationResponse {
|
||||||
|
status: 'pending' | 'candidate';
|
||||||
|
candidate_count: number;
|
||||||
|
primary: PurchasePaymentCandidatePrimaryResponse | null;
|
||||||
|
reasons: PurchasePaymentCandidateReason[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
export interface PurchaseSummaryResponse extends PurchaseStatusResponse {
|
||||||
@@ -49,11 +121,17 @@ export interface PurchaseDetailItemResponse {
|
|||||||
nombre: string;
|
nombre: string;
|
||||||
descripcion: string | null;
|
descripcion: string | null;
|
||||||
slug: string;
|
slug: string;
|
||||||
imagen: string | null;
|
imagen?: string | null;
|
||||||
attributes: PurchaseDetailAttributeResponse[];
|
attributes: PurchaseDetailAttributeResponse[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PurchaseCheckoutEventResponse {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
image: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
||||||
id: number;
|
id: number;
|
||||||
cart_id: number | null;
|
cart_id: number | null;
|
||||||
@@ -68,6 +146,7 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
email: string | null;
|
email: string | null;
|
||||||
items_source: 'purchase';
|
items_source: 'purchase';
|
||||||
items: PurchaseDetailItemResponse[];
|
items: PurchaseDetailItemResponse[];
|
||||||
|
event?: PurchaseCheckoutEventResponse | null;
|
||||||
tickets_count?: number;
|
tickets_count?: number;
|
||||||
has_generated_tickets?: boolean;
|
has_generated_tickets?: boolean;
|
||||||
subtotal: string;
|
subtotal: string;
|
||||||
@@ -78,30 +157,40 @@ export interface PurchaseDetailResponse extends PurchaseStatusResponse {
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CheckoutService extends BaseApiService {
|
export class CheckoutService extends BaseApiService {
|
||||||
|
private readonly catalogAvailabilityService = inject(CatalogAvailabilityService);
|
||||||
|
|
||||||
async startCheckout(
|
async startCheckout(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
payload: StartCheckoutPayload,
|
payload: StartCheckoutPayload,
|
||||||
): Promise<PurchaseDetailResponse> {
|
): Promise<PurchaseDetailResponse> {
|
||||||
const response = await firstValueFrom(
|
try {
|
||||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
const response = await firstValueFrom(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
||||||
payload,
|
`${environment.url}tenants/${tenantCode}/compras/start-checkout`,
|
||||||
),
|
payload,
|
||||||
);
|
),
|
||||||
|
);
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
||||||
|
|
||||||
if (!purchase?.id) {
|
if (!purchase?.id) {
|
||||||
throw new Error('Error al crear la compra.');
|
throw new Error('Error al crear la compra.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return purchase;
|
||||||
|
} catch (error) {
|
||||||
|
const responseBody = (error as { error?: unknown } | null)?.error;
|
||||||
|
if (!isExpiredStockReservationResponse(responseBody)) {
|
||||||
|
this.catalogAvailabilityService.notifyAvailabilityChanged();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return purchase;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async generatePaymentIntent(
|
async generatePaymentIntent(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
method: 'qr' | 'transfer' | 'telepagos',
|
method: 'qr' | 'transfer',
|
||||||
payerDni?: string,
|
payerDni?: string,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
const payload: any = { method };
|
const payload: any = { method };
|
||||||
@@ -140,68 +229,6 @@ export class CheckoutService extends BaseApiService {
|
|||||||
return purchase;
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateItemQuantity(
|
|
||||||
tenantCode: string,
|
|
||||||
purchaseId: number,
|
|
||||||
itemId: number,
|
|
||||||
quantity: number,
|
|
||||||
): Promise<PurchaseDetailResponse> {
|
|
||||||
const response = await firstValueFrom(
|
|
||||||
this.http.patch<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/items/${itemId}`,
|
|
||||||
{ quantity },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
|
||||||
if (!purchase) {
|
|
||||||
throw new Error('Error al actualizar la cantidad del producto.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return purchase;
|
|
||||||
}
|
|
||||||
|
|
||||||
async prepareItemEditing(
|
|
||||||
tenantCode: string,
|
|
||||||
purchaseId: number,
|
|
||||||
): Promise<PurchaseDetailResponse> {
|
|
||||||
const response = await firstValueFrom(
|
|
||||||
this.http.post<{ data?: PurchaseDetailResponse } | PurchaseDetailResponse>(
|
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/edit-items`,
|
|
||||||
{},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseDetailResponse>(response);
|
|
||||||
if (!purchase) {
|
|
||||||
throw new Error('Error al preparar la compra para editarla.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return purchase;
|
|
||||||
}
|
|
||||||
|
|
||||||
async completePurchase(
|
|
||||||
tenantCode: string,
|
|
||||||
purchaseId: number,
|
|
||||||
): Promise<PurchaseStatusResponse> {
|
|
||||||
const response = await firstValueFrom(
|
|
||||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/complete`,
|
|
||||||
{},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const purchase = this.extractResponseData<PurchaseStatusResponse>(response);
|
|
||||||
|
|
||||||
if (!purchase) {
|
|
||||||
throw new Error('Error al finalizar la compra.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: purchase.status ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async submitPurchaseForReview(
|
async submitPurchaseForReview(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
purchaseId: number,
|
purchaseId: number,
|
||||||
@@ -218,13 +245,10 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
throw new Error('Error al enviar la compra a revisi\u00f3n.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { status: purchase.status ?? null };
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancelPurchase(
|
async cancelPurchase(tenantCode: string, purchaseId: number): Promise<PurchaseStatusResponse> {
|
||||||
tenantCode: string,
|
|
||||||
purchaseId: number,
|
|
||||||
): Promise<PurchaseStatusResponse> {
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
this.http.post<{ data?: PurchaseStatusResponse } | PurchaseStatusResponse>(
|
||||||
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/cancel`,
|
`${environment.url}tenants/${tenantCode}/compras/${purchaseId}/cancel`,
|
||||||
@@ -237,19 +261,25 @@ export class CheckoutService extends BaseApiService {
|
|||||||
throw new Error('Error al cancelar la compra.');
|
throw new Error('Error al cancelar la compra.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return { status: purchase.status ?? null };
|
return purchase;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getPurchases(
|
async getPurchases(
|
||||||
tenantCode: string,
|
tenantCode: string,
|
||||||
status?: string,
|
status?: string,
|
||||||
): Promise<{ data: PurchaseSummaryResponse[] }> {
|
pagination: ApiPaginationQueryParams = {},
|
||||||
let url = `${environment.url}tenants/${tenantCode}/compras`;
|
): Promise<ApiPaginatedResponse<PurchaseSummaryResponse[]>> {
|
||||||
if (status) {
|
const params: Record<string, string | number> = {};
|
||||||
url += `?status=${status}`;
|
|
||||||
}
|
if (status) params['status'] = status;
|
||||||
|
if (pagination.page) params['page'] = pagination.page;
|
||||||
|
if (pagination.per_page) params['per_page'] = pagination.per_page;
|
||||||
|
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.get<{ data: PurchaseSummaryResponse[] }>(url),
|
this.http.get<ApiPaginatedResponse<PurchaseSummaryResponse[]>>(
|
||||||
|
`${environment.url}tenants/${tenantCode}/compras`,
|
||||||
|
{ params },
|
||||||
|
),
|
||||||
);
|
);
|
||||||
if (!response) {
|
if (!response) {
|
||||||
throw new Error('Error al obtener las compras.');
|
throw new Error('Error al obtener las compras.');
|
||||||
|
|||||||
59
src/app/core/services/event-date-notice.service.spec.ts
Normal file
59
src/app/core/services/event-date-notice.service.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { EventDateNotice, EventDateNoticeService } from './event-date-notice.service';
|
||||||
|
import { ApiResponse } from './api-response.interface';
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
|
||||||
|
describe('EventDateNoticeService', () => {
|
||||||
|
let service: EventDateNoticeService;
|
||||||
|
let httpMock: HttpTestingController;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
EventDateNoticeService,
|
||||||
|
provideHttpClient(),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: { getTenant: () => ({ codigo: 'festival' }) },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(EventDateNoticeService);
|
||||||
|
httpMock = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => httpMock.verify());
|
||||||
|
|
||||||
|
it('claims pending notices for the active tenant', () => {
|
||||||
|
const response = {
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
type: 'suspended' as const,
|
||||||
|
change_ids: [10],
|
||||||
|
title: 'FECHA CANCELADA!',
|
||||||
|
message: [{ text: 'La fecha fue cancelada.', bold: false }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let result: ApiResponse<EventDateNotice[]> | undefined;
|
||||||
|
|
||||||
|
service.claim().subscribe((value) => (result = value));
|
||||||
|
|
||||||
|
const request = httpMock.expectOne(
|
||||||
|
`${environment.url}tenants/festival/event-date-notices/claim`,
|
||||||
|
);
|
||||||
|
expect(request.request.method).toBe('POST');
|
||||||
|
expect(request.request.body).toEqual({});
|
||||||
|
|
||||||
|
request.flush(response);
|
||||||
|
|
||||||
|
expect(result).toEqual(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
39
src/app/core/services/event-date-notice.service.ts
Normal file
39
src/app/core/services/event-date-notice.service.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { inject, Injectable } from '@angular/core';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { ApiResponse } from './api-response.interface';
|
||||||
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
|
||||||
|
export type EventDateNoticeType = 'rescheduled' | 'suspended';
|
||||||
|
|
||||||
|
export interface EventDateNoticeSegment {
|
||||||
|
text: string;
|
||||||
|
bold: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventDateNotice {
|
||||||
|
type: EventDateNoticeType;
|
||||||
|
change_ids: number[];
|
||||||
|
title: string;
|
||||||
|
message: EventDateNoticeSegment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({ providedIn: 'root' })
|
||||||
|
export class EventDateNoticeService extends BaseApiService {
|
||||||
|
private readonly tenantService = inject(TenantService);
|
||||||
|
|
||||||
|
claim(): Observable<ApiResponse<EventDateNotice[]>> {
|
||||||
|
const tenant = this.tenantService.getTenant();
|
||||||
|
|
||||||
|
if (!tenant) {
|
||||||
|
throw new Error('No se pudo resolver el tenant activo.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.withoutLoading().http.post<ApiResponse<EventDateNotice[]>>(
|
||||||
|
`${environment.url}tenants/${tenant.codigo}/event-date-notices/claim`,
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/app/core/services/event/event.interface.ts
Normal file
36
src/app/core/services/event/event.interface.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
|
||||||
|
|
||||||
|
export interface StoreEvent {
|
||||||
|
id: number;
|
||||||
|
slug: string;
|
||||||
|
event_category_id: number | null;
|
||||||
|
title: string;
|
||||||
|
subtitle: string | null;
|
||||||
|
description: string | null;
|
||||||
|
location: string | null;
|
||||||
|
exact_location: { latitude: number; longitude: number } | null;
|
||||||
|
date_text: string | null;
|
||||||
|
start_time?: string | null;
|
||||||
|
starts_at?: string | null;
|
||||||
|
dates?: { id: number; date: string; time_start: string }[];
|
||||||
|
social_media?: { code: string; url: string }[];
|
||||||
|
attachment_id: number | null;
|
||||||
|
image: string | null;
|
||||||
|
catalog_items?: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string | null;
|
||||||
|
price: string;
|
||||||
|
image: string | null;
|
||||||
|
requires_selection: boolean;
|
||||||
|
maximum_quantity: number | null;
|
||||||
|
variants: {
|
||||||
|
id: number;
|
||||||
|
price: string;
|
||||||
|
event_date_ids: number[];
|
||||||
|
maximum_quantity: number | null;
|
||||||
|
}[];
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StoreEventPage = ApiPaginatedResponse<StoreEvent[]>;
|
||||||
24
src/app/core/services/event/event.service.ts
Normal file
24
src/app/core/services/event/event.service.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { inject, Injectable } from '@angular/core';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
import { BaseApiService } from '../base-api.service';
|
||||||
|
import { ApiResponse } from '../api-response.interface';
|
||||||
|
import { TenantService } from '../tenant.service';
|
||||||
|
import { StoreEvent, StoreEventPage } from './event.interface';
|
||||||
|
|
||||||
|
@Injectable({ providedIn: 'root' })
|
||||||
|
export class EventService extends BaseApiService {
|
||||||
|
private readonly tenantService = inject(TenantService);
|
||||||
|
|
||||||
|
list(page: number, query = '', categoryId?: number): Observable<StoreEventPage> {
|
||||||
|
return this.http.get<StoreEventPage>(`${this.tenantService.getTenantApiUrl()}/events`, {
|
||||||
|
params: { page, ...(query ? { q: query } : {}), ...(categoryId ? { category_id: categoryId } : {}) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get(slug: string): Observable<ApiResponse<StoreEvent>> {
|
||||||
|
return this.http.get<ApiResponse<StoreEvent>>(
|
||||||
|
`${this.tenantService.getTenantApiUrl()}/events/${slug}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import { firstValueFrom } from 'rxjs';
|
|||||||
|
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
import { MODAL_DATA, ModalRef, ModalService } from './modal.service';
|
||||||
@@ -79,6 +80,21 @@ describe('ModalService', () => {
|
|||||||
expect(ref.dismissReason()).toBeNull();
|
expect(ref.dismissReason()).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps a modal opened synchronously from an afterClosed subscriber', () => {
|
||||||
|
const firstRef = service.open(FirstTestModalComponent);
|
||||||
|
let secondRef: ModalRef | undefined;
|
||||||
|
|
||||||
|
firstRef.afterClosed$.subscribe(() => {
|
||||||
|
secondRef = service.open(SecondTestModalComponent);
|
||||||
|
});
|
||||||
|
|
||||||
|
firstRef.close();
|
||||||
|
|
||||||
|
expect(secondRef).toBeDefined();
|
||||||
|
expect(service.activeModal()?.ref).toBe(secondRef);
|
||||||
|
expect(service.activeModal()?.component).toBe(SecondTestModalComponent);
|
||||||
|
});
|
||||||
|
|
||||||
it('tracks dismiss reasons when closing programmatically', () => {
|
it('tracks dismiss reasons when closing programmatically', () => {
|
||||||
const ref = service.open(FirstTestModalComponent);
|
const ref = service.open(FirstTestModalComponent);
|
||||||
const closedSpy = vi.fn();
|
const closedSpy = vi.fn();
|
||||||
@@ -121,7 +137,7 @@ describe('ModalService', () => {
|
|||||||
it('opens the standard confirm modal with default labels', () => {
|
it('opens the standard confirm modal with default labels', () => {
|
||||||
const result$ = service.openConfirm({
|
const result$ = service.openConfirm({
|
||||||
title: 'Confirmar compra',
|
title: 'Confirmar compra',
|
||||||
content: 'Esto confirmara la compra actual.',
|
description: 'Esto confirmara la compra actual.',
|
||||||
});
|
});
|
||||||
|
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
@@ -129,9 +145,9 @@ describe('ModalService', () => {
|
|||||||
expect(activeModal?.component).toBe(ConfirmModalComponent);
|
expect(activeModal?.component).toBe(ConfirmModalComponent);
|
||||||
expect(result$).toBeDefined();
|
expect(result$).toBeDefined();
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
title: 'Confirmar compra',
|
|
||||||
data: {
|
data: {
|
||||||
content: 'Esto confirmara la compra actual.',
|
title: 'Confirmar compra',
|
||||||
|
description: 'Esto confirmara la compra actual.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
cancelLabel: 'Cancelar',
|
cancelLabel: 'Cancelar',
|
||||||
},
|
},
|
||||||
@@ -145,7 +161,7 @@ describe('ModalService', () => {
|
|||||||
it('maps the confirm modal close result to true', async () => {
|
it('maps the confirm modal close result to true', async () => {
|
||||||
const result$ = service.openConfirm({
|
const result$ = service.openConfirm({
|
||||||
title: 'Confirmar compra',
|
title: 'Confirmar compra',
|
||||||
content: 'Esto confirmara la compra actual.',
|
description: 'Esto confirmara la compra actual.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
@@ -158,11 +174,13 @@ describe('ModalService', () => {
|
|||||||
it('maps dismissing a confirm modal to false', async () => {
|
it('maps dismissing a confirm modal to false', async () => {
|
||||||
const result$ = service.openConfirmDelete({
|
const result$ = service.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
content: 'Se eliminara el producto.',
|
description: 'Se eliminara el producto.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
|
|
||||||
|
expect(activeModal?.config.size).toBe('sm');
|
||||||
|
|
||||||
activeModal?.ref.dismiss('escape');
|
activeModal?.ref.dismiss('escape');
|
||||||
|
|
||||||
await expect(resultPromise).resolves.toBe(false);
|
await expect(resultPromise).resolves.toBe(false);
|
||||||
@@ -171,7 +189,7 @@ describe('ModalService', () => {
|
|||||||
it('opens the delete confirm modal preserving modal overrides', () => {
|
it('opens the delete confirm modal preserving modal overrides', () => {
|
||||||
service.openConfirmDelete({
|
service.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
content: 'Se eliminara el producto.',
|
description: 'Se eliminara el producto.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
cancelLabel: 'Conservar',
|
cancelLabel: 'Conservar',
|
||||||
size: 'lg',
|
size: 'lg',
|
||||||
@@ -184,9 +202,9 @@ describe('ModalService', () => {
|
|||||||
|
|
||||||
expect(activeModal?.component).toBe(ConfirmDeleteModalComponent);
|
expect(activeModal?.component).toBe(ConfirmDeleteModalComponent);
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
title: 'Eliminar producto',
|
|
||||||
data: {
|
data: {
|
||||||
content: 'Se eliminara el producto.',
|
title: 'Eliminar producto',
|
||||||
|
description: 'Se eliminara el producto.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
cancelLabel: 'Conservar',
|
cancelLabel: 'Conservar',
|
||||||
},
|
},
|
||||||
@@ -200,16 +218,16 @@ describe('ModalService', () => {
|
|||||||
it('opens the simple modal with default button label', () => {
|
it('opens the simple modal with default button label', () => {
|
||||||
service.openSimple({
|
service.openSimple({
|
||||||
title: 'Aviso',
|
title: 'Aviso',
|
||||||
content: 'Este es un aviso simple.',
|
description: 'Este es un aviso simple.',
|
||||||
});
|
});
|
||||||
|
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
|
|
||||||
expect(activeModal?.component).toBe(SimpleModalComponent);
|
expect(activeModal?.component).toBe(SimpleModalComponent);
|
||||||
expect(activeModal?.config).toEqual({
|
expect(activeModal?.config).toEqual({
|
||||||
title: 'Aviso',
|
|
||||||
data: {
|
data: {
|
||||||
content: 'Este es un aviso simple.',
|
title: 'Aviso',
|
||||||
|
description: 'Este es un aviso simple.',
|
||||||
buttonLabel: 'Entendido',
|
buttonLabel: 'Entendido',
|
||||||
},
|
},
|
||||||
size: 'md',
|
size: 'md',
|
||||||
@@ -222,7 +240,7 @@ describe('ModalService', () => {
|
|||||||
it('maps the simple modal close result to undefined', async () => {
|
it('maps the simple modal close result to undefined', async () => {
|
||||||
const result$ = service.openSimple({
|
const result$ = service.openSimple({
|
||||||
title: 'Aviso',
|
title: 'Aviso',
|
||||||
content: 'Este es un aviso simple.',
|
description: 'Este es un aviso simple.',
|
||||||
});
|
});
|
||||||
const activeModal = service.activeModal();
|
const activeModal = service.activeModal();
|
||||||
const resultPromise = firstValueFrom(result$);
|
const resultPromise = firstValueFrom(result$);
|
||||||
@@ -256,6 +274,36 @@ describe('ModalService', () => {
|
|||||||
showCloseButton: true,
|
showCloseButton: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens the image viewer fullscreen with normalized zoom limits', () => {
|
||||||
|
service.openImage({
|
||||||
|
title: 'Producto',
|
||||||
|
src: '/images/producto.webp',
|
||||||
|
alt: 'Producto visto de frente',
|
||||||
|
initialZoom: 8,
|
||||||
|
minZoom: 0,
|
||||||
|
maxZoom: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
const activeModal = service.activeModal();
|
||||||
|
|
||||||
|
expect(activeModal?.component).toBe(ImageModalComponent);
|
||||||
|
expect(activeModal?.config).toEqual({
|
||||||
|
title: 'Producto',
|
||||||
|
size: 'full',
|
||||||
|
presentation: 'fullscreen-media',
|
||||||
|
data: {
|
||||||
|
src: '/images/producto.webp',
|
||||||
|
alt: 'Producto visto de frente',
|
||||||
|
initialZoom: 3,
|
||||||
|
minZoom: 0.1,
|
||||||
|
maxZoom: 3,
|
||||||
|
},
|
||||||
|
closeOnBackdrop: true,
|
||||||
|
closeOnEscape: true,
|
||||||
|
showCloseButton: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
|
|||||||
@@ -2,16 +2,19 @@ import { InjectionToken, Injectable, Type, signal } from '@angular/core';
|
|||||||
import { Observable, Subject, map } from 'rxjs';
|
import { Observable, Subject, map } from 'rxjs';
|
||||||
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
import { ConfirmDeleteModalComponent } from '../../shared/components/confirm-delete-modal/confirm-delete-modal.component';
|
||||||
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../shared/components/confirm-modal/confirm-modal.component';
|
||||||
|
import { ImageModalComponent } from '../../shared/components/image-modal/image-modal.component';
|
||||||
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
import { QrModalComponent } from '../../shared/components/qr-modal/qr-modal.component';
|
||||||
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
import { SimpleModalComponent } from '../../shared/components/simple-modal/simple-modal.component';
|
||||||
|
|
||||||
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
export type ModalSize = 'qr' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||||
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced';
|
export type ModalDismissReason = 'backdrop' | 'escape' | 'programmatic' | 'replaced' | 'swipe';
|
||||||
|
export type ModalPresentation = 'dialog' | 'fullscreen-media';
|
||||||
|
|
||||||
export interface ModalConfig<TData = unknown> {
|
export interface ModalConfig<TData = unknown> {
|
||||||
title?: string;
|
title?: string;
|
||||||
data?: TData;
|
data?: TData;
|
||||||
size?: ModalSize;
|
size?: ModalSize;
|
||||||
|
presentation?: ModalPresentation;
|
||||||
closeOnBackdrop?: boolean;
|
closeOnBackdrop?: boolean;
|
||||||
closeOnEscape?: boolean;
|
closeOnEscape?: boolean;
|
||||||
showCloseButton?: boolean;
|
showCloseButton?: boolean;
|
||||||
@@ -28,24 +31,28 @@ export interface NormalizedModalConfig<TData = unknown> extends Omit<
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ConfirmModalData {
|
export interface ConfirmModalData {
|
||||||
content: string;
|
title: string;
|
||||||
|
description?: string;
|
||||||
confirmLabel: string;
|
confirmLabel: string;
|
||||||
cancelLabel: string;
|
cancelLabel: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ConfirmModalConfig extends Omit<ModalConfig<ConfirmModalData>, 'data'> {
|
export interface ConfirmModalConfig extends Omit<ModalConfig<ConfirmModalData>, 'data'> {
|
||||||
content: string;
|
title: string;
|
||||||
|
description?: string;
|
||||||
confirmLabel?: string;
|
confirmLabel?: string;
|
||||||
cancelLabel?: string;
|
cancelLabel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SimpleModalData {
|
export interface SimpleModalData {
|
||||||
content: string;
|
title: string;
|
||||||
|
description?: string;
|
||||||
buttonLabel: string;
|
buttonLabel: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SimpleModalConfig extends Omit<ModalConfig<SimpleModalData>, 'data'> {
|
export interface SimpleModalConfig extends Omit<ModalConfig<SimpleModalData>, 'data'> {
|
||||||
content: string;
|
title: string;
|
||||||
|
description?: string;
|
||||||
buttonLabel?: string;
|
buttonLabel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +69,25 @@ export interface QrModalConfig extends Omit<ModalConfig<QrModalData>, 'data' | '
|
|||||||
ticket: string;
|
ticket: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ImageModalData {
|
||||||
|
src: string;
|
||||||
|
alt: string;
|
||||||
|
initialZoom: number;
|
||||||
|
minZoom: number;
|
||||||
|
maxZoom: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageModalConfig extends Omit<
|
||||||
|
ModalConfig<ImageModalData>,
|
||||||
|
'data' | 'presentation' | 'size'
|
||||||
|
> {
|
||||||
|
src: string;
|
||||||
|
alt: string;
|
||||||
|
initialZoom?: number;
|
||||||
|
minZoom?: number;
|
||||||
|
maxZoom?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
export interface ActiveModalState<TResult = unknown, TData = unknown> {
|
||||||
component: Type<unknown>;
|
component: Type<unknown>;
|
||||||
config: NormalizedModalConfig<TData>;
|
config: NormalizedModalConfig<TData>;
|
||||||
@@ -166,7 +192,10 @@ export class ModalService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
openConfirmDeleteRef(config: ConfirmModalConfig): ModalRef<boolean> {
|
openConfirmDeleteRef(config: ConfirmModalConfig): ModalRef<boolean> {
|
||||||
return this.open(ConfirmDeleteModalComponent, this.buildConfirmModalConfig(config));
|
return this.open(
|
||||||
|
ConfirmDeleteModalComponent,
|
||||||
|
this.buildConfirmModalConfig({ size: 'sm', ...config }),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
openSimple(config: SimpleModalConfig): Observable<void> {
|
openSimple(config: SimpleModalConfig): Observable<void> {
|
||||||
@@ -192,13 +221,40 @@ export class ModalService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
openImage(config: ImageModalConfig): Observable<void> {
|
||||||
|
return this.openImageRef(config).afterClosed$.pipe(map(() => undefined));
|
||||||
|
}
|
||||||
|
|
||||||
|
openImageRef(config: ImageModalConfig): ModalRef<void> {
|
||||||
|
const { src, alt, initialZoom = 1, minZoom = 1, maxZoom = 4, ...modalConfig } = config;
|
||||||
|
const normalizedMinZoom = Math.max(0.1, minZoom);
|
||||||
|
const normalizedMaxZoom = Math.max(normalizedMinZoom, maxZoom);
|
||||||
|
const normalizedInitialZoom = Math.min(
|
||||||
|
normalizedMaxZoom,
|
||||||
|
Math.max(normalizedMinZoom, initialZoom),
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.open(ImageModalComponent, {
|
||||||
|
...modalConfig,
|
||||||
|
size: 'full',
|
||||||
|
presentation: 'fullscreen-media',
|
||||||
|
data: {
|
||||||
|
src,
|
||||||
|
alt,
|
||||||
|
initialZoom: normalizedInitialZoom,
|
||||||
|
minZoom: normalizedMinZoom,
|
||||||
|
maxZoom: normalizedMaxZoom,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
private close<TResult>(ref: ModalRef<TResult>, result?: TResult): void {
|
||||||
if (this.activeModalState()?.ref !== ref) {
|
if (this.activeModalState()?.ref !== ref) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ref.finalize(result);
|
|
||||||
this.activeModalState.set(null);
|
this.activeModalState.set(null);
|
||||||
|
ref.finalize(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
private dismiss<TResult>(
|
private dismiss<TResult>(
|
||||||
@@ -209,8 +265,8 @@ export class ModalService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ref.finalize(undefined, reason);
|
|
||||||
this.activeModalState.set(null);
|
this.activeModalState.set(null);
|
||||||
|
ref.finalize(undefined, reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeConfig<TData>(config: ModalConfig<TData>): NormalizedModalConfig<TData> {
|
private normalizeConfig<TData>(config: ModalConfig<TData>): NormalizedModalConfig<TData> {
|
||||||
@@ -222,7 +278,8 @@ export class ModalService {
|
|||||||
|
|
||||||
private buildConfirmModalConfig(config: ConfirmModalConfig): ModalConfig<ConfirmModalData> {
|
private buildConfirmModalConfig(config: ConfirmModalConfig): ModalConfig<ConfirmModalData> {
|
||||||
const {
|
const {
|
||||||
content,
|
title,
|
||||||
|
description,
|
||||||
confirmLabel = DEFAULT_CONFIRM_MODAL_LABELS.confirmLabel,
|
confirmLabel = DEFAULT_CONFIRM_MODAL_LABELS.confirmLabel,
|
||||||
cancelLabel = DEFAULT_CONFIRM_MODAL_LABELS.cancelLabel,
|
cancelLabel = DEFAULT_CONFIRM_MODAL_LABELS.cancelLabel,
|
||||||
...modalConfig
|
...modalConfig
|
||||||
@@ -231,7 +288,8 @@ export class ModalService {
|
|||||||
return {
|
return {
|
||||||
...modalConfig,
|
...modalConfig,
|
||||||
data: {
|
data: {
|
||||||
content,
|
title,
|
||||||
|
description,
|
||||||
confirmLabel,
|
confirmLabel,
|
||||||
cancelLabel,
|
cancelLabel,
|
||||||
},
|
},
|
||||||
@@ -239,12 +297,13 @@ export class ModalService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private buildSimpleModalConfig(config: SimpleModalConfig): ModalConfig<SimpleModalData> {
|
private buildSimpleModalConfig(config: SimpleModalConfig): ModalConfig<SimpleModalData> {
|
||||||
const { content, buttonLabel = 'Entendido', ...modalConfig } = config;
|
const { title, description, buttonLabel = 'Entendido', ...modalConfig } = config;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...modalConfig,
|
...modalConfig,
|
||||||
data: {
|
data: {
|
||||||
content,
|
title,
|
||||||
|
description,
|
||||||
buttonLabel,
|
buttonLabel,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
50
src/app/core/services/tenant-url.serializer.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import '@angular/compiler';
|
||||||
|
import { DefaultUrlSerializer } from '@angular/router';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
import { Tenant } from './tenant.interface';
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
import { TenantUrlSerializer } from './tenant-url.serializer';
|
||||||
|
|
||||||
|
describe('TenantUrlSerializer', () => {
|
||||||
|
const defaultSerializer = new DefaultUrlSerializer();
|
||||||
|
|
||||||
|
function createSerializer(basePath: string): TenantUrlSerializer {
|
||||||
|
const tenantService = {
|
||||||
|
getTenant: () => ({ base_path: basePath }) as Tenant,
|
||||||
|
} as TenantService;
|
||||||
|
|
||||||
|
return new TenantUrlSerializer(tenantService);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('keeps root tenants unchanged', () => {
|
||||||
|
const serializer = createSerializer('/');
|
||||||
|
const tree = serializer.parse('/producto/123?ref=home');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/producto/123?ref=home');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes the tenant base path when parsing and restores it when serializing', () => {
|
||||||
|
const serializer = createSerializer('/desfile');
|
||||||
|
const tree = serializer.parse('/desfile/producto/123?ref=home#detalle');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/producto/123?ref=home#detalle');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/desfile/producto/123?ref=home#detalle');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps the tenant base path to the application root', () => {
|
||||||
|
const serializer = createSerializer('/desfile/');
|
||||||
|
const tree = serializer.parse('/desfile');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/');
|
||||||
|
expect(serializer.serialize(tree)).toBe('/desfile');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not strip partial path segment matches', () => {
|
||||||
|
const serializer = createSerializer('/desfile');
|
||||||
|
const tree = serializer.parse('/desfile-shop/producto/123');
|
||||||
|
|
||||||
|
expect(defaultSerializer.serialize(tree)).toBe('/desfile-shop/producto/123');
|
||||||
|
});
|
||||||
|
});
|
||||||
66
src/app/core/services/tenant-url.serializer.ts
Normal file
66
src/app/core/services/tenant-url.serializer.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import { DefaultUrlSerializer, UrlSerializer, UrlTree } from '@angular/router';
|
||||||
|
|
||||||
|
import { TenantService } from './tenant.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TenantUrlSerializer extends UrlSerializer {
|
||||||
|
private readonly defaultSerializer = new DefaultUrlSerializer();
|
||||||
|
|
||||||
|
constructor(private readonly tenantService: TenantService) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
override parse(url: string): UrlTree {
|
||||||
|
return this.defaultSerializer.parse(this.removeBasePath(url));
|
||||||
|
}
|
||||||
|
|
||||||
|
override serialize(tree: UrlTree): string {
|
||||||
|
const url = this.defaultSerializer.serialize(tree);
|
||||||
|
const basePath = this.basePath();
|
||||||
|
|
||||||
|
if (basePath === '/') {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
return url === '/' ? basePath : `${basePath}${url}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private removeBasePath(url: string): string {
|
||||||
|
const basePath = this.basePath();
|
||||||
|
|
||||||
|
if (basePath === '/' || !this.startsWithCompletePathSegment(url, basePath)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainder = url.slice(basePath.length);
|
||||||
|
|
||||||
|
if (remainder === '') {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return remainder.startsWith('?') || remainder.startsWith('#')
|
||||||
|
? `/${remainder}`
|
||||||
|
: remainder;
|
||||||
|
}
|
||||||
|
|
||||||
|
private basePath(): string {
|
||||||
|
const configuredPath = this.tenantService.getTenant()?.base_path?.trim() ?? '/';
|
||||||
|
|
||||||
|
if (configuredPath === '' || configuredPath === '/') {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `/${configuredPath.replace(/^\/+|\/+$/g, '')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private startsWithCompletePathSegment(url: string, basePath: string): boolean {
|
||||||
|
if (!url.startsWith(basePath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const boundary = url.charAt(basePath.length);
|
||||||
|
|
||||||
|
return boundary === '' || boundary === '/' || boundary === '?' || boundary === '#';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,15 @@
|
|||||||
import { ApiResponse } from './api-response.interface';
|
import { ApiResponse } from './api-response.interface';
|
||||||
|
|
||||||
|
export type CartEditingPolicyCode = 'disabled' | 'quantity_and_remove' | 'full';
|
||||||
|
|
||||||
|
export interface CartEditingPolicy {
|
||||||
|
code: CartEditingPolicyCode;
|
||||||
|
allow_modify: boolean;
|
||||||
|
allow_delete: boolean;
|
||||||
|
allow_update_quantity: boolean;
|
||||||
|
allow_update_variant: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface BankAccount {
|
export interface BankAccount {
|
||||||
id: number;
|
id: number;
|
||||||
tenant_code: string;
|
tenant_code: string;
|
||||||
@@ -10,17 +20,71 @@ export interface BankAccount {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface HeroConfig {
|
export interface HeroConfig {
|
||||||
background_image?: string | null;
|
background_image_id?: string | ResponsiveImage | null;
|
||||||
title_html?: string | null;
|
title_html?: string | null;
|
||||||
description_html?: string | null;
|
description_html?: string | null;
|
||||||
button_text?: string | null;
|
button_text?: string | null;
|
||||||
button_href?: string | null;
|
button_href?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ResponsiveImage {
|
||||||
|
desktop: string;
|
||||||
|
mobile: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdditionalInfoConfig {
|
||||||
|
description?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventDate {
|
||||||
|
id?: number;
|
||||||
|
date: string;
|
||||||
|
start_time: string;
|
||||||
|
end_time: string;
|
||||||
|
info_text: string | null;
|
||||||
|
isCanceled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface EventConfig {
|
export interface EventConfig {
|
||||||
|
id?: number;
|
||||||
title?: string | null;
|
title?: string | null;
|
||||||
location?: string | null;
|
location?: string | null;
|
||||||
dates?: string[] | null;
|
dates_text?: string | null;
|
||||||
|
dates?: EventDate[] | null;
|
||||||
|
contact?: SocialMedia[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActiveEventDate {
|
||||||
|
id: number;
|
||||||
|
date: string;
|
||||||
|
time_start: string;
|
||||||
|
time_end: string;
|
||||||
|
info_text: string | null;
|
||||||
|
isCanceled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TenantEvent {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
subtitle: string | null;
|
||||||
|
description: string | null;
|
||||||
|
location: string | null;
|
||||||
|
date_text: string | null;
|
||||||
|
dates: ActiveEventDate[];
|
||||||
|
social_media: SocialMedia[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WebsiteExtras {
|
||||||
|
carousel?: string[];
|
||||||
|
immersiveHeroCarousel?: string[];
|
||||||
|
immersiveHero?: {
|
||||||
|
eyebrow: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
heroConfig?: HeroConfig | null;
|
||||||
|
additionalInfoConfig?: AdditionalInfoConfig | null;
|
||||||
|
[extraName: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Menu {
|
export interface Menu {
|
||||||
@@ -52,6 +116,13 @@ export interface Tenant {
|
|||||||
codigo: string;
|
codigo: string;
|
||||||
nombre: string;
|
nombre: string;
|
||||||
dominio: string;
|
dominio: string;
|
||||||
|
base_path?: string;
|
||||||
|
timezone?: string;
|
||||||
|
site_title?: string | null;
|
||||||
|
asset_url?: string | null;
|
||||||
|
address?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
|
favicon?: string | null;
|
||||||
primary_color: string;
|
primary_color: string;
|
||||||
secondary_color: string;
|
secondary_color: string;
|
||||||
danger_color: string;
|
danger_color: string;
|
||||||
@@ -60,17 +131,32 @@ export interface Tenant {
|
|||||||
footer_bg_color: string;
|
footer_bg_color: string;
|
||||||
header_logo: string;
|
header_logo: string;
|
||||||
footer_logo: string;
|
footer_logo: string;
|
||||||
|
header_bg_image?: string | null;
|
||||||
|
footer_bg_image?: string | null;
|
||||||
|
storefront_website_type_code?: string | null;
|
||||||
|
header_type?: 'standard' | 'immersive';
|
||||||
|
checkout_summary_type?: 'default' | 'event';
|
||||||
|
extras?: WebsiteExtras;
|
||||||
|
event?: TenantEvent | null;
|
||||||
selected_bank_account_id?: number | null;
|
selected_bank_account_id?: number | null;
|
||||||
selected_bank_account?: BankAccount | null;
|
selected_bank_account?: BankAccount | null;
|
||||||
hero_config?: HeroConfig | null;
|
search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart' | 'ticket_selector';
|
||||||
event_config?: EventConfig | null;
|
search_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel' | 'single';
|
||||||
search_product_layout?: 'row' | 'column_with_image' | 'column_with_cart';
|
|
||||||
search_group_layout?: 'paginated' | 'simple' | 'simple_vertical' | 'carousel';
|
|
||||||
search_items_per_page?: number;
|
search_items_per_page?: number;
|
||||||
main_carousel_images?: string[];
|
display_categories?: boolean;
|
||||||
|
display_seach_bar?: boolean;
|
||||||
|
display_cart?: boolean;
|
||||||
|
cart_editing_policy?: CartEditingPolicy;
|
||||||
|
checkout_editing_policy?: CartEditingPolicy;
|
||||||
|
display_cart_item_images?: boolean;
|
||||||
|
allow_ticket_refund?: boolean;
|
||||||
|
allow_ticket_total_refund?: boolean;
|
||||||
|
allow_ticket_partial_refund?: boolean;
|
||||||
|
ticket_partial_refund_percentage?: string;
|
||||||
social_media?: SocialMedia[];
|
social_media?: SocialMedia[];
|
||||||
menues?: Menu[];
|
menues?: Menu[];
|
||||||
categories: Category[];
|
categories?: Category[];
|
||||||
|
event_categories?: Category[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TenantBootstrapResponse = ApiResponse<Tenant>;
|
export type TenantBootstrapResponse = ApiResponse<Tenant>;
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ import { PLATFORM_ID, REQUEST, RESPONSE_INIT, TransferState } from '@angular/cor
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TimeoutError } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||||
import { TENANT_SSR_STATE_KEY } from './tenant-ssr-cache.store';
|
import { TENANT_SSR_STATE_KEY } from './tenant-ssr-cache.store';
|
||||||
import { TenantService } from './tenant.service';
|
import { TenantService } from './tenant.service';
|
||||||
@@ -13,6 +15,7 @@ const tenant: Tenant = {
|
|||||||
codigo: 'test',
|
codigo: 'test',
|
||||||
nombre: 'Test Tenant',
|
nombre: 'Test Tenant',
|
||||||
dominio: 'localhost',
|
dominio: 'localhost',
|
||||||
|
asset_url: 'https://s3.example.com/assets',
|
||||||
primary_color: '#6376F3',
|
primary_color: '#6376F3',
|
||||||
secondary_color: '#A0A0A0',
|
secondary_color: '#A0A0A0',
|
||||||
danger_color: '#FF8888',
|
danger_color: '#FF8888',
|
||||||
@@ -29,19 +32,20 @@ const tenant: Tenant = {
|
|||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
nombre: 'Manga corta',
|
nombre: 'Manga corta',
|
||||||
subcategories: []
|
subcategories: [],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const tenantResponse: TenantBootstrapResponse = {
|
const tenantResponse: TenantBootstrapResponse = {
|
||||||
data: tenant
|
data: tenant,
|
||||||
};
|
};
|
||||||
|
|
||||||
describe('TenantService', () => {
|
describe('TenantService', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
document.head.querySelectorAll('link[rel="preconnect"]').forEach((link) => link.remove());
|
||||||
try {
|
try {
|
||||||
window.history.replaceState({}, '', 'http://localhost:4200/');
|
window.history.replaceState({}, '', 'http://localhost:4200/');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -51,14 +55,16 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
it('requests the tenant bootstrap endpoint using the current hostname and stores the response', async () => {
|
it('requests the tenant bootstrap endpoint using the current hostname and stores the response', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
const bootstrapPromise = service.bootstrap();
|
||||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/localhost`);
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||||
|
);
|
||||||
|
|
||||||
expect(request.request.method).toBe('GET');
|
expect(request.request.method).toBe('GET');
|
||||||
|
|
||||||
@@ -68,13 +74,16 @@ describe('TenantService', () => {
|
|||||||
expect(service.status()).toBe('ready');
|
expect(service.status()).toBe('ready');
|
||||||
expect(service.tenant()).toEqual(tenant);
|
expect(service.tenant()).toEqual(tenant);
|
||||||
expect(service.getTenant()).toEqual(tenant);
|
expect(service.getTenant()).toEqual(tenant);
|
||||||
|
expect(
|
||||||
|
document.head.querySelector('link[rel="preconnect"][href="https://s3.example.com/"]'),
|
||||||
|
).not.toBeNull();
|
||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hydrates the tenant from TransferState without performing HTTP on the browser', async () => {
|
it('hydrates the tenant from TransferState without performing HTTP on the browser', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -83,7 +92,7 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
transferState.set(TENANT_SSR_STATE_KEY, {
|
transferState.set(TENANT_SSR_STATE_KEY, {
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant
|
tenant,
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(service.bootstrap()).resolves.toBeUndefined();
|
await expect(service.bootstrap()).resolves.toBeUndefined();
|
||||||
@@ -109,12 +118,12 @@ describe('TenantService', () => {
|
|||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
headers: {
|
||||||
'x-forwarded-host': 'STORE.EXAMPLE.COM:443, proxy.internal',
|
'x-forwarded-host': 'STORE.EXAMPLE.COM:443, proxy.internal',
|
||||||
host: 'ignored.example.com'
|
host: 'ignored.example.com',
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
},
|
},
|
||||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -122,7 +131,9 @@ describe('TenantService', () => {
|
|||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
const bootstrapPromise = service.bootstrap();
|
||||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/store.example.com`);
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=store.example.com&path=/render`,
|
||||||
|
);
|
||||||
|
|
||||||
request.flush(tenantResponse);
|
request.flush(tenantResponse);
|
||||||
|
|
||||||
@@ -131,7 +142,7 @@ describe('TenantService', () => {
|
|||||||
expect(service.tenant()).toEqual(tenant);
|
expect(service.tenant()).toEqual(tenant);
|
||||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant
|
tenant,
|
||||||
});
|
});
|
||||||
expect(responseInit.status).toBeUndefined();
|
expect(responseInit.status).toBeUndefined();
|
||||||
|
|
||||||
@@ -151,12 +162,12 @@ describe('TenantService', () => {
|
|||||||
provide: REQUEST,
|
provide: REQUEST,
|
||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
headers: {
|
||||||
host: 'missing.example.com:8443'
|
host: 'missing.example.com:8443',
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
},
|
},
|
||||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
@@ -164,7 +175,9 @@ describe('TenantService', () => {
|
|||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
const bootstrapPromise = service.bootstrap();
|
||||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/missing.example.com`);
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=missing.example.com&path=/render`,
|
||||||
|
);
|
||||||
|
|
||||||
request.flush({ message: 'Not Found' }, { status: 404, statusText: 'Not Found' });
|
request.flush({ message: 'Not Found' }, { status: 404, statusText: 'Not Found' });
|
||||||
|
|
||||||
@@ -173,7 +186,7 @@ describe('TenantService', () => {
|
|||||||
expect(service.tenant()).toBeNull();
|
expect(service.tenant()).toBeNull();
|
||||||
expect(service.getTenant()).toBeNull();
|
expect(service.getTenant()).toBeNull();
|
||||||
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
expect(transferState.get(TENANT_SSR_STATE_KEY, null)).toEqual({
|
||||||
status: 'not-found'
|
status: 'not-found',
|
||||||
});
|
});
|
||||||
expect(responseInit.status).toBe(404);
|
expect(responseInit.status).toBe(404);
|
||||||
|
|
||||||
@@ -182,14 +195,16 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
it('rejects when the bootstrap response does not contain tenant data', async () => {
|
it('rejects when the bootstrap response does not contain tenant data', async () => {
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService]
|
providers: [provideHttpClient(), provideHttpClientTesting(), TenantService],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
const bootstrapPromise = service.bootstrap();
|
||||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/localhost`);
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||||
|
);
|
||||||
|
|
||||||
request.flush({});
|
request.flush({});
|
||||||
|
|
||||||
@@ -213,19 +228,21 @@ describe('TenantService', () => {
|
|||||||
provide: REQUEST,
|
provide: REQUEST,
|
||||||
useValue: new Request('https://internal.example/render', {
|
useValue: new Request('https://internal.example/render', {
|
||||||
headers: {
|
headers: {
|
||||||
host: 'broken.example.com'
|
host: 'broken.example.com',
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
},
|
},
|
||||||
{ provide: RESPONSE_INIT, useValue: responseInit }
|
{ provide: RESPONSE_INIT, useValue: responseInit },
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const service = TestBed.inject(TenantService);
|
const service = TestBed.inject(TenantService);
|
||||||
const httpController = TestBed.inject(HttpTestingController);
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
const bootstrapPromise = service.bootstrap();
|
const bootstrapPromise = service.bootstrap();
|
||||||
const request = httpController.expectOne(`${environment.url}tenants/bootstrap/broken.example.com`);
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=broken.example.com&path=/render`,
|
||||||
|
);
|
||||||
|
|
||||||
request.flush({ message: 'Boom' }, { status: 500, statusText: 'Server Error' });
|
request.flush({ message: 'Boom' }, { status: 500, statusText: 'Server Error' });
|
||||||
|
|
||||||
@@ -235,4 +252,39 @@ describe('TenantService', () => {
|
|||||||
|
|
||||||
httpController.verify();
|
httpController.verify();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('rejects and cancels a tenant bootstrap request that exceeds the configured timeout', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
|
||||||
|
try {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideHttpClient(),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
TenantService,
|
||||||
|
{ provide: BOOTSTRAP_REQUEST_TIMEOUT_MS, useValue: 25 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const service = TestBed.inject(TenantService);
|
||||||
|
const httpController = TestBed.inject(HttpTestingController);
|
||||||
|
|
||||||
|
const bootstrapPromise = service.bootstrap();
|
||||||
|
const rejection = expect(bootstrapPromise).rejects.toBeInstanceOf(TimeoutError);
|
||||||
|
const request = httpController.expectOne(
|
||||||
|
`${environment.url}tenants/bootstrap?dominio=localhost&path=/`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(25);
|
||||||
|
await rejection;
|
||||||
|
|
||||||
|
expect(request.cancelled).toBe(true);
|
||||||
|
expect(service.status()).toBe('idle');
|
||||||
|
expect(service.tenant()).toBeNull();
|
||||||
|
|
||||||
|
httpController.verify();
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
|
import { DOCUMENT, isPlatformBrowser, isPlatformServer } from '@angular/common';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import {
|
import {
|
||||||
inject,
|
inject,
|
||||||
@@ -7,29 +7,32 @@ import {
|
|||||||
REQUEST,
|
REQUEST,
|
||||||
RESPONSE_INIT,
|
RESPONSE_INIT,
|
||||||
signal,
|
signal,
|
||||||
TransferState
|
TransferState,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { IS_DISCOVERING_ROUTES } from '@angular/ssr';
|
import { IS_DISCOVERING_ROUTES } from '@angular/ssr';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom, timeout } from 'rxjs';
|
||||||
|
|
||||||
import { environment } from '../../../environments/environment';
|
import { environment } from '../../../environments/environment';
|
||||||
import { BaseApiService } from './base-api.service';
|
import { BaseApiService } from './base-api.service';
|
||||||
|
import { BOOTSTRAP_REQUEST_TIMEOUT_MS } from './bootstrap-request-timeout';
|
||||||
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
import { Tenant, TenantBootstrapResponse } from './tenant.interface';
|
||||||
import {
|
import {
|
||||||
TENANT_SSR_STATE_KEY,
|
TENANT_SSR_STATE_KEY,
|
||||||
TenantBootstrapStatus,
|
TenantBootstrapStatus,
|
||||||
TenantSsrState
|
TenantSsrState,
|
||||||
} from './tenant-ssr-cache.store';
|
} from './tenant-ssr-cache.store';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class TenantService extends BaseApiService {
|
export class TenantService extends BaseApiService {
|
||||||
|
private readonly document = inject(DOCUMENT);
|
||||||
private readonly platformId = inject(PLATFORM_ID);
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
private readonly request = inject(REQUEST, { optional: true });
|
private readonly request = inject(REQUEST, { optional: true });
|
||||||
private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
|
private readonly responseInit = inject(RESPONSE_INIT, { optional: true });
|
||||||
private readonly transferState = inject(TransferState);
|
private readonly transferState = inject(TransferState);
|
||||||
private readonly isDiscoveringRoutes = inject(IS_DISCOVERING_ROUTES, { optional: true }) ?? false;
|
private readonly isDiscoveringRoutes = inject(IS_DISCOVERING_ROUTES, { optional: true }) ?? false;
|
||||||
|
private readonly bootstrapRequestTimeoutMs = inject(BOOTSTRAP_REQUEST_TIMEOUT_MS);
|
||||||
private readonly tenantState = signal<Tenant | null>(null);
|
private readonly tenantState = signal<Tenant | null>(null);
|
||||||
private readonly statusState = signal<TenantBootstrapStatus>('idle');
|
private readonly statusState = signal<TenantBootstrapStatus>('idle');
|
||||||
|
|
||||||
@@ -48,7 +51,6 @@ export class TenantService extends BaseApiService {
|
|||||||
return `${environment.url}tenants/${tenant.codigo}`;
|
return `${environment.url}tenants/${tenant.codigo}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async bootstrap(): Promise<void> {
|
async bootstrap(): Promise<void> {
|
||||||
if (this.statusState() !== 'idle') {
|
if (this.statusState() !== 'idle') {
|
||||||
return;
|
return;
|
||||||
@@ -69,13 +71,18 @@ export class TenantService extends BaseApiService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const domain = this.resolveDomain();
|
const { domain, path } = this.resolveRequestContext();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await firstValueFrom(
|
const response = await firstValueFrom(
|
||||||
this.http.get<TenantBootstrapResponse>(
|
this.http
|
||||||
`${environment.url}tenants/bootstrap/${domain}`
|
.get<TenantBootstrapResponse>(`${environment.url}tenants/bootstrap`, {
|
||||||
)
|
params: {
|
||||||
|
dominio: domain,
|
||||||
|
path,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.pipe(timeout(this.bootstrapRequestTimeoutMs)),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!response?.data) {
|
if (!response?.data) {
|
||||||
@@ -85,7 +92,7 @@ export class TenantService extends BaseApiService {
|
|||||||
this.setReady(response.data);
|
this.setReady(response.data);
|
||||||
this.persistSsrState({
|
this.persistSsrState({
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
tenant: response.data
|
tenant: response.data,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.isNotFoundError(error)) {
|
if (this.isNotFoundError(error)) {
|
||||||
@@ -103,7 +110,7 @@ export class TenantService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveDomain(): string {
|
private resolveRequestContext(): { domain: string; path: string } {
|
||||||
if (isPlatformBrowser(this.platformId)) {
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
const domain = window.location.hostname;
|
const domain = window.location.hostname;
|
||||||
|
|
||||||
@@ -111,7 +118,10 @@ export class TenantService extends BaseApiService {
|
|||||||
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.normalizeHost(domain);
|
return {
|
||||||
|
domain: this.normalizeHost(domain),
|
||||||
|
path: this.normalizePath(window.location.pathname),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const requestHost =
|
const requestHost =
|
||||||
@@ -123,7 +133,14 @@ export class TenantService extends BaseApiService {
|
|||||||
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
throw new Error('Tenant bootstrap could not resolve the current domain.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.normalizeHost(requestHost);
|
const forwardedPath =
|
||||||
|
this.request?.headers.get('x-forwarded-uri') ?? this.request?.headers.get('x-original-uri');
|
||||||
|
const requestPath = forwardedPath ?? (this.request ? new URL(this.request.url).pathname : '/');
|
||||||
|
|
||||||
|
return {
|
||||||
|
domain: this.normalizeHost(requestHost),
|
||||||
|
path: this.normalizePath(requestPath),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeHost(host: string): string {
|
private normalizeHost(host: string): string {
|
||||||
@@ -145,6 +162,16 @@ export class TenantService extends BaseApiService {
|
|||||||
return normalizedHost.replace(/:\d+$/, '');
|
return normalizedHost.replace(/:\d+$/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private normalizePath(path: string): string {
|
||||||
|
const pathname = path.split(/[?#]/, 1)[0]?.trim() ?? '';
|
||||||
|
|
||||||
|
if (!pathname || pathname === '/') {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `/${pathname.replace(/^\/+|\/+$/g, '')}`;
|
||||||
|
}
|
||||||
|
|
||||||
private applyState(state: TenantSsrState): void {
|
private applyState(state: TenantSsrState): void {
|
||||||
if (state.status === 'ready') {
|
if (state.status === 'ready') {
|
||||||
this.setReady(state.tenant);
|
this.setReady(state.tenant);
|
||||||
@@ -156,10 +183,44 @@ export class TenantService extends BaseApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setReady(tenant: Tenant): void {
|
private setReady(tenant: Tenant): void {
|
||||||
|
if (isPlatformBrowser(this.platformId) && !environment.production) {
|
||||||
|
console.info('[Tenant bootstrap]', tenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ensureAssetPreconnect(tenant.asset_url);
|
||||||
this.tenantState.set(tenant);
|
this.tenantState.set(tenant);
|
||||||
this.statusState.set('ready');
|
this.statusState.set('ready');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ensureAssetPreconnect(assetUrl: string | null | undefined): void {
|
||||||
|
if (!assetUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let origin: string;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = new URL(assetUrl);
|
||||||
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
origin = url.origin;
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingPreconnects =
|
||||||
|
this.document.head.querySelectorAll<HTMLLinkElement>('link[rel="preconnect"]');
|
||||||
|
if ([...existingPreconnects].some((link) => link.href === `${origin}/`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = this.document.createElement('link');
|
||||||
|
link.rel = 'preconnect';
|
||||||
|
link.href = origin;
|
||||||
|
this.document.head.append(link);
|
||||||
|
}
|
||||||
|
|
||||||
private setNotFound(): void {
|
private setNotFound(): void {
|
||||||
this.tenantState.set(null);
|
this.tenantState.set(null);
|
||||||
this.statusState.set('not-found');
|
this.statusState.set('not-found');
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { DOCUMENT } from '@angular/common';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { vi } from 'vitest';
|
import { vi } from 'vitest';
|
||||||
import { ToastService } from './toast.service';
|
import { ToastService } from './toast.service';
|
||||||
@@ -6,14 +7,16 @@ describe('ToastService', () => {
|
|||||||
let service: ToastService;
|
let service: ToastService;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [ToastService]
|
providers: [ToastService]
|
||||||
});
|
});
|
||||||
|
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
|
||||||
service = TestBed.inject(ToastService);
|
service = TestBed.inject(ToastService);
|
||||||
vi.useFakeTimers();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.removeItem('shopit.pending-toast');
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -98,4 +101,23 @@ describe('ToastService', () => {
|
|||||||
|
|
||||||
expect(service.toasts().length).toBe(1);
|
expect(service.toasts().length).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should restore a toast queued for after a full page reload', () => {
|
||||||
|
service.showAfterReload('Sesión iniciada correctamente.', 'success', 0);
|
||||||
|
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
TestBed.configureTestingModule({ providers: [ToastService] });
|
||||||
|
service = TestBed.inject(ToastService);
|
||||||
|
|
||||||
|
expect(service.toasts()).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
message: 'Sesión iniciada correctamente.',
|
||||||
|
type: 'success',
|
||||||
|
duration: 0,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
TestBed.inject(DOCUMENT).defaultView?.sessionStorage.getItem('shopit.pending-toast'),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { Injectable, signal } from '@angular/core';
|
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
|
||||||
|
import { inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
||||||
|
|
||||||
|
const PENDING_TOAST_STORAGE_KEY = 'shopit.pending-toast';
|
||||||
|
|
||||||
export interface Toast {
|
export interface Toast {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -11,9 +14,15 @@ export interface Toast {
|
|||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class ToastService {
|
export class ToastService {
|
||||||
|
private readonly document = inject(DOCUMENT);
|
||||||
|
private readonly platformId = inject(PLATFORM_ID);
|
||||||
private readonly toastsSignal = signal<Toast[]>([]);
|
private readonly toastsSignal = signal<Toast[]>([]);
|
||||||
readonly toasts = this.toastsSignal.asReadonly();
|
readonly toasts = this.toastsSignal.asReadonly();
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.restorePendingToast();
|
||||||
|
}
|
||||||
|
|
||||||
show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string {
|
show(message: string, type: 'success' | 'danger' | 'info' = 'info', duration = 3000): string {
|
||||||
const id = Math.random().toString(36).substring(2, 9);
|
const id = Math.random().toString(36).substring(2, 9);
|
||||||
const newToast: Toast = { id, message, type, duration };
|
const newToast: Toast = { id, message, type, duration };
|
||||||
@@ -41,7 +50,50 @@ export class ToastService {
|
|||||||
return this.show(message, 'success', duration);
|
return this.show(message, 'success', duration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
showAfterReload(
|
||||||
|
message: string,
|
||||||
|
type: Toast['type'] = 'info',
|
||||||
|
duration = 3000,
|
||||||
|
): void {
|
||||||
|
if (!isPlatformBrowser(this.platformId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.document.defaultView?.sessionStorage.setItem(
|
||||||
|
PENDING_TOAST_STORAGE_KEY,
|
||||||
|
JSON.stringify({ message, type, duration }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
dismiss(id: string): void {
|
dismiss(id: string): void {
|
||||||
this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id));
|
this.toastsSignal.update((toasts) => toasts.filter((t) => t.id !== id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private restorePendingToast(): void {
|
||||||
|
if (!isPlatformBrowser(this.platformId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const storage = this.document.defaultView?.sessionStorage;
|
||||||
|
const pendingToast = storage?.getItem(PENDING_TOAST_STORAGE_KEY);
|
||||||
|
|
||||||
|
if (!pendingToast) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
storage?.removeItem(PENDING_TOAST_STORAGE_KEY);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(pendingToast) as Partial<Toast>;
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof parsed.message === 'string' &&
|
||||||
|
(parsed.type === 'success' || parsed.type === 'danger' || parsed.type === 'info')
|
||||||
|
) {
|
||||||
|
this.show(parsed.message, parsed.type, parsed.duration);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed session data left by an older or interrupted client.
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,9 @@
|
|||||||
Abrir modal ancho
|
Abrir modal ancho
|
||||||
</app-button>
|
</app-button>
|
||||||
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
<app-button (click)="openSimpleModal()"> Abrir simple modal </app-button>
|
||||||
|
<app-button variant="secondary" (click)="openImageModal()">
|
||||||
|
Abrir visor de imagen
|
||||||
|
</app-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-showcase__result" data-testid="modal-last-result">
|
<div class="modal-showcase__result" data-testid="modal-last-result">
|
||||||
{{ lastModalResult }}
|
{{ lastModalResult }}
|
||||||
@@ -703,7 +706,7 @@
|
|||||||
<app-location-map
|
<app-location-map
|
||||||
[locations]="mapLocations"
|
[locations]="mapLocations"
|
||||||
[markerColor]="tenant()?.primary_color ?? '#24a9e0'"
|
[markerColor]="tenant()?.primary_color ?? '#24a9e0'"
|
||||||
mapStyle="minimal-light"
|
mapStyle="standard"
|
||||||
ariaLabel="Mapa de puntos de atención en Rosario"
|
ariaLabel="Mapa de puntos de atención en Rosario"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -754,6 +757,29 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section
|
||||||
|
class="component-demo component-demo--ticket-selector card shadow-sm mt-4"
|
||||||
|
data-testid="ticket-selector-demo"
|
||||||
|
>
|
||||||
|
<div class="card-body">
|
||||||
|
<span class="eyebrow">Reusable Component</span>
|
||||||
|
<h2 class="mb-2">Selector de entradas (Ticket Selector Layout)</h2>
|
||||||
|
<p class="text-muted mb-4">
|
||||||
|
Demo de selección encadenada por tipo, sector, fila y asiento. Las combinaciones sin stock
|
||||||
|
no aparecen como disponibles.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<app-product-ticket-selector
|
||||||
|
[productId]="1"
|
||||||
|
[title]="testTicketSelectorProduct.title"
|
||||||
|
[description]="testTicketSelectorProduct.description"
|
||||||
|
[price]="testTicketSelectorProduct.price"
|
||||||
|
[imageUrl]="testTicketSelectorProduct.imageUrl"
|
||||||
|
(buy)="onTicketBuy($event)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<app-store-section title="PRODUCTOS" class="component-demo store-section-demo mt-5">
|
<app-store-section title="PRODUCTOS" class="component-demo store-section-demo mt-5">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
@for (product of testProducts; track product.title) {
|
@for (product of testProducts; track product.title) {
|
||||||
|
|||||||
@@ -15,6 +15,10 @@
|
|||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.component-demo--ticket-selector {
|
||||||
|
width: min(100%, 76rem);
|
||||||
|
}
|
||||||
|
|
||||||
.store-section-demo {
|
.store-section-demo {
|
||||||
width: min(100%, 64rem);
|
width: min(100%, 64rem);
|
||||||
}
|
}
|
||||||
@@ -77,7 +81,7 @@ h1 {
|
|||||||
|
|
||||||
.modal-showcase__result {
|
.modal-showcase__result {
|
||||||
padding: 0.875rem 1rem;
|
padding: 0.875rem 1rem;
|
||||||
border: 1px dashed rgba(32, 32, 32, 0.14);
|
border: 1px dashed var(--border-color);
|
||||||
border-radius: 0.875rem;
|
border-radius: 0.875rem;
|
||||||
background: linear-gradient(180deg, rgba(248, 248, 248, 0.92), rgba(255, 255, 255, 0.98));
|
background: linear-gradient(180deg, rgba(248, 248, 248, 0.92), rgba(255, 255, 255, 0.98));
|
||||||
color: #495057;
|
color: #495057;
|
||||||
@@ -231,7 +235,7 @@ h1 {
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 120px;
|
height: 120px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
border: 1px solid #dee2e6;
|
border: 1px solid var(--border-color);
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
|
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||||
@@ -281,7 +285,7 @@ h1 {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
border: 1px solid #dee2e6;
|
border: 1px solid var(--border-color);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background-color: #ffffff;
|
background-color: #ffffff;
|
||||||
transition:
|
transition:
|
||||||
@@ -296,7 +300,7 @@ h1 {
|
|||||||
&__preview {
|
&__preview {
|
||||||
height: 80px;
|
height: 80px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-bottom: 1px solid #dee2e6;
|
border-bottom: 1px solid var(--border-color);
|
||||||
transition: opacity 0.2s ease;
|
transition: opacity 0.2s ease;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
@@ -337,7 +341,7 @@ h1 {
|
|||||||
background-color: #eaeaea;
|
background-color: #eaeaea;
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
border: 1px solid #dee2e6;
|
border: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
&__row {
|
&__row {
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ function createModalServiceStub() {
|
|||||||
open: vi.fn(),
|
open: vi.fn(),
|
||||||
openConfirm: vi.fn().mockReturnValue(of(true)),
|
openConfirm: vi.fn().mockReturnValue(of(true)),
|
||||||
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
openConfirmDelete: vi.fn().mockReturnValue(of(false)),
|
||||||
|
openImage: vi.fn().mockReturnValue(of(undefined)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,6 +282,9 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
const deleteButton = buttons.find((button) =>
|
const deleteButton = buttons.find((button) =>
|
||||||
button.textContent?.includes('Abrir confirm delete'),
|
button.textContent?.includes('Abrir confirm delete'),
|
||||||
) as HTMLButtonElement;
|
) as HTMLButtonElement;
|
||||||
|
const imageButton = buttons.find((button) =>
|
||||||
|
button.textContent?.includes('Abrir visor de imagen'),
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Todavia no se abrio ningun modal.',
|
'Todavia no se abrio ningun modal.',
|
||||||
@@ -290,18 +294,25 @@ describe('ReutilizablesTestPageComponent', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
deleteButton.click();
|
deleteButton.click();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
imageButton.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
expect(modalServiceStub.openConfirm).toHaveBeenCalledWith({
|
||||||
title: 'Confirmar accion',
|
title: 'Confirmar accion',
|
||||||
content: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
description: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
});
|
});
|
||||||
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalledWith({
|
expect(modalServiceStub.openConfirmDelete).toHaveBeenCalledWith({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
content:
|
description:
|
||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
});
|
});
|
||||||
|
expect(modalServiceStub.openImage).toHaveBeenCalledWith({
|
||||||
|
title: 'Mochila urbana roja',
|
||||||
|
src: '/images/carousel-mochila-roja.webp',
|
||||||
|
alt: 'Mochila urbana roja vista de frente',
|
||||||
|
});
|
||||||
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
expect(element.querySelector('[data-testid="modal-last-result"]')?.textContent).toContain(
|
||||||
'Resultado: false',
|
'Resultado: false',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { InputComponent } from '../../../../shared/components/input/input.compon
|
|||||||
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
|
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
|
||||||
import { ProductColumnWithImageComponent } from '../../../../shared/components/product-column-with-image/product-column-with-image.component';
|
import { ProductColumnWithImageComponent } from '../../../../shared/components/product-column-with-image/product-column-with-image.component';
|
||||||
import { ProductRowCardComponent } from '../../../../shared/components/product-row-card/product-row-card.component';
|
import { ProductRowCardComponent } from '../../../../shared/components/product-row-card/product-row-card.component';
|
||||||
|
import { ProductTicketSelectorComponent } from '../../../../shared/components/product-ticket-selector/product-ticket-selector.component';
|
||||||
import { ProductVerticalWithCartCardComponent } from '../../../../shared/components/product-vertical-with-cart-card/product-vertical-with-cart-card.component';
|
import { ProductVerticalWithCartCardComponent } from '../../../../shared/components/product-vertical-with-cart-card/product-vertical-with-cart-card.component';
|
||||||
import { StoreSectionComponent } from '../../../../shared/components/store-section/store-section.component';
|
import { StoreSectionComponent } from '../../../../shared/components/store-section/store-section.component';
|
||||||
import { ModalService } from '../../../../core/services/modal.service';
|
import { ModalService } from '../../../../core/services/modal.service';
|
||||||
@@ -32,6 +33,11 @@ interface CarouselProductMock {
|
|||||||
imageUrl: string;
|
imageUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ticketOption = (value: string, label: string = value): { value: string; label: string } => ({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
});
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-reutilizables-test-page',
|
selector: 'app-reutilizables-test-page',
|
||||||
imports: [
|
imports: [
|
||||||
@@ -41,6 +47,7 @@ interface CarouselProductMock {
|
|||||||
PaginatorComponent,
|
PaginatorComponent,
|
||||||
ProductColumnWithImageComponent,
|
ProductColumnWithImageComponent,
|
||||||
ProductRowCardComponent,
|
ProductRowCardComponent,
|
||||||
|
ProductTicketSelectorComponent,
|
||||||
ProductVerticalWithCartCardComponent,
|
ProductVerticalWithCartCardComponent,
|
||||||
StoreSectionComponent,
|
StoreSectionComponent,
|
||||||
IconButtonComponent,
|
IconButtonComponent,
|
||||||
@@ -204,8 +211,9 @@ export class ReutilizablesTestPageComponent {
|
|||||||
'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
|
'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
|
||||||
price: 10000,
|
price: 10000,
|
||||||
variants: [
|
variants: [
|
||||||
{ label: '10 de Octubre', value: '10-oct' },
|
{ id: '10-oct-manana', values: { fecha: '10 de Octubre', turno: 'Mañana' } },
|
||||||
{ label: '11 de Octubre', value: '11-oct' },
|
{ id: '10-oct-tarde', values: { fecha: '10 de Octubre', turno: 'Tarde' } },
|
||||||
|
{ id: '11-oct-tarde', values: { fecha: '11 de Octubre', turno: 'Tarde' } },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -215,6 +223,125 @@ export class ReutilizablesTestPageComponent {
|
|||||||
price: 11500,
|
price: 11500,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
protected readonly testTicketSelectorProduct = {
|
||||||
|
title: 'ENTRADAS DESFILE PURA TENDENCIA',
|
||||||
|
description: '',
|
||||||
|
price: 40000,
|
||||||
|
imageUrl: '/images/ticket-selector-entrada-pasarela.png',
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
id: 1001,
|
||||||
|
precio: 250000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
|
sector: ticketOption('a', 'Sector A'),
|
||||||
|
fila: ticketOption('1', 'Fila 1'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1002,
|
||||||
|
precio: 250000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
|
sector: ticketOption('a', 'Sector A'),
|
||||||
|
fila: ticketOption('1', 'Fila 1'),
|
||||||
|
asiento: ticketOption('2', 'Asiento 2'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1003,
|
||||||
|
precio: 250000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
|
sector: ticketOption('c', 'Sector C'),
|
||||||
|
fila: ticketOption('1', 'Fila 1'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1004,
|
||||||
|
precio: 200000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
|
sector: ticketOption('a', 'Sector A'),
|
||||||
|
fila: ticketOption('2', 'Fila 2'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1005,
|
||||||
|
precio: 200000,
|
||||||
|
maximum_addable_quantity: 0,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('vip_lunch', 'VIP + Lunch'),
|
||||||
|
sector: ticketOption('a', 'Sector A'),
|
||||||
|
fila: ticketOption('2', 'Fila 2'),
|
||||||
|
asiento: ticketOption('2', 'Asiento 2'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1006,
|
||||||
|
precio: 100000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('general', 'General'),
|
||||||
|
sector: ticketOption('b', 'Sector B'),
|
||||||
|
fila: ticketOption('3', 'Fila 3'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1007,
|
||||||
|
precio: 100000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('general', 'General'),
|
||||||
|
sector: ticketOption('b', 'Sector B'),
|
||||||
|
fila: ticketOption('3', 'Fila 3'),
|
||||||
|
asiento: ticketOption('2', 'Asiento 2'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1008,
|
||||||
|
precio: 90000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('general', 'General'),
|
||||||
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
fila: ticketOption('3', 'Fila 3'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1009,
|
||||||
|
precio: 65000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('general', 'General'),
|
||||||
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
fila: ticketOption('4', 'Fila 4'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 1010,
|
||||||
|
precio: 40000,
|
||||||
|
maximum_addable_quantity: 1,
|
||||||
|
values: {
|
||||||
|
tipo: ticketOption('general', 'General'),
|
||||||
|
sector: ticketOption('d', 'Sector D'),
|
||||||
|
fila: ticketOption('5', 'Fila 5'),
|
||||||
|
asiento: ticketOption('1', 'Asiento 1'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
protected readonly cartMockItems: CartItemMock[] = [
|
protected readonly cartMockItems: CartItemMock[] = [
|
||||||
{
|
{
|
||||||
imageUrl: null,
|
imageUrl: null,
|
||||||
@@ -271,6 +398,12 @@ export class ReutilizablesTestPageComponent {
|
|||||||
alert(`Comprando: ${productTitle}`);
|
alert(`Comprando: ${productTitle}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected onTicketBuy(variantIds: number[]): void {
|
||||||
|
this.toastService.success(
|
||||||
|
`Compra iniciada para ${variantIds.length} entrada/s: ${variantIds.join(', ')}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
protected onFileChange(file: File | null): void {
|
protected onFileChange(file: File | null): void {
|
||||||
this.fileName = file?.name ?? '';
|
this.fileName = file?.name ?? '';
|
||||||
}
|
}
|
||||||
@@ -315,7 +448,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openBasicModal(): void {
|
protected openBasicModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Confirmar accion',
|
title: 'Confirmar accion',
|
||||||
content: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
description: 'Caso base para verificar apertura, cierre y devolucion de resultado.',
|
||||||
confirmLabel: 'Confirmar',
|
confirmLabel: 'Confirmar',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -323,7 +456,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openConfirmDeleteModal(): void {
|
protected openConfirmDeleteModal(): void {
|
||||||
this.openConfirmDelete({
|
this.openConfirmDelete({
|
||||||
title: 'Eliminar producto',
|
title: 'Eliminar producto',
|
||||||
content:
|
description:
|
||||||
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
'Esta accion eliminara el producto del catalogo. Podras volver a crearlo manualmente.',
|
||||||
confirmLabel: 'Eliminar',
|
confirmLabel: 'Eliminar',
|
||||||
});
|
});
|
||||||
@@ -332,7 +465,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openLockedModal(): void {
|
protected openLockedModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Modal bloqueado',
|
title: 'Modal bloqueado',
|
||||||
content: 'Este modal no se cierra tocando el backdrop ni con la tecla Escape.',
|
description: 'Este modal no se cierra tocando el backdrop ni con la tecla Escape.',
|
||||||
confirmLabel: 'Entendido',
|
confirmLabel: 'Entendido',
|
||||||
closeOnBackdrop: false,
|
closeOnBackdrop: false,
|
||||||
closeOnEscape: false,
|
closeOnEscape: false,
|
||||||
@@ -342,7 +475,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
protected openWideModal(): void {
|
protected openWideModal(): void {
|
||||||
this.openConfirmModal({
|
this.openConfirmModal({
|
||||||
title: 'Modal ancho',
|
title: 'Modal ancho',
|
||||||
content: 'Demuestra una variante visual mas amplia para contenido mas pesado.',
|
description: 'Demuestra una variante visual mas amplia para contenido mas pesado.',
|
||||||
confirmLabel: 'Seguir',
|
confirmLabel: 'Seguir',
|
||||||
size: 'xl',
|
size: 'xl',
|
||||||
});
|
});
|
||||||
@@ -352,7 +485,7 @@ export class ReutilizablesTestPageComponent {
|
|||||||
this.modalService
|
this.modalService
|
||||||
.openSimple({
|
.openSimple({
|
||||||
title: 'Mensaje del sistema',
|
title: 'Mensaje del sistema',
|
||||||
content: 'Este es un mensaje simple del sistema que no requiere confirmación.',
|
description: 'Este es un mensaje simple del sistema que no requiere confirmación.',
|
||||||
buttonLabel: 'Entendido',
|
buttonLabel: 'Entendido',
|
||||||
})
|
})
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
@@ -360,6 +493,14 @@ export class ReutilizablesTestPageComponent {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openImageModal(): void {
|
||||||
|
this.modalService.openImage({
|
||||||
|
title: 'Mochila urbana roja',
|
||||||
|
src: '/images/carousel-mochila-roja.webp',
|
||||||
|
alt: 'Mochila urbana roja vista de frente',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
private openConfirmModal(config: Parameters<ModalService['openConfirm']>[0]): void {
|
||||||
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
this.modalService.openConfirm(config).subscribe((confirmed) => {
|
||||||
this.lastModalResult = `Resultado: ${confirmed}`;
|
this.lastModalResult = `Resultado: ${confirmed}`;
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<a class="event-card" [routerLink]="['/evento', event().slug]">
|
||||||
|
<div class="event-card__image">
|
||||||
|
@if (event().image) {
|
||||||
|
<img [src]="event().image" [alt]="event().title" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="event-card__body">
|
||||||
|
<h2 class="event-card__title">{{ event().title | uppercase }}</h2>
|
||||||
|
@if (event().subtitle) {
|
||||||
|
<p class="event-card__subtitle">{{ event().subtitle }}</p>
|
||||||
|
}
|
||||||
|
@if (event().date_text) {
|
||||||
|
<p class="event-card__meta"><i class="fa-regular fa-calendar" aria-hidden="true"></i>{{ event().date_text }}</p>
|
||||||
|
}
|
||||||
|
@if (event().location) {
|
||||||
|
<p class="event-card__meta"><i class="fa-solid fa-location-dot" aria-hidden="true"></i>{{ event().location }}</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.event-card { display: block; height: 100%; color: inherit; background: #fff; text-decoration: none; box-shadow: 0 12px 30px rgba(0, 0, 0, .05); transition: transform .2s, box-shadow .2s; }
|
||||||
|
.event-card:hover { transform: translateY(-3px); box-shadow: 0 16px 32px rgba(0, 0, 0, .1); }
|
||||||
|
.event-card:focus-visible { outline: 2px solid var(--tenant-primary); outline-offset: 3px; }
|
||||||
|
.event-card__image { width: 100%; aspect-ratio: 1.43; background: #e5e6e7; }
|
||||||
|
.event-card__image img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||||
|
.event-card__body { padding: 1rem 1.1rem 1.2rem; }
|
||||||
|
.event-card__title { margin: 0; font-size: 15px; font-weight: 700; line-height: 1.3; color: #666666; }
|
||||||
|
.event-card__subtitle { margin: .25rem 0 .8rem; font-size: 12px; font-weight: 400; color: #666666; }
|
||||||
|
.event-card__meta { display: flex; align-items: baseline; gap: .45rem; margin: .2rem 0 0; font-size: 9px; font-weight: 400; font-style: italic; color: #666666; }
|
||||||
|
.event-card__meta i { width: .75rem; flex: none; }
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
|
||||||
|
import { UpperCasePipe } from '@angular/common';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
|
||||||
|
import { StoreEvent } from '../../../../core/services/event/event.interface';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-event-card',
|
||||||
|
imports: [RouterLink, UpperCasePipe],
|
||||||
|
templateUrl: './event-card.component.html',
|
||||||
|
styleUrl: './event-card.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
})
|
||||||
|
export class EventCardComponent {
|
||||||
|
readonly event = input.required<StoreEvent>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
@if (loading()) {
|
||||||
|
<p class="event-list__message">Cargando eventos...</p>
|
||||||
|
} @else if (error()) {
|
||||||
|
<p class="event-list__message" role="alert">No pudimos cargar los eventos.</p>
|
||||||
|
} @else if (results(); as page) {
|
||||||
|
@if (page.data.length) {
|
||||||
|
<div class="event-list__grid">
|
||||||
|
@for (event of page.data; track event.id) {
|
||||||
|
<app-event-card [event]="event" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (page.meta.last_page > 1) {
|
||||||
|
<div class="event-list__pagination">
|
||||||
|
<app-paginator [page]="page.meta.current_page" [totalPages]="page.meta.last_page" (pageChange)="changePage($event)" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<p class="event-list__message">{{ search() ? 'No encontramos eventos para tu búsqueda.' : 'No hay eventos disponibles en este momento.' }}</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.event-list__grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: clamp(1.25rem, 3vw, 2.5rem); }
|
||||||
|
.event-list__pagination { display: flex; justify-content: center; margin-top: 3rem; }
|
||||||
|
.event-list__message { text-align: center; padding: 2rem 0; }
|
||||||
|
@media (max-width: 767.98px) { .event-list__grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
@media (max-width: 479.98px) { .event-list__grid { grid-template-columns: 1fr; } }
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { ChangeDetectionStrategy, Component, DestroyRef, inject, input, OnInit, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
import { catchError, combineLatest, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs';
|
||||||
|
|
||||||
|
import { EventService } from '../../../../core/services/event/event.service';
|
||||||
|
import { StoreEventPage } from '../../../../core/services/event/event.interface';
|
||||||
|
import { PaginatorComponent } from '../../../../shared/components/paginator/paginator.component';
|
||||||
|
import { EventCardComponent } from '../event-card/event-card.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-event-list',
|
||||||
|
imports: [EventCardComponent, PaginatorComponent],
|
||||||
|
templateUrl: './event-list.component.html',
|
||||||
|
styleUrl: './event-list.component.scss',
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
})
|
||||||
|
export class EventListComponent implements OnInit {
|
||||||
|
private readonly eventService = inject(EventService);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
|
readonly search = input(false);
|
||||||
|
readonly categoryId = input<number | null>(null);
|
||||||
|
protected readonly results = signal<StoreEventPage | null>(null);
|
||||||
|
protected readonly loading = signal(true);
|
||||||
|
protected readonly error = signal(false);
|
||||||
|
protected readonly query = signal('');
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
combineLatest([this.route.queryParamMap, this.route.paramMap]).pipe(
|
||||||
|
map(([params, routeParams]) => {
|
||||||
|
const requestedPage = Number(params.get('page'));
|
||||||
|
return {
|
||||||
|
page: Number.isSafeInteger(requestedPage) && requestedPage > 0 ? requestedPage : 1,
|
||||||
|
query: this.search() ? (params.get('q') ?? '').trim() : '',
|
||||||
|
categoryId: this.categoryId() === null ? null : Number(routeParams.get('id')),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
distinctUntilChanged((a, b) => a.page === b.page && a.query === b.query && a.categoryId === b.categoryId),
|
||||||
|
tap(({ query }) => {
|
||||||
|
this.query.set(query);
|
||||||
|
this.loading.set(true);
|
||||||
|
this.error.set(false);
|
||||||
|
this.results.set(null);
|
||||||
|
}),
|
||||||
|
switchMap(({ page, query, categoryId }) => this.eventService.list(page, query, categoryId ?? undefined).pipe(
|
||||||
|
catchError(() => {
|
||||||
|
this.error.set(true);
|
||||||
|
return of(null);
|
||||||
|
}),
|
||||||
|
)),
|
||||||
|
takeUntilDestroyed(this.destroyRef),
|
||||||
|
).subscribe((results) => {
|
||||||
|
this.results.set(results);
|
||||||
|
this.loading.set(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected changePage(page: number): void {
|
||||||
|
void this.router.navigate([], {
|
||||||
|
relativeTo: this.route,
|
||||||
|
queryParams: { page: page === 1 ? null : page },
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
.menu-content-section__header {
|
.menu-content-section__header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.75rem;
|
gap: var(--menu-content-prefix-gap, 0.75rem);
|
||||||
margin-bottom: 1.25rem;
|
margin-bottom: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,12 @@
|
|||||||
</a>
|
</a>
|
||||||
}
|
}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
@if (sidebarContent.template(); as sidebarTemplate) {
|
||||||
|
<div class="menu-page-layout__context">
|
||||||
|
<ng-container [ngTemplateOutlet]="sidebarTemplate" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<main class="menu-page-layout__content">
|
<main class="menu-page-layout__content">
|
||||||
|
|||||||
@@ -40,6 +40,10 @@
|
|||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
&__context {
|
||||||
|
margin-top: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
&__link {
|
&__link {
|
||||||
color: #888888;
|
color: #888888;
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
|
|||||||
@@ -1,11 +1,34 @@
|
|||||||
import { signal } from '@angular/core';
|
import { Component, signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { ActivatedRoute, provideRouter } from '@angular/router';
|
import { ActivatedRoute, provideRouter } from '@angular/router';
|
||||||
|
import { RouterTestingHarness } from '@angular/router/testing';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { Tenant } from '../../../../core/services/tenant.interface';
|
import { Tenant } from '../../../../core/services/tenant.interface';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
import { MenuPageLayoutComponent } from './menu-page-layout.component';
|
import { MenuPageLayoutComponent } from './menu-page-layout.component';
|
||||||
|
import { MenuPageSidebarContentDirective } from './menu-page-sidebar-content.directive';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-sidebar-test-badge',
|
||||||
|
template: '<strong class="sidebar-test-badge">Componente contextual</strong>',
|
||||||
|
})
|
||||||
|
class SidebarTestBadgeComponent {}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
imports: [MenuPageSidebarContentDirective, SidebarTestBadgeComponent],
|
||||||
|
template: `
|
||||||
|
<p class="routed-page-content">Contenido principal</p>
|
||||||
|
|
||||||
|
<ng-template menuPageSidebarContent>
|
||||||
|
<p class="sidebar-context-copy">{{ contextualCopy }}</p>
|
||||||
|
<app-sidebar-test-badge />
|
||||||
|
</ng-template>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
class SidebarTestPageComponent {
|
||||||
|
protected readonly contextualCopy = 'HTML declarado por la página';
|
||||||
|
}
|
||||||
|
|
||||||
function createTenant(): Tenant {
|
function createTenant(): Tenant {
|
||||||
return {
|
return {
|
||||||
@@ -133,4 +156,44 @@ describe('MenuPageLayoutComponent', () => {
|
|||||||
'Consultas habituales',
|
'Consultas habituales',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders page-owned HTML and components below the sidebar navigation', async () => {
|
||||||
|
const tenant = signal(createTenant());
|
||||||
|
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideRouter([
|
||||||
|
{
|
||||||
|
path: 'mi-cuenta',
|
||||||
|
component: MenuPageLayoutComponent,
|
||||||
|
data: {
|
||||||
|
menuCode: 'account',
|
||||||
|
navigationLabel: 'Secciones de mi cuenta',
|
||||||
|
},
|
||||||
|
children: [{ path: 'tickets', component: SidebarTestPageComponent }],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: { tenant: tenant.asReadonly() },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
const harness = await RouterTestingHarness.create('/mi-cuenta/tickets');
|
||||||
|
const element = harness.routeNativeElement as HTMLElement;
|
||||||
|
const navigation = element.querySelector('.menu-page-layout__nav');
|
||||||
|
const context = element.querySelector('.menu-page-layout__context');
|
||||||
|
|
||||||
|
expect(context?.previousElementSibling).toBe(navigation);
|
||||||
|
expect(context?.querySelector('.sidebar-context-copy')?.textContent?.trim()).toBe(
|
||||||
|
'HTML declarado por la página',
|
||||||
|
);
|
||||||
|
expect(context?.querySelector('.sidebar-test-badge')?.textContent?.trim()).toBe(
|
||||||
|
'Componente contextual',
|
||||||
|
);
|
||||||
|
expect(element.querySelector('.routed-page-content')?.textContent?.trim()).toBe(
|
||||||
|
'Contenido principal',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
|
import { NgTemplateOutlet } from '@angular/common';
|
||||||
import { Component, computed, inject } from '@angular/core';
|
import { Component, computed, inject } from '@angular/core';
|
||||||
import { ActivatedRoute, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
import { ActivatedRoute, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
||||||
|
|
||||||
import { findMenu } from '../../../../core/services/menu.utils';
|
import { findMenu } from '../../../../core/services/menu.utils';
|
||||||
import { TenantService } from '../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../core/services/tenant.service';
|
||||||
|
import { MenuPageSidebarContentService } from './menu-page-sidebar-content.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-menu-page-layout',
|
selector: 'app-menu-page-layout',
|
||||||
imports: [RouterLink, RouterLinkActive, RouterOutlet],
|
imports: [NgTemplateOutlet, RouterLink, RouterLinkActive, RouterOutlet],
|
||||||
|
providers: [MenuPageSidebarContentService],
|
||||||
templateUrl: './menu-page-layout.component.html',
|
templateUrl: './menu-page-layout.component.html',
|
||||||
styleUrl: './menu-page-layout.component.scss',
|
styleUrl: './menu-page-layout.component.scss',
|
||||||
})
|
})
|
||||||
export class MenuPageLayoutComponent {
|
export class MenuPageLayoutComponent {
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
protected readonly sidebarContent = inject(MenuPageSidebarContentService);
|
||||||
|
|
||||||
protected readonly navigationLabel =
|
protected readonly navigationLabel =
|
||||||
(this.route.snapshot.data['navigationLabel'] as string | undefined) ?? 'Secciones';
|
(this.route.snapshot.data['navigationLabel'] as string | undefined) ?? 'Secciones';
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { Directive, inject, OnDestroy, OnInit, TemplateRef } from '@angular/core';
|
||||||
|
|
||||||
|
import { MenuPageSidebarContentService } from './menu-page-sidebar-content.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Projects page-owned content into the sidebar of the closest menu page layout.
|
||||||
|
* The template keeps the declaration context of the routed page, so it can use
|
||||||
|
* that page's fields, bindings and imported components.
|
||||||
|
*/
|
||||||
|
@Directive({
|
||||||
|
selector: 'ng-template[menuPageSidebarContent]',
|
||||||
|
})
|
||||||
|
export class MenuPageSidebarContentDirective implements OnInit, OnDestroy {
|
||||||
|
private readonly template = inject(TemplateRef<unknown>);
|
||||||
|
private readonly sidebarContent = inject(MenuPageSidebarContentService);
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.sidebarContent.register(this.template);
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.sidebarContent.unregister(this.template);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { Injectable, signal, TemplateRef } from '@angular/core';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MenuPageSidebarContentService {
|
||||||
|
private readonly templateState = signal<TemplateRef<unknown> | null>(null);
|
||||||
|
|
||||||
|
readonly template = this.templateState.asReadonly();
|
||||||
|
|
||||||
|
register(template: TemplateRef<unknown>): void {
|
||||||
|
this.templateState.set(template);
|
||||||
|
}
|
||||||
|
|
||||||
|
unregister(template: TemplateRef<unknown>): void {
|
||||||
|
if (this.templateState() === template) {
|
||||||
|
this.templateState.set(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<div class="attribute-selector">
|
<div class="attribute-selector">
|
||||||
@for (attribute of attributes(); track attribute.id) {
|
@for (attribute of visibleAttributes(); track attribute.codigo) {
|
||||||
<div class="attribute-selector__row">
|
<div class="attribute-selector__row">
|
||||||
<span class="attribute-selector__label">{{ attribute.nombre }}:</span>
|
<span class="attribute-selector__label">{{ attribute.nombre }}:</span>
|
||||||
|
|
||||||
@@ -10,12 +10,14 @@
|
|||||||
type="button"
|
type="button"
|
||||||
class="attribute-selector__swatch"
|
class="attribute-selector__swatch"
|
||||||
[class.attribute-selector__swatch--selected]="hasSelectedOption(attribute, option)"
|
[class.attribute-selector__swatch--selected]="hasSelectedOption(attribute, option)"
|
||||||
[class.attribute-selector__swatch--disabled]="!availableOptions()[attribute.id][option.id]"
|
[class.attribute-selector__swatch--disabled]="
|
||||||
|
!availableOptions()[attribute.codigo][option.id]
|
||||||
|
"
|
||||||
[style.background-color]="getOptionSwatchColor(option)"
|
[style.background-color]="getOptionSwatchColor(option)"
|
||||||
[attr.aria-label]="option.label"
|
[attr.aria-label]="option.label"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[title]="option.label"
|
[title]="option.label"
|
||||||
[disabled]="!availableOptions()[attribute.id][option.id]"
|
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
<span class="visually-hidden">{{ option.label }}</span>
|
<span class="visually-hidden">{{ option.label }}</span>
|
||||||
@@ -24,10 +26,14 @@
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="attribute-selector__text-option"
|
class="attribute-selector__text-option"
|
||||||
[class.attribute-selector__text-option--selected]="hasSelectedOption(attribute, option)"
|
[class.attribute-selector__text-option--selected]="
|
||||||
[class.attribute-selector__text-option--disabled]="!availableOptions()[attribute.id][option.id]"
|
hasSelectedOption(attribute, option)
|
||||||
|
"
|
||||||
|
[class.attribute-selector__text-option--disabled]="
|
||||||
|
!availableOptions()[attribute.codigo][option.id]
|
||||||
|
"
|
||||||
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
[attr.aria-pressed]="hasSelectedOption(attribute, option)"
|
||||||
[disabled]="!availableOptions()[attribute.id][option.id]"
|
[disabled]="!availableOptions()[attribute.codigo][option.id]"
|
||||||
(click)="selectAttributeOption(attribute, option)"
|
(click)="selectAttributeOption(attribute, option)"
|
||||||
>
|
>
|
||||||
{{ option.label }}
|
{{ option.label }}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
&__text-option {
|
&__text-option {
|
||||||
border: 1px solid #dcdcdc;
|
border: 1px solid var(--border-color);
|
||||||
background: #ffffff;
|
background: #ffffff;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
transition: border-color 0.2s ease, color 0.2s ease, background-color 0.2s ease;
|
transition: border-color 0.2s ease, color 0.2s ease, background-color 0.2s ease;
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { beforeEach, describe, expect, it } from 'vitest';
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
|
import {
|
||||||
|
CatalogItemVariant,
|
||||||
|
ProductAttribute,
|
||||||
|
} from '../../../../core/services/catalog/catalog.interface';
|
||||||
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';
|
||||||
|
|
||||||
describe('ProductAttributeSelectorComponent', () => {
|
describe('ProductAttributeSelectorComponent', () => {
|
||||||
@@ -24,6 +27,63 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
}).compileComponents();
|
}).compileComponents();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([{ size: { value: 'S', label: 'Small' } }, { size: [{ value: 'S', label: 'Small' }] }])(
|
||||||
|
'initializes and matches structured variant values: %j',
|
||||||
|
(values) => {
|
||||||
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
|
const variant: CatalogItemVariant = { id: 1, maximum_addable_quantity: null, values };
|
||||||
|
const emittedIds: Array<number | null> = [];
|
||||||
|
fixture.componentInstance.variantChange.subscribe((selected) =>
|
||||||
|
emittedIds.push(selected?.id ?? null),
|
||||||
|
);
|
||||||
|
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
||||||
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
|
fixture.componentRef.setInput('variants', [variant]);
|
||||||
|
fixture.componentRef.setInput('selectedVariant', variant);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const button = fixture.nativeElement.querySelector(
|
||||||
|
'.attribute-selector__text-option',
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
expect(button.getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(button.disabled).toBe(false);
|
||||||
|
expect(emittedIds.at(-1)).toBe(1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([0, 2, null])(
|
||||||
|
'uses maximum quantity %s for alternatives to a preselected option',
|
||||||
|
(maximum) => {
|
||||||
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
|
const variants: CatalogItemVariant[] = [
|
||||||
|
{ id: 1, maximum_addable_quantity: 3, values: { size: { value: 'S', label: 'Small' } } },
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
maximum_addable_quantity: maximum,
|
||||||
|
values: { size: { value: 'M', label: 'Medium' } },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const emittedIds: Array<number | null> = [];
|
||||||
|
fixture.componentInstance.variantChange.subscribe((variant) =>
|
||||||
|
emittedIds.push(variant?.id ?? null),
|
||||||
|
);
|
||||||
|
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
||||||
|
fixture.componentRef.setInput('inventoryPolicy', maximum === null ? 'unlimited' : 'tracked');
|
||||||
|
fixture.componentRef.setInput('variants', variants);
|
||||||
|
fixture.componentRef.setInput('selectedVariant', variants[0]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const buttons = fixture.nativeElement.querySelectorAll(
|
||||||
|
'.attribute-selector__text-option',
|
||||||
|
) as NodeListOf<HTMLButtonElement>;
|
||||||
|
expect(buttons[1].disabled).toBe(maximum === 0);
|
||||||
|
buttons[1].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(emittedIds.at(-1)).toBe(maximum === 0 ? 1 : 2);
|
||||||
|
expect(buttons[0].disabled).toBe(false);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('keeps an unlimited option available when maximum quantity is null', () => {
|
it('keeps an unlimited option available when maximum quantity is null', () => {
|
||||||
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
fixture.componentRef.setInput('attributes', [sizeAttribute]);
|
||||||
@@ -31,7 +91,7 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: null,
|
maximum_addable_quantity: null,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -51,12 +111,12 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
fixture.componentRef.setInput('variants', [
|
fixture.componentRef.setInput('variants', [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
stock_tecnico: 0,
|
maximum_addable_quantity: 0,
|
||||||
values: { size: 'S' },
|
values: { size: 'S' },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
stock_tecnico: 2,
|
maximum_addable_quantity: 2,
|
||||||
values: { size: 'M' },
|
values: { size: 'M' },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -68,4 +128,94 @@ describe('ProductAttributeSelectorComponent', () => {
|
|||||||
expect(buttons[0].disabled).toBe(true);
|
expect(buttons[0].disabled).toBe(true);
|
||||||
expect(buttons[1].disabled).toBe(false);
|
expect(buttons[1].disabled).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('allows multiple event dates and emits the exact matching variant', () => {
|
||||||
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
|
const emittedIds: Array<number | null> = [];
|
||||||
|
fixture.componentInstance.variantChange.subscribe((variant) =>
|
||||||
|
emittedIds.push(variant?.id ?? null),
|
||||||
|
);
|
||||||
|
fixture.componentRef.setInput('attributes', [
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
codigo: 'event_date',
|
||||||
|
nombre: 'Fecha',
|
||||||
|
is_required: true,
|
||||||
|
allow_multi_select: true,
|
||||||
|
metadata_schema: null,
|
||||||
|
type: 'event_date',
|
||||||
|
options: [
|
||||||
|
{ id: 101, value: '1', label: '09/10/2026', sort_order: 0, metadata: null },
|
||||||
|
{ id: 102, value: '2', label: '10/10/2026', sort_order: 1, metadata: null },
|
||||||
|
],
|
||||||
|
} satisfies ProductAttribute,
|
||||||
|
]);
|
||||||
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
|
fixture.componentRef.setInput('variants', [
|
||||||
|
{ id: 1, maximum_addable_quantity: null, values: { event_date: '1' } },
|
||||||
|
{ id: 2, maximum_addable_quantity: null, values: { event_date: '2' } },
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
maximum_addable_quantity: null,
|
||||||
|
values: {
|
||||||
|
event_date: [
|
||||||
|
{ value: '1', label: '09/10/2026' },
|
||||||
|
{ value: '2', label: '10/10/2026' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const buttons = Array.from(
|
||||||
|
fixture.nativeElement.querySelectorAll('.attribute-selector__text-option'),
|
||||||
|
) as HTMLButtonElement[];
|
||||||
|
buttons[0].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
buttons[1].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect(buttons[0].getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(buttons[1].getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(emittedIds).toContain(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides configured attributes and matches variants using only visible selections', () => {
|
||||||
|
const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
|
||||||
|
const emittedIds: Array<number | null> = [];
|
||||||
|
fixture.componentInstance.variantChange.subscribe((variant) =>
|
||||||
|
emittedIds.push(variant?.id ?? null),
|
||||||
|
);
|
||||||
|
fixture.componentRef.setInput('attributes', [
|
||||||
|
sizeAttribute,
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
codigo: 'internal_type',
|
||||||
|
nombre: 'Internal type',
|
||||||
|
is_required: true,
|
||||||
|
show_in_selector: false,
|
||||||
|
metadata_schema: null,
|
||||||
|
type: 'select',
|
||||||
|
options: [
|
||||||
|
{ id: 30, value: 'adult', label: 'Adult', sort_order: 0, metadata: null },
|
||||||
|
{ id: 40, value: 'child', label: 'Child', sort_order: 1, metadata: null },
|
||||||
|
],
|
||||||
|
} satisfies ProductAttribute,
|
||||||
|
]);
|
||||||
|
fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
|
||||||
|
fixture.componentRef.setInput('variants', [
|
||||||
|
{ id: 1, maximum_addable_quantity: null, values: { size: 'S', internal_type: 'adult' } },
|
||||||
|
{ id: 2, maximum_addable_quantity: null, values: { size: 'M', internal_type: 'child' } },
|
||||||
|
]);
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const labels = fixture.nativeElement.querySelectorAll('.attribute-selector__label');
|
||||||
|
const buttons = fixture.nativeElement.querySelectorAll('.attribute-selector__text-option');
|
||||||
|
|
||||||
|
expect(labels).toHaveLength(1);
|
||||||
|
expect(labels[0].textContent).toContain('Size');
|
||||||
|
buttons[1].click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(emittedIds).toContain(2);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -32,48 +32,62 @@ export class ProductAttributeSelectorComponent {
|
|||||||
|
|
||||||
public variantChange = output<CatalogItemVariant | null>();
|
public variantChange = output<CatalogItemVariant | null>();
|
||||||
|
|
||||||
protected readonly selectedAttributeOptions = signal<Record<number, number>>({});
|
protected readonly visibleAttributes = computed(() =>
|
||||||
|
this.attributes().filter((attribute) => attribute.show_in_selector !== false),
|
||||||
|
);
|
||||||
|
|
||||||
|
protected readonly selectedAttributeOptions = signal<Record<string, number[]>>({});
|
||||||
|
|
||||||
protected readonly availableOptions = computed(() => {
|
protected readonly availableOptions = computed(() => {
|
||||||
const selections = this.selectedAttributeOptions();
|
const selections = this.selectedAttributeOptions();
|
||||||
const variants = this.variants();
|
const variants = this.variants();
|
||||||
const attributes = this.attributes();
|
const attributes = this.visibleAttributes();
|
||||||
|
|
||||||
const availability: Record<number, Record<number, boolean>> = {};
|
const availability: Record<string, Record<number, boolean>> = {};
|
||||||
|
|
||||||
for (const attribute of attributes) {
|
for (const attribute of attributes) {
|
||||||
availability[attribute.id] = {};
|
availability[attribute.codigo] = {};
|
||||||
for (const option of attribute.options) {
|
for (const option of attribute.options) {
|
||||||
const optionNormalized = this.normalizeText(option.value || option.label);
|
const optionNormalized = this.normalizeText(option.value || option.label);
|
||||||
|
const selectedForAttribute = selections[attribute.codigo] ?? [];
|
||||||
|
|
||||||
const isAvailable = variants.some((variant) => {
|
const isAvailable = variants.some((variant) => {
|
||||||
if (!this.isVariantAvailable(variant)) return false;
|
if (!this.isVariantAvailable(variant)) return false;
|
||||||
|
|
||||||
const variantAttrValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
|
const variantAttrValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||||
if (!variantAttrValue || this.normalizeText(variantAttrValue) !== optionNormalized) {
|
const desiredOptionIds = !attribute.allow_multi_select
|
||||||
|
? [option.id]
|
||||||
|
: selectedForAttribute.includes(option.id)
|
||||||
|
? selectedForAttribute
|
||||||
|
: [...selectedForAttribute, option.id];
|
||||||
|
const desiredValues = desiredOptionIds
|
||||||
|
.map((id) => attribute.options.find((candidate) => candidate.id === id))
|
||||||
|
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||||
|
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
|
||||||
|
|
||||||
|
if (
|
||||||
|
!variantAttrValues.includes(optionNormalized) ||
|
||||||
|
!desiredValues.every((value) => variantAttrValues.includes(value))
|
||||||
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const otherAttr of attributes) {
|
for (const otherAttr of attributes) {
|
||||||
if (otherAttr.id === attribute.id) continue;
|
if (otherAttr.codigo === attribute.codigo) continue;
|
||||||
const selectedOptionId = selections[otherAttr.id];
|
const selectedOptionIds = selections[otherAttr.codigo] ?? [];
|
||||||
if (selectedOptionId !== undefined) {
|
const selectedValues = selectedOptionIds
|
||||||
const selectedOption = otherAttr.options.find((o) => o.id === selectedOptionId);
|
.map((id) => otherAttr.options.find((candidate) => candidate.id === id))
|
||||||
if (selectedOption) {
|
.filter((candidate): candidate is ProductAttributeOption => candidate !== undefined)
|
||||||
const selectedNormalized = this.normalizeText(
|
.map((candidate) => this.normalizeText(candidate.value || candidate.label));
|
||||||
selectedOption.value || selectedOption.label,
|
const variantValues = this.getVariantAttributeValues(otherAttr, variant.values);
|
||||||
);
|
if (!selectedValues.every((value) => variantValues.includes(value))) {
|
||||||
const vAttrValue = this.getDefaultVariantAttributeValue(otherAttr, variant.values);
|
return false;
|
||||||
if (!vAttrValue || this.normalizeText(vAttrValue) !== selectedNormalized) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
availability[attribute.id][option.id] = isAvailable;
|
availability[attribute.codigo][option.id] = isAvailable;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +100,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const attributes = this.attributes();
|
const attributes = this.visibleAttributes();
|
||||||
const defaultVariant = this.selectedVariant();
|
const defaultVariant = this.selectedVariant();
|
||||||
|
|
||||||
untracked(() => {
|
untracked(() => {
|
||||||
@@ -97,7 +111,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
effect(() => {
|
effect(() => {
|
||||||
const selections = this.selectedAttributeOptions();
|
const selections = this.selectedAttributeOptions();
|
||||||
const variants = this.variants();
|
const variants = this.variants();
|
||||||
const attributes = this.attributes();
|
const attributes = this.visibleAttributes();
|
||||||
|
|
||||||
untracked(() => {
|
untracked(() => {
|
||||||
this.emitMatchingVariant(selections, variants, attributes);
|
this.emitMatchingVariant(selections, variants, attributes);
|
||||||
@@ -109,17 +123,28 @@ export class ProductAttributeSelectorComponent {
|
|||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
option: ProductAttributeOption,
|
option: ProductAttributeOption,
|
||||||
): boolean {
|
): boolean {
|
||||||
return this.selectedAttributeOptions()[attribute.id] === option.id;
|
return (this.selectedAttributeOptions()[attribute.codigo] ?? []).includes(option.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected selectAttributeOption(
|
protected selectAttributeOption(
|
||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
option: ProductAttributeOption,
|
option: ProductAttributeOption,
|
||||||
): void {
|
): void {
|
||||||
this.selectedAttributeOptions.update((current) => ({
|
this.selectedAttributeOptions.update((current) => {
|
||||||
...current,
|
const selected = current[attribute.codigo] ?? [];
|
||||||
[attribute.id]: option.id,
|
const isMultiple = attribute.allow_multi_select ?? false;
|
||||||
}));
|
let next: number[];
|
||||||
|
|
||||||
|
if (!isMultiple) {
|
||||||
|
next = [option.id];
|
||||||
|
} else if (selected.includes(option.id)) {
|
||||||
|
next = selected.filter((id) => id !== option.id);
|
||||||
|
} else {
|
||||||
|
next = [...selected, option.id];
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...current, [attribute.codigo]: next };
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected isColorOption(option: ProductAttributeOption): boolean {
|
protected isColorOption(option: ProductAttributeOption): boolean {
|
||||||
@@ -134,51 +159,44 @@ export class ProductAttributeSelectorComponent {
|
|||||||
attributes: ProductAttribute[],
|
attributes: ProductAttribute[],
|
||||||
defaultVariant: CatalogItemVariant | null,
|
defaultVariant: CatalogItemVariant | null,
|
||||||
): void {
|
): void {
|
||||||
const selections: Record<number, number> = {};
|
const selections: Record<string, number[]> = {};
|
||||||
|
|
||||||
for (const attribute of attributes) {
|
for (const attribute of attributes) {
|
||||||
const optionId = this.findDefaultOptionId(attribute, defaultVariant);
|
const optionIds = this.findDefaultOptionIds(attribute, defaultVariant);
|
||||||
if (optionId !== null) {
|
if (optionIds.length > 0) {
|
||||||
selections[attribute.id] = optionId;
|
selections[attribute.codigo] = optionIds;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.selectedAttributeOptions.set(selections);
|
this.selectedAttributeOptions.set(selections);
|
||||||
}
|
}
|
||||||
|
|
||||||
private findDefaultOptionId(
|
private findDefaultOptionIds(
|
||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
variant: CatalogItemVariant | null,
|
variant: CatalogItemVariant | null,
|
||||||
): number | null {
|
): number[] {
|
||||||
if (!variant) {
|
if (!variant) {
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultValue = this.getDefaultVariantAttributeValue(attribute, variant.values);
|
const defaultValues = this.getVariantAttributeValues(attribute, variant.values);
|
||||||
if (!defaultValue) {
|
if (defaultValues.length === 0) {
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedValue = this.normalizeText(defaultValue);
|
return attribute.options
|
||||||
const matchByValue = attribute.options.find(
|
.filter(
|
||||||
(option) => this.normalizeText(option.value) === normalizedValue,
|
(option) =>
|
||||||
);
|
defaultValues.includes(this.normalizeText(option.value)) ||
|
||||||
|
defaultValues.includes(this.normalizeText(option.label)),
|
||||||
if (matchByValue) {
|
)
|
||||||
return matchByValue.id;
|
.map((option) => option.id);
|
||||||
}
|
|
||||||
|
|
||||||
const matchByLabel = attribute.options.find(
|
|
||||||
(option) => this.normalizeText(option.label) === normalizedValue,
|
|
||||||
);
|
|
||||||
|
|
||||||
return matchByLabel?.id ?? null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private getDefaultVariantAttributeValue(
|
private getVariantAttributeValues(
|
||||||
attribute: ProductAttribute,
|
attribute: ProductAttribute,
|
||||||
variantAttributes: Record<string, string>,
|
variantAttributes: CatalogItemVariant['values'],
|
||||||
): string | null {
|
): string[] {
|
||||||
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
const normalizedCodigo = this.normalizeText(attribute.codigo);
|
||||||
const normalizedNombre = this.normalizeText(attribute.nombre);
|
const normalizedNombre = this.normalizeText(attribute.nombre);
|
||||||
|
|
||||||
@@ -186,11 +204,13 @@ export class ProductAttributeSelectorComponent {
|
|||||||
const normalizedKey = this.normalizeText(key);
|
const normalizedKey = this.normalizeText(key);
|
||||||
|
|
||||||
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
if (normalizedKey === normalizedCodigo || normalizedKey === normalizedNombre) {
|
||||||
return value;
|
return (Array.isArray(value) ? value : [value]).map((item) =>
|
||||||
|
this.normalizeText(typeof item === 'string' ? item : item.value || item.label),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeText(value: string | null | undefined): string {
|
private normalizeText(value: string | null | undefined): string {
|
||||||
@@ -202,7 +222,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
private isVariantAvailable(variant: CatalogItemVariant): boolean {
|
||||||
return this.inventoryPolicy() === 'unlimited' || (variant.stock_tecnico ?? 0) > 0;
|
return variant.maximum_addable_quantity !== 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private findFirstHexValue(value: unknown): string | null {
|
private findFirstHexValue(value: unknown): string | null {
|
||||||
@@ -234,7 +254,7 @@ export class ProductAttributeSelectorComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private emitMatchingVariant(
|
private emitMatchingVariant(
|
||||||
selections: Record<number, number>,
|
selections: Record<string, number[]>,
|
||||||
variants: CatalogItemVariant[],
|
variants: CatalogItemVariant[],
|
||||||
attributes: ProductAttribute[],
|
attributes: ProductAttribute[],
|
||||||
): void {
|
): void {
|
||||||
@@ -243,18 +263,22 @@ export class ProductAttributeSelectorComponent {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedValuesById: Record<number, string> = {};
|
const selectedValuesByCode: Record<string, string[]> = {};
|
||||||
let allSelected = true;
|
let allSelected = true;
|
||||||
for (const attr of attributes) {
|
for (const attr of attributes) {
|
||||||
const selectedOptionId = selections[attr.id];
|
const selectedOptionIds = selections[attr.codigo] ?? [];
|
||||||
if (selectedOptionId === undefined) {
|
if (
|
||||||
|
selectedOptionIds.length === 0 ||
|
||||||
|
(!attr.allow_multi_select && selectedOptionIds.length !== 1)
|
||||||
|
) {
|
||||||
allSelected = false;
|
allSelected = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const option = attr.options.find((o) => o.id === selectedOptionId);
|
selectedValuesByCode[attr.codigo] = selectedOptionIds
|
||||||
if (option) {
|
.map((id) => attr.options.find((option) => option.id === id))
|
||||||
selectedValuesById[attr.id] = this.normalizeText(option.value || option.label);
|
.filter((option): option is ProductAttributeOption => option !== undefined)
|
||||||
}
|
.map((option) => this.normalizeText(option.value || option.label))
|
||||||
|
.sort();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!allSelected) {
|
if (!allSelected) {
|
||||||
@@ -264,10 +288,12 @@ export class ProductAttributeSelectorComponent {
|
|||||||
|
|
||||||
const matchingVariant = variants.find((variant) => {
|
const matchingVariant = variants.find((variant) => {
|
||||||
return attributes.every((attr) => {
|
return attributes.every((attr) => {
|
||||||
const selectedValue = selectedValuesById[attr.id];
|
const selectedValues = selectedValuesByCode[attr.codigo];
|
||||||
const variantValue = this.getDefaultVariantAttributeValue(attr, variant.values);
|
const variantValues = this.getVariantAttributeValues(attr, variant.values).sort();
|
||||||
if (!variantValue) return false;
|
return (
|
||||||
return this.normalizeText(variantValue) === selectedValue;
|
selectedValues.length === variantValues.length &&
|
||||||
|
selectedValues.every((value, index) => value === variantValues[index])
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@
|
|||||||
<!-- Thumbnails Row -->
|
<!-- Thumbnails Row -->
|
||||||
@if (images().length > 1) {
|
@if (images().length > 1) {
|
||||||
<div class="product-carousel__thumbnails">
|
<div class="product-carousel__thumbnails">
|
||||||
@for (image of images(); track image; let idx = $index) {
|
@for (image of images(); track $index; let idx = $index) {
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
class="product-carousel__thumbnail border-0 p-0 overflow-hidden bg-light"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
:host {
|
:host {
|
||||||
display: block;
|
display: block;
|
||||||
border-bottom: 1px solid #dddddd;
|
border-bottom: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
:host(:last-child) {
|
:host(:last-child) {
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
aspect-ratio: 4 / 3;
|
aspect-ratio: 4 / 3;
|
||||||
border-radius: 5px 0 0 5px;
|
border-radius: 5px 0 0 5px;
|
||||||
background-color: #ffffff;
|
background-color: #ffffff;
|
||||||
border: 1px solid #eaeaea;
|
border: 1px solid var(--border-color);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
|
||||||
img {
|
img {
|
||||||
|
|||||||
@@ -1,11 +1,29 @@
|
|||||||
<div class="purchase-item" [routerLink]="[purchase.id]" style="cursor: pointer;">
|
<div class="purchase-item" [routerLink]="[purchase.id]">
|
||||||
<div class="purchase-info">
|
<div class="purchase-info">
|
||||||
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
<span class="purchase-id">Compra {{ purchase.id }}.</span>
|
||||||
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
<span class="purchase-date">Fecha de compra: {{ purchase.date }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="purchase-action">
|
|
||||||
<svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow-icon">
|
@if (purchase.statusMessage) {
|
||||||
<path d="M1 1L7 7L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
<span class="purchase-status">{{ purchase.statusMessage }}</span>
|
||||||
</svg>
|
}
|
||||||
</div>
|
|
||||||
</div>
|
<div class="purchase-action">
|
||||||
|
<svg
|
||||||
|
width="8"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 8 14"
|
||||||
|
fill="none"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
class="arrow-icon"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M1 1L7 7L1 13"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|||||||
@@ -2,33 +2,57 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 16px;
|
gap: 16px;
|
||||||
padding-left:0;
|
padding: 16px;
|
||||||
transition: box-shadow 0.2s, border-radius 0.2s;
|
padding-left: 0;
|
||||||
|
transition:
|
||||||
|
box-shadow 0.2s,
|
||||||
|
border-radius 0.2s;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-item:hover {
|
.purchase-item:hover {
|
||||||
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
|
box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.07);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-item:hover .arrow-icon {
|
.purchase-item:hover .arrow-icon {
|
||||||
color: #5b75ff; /* Blue on hover */
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-info {
|
.purchase-info {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-id {
|
.purchase-id {
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.purchase-date {
|
.purchase-date {
|
||||||
font-weight: 325;
|
font-weight: 325;
|
||||||
color: #666666;
|
color: #666666;
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-status {
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 20px;
|
||||||
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-action {
|
||||||
|
display: flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
.arrow-icon {
|
.arrow-icon {
|
||||||
width: 8px;
|
width: 8px;
|
||||||
height: 14px;
|
height: 14px;
|
||||||
|
|||||||
@@ -9,6 +9,5 @@ import { RouterLink } from '@angular/router';
|
|||||||
styleUrl: './purchase-list-item.scss',
|
styleUrl: './purchase-list-item.scss',
|
||||||
})
|
})
|
||||||
export class PurchaseListItem {
|
export class PurchaseListItem {
|
||||||
@Input() purchase!: { id: number; date: string };
|
@Input() purchase!: { id: number; date: string; statusMessage?: string | null };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,29 +1,36 @@
|
|||||||
<div class="purchase-list-container">
|
<div class="purchase-list-container">
|
||||||
<ng-container *ngIf="isLoading(); else contentTpl">
|
@if (isLoading()) {
|
||||||
<!-- Skeleton -->
|
@for (i of [1, 2, 3, 4]; track i) {
|
||||||
<div class="skeleton-item" *ngFor="let i of [1, 2, 3, 4]">
|
<div class="skeleton-item">
|
||||||
<div class="skeleton-info">
|
<div class="skeleton-info">
|
||||||
<div class="skeleton-id"></div>
|
<div class="skeleton-id"></div>
|
||||||
<div class="skeleton-date"></div>
|
<div class="skeleton-date"></div>
|
||||||
</div>
|
|
||||||
<div class="skeleton-action"></div>
|
|
||||||
</div>
|
</div>
|
||||||
</ng-container>
|
<div class="skeleton-action"></div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
@if (purchases().length > 0) {
|
||||||
|
@for (purchase of purchases(); track purchase.id; let last = $last) {
|
||||||
|
<app-purchase-list-item [purchase]="purchase"></app-purchase-list-item>
|
||||||
|
@if (!last) {
|
||||||
|
<div class="purchase-divider"></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<div class="empty-state">Aún no hay compras realizadas</div>
|
||||||
|
}
|
||||||
|
|
||||||
<ng-template #contentTpl>
|
@if (pagination(); as paginationData) {
|
||||||
<ng-container *ngIf="purchases().length > 0; else emptyTpl">
|
@if (paginationData.last_page > 1) {
|
||||||
<ng-container *ngFor="let purchase of purchases(); let last = last">
|
<app-paginator
|
||||||
<app-purchase-list-item
|
class="purchase-list__paginator"
|
||||||
[purchase]="purchase">
|
[page]="paginationData.current_page"
|
||||||
</app-purchase-list-item>
|
[totalPages]="paginationData.last_page"
|
||||||
<div class="purchase-divider" *ngIf="!last"></div>
|
[disabled]="isLoading()"
|
||||||
</ng-container>
|
(pageChange)="onPageChange($event)"
|
||||||
</ng-container>
|
></app-paginator>
|
||||||
</ng-template>
|
}
|
||||||
|
}
|
||||||
<ng-template #emptyTpl>
|
}
|
||||||
<div class="empty-state">
|
</div>
|
||||||
Aún no hay compras realizadas
|
|
||||||
</div>
|
|
||||||
</ng-template>
|
|
||||||
</div>
|
|
||||||
|
|||||||
@@ -4,9 +4,14 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-list__paginator {
|
||||||
|
align-self: center;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
.purchase-divider {
|
.purchase-divider {
|
||||||
height: 1px;
|
height: 1px;
|
||||||
background-color: #DDDDDD;
|
background-color: #dddddd;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +28,7 @@
|
|||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 1rem 0;
|
padding: 1rem 0;
|
||||||
border-bottom: 1px solid #DDDDDD;
|
border-bottom: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.skeleton-item:last-child {
|
.skeleton-item:last-child {
|
||||||
@@ -39,7 +44,7 @@
|
|||||||
.skeleton-id {
|
.skeleton-id {
|
||||||
width: 100px;
|
width: 100px;
|
||||||
height: 1rem;
|
height: 1rem;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
@@ -47,7 +52,7 @@
|
|||||||
.skeleton-date {
|
.skeleton-date {
|
||||||
width: 150px;
|
width: 150px;
|
||||||
height: 0.8rem;
|
height: 0.8rem;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
@@ -55,19 +60,19 @@
|
|||||||
.skeleton-action {
|
.skeleton-action {
|
||||||
width: 24px;
|
width: 24px;
|
||||||
height: 24px;
|
height: 24px;
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
animation: pulse 1.5s infinite ease-in-out;
|
animation: pulse 1.5s infinite ease-in-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes pulse {
|
@keyframes pulse {
|
||||||
0% {
|
0% {
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
}
|
}
|
||||||
50% {
|
50% {
|
||||||
background-color: #E0E0E0;
|
background-color: #e0e0e0;
|
||||||
}
|
}
|
||||||
100% {
|
100% {
|
||||||
background-color: #EEEEEE;
|
background-color: #eeeeee;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,24 @@
|
|||||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
|
||||||
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
|
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
|
||||||
import { CheckoutService, PurchaseSummaryResponse } from '../../../../../../core/services/checkout.service';
|
import {
|
||||||
|
CheckoutService,
|
||||||
|
PurchaseSummaryResponse,
|
||||||
|
} from '../../../../../../core/services/checkout.service';
|
||||||
import { ToastService } from '../../../../../../core/services/toast.service';
|
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||||
import { TenantService } from '../../../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||||
|
import { ApiPaginationMeta } from '../../../../../../core/services/api-paginated-response.interface';
|
||||||
|
import { PaginatorComponent } from '../../../../../../shared/components/paginator/paginator.component';
|
||||||
|
|
||||||
type PurchaseListViewModel = {
|
type PurchaseListViewModel = {
|
||||||
id: number;
|
id: number;
|
||||||
date: string;
|
date: string;
|
||||||
|
statusMessage: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-list',
|
selector: 'app-purchase-list',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, PurchaseListItem],
|
imports: [PurchaseListItem, PaginatorComponent],
|
||||||
templateUrl: './purchase-list.html',
|
templateUrl: './purchase-list.html',
|
||||||
styleUrl: './purchase-list.scss',
|
styleUrl: './purchase-list.scss',
|
||||||
})
|
})
|
||||||
@@ -22,21 +27,28 @@ export class PurchaseList implements OnInit {
|
|||||||
private readonly toastService = inject(ToastService);
|
private readonly toastService = inject(ToastService);
|
||||||
private readonly tenantService = inject(TenantService);
|
private readonly tenantService = inject(TenantService);
|
||||||
|
|
||||||
purchases = signal<PurchaseListViewModel[]>([]);
|
protected readonly purchases = signal<PurchaseListViewModel[]>([]);
|
||||||
isLoading = signal<boolean>(true);
|
protected readonly pagination = signal<ApiPaginationMeta | null>(null);
|
||||||
|
protected readonly isLoading = signal(true);
|
||||||
|
|
||||||
async ngOnInit(): Promise<void> {
|
async ngOnInit(): Promise<void> {
|
||||||
|
await this.loadPurchases();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async onPageChange(page: number): Promise<void> {
|
||||||
|
await this.loadPurchases(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadPurchases(page = 1): Promise<void> {
|
||||||
|
this.isLoading.set(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const tenantCode = this.tenantService.tenant()?.codigo || '';
|
|
||||||
|
|
||||||
const response = await this.checkoutService
|
const response = await this.checkoutService
|
||||||
.withCustomLoading()
|
.withCustomLoading()
|
||||||
.getPurchases(tenantCode, 'paid');
|
.getPurchases(this.tenantCode(), 'paid,in_review', { page });
|
||||||
const mappedPurchases = response.data.map((purchase: PurchaseSummaryResponse) => ({
|
|
||||||
id: purchase.id,
|
this.purchases.set(this.mapPurchases(response.data));
|
||||||
date: this.formatDate(purchase.created_at),
|
this.pagination.set(response.meta);
|
||||||
}));
|
|
||||||
this.purchases.set(mappedPurchases);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.toastService.danger('Hubo un error al cargar las compras');
|
this.toastService.danger('Hubo un error al cargar las compras');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -44,6 +56,18 @@ export class PurchaseList implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private tenantCode(): string {
|
||||||
|
return this.tenantService.tenant()?.codigo || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private mapPurchases(purchases: PurchaseSummaryResponse[]): PurchaseListViewModel[] {
|
||||||
|
return purchases.map((purchase) => ({
|
||||||
|
id: purchase.id,
|
||||||
|
date: this.formatDate(purchase.created_at),
|
||||||
|
statusMessage: purchase.status === 'in_review' ? 'Esperando confirmación' : null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
private formatDate(value: string | null): string {
|
private formatDate(value: string | null): string {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return '-';
|
return '-';
|
||||||
|
|||||||
@@ -15,6 +15,27 @@
|
|||||||
@if (isLoading()) {
|
@if (isLoading()) {
|
||||||
<p class="purchase-loading">Cargando detalle de compra...</p>
|
<p class="purchase-loading">Cargando detalle de compra...</p>
|
||||||
} @else if (purchase(); as purchase) {
|
} @else if (purchase(); as purchase) {
|
||||||
|
@if (purchase.isInReview) {
|
||||||
|
<section class="purchase-review" aria-labelledby="purchase-review-title">
|
||||||
|
<h3 id="purchase-review-title" class="purchase-review__title">ESPERANDO CONFIRMACIÓN</h3>
|
||||||
|
<p class="purchase-review__message">
|
||||||
|
Tu compra aún no ha sido confirmada.<br />
|
||||||
|
Si no te contactaste con nosotros, podés hacerlo a través del siguiente WhatsApp
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@if (whatsappUrl()) {
|
||||||
|
<app-button
|
||||||
|
type="button"
|
||||||
|
variant="primary"
|
||||||
|
hostClass="purchase-review__button"
|
||||||
|
(click)="openWhatsApp()"
|
||||||
|
>
|
||||||
|
WhatsApp
|
||||||
|
</app-button>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="d-flex justify-content-between align-items-center mb-4 pb-3"
|
class="d-flex justify-content-between align-items-center mb-4 pb-3"
|
||||||
style="border-bottom: 1px solid #dddddd"
|
style="border-bottom: 1px solid #dddddd"
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.account-page {
|
.account-page {
|
||||||
|
--menu-content-prefix-gap: 0;
|
||||||
|
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 600px;
|
max-width: 600px;
|
||||||
@@ -50,6 +52,32 @@
|
|||||||
font-size: 17px;
|
font-size: 17px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.purchase-review {
|
||||||
|
padding-bottom: 2rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
border-bottom: 1px solid #dddddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__title {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__message {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: #777777;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.purchase-review__button {
|
||||||
|
width: 185px;
|
||||||
|
}
|
||||||
|
|
||||||
.purchase-loading,
|
.purchase-loading,
|
||||||
.purchase-empty {
|
.purchase-empty {
|
||||||
color: #666666;
|
color: #666666;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { CommonModule } from '@angular/common';
|
import { Component, OnInit, computed, inject, signal } from '@angular/core';
|
||||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
|
||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -8,6 +7,7 @@ import {
|
|||||||
} from '../../../../../../core/services/checkout.service';
|
} from '../../../../../../core/services/checkout.service';
|
||||||
import { TenantService } from '../../../../../../core/services/tenant.service';
|
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||||
import { ToastService } from '../../../../../../core/services/toast.service';
|
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||||
|
import { ButtonComponent } from '../../../../../../shared/components/button/button.component';
|
||||||
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
|
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
|
||||||
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
|
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';
|
||||||
|
|
||||||
@@ -16,12 +16,13 @@ type PurchaseDetailViewModel = {
|
|||||||
date: string;
|
date: string;
|
||||||
total: string;
|
total: string;
|
||||||
items: PurchaseItemViewModel[];
|
items: PurchaseItemViewModel[];
|
||||||
|
isInReview: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-purchase-detail-page',
|
selector: 'app-purchase-detail-page',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, RouterLink, PurchaseItem, MenuContentSectionComponent],
|
imports: [RouterLink, PurchaseItem, MenuContentSectionComponent, ButtonComponent],
|
||||||
templateUrl: './purchase-detail-page.html',
|
templateUrl: './purchase-detail-page.html',
|
||||||
styleUrl: './purchase-detail-page.scss',
|
styleUrl: './purchase-detail-page.scss',
|
||||||
})
|
})
|
||||||
@@ -34,6 +35,12 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
|
|
||||||
readonly isLoading = signal(true);
|
readonly isLoading = signal(true);
|
||||||
readonly purchase = signal<PurchaseDetailViewModel | null>(null);
|
readonly purchase = signal<PurchaseDetailViewModel | null>(null);
|
||||||
|
protected readonly whatsappUrl = computed(
|
||||||
|
() =>
|
||||||
|
this.tenantService
|
||||||
|
.tenant()
|
||||||
|
?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? null,
|
||||||
|
);
|
||||||
|
|
||||||
async ngOnInit(): Promise<void> {
|
async ngOnInit(): Promise<void> {
|
||||||
const purchaseId = this.route.snapshot.paramMap.get('id');
|
const purchaseId = this.route.snapshot.paramMap.get('id');
|
||||||
@@ -54,6 +61,7 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
date: this.formatDate(response.created_at),
|
date: this.formatDate(response.created_at),
|
||||||
total: response.total,
|
total: response.total,
|
||||||
items: this.mapItems(response),
|
items: this.mapItems(response),
|
||||||
|
isInReview: response.status === 'in_review',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to fetch purchase detail:', error);
|
console.error('Failed to fetch purchase detail:', error);
|
||||||
@@ -64,6 +72,14 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected openWhatsApp(): void {
|
||||||
|
const url = this.whatsappUrl();
|
||||||
|
|
||||||
|
if (url) {
|
||||||
|
window.open(url, '_blank', 'noopener,noreferrer');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private formatDate(value: string | null): string {
|
private formatDate(value: string | null): string {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
return '-';
|
return '-';
|
||||||
@@ -87,7 +103,7 @@ export class PurchaseDetailPage implements OnInit {
|
|||||||
id: item.id,
|
id: item.id,
|
||||||
title: item.item_details.nombre || 'Producto sin nombre',
|
title: item.item_details.nombre || 'Producto sin nombre',
|
||||||
description: item.item_details.descripcion,
|
description: item.item_details.descripcion,
|
||||||
imageUrl: item.item_details.imagen,
|
imageUrl: item.item_details.imagen ?? null,
|
||||||
quantity: item.quantity,
|
quantity: item.quantity,
|
||||||
attributes: item.item_details.attributes.map((attribute) => ({
|
attributes: item.item_details.attributes.map((attribute) => ({
|
||||||
label: attribute.name,
|
label: attribute.name,
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<a class="ticket-event row flex-nowrap align-items-center gx-3 mx-0" [routerLink]="[event().id]">
|
||||||
|
<span class="col-4 col-sm-3">
|
||||||
|
<span class="ticket-event__image-wrapper">
|
||||||
|
@if (event().image; as image) {
|
||||||
|
<img class="ticket-event__image" [src]="image" alt="" />
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span class="ticket-event__title col">{{ event().title }}</span>
|
||||||
|
|
||||||
|
<span class="col-auto">
|
||||||
|
<svg
|
||||||
|
class="ticket-event__arrow"
|
||||||
|
width="8"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 8 14"
|
||||||
|
fill="none"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d="M1 1L7 7L1 13"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event {
|
||||||
|
min-height: 84px;
|
||||||
|
padding: 12px 8px;
|
||||||
|
color: #666666;
|
||||||
|
text-decoration: none;
|
||||||
|
transition:
|
||||||
|
box-shadow 0.2s,
|
||||||
|
border-radius 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event:hover,
|
||||||
|
.ticket-event:focus-visible {
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 0 30px rgba(0, 0, 0, 0.07);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event:focus-visible {
|
||||||
|
outline: 2px solid var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event__image-wrapper {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
aspect-ratio: 19 / 13;
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 3px;
|
||||||
|
background: #dddddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event__image {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event__title {
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.3;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event__arrow {
|
||||||
|
color: #888888;
|
||||||
|
transition: color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-event:hover .ticket-event__arrow,
|
||||||
|
.ticket-event:focus-visible .ticket-event__arrow {
|
||||||
|
color: var(--color-primary, var(--tenant-primary, #5b75ff));
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
import { RouterLink } from '@angular/router';
|
||||||
|
|
||||||
|
import { TicketEventResponse } from '../../../tickets-page/ticket.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-ticket-event-list-item',
|
||||||
|
imports: [RouterLink],
|
||||||
|
templateUrl: './ticket-event-list-item.html',
|
||||||
|
styleUrl: './ticket-event-list-item.scss',
|
||||||
|
})
|
||||||
|
export class TicketEventListItem {
|
||||||
|
readonly event = input.required<TicketEventResponse>();
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<app-menu-content-section
|
||||||
|
class="ticket-events-page"
|
||||||
|
menuCode="account.tickets"
|
||||||
|
titleId="ticket-events-page-title"
|
||||||
|
>
|
||||||
|
<div class="ticket-events-list" [attr.aria-busy]="isLoading()">
|
||||||
|
@if (isLoading()) {
|
||||||
|
@for (item of [1, 2, 3, 4]; track item) {
|
||||||
|
<div
|
||||||
|
class="ticket-events-list__skeleton row flex-nowrap align-items-center gx-3 mx-0"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<span class="col-4 col-sm-3">
|
||||||
|
<span class="ticket-events-list__skeleton-image"></span>
|
||||||
|
</span>
|
||||||
|
<span class="col">
|
||||||
|
<span class="ticket-events-list__skeleton-title"></span>
|
||||||
|
</span>
|
||||||
|
<span class="col-auto">
|
||||||
|
<span class="ticket-events-list__skeleton-arrow"></span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
} @else if (events().length) {
|
||||||
|
@for (event of events(); track event.id; let last = $last) {
|
||||||
|
<app-ticket-event-list-item [event]="event" />
|
||||||
|
@if (!last) {
|
||||||
|
<div class="ticket-events-list__divider"></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<p class="ticket-events-list__empty">Aún no tenés eventos con tickets.</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</app-menu-content-section>
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-page {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__divider {
|
||||||
|
width: 100%;
|
||||||
|
height: 1px;
|
||||||
|
background: var(--border-color, #dddddd);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__empty {
|
||||||
|
margin: 0;
|
||||||
|
padding: 2rem 0;
|
||||||
|
color: #666666;
|
||||||
|
font-size: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__skeleton {
|
||||||
|
min-height: 84px;
|
||||||
|
padding: 12px 8px;
|
||||||
|
border-bottom: 1px solid var(--border-color, #dddddd);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__skeleton-image,
|
||||||
|
.ticket-events-list__skeleton-title,
|
||||||
|
.ticket-events-list__skeleton-arrow {
|
||||||
|
display: block;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: #eeeeee;
|
||||||
|
animation: ticket-events-pulse 1.5s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__skeleton-image {
|
||||||
|
width: 100%;
|
||||||
|
aspect-ratio: 19 / 13;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__skeleton-title {
|
||||||
|
width: min(250px, 80%);
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ticket-events-list__skeleton-arrow {
|
||||||
|
width: 8px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes ticket-events-pulse {
|
||||||
|
50% {
|
||||||
|
background-color: #e0e0e0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { signal } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { TenantService } from '../../../../../../core/services/tenant.service';
|
||||||
|
import { ToastService } from '../../../../../../core/services/toast.service';
|
||||||
|
import { TicketService } from '../tickets-page/ticket.service';
|
||||||
|
import { TicketEventsPage } from './ticket-events-page';
|
||||||
|
|
||||||
|
function withCustomLoading<T extends object>(service: T): T & { withCustomLoading: () => T } {
|
||||||
|
return Object.assign(service, { withCustomLoading: () => service });
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('TicketEventsPage', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
provideRouter([]),
|
||||||
|
{
|
||||||
|
provide: TenantService,
|
||||||
|
useValue: {
|
||||||
|
tenant: signal({
|
||||||
|
menues: [
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
code: 'account.tickets',
|
||||||
|
label: 'Tickets',
|
||||||
|
parent_menu_code: 'account',
|
||||||
|
content_type: 'dynamic',
|
||||||
|
route: '/mi-cuenta/tickets',
|
||||||
|
submenues: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).asReadonly(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ provide: ToastService, useValue: { danger: vi.fn() } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the users events with image, title and detail link', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [TicketEventsPage] })
|
||||||
|
.overrideComponent(TicketEventsPage, {
|
||||||
|
set: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: TicketService,
|
||||||
|
useValue: withCustomLoading({
|
||||||
|
getTicketEvents: () =>
|
||||||
|
Promise.resolve([
|
||||||
|
{ id: 27, title: 'Copa del mundo', image: 'https://example.com/event.jpg' },
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(TicketEventsPage);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
const page = fixture.nativeElement as HTMLElement;
|
||||||
|
const link = page.querySelector<HTMLAnchorElement>('.ticket-event');
|
||||||
|
|
||||||
|
expect(page.textContent).toContain('TICKETS');
|
||||||
|
expect(page.textContent).toContain('Copa del mundo');
|
||||||
|
expect(link?.getAttribute('href')).toBe('/27');
|
||||||
|
expect(link?.querySelector('img')?.getAttribute('src')).toBe('https://example.com/event.jpg');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the empty state when the user has no ticket events', async () => {
|
||||||
|
await TestBed.configureTestingModule({ imports: [TicketEventsPage] })
|
||||||
|
.overrideComponent(TicketEventsPage, {
|
||||||
|
set: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: TicketService,
|
||||||
|
useValue: withCustomLoading({ getTicketEvents: () => Promise.resolve([]) }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.compileComponents();
|
||||||
|
|
||||||
|
const fixture = TestBed.createComponent(TicketEventsPage);
|
||||||
|
fixture.detectChanges();
|
||||||
|
await fixture.whenStable();
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
expect((fixture.nativeElement as HTMLElement).textContent).toContain(
|
||||||
|
'Aún no tenés eventos con tickets.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user