Compare commits

...

19 Commits

Author SHA1 Message Date
Thanh Quy - wolf 342e1b43aa refactor: remove name field from CreateShift and update ShiftEntity to allow nullable name 2026-05-14 12:21:56 +07:00
Thanh Quy - wolf 997fb313ae Merge branch 'main' of https://git.demonkernel.io.vn/FoodSurf/backend into quy-connect-frontend
Quy pull main 13/5
2026-05-13 21:16:26 +07:00
gitea-actions eef3fb773b chore: release [ci skip] 2026-05-13 09:48:14 +00:00
TakahashiNguyen 5d0a047602 fix: better cart response (#57)
Release package / release (push) Successful in 24m23s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #57
2026-05-13 09:24:19 +00:00
gitea-actions 8b2d3e7bef chore: release [ci skip] 2026-05-13 07:50:55 +00:00
Thanhquy-wolf cc33840409 Merge branch 'main' of https://git.demonkernel.io.vn/FoodSurf/backend into quy-connect-frontend
Quy pull main 13/5 lan 2
2026-05-13 07:36:48 +00:00
TakahashiNguyen e72ccf4e96 fix: trigger release version (#56)
Release package / release (push) Successful in 26m35s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #56
2026-05-13 07:24:52 +00:00
Thanh Quy - wolf 0a3f6500e2 Merge branch 'main' of https://git.demonkernel.io.vn/FoodSurf/backend into quy-connect-frontend
Quy pull main
2026-05-13 14:18:47 +07:00
gitea-actions 8487a8ff19 chore: release [ci skip] 2026-05-13 04:57:08 +00:00
TakahashiNguyen dc5bc731b3 fix: add menu item fields (#55)
Release package / release (push) Failing after 1m57s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #55
2026-05-13 04:41:05 +00:00
Thanh Quy - wolf a0984da351 Merge branch 'main' of https://git.demonkernel.io.vn/FoodSurf/backend into quy-connect-frontend
Pull main tracking dev quy
2026-05-13 10:42:57 +07:00
TakahashiNguyen d45ed26a07 fix: better graphql response (#54)
Release package / release (push) Failing after 25m5s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #54
2026-05-13 03:24:18 +00:00
gitea-actions 4a0e0e935c chore: release [ci skip] 2026-05-12 15:20:49 +00:00
TakahashiNguyen 43734b51aa fix: resolved minor issue (#53)
Release package / release (push) Successful in 19m13s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #53
2026-05-12 15:01:58 +00:00
gitea-actions 6777581022 chore: release [ci skip] 2026-05-12 05:51:30 +00:00
TakahashiNguyen 88244cb56f fix: add payment features (#52)
Release package / release (push) Successful in 30m1s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #52
2026-05-12 05:22:08 +00:00
gitea-actions 6032a7c31b chore: release [ci skip] 2026-05-12 02:40:32 +00:00
TakahashiNguyen 345d4c056c fix: add shift features (#51)
Release package / release (push) Successful in 26m36s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #51
2026-05-12 02:14:21 +00:00
Thanh Quy - wolf 483ba3dee0 feat: add Docker and PostgreSQL health check script 2026-04-18 19:02:22 +07:00
46 changed files with 1120 additions and 92 deletions
+34 -9
View File
@@ -15,13 +15,41 @@ permissions:
checks: write
jobs:
build-and-test:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Install dependencies with Proxy
env:
http_proxy: "http://host.docker.internal:3142"
https_proxy: "http://host.docker.internal:3142"
run: |
# Kiểm tra proxy có hoạt động không
echo "Acquire::http::Proxy \"$http_proxy\";" > /etc/apt/apt.conf.d/80proxy
apt-get update
apt-get install -y --no-install-recommends --no-install-suggests \
openjdk-25-jdk-headless docker-cli docker-buildx zstd maven
- name: Cache Maven packages
uses: actions/cache@v4
with:
fetch-depth: 0
path: |
~/.m2/repository
**/target/native-image-cache
**/target/reports
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-maven-
- name: Build native with Maven
run: |
mvn -B clean install -DskipTests -Pnative \
-Dquarkus.container-image.push=false
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Install dependencies with Proxy
env:
@@ -46,16 +74,13 @@ jobs:
**/target/native-image-cache
**/target/reports
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
restore-keys: ${{ runner.os }}-maven-
- name: Build and Test all module
- name: Run Tests
env:
TESTCONTAINERS_RYUK_DISABLED: true
run: |
mvn -B clean install -Pnative \
-Dquarkus.container-image.push=false \
-Dquarkus.container-image.registry=git.demonkernel.io.vn
mvn clean test -Dquarkus.main.run-tests=true
- name: Publish Test Report
uses: dorny/test-reporter@v3
+1 -1
View File
@@ -13,7 +13,7 @@ plugins:
mvn versions:set -DnewVersion=${nextRelease.version} &&
sed -i "/image:.*-service:/ s|:[^:]*$|:${nextRelease.version}|" k8s/base/*.yaml &&
if [ "${branch.name}" = "main" ]; then
mvn package -B -Pnative -Dquarkus.container-image.tag=${nextRelease.version} -DskipTests
mvn package -B -Pnative -Dquarkus.container-image.tag=${nextRelease.version} -DskipTests -Ppush
fi
- - "@saithodev/semantic-release-gitea"
- giteaUrl: "https://git.demonkernel.io.vn/"
+45
View File
@@ -1,3 +1,48 @@
## [1.5.30](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.29...v1.5.30) (2026-05-13)
### Bug Fixes
* better cart response ([#57](https://git.demonkernel.io.vn/FoodSurf/backend/issues/57)) ([5d0a047](https://git.demonkernel.io.vn/FoodSurf/backend/commit/5d0a0476029cee55f8fbe6ec6e9565ca53ee16bc))
## [1.5.29](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.28...v1.5.29) (2026-05-13)
### Bug Fixes
* add menu item fields ([#55](https://git.demonkernel.io.vn/FoodSurf/backend/issues/55)) ([dc5bc73](https://git.demonkernel.io.vn/FoodSurf/backend/commit/dc5bc731b3345663d2640a500ecfb77e81929ab2))
* better graphql response ([#54](https://git.demonkernel.io.vn/FoodSurf/backend/issues/54)) ([d45ed26](https://git.demonkernel.io.vn/FoodSurf/backend/commit/d45ed26a07ca5af39ea63e82a9e6453e4aedf0c4))
* trigger release version ([#56](https://git.demonkernel.io.vn/FoodSurf/backend/issues/56)) ([e72ccf4](https://git.demonkernel.io.vn/FoodSurf/backend/commit/e72ccf4e960b1623b604c85cbeef54ab8c8d97b3))
## [1.5.30](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.29...v1.5.30) (2026-05-13)
### Bug Fixes
* add menu item fields ([#55](https://git.demonkernel.io.vn/FoodSurf/backend/issues/55)) ([dc5bc73](https://git.demonkernel.io.vn/FoodSurf/backend/commit/dc5bc731b3345663d2640a500ecfb77e81929ab2))
## [1.5.28](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.27...v1.5.28) (2026-05-12)
### Bug Fixes
* resolved minor issue ([#53](https://git.demonkernel.io.vn/FoodSurf/backend/issues/53)) ([43734b5](https://git.demonkernel.io.vn/FoodSurf/backend/commit/43734b51aafad7f823ff5d34322cc6fb6f4e6699))
## [1.5.27](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.26...v1.5.27) (2026-05-12)
### Bug Fixes
* add payment features ([#52](https://git.demonkernel.io.vn/FoodSurf/backend/issues/52)) ([88244cb](https://git.demonkernel.io.vn/FoodSurf/backend/commit/88244cb56f28193cd8cb0da78d5b8d290870284b))
## [1.5.26](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.25...v1.5.26) (2026-05-12)
### Bug Fixes
* add shift features ([#51](https://git.demonkernel.io.vn/FoodSurf/backend/issues/51)) ([345d4c0](https://git.demonkernel.io.vn/FoodSurf/backend/commit/345d4c056ccf6ab5f7c455a17e8a3eedfde3ac62))
* better getCart ([#49](https://git.demonkernel.io.vn/FoodSurf/backend/issues/49)) ([4290f48](https://git.demonkernel.io.vn/FoodSurf/backend/commit/4290f482f4aa74467982cc5aa6293d9d308538d3))
## [1.5.26](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.25...v1.5.26) (2026-05-11)
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -2,7 +2,9 @@ package com.drinkool.entities;
import com.drinkool.Role;
import com.drinkool.models.UserModel;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@@ -10,6 +12,7 @@ import java.util.List;
@Table(name = Role.Manager)
public class ManagerEntity extends UserModel {
@JsonIgnore
@OneToMany(
mappedBy = "serve",
cascade = CascadeType.ALL,
@@ -17,7 +20,23 @@ public class ManagerEntity extends UserModel {
)
public List<StaffEntity> staffs = new ArrayList<>();
@JsonIgnore
@Column(nullable = true)
public String bankAccount;
public ManagerEntity() {
super(Role.Manager);
}
@Transactional
public void signup(
String name,
String phone,
String bankAccount,
String rawPassword
) {
this.bankAccount = bankAccount;
super.signup(name, phone, rawPassword);
}
}
@@ -65,7 +65,6 @@ public class CustomerService extends BaseService<CustomerEntity> {
return Response.accepted()
.header(InternalValue.userId, customer.id.toString())
.header(InternalValue.role, Role.Customer)
.entity(customer)
.build();
}
@@ -8,6 +8,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import java.util.UUID;
import org.eclipse.microprofile.reactive.messaging.*;
@Path(Role.Manager)
@@ -27,7 +28,12 @@ public class ManagerService extends BaseService<ManagerEntity> {
public Response signup(ManagerSignup input) {
ManagerEntity newManager = new ManagerEntity();
newManager.signup(input.name, input.phone, input.password);
newManager.signup(
input.name,
input.phone,
input.bankAccount,
input.password
);
ManagerCreate message = new ManagerCreate();
message.id = newManager.id;
@@ -60,9 +66,41 @@ public class ManagerService extends BaseService<ManagerEntity> {
.build();
return Response.accepted()
.entity(manager)
.header(InternalValue.userId, manager.id.toString())
.header(InternalValue.role, Role.Manager)
.entity(manager)
.build();
}
@GET
@Path("/{id}/payment-qr")
public Response getManagerPaymentQr(
@PathParam("id") UUID id,
@QueryParam("amount") Long amount,
@QueryParam("cartId") String cartId
) {
ManagerEntity manager = ManagerEntity.findById(id);
if (manager == null) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("ManagerNotFound")
.build();
}
if (manager.bankAccount == null || manager.bankAccount.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("ManagerHasNotConfiguredBankInfo")
.build();
}
String description = cartId;
return Response.ok(
String.format(
"https://img.vietqr.io/image/%s-compact.png?amount=%d&addInfo=%s",
manager.bankAccount,
amount,
description
)
).build();
}
}
@@ -43,6 +43,7 @@ public class StaffService extends BaseService<StaffEntity> {
return Response.status(Response.Status.CREATED)
.header(InternalValue.userId, staff.id.toString())
.header(InternalValue.managerId, manager.id.toString())
.header(InternalValue.role, Role.Staff)
.build();
}
@@ -64,8 +65,8 @@ public class StaffService extends BaseService<StaffEntity> {
return Response.accepted()
.header(InternalValue.userId, staff.id.toString())
.header(InternalValue.managerId, staff.serve.id.toString())
.header(InternalValue.role, Role.Staff)
.entity(staff)
.build();
}
}
@@ -10,12 +10,8 @@ import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.kafka.*;
import io.restassured.http.ContentType;
import io.smallrye.reactive.messaging.kafka.companion.ConsumerTask;
import io.smallrye.reactive.messaging.kafka.companion.KafkaCompanion;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import net.datafaker.Faker;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -0,0 +1,22 @@
package com.drinkool.controllers;
import com.drinkool.Role;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Response;
import java.util.UUID;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
@RegisterRestClient(configKey = "eatery")
@Path(Role.Manager)
public interface ManagerController {
@GET
@Path(Role.Manager + "/{id}/payment-qr")
public Response getManagerPaymentQr(
@PathParam("id") UUID id,
@QueryParam("amount") Long amount,
@QueryParam("cartId") String cartId
);
}
@@ -15,4 +15,6 @@ public class Cart {
public UUID userId;
public UUID eateryId;
public List<CartItem> items;
public long totalAmount;
public String paymentQrUrl;
}
@@ -11,4 +11,7 @@ public class CartItem {
public String productId;
public Integer quantity;
public Double priceAtTimeOfAdding;
public Double subTotal;
}
@@ -2,19 +2,20 @@ package com.drinkool.services;
import com.drinkool.InternalValue;
import com.drinkool.controllers.EateryController;
import com.drinkool.controllers.ManagerController;
import com.drinkool.dtos.Cart;
import com.drinkool.dtos.CartItem;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.hash.HashCommands;
import io.quarkus.redis.datasource.value.ValueCommands;
import io.smallrye.mutiny.Uni;
import io.smallrye.mutiny.infrastructure.Infrastructure;
import io.vertx.core.http.HttpServerRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.eclipse.microprofile.graphql.GraphQLApi;
@@ -35,6 +36,10 @@ public class CartService {
@RestClient
EateryController eateryController;
@Inject
@RestClient
ManagerController managerController;
private final HashCommands<String, String, String> hashCommands;
private final ValueCommands<String, String> valueCommands;
@@ -50,6 +55,7 @@ public class CartService {
return eateryController
.getEateryById(eateryId)
.emitOn(Infrastructure.getDefaultWorkerPool())
.onItem()
.transform(response -> {
if (response.getStatus() != Response.Status.OK.getStatusCode()) {
@@ -58,6 +64,7 @@ public class CartService {
String cartId = UUID.randomUUID().toString();
String redisKey = "cart:" + cartId;
String ownerId = response.getEntity().toString();
hashCommands.hset(
redisKey,
@@ -65,7 +72,9 @@ public class CartService {
"_metadata_owner",
userId != null ? userId : "GUEST",
"_metadata_eatery",
eateryId.toString()
eateryId.toString(),
"_metadata_eateryManagerId",
ownerId
)
);
@@ -87,55 +96,94 @@ public class CartService {
@Query("getCart")
public Cart getCart(@Name("cartId") UUID cartId) throws GraphQLException {
String key = "cart:" + cartId;
String priceKey = "cart_prices:" + cartId;
Map<String, String> data = hashCommands.hgetall(key);
Map<String, String> itemPrices = hashCommands.hgetall(priceKey);
String managerId = hashCommands.hget(key, "_metadata_eateryManagerId");
if (data.isEmpty()) {
throw new GraphQLException("NotFoundCart");
}
List<CartItem> items = new ArrayList<>();
Cart cart = new Cart();
cart.Id = cartId;
cart.eateryId = UUID.fromString(data.get("_metadata_eatery"));
String ownerStr = data.get("_metadata_owner");
cart.userId = "GUEST".equals(ownerStr) ? null : UUID.fromString(ownerStr);
cart.items = new ArrayList<>();
data.forEach((k, v) -> {
if (!k.startsWith("_")) {
items.add(new CartItem(k, Integer.parseInt(v)));
}
});
long total = 0;
return new Cart(
cartId,
UUID.fromString(data.get("_metadata_owner")),
UUID.fromString(data.get("_metadata_eatery")),
items
);
for (Map.Entry<String, String> entry : data.entrySet()) {
String field = entry.getKey();
if (field.startsWith("_metadata_")) continue;
Integer qty = Integer.parseInt(entry.getValue());
Double price = Double.parseDouble(itemPrices.getOrDefault(field, "0"));
Double subTotal = qty * price;
CartItem item = new CartItem();
item.productId = field;
item.quantity = qty;
item.priceAtTimeOfAdding = price;
item.subTotal = subTotal;
cart.items.add(item);
total += subTotal;
}
cart.totalAmount = total;
try {
Response response = managerController.getManagerPaymentQr(
UUID.fromString(managerId),
total,
cartId.toString()
);
cart.paymentQrUrl = response.readEntity(String.class);
} catch (Exception e) {
cart.paymentQrUrl = "";
}
return cart;
}
@Mutation("addItem")
public Uni<Cart> addItem(
public Cart addItem(
@Name("cartId") UUID cartId,
@Name("menuItemId") UUID menuItemId,
@Name("quantity") long quantity
) {
) throws GraphQLException {
String key = "cart:" + cartId;
String priceKey = "cart_prices:" + cartId;
UUID eateryId = UUID.fromString(hashCommands.hget(key, "_metadata_eatery"));
String eateryIdStr = hashCommands.hget(key, "_metadata_eatery");
if (eateryIdStr == null) throw new RuntimeException("CartNotFound");
return eateryController
UUID eateryId = UUID.fromString(eateryIdStr);
Response response = eateryController
.checkMenuItemExists(eateryId, menuItemId)
.onItem()
.transform(response -> {
if (response.getStatus() != Response.Status.OK.getStatusCode()) {
throw new RuntimeException("NotFoundEatery");
}
.await()
.indefinitely();
hashCommands.hincrby(key, menuItemId.toString(), quantity);
hashCommands.getDataSource().key().expire(key, Duration.ofDays(30));
if (response.getStatus() != Response.Status.OK.getStatusCode()) {
throw new GraphQLException("NotFoundMenuItemInEatery");
}
try {
return getCart(cartId);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
});
Double menuItemPrice = response.readEntity(Double.class);
hashCommands.hincrby(key, menuItemId.toString(), quantity);
hashCommands.hset(
priceKey,
menuItemId.toString(),
String.valueOf(menuItemPrice)
);
hashCommands.getDataSource().key().expire(key, Duration.ofDays(30));
hashCommands.getDataSource().key().expire(priceKey, Duration.ofDays(30));
return getCart(cartId);
}
}
@@ -21,3 +21,4 @@ quarkus.redis.hosts=redis://${REDIS_SERVICE_SERVICE_HOST:localhost}:${REDIS_SERV
# Rest Client
quarkus.rest-client.eatery.url=http://eatery-service
quarkus.rest-client.account.url=http://account-service
@@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.drinkool.controllers.EateryController;
import com.drinkool.controllers.ManagerController;
import com.drinkool.dtos.Cart;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.hash.HashCommands;
@@ -40,6 +41,10 @@ public class CartServiceTest {
@RestClient
EateryController eateryController;
@InjectMock
@RestClient
ManagerController managerController;
@Inject
RedisDataSource redisDataSource;
@@ -59,7 +64,7 @@ public class CartServiceTest {
UUID eateryId = UUID.randomUUID();
when(eateryController.getEateryById(eateryId)).thenReturn(
Uni.createFrom().item(Response.ok().build())
Uni.createFrom().item(Response.ok(UUID.randomUUID()).build())
);
String cartId = cartService
@@ -119,7 +124,7 @@ public class CartServiceTest {
}
@Test
void testAddItem_Success() {
void testAddItem_Success() throws GraphQLException {
UUID cartId = UUID.randomUUID();
UUID eateryId = UUID.randomUUID();
UUID menuItemId = UUID.randomUUID();
@@ -129,13 +134,10 @@ public class CartServiceTest {
hashCommands.hset(key, "_metadata_owner", UUID.randomUUID().toString());
when(eateryController.checkMenuItemExists(eateryId, menuItemId)).thenReturn(
Uni.createFrom().item(Response.ok().build())
Uni.createFrom().item(Response.ok(17.0).build())
);
Cart result = cartService
.addItem(cartId, menuItemId, 2L)
.await()
.atMost(Duration.ofSeconds(5));
Cart result = cartService.addItem(cartId, menuItemId, 2L);
assertNotNull(result);
assertEquals(cartId, result.getId());
+248
View File
@@ -0,0 +1,248 @@
# =============================================================
# Docker & PostgreSQL Health Check for Quarkus Dev Environment
# Dành cho sinh viên học Docker/Java
# =============================================================
$ErrorActionPreference = "SilentlyContinue"
# --- Color helpers ---
function Pass($msg) { Write-Host " [PASS] $msg" -ForegroundColor Green }
function Fail($msg) { Write-Host " [FAIL] $msg" -ForegroundColor Red }
function Info($msg) { Write-Host " [INFO] $msg" -ForegroundColor Cyan }
function Warn($msg) { Write-Host " [WARN] $msg" -ForegroundColor Yellow }
function Title($msg) { Write-Host "`n===== $msg =====" -ForegroundColor Magenta }
function Cmd($msg) { Write-Host " >> $msg" -ForegroundColor DarkGray }
$results = @{} # track pass/fail for summary
# =============================================================
# 1. Docker Desktop process check
# =============================================================
Title "1. Docker Desktop Process"
Cmd "Get-Process 'Docker Desktop' ..."
$dockerDesktop = Get-Process -Name "Docker Desktop" -ErrorAction SilentlyContinue
if ($dockerDesktop) {
Pass "Docker Desktop dang chay (PID: $($dockerDesktop.Id))"
$results["Docker Desktop"] = $true
} else {
Fail "Docker Desktop KHONG chay"
Info "Hay mo Docker Desktop tu Start Menu va doi 1-2 phut"
$results["Docker Desktop"] = $false
}
# =============================================================
# 2. Docker Windows service
# =============================================================
Title "2. Docker Service Status"
Cmd "Get-Service 'com.docker.service' ..."
$svc = Get-Service -Name "com.docker.service" -ErrorAction SilentlyContinue
if ($svc) {
if ($svc.Status -eq "Running") {
Pass "Docker service dang chay (Status: $($svc.Status))"
$results["Docker Service"] = $true
} else {
Fail "Docker service ton tai nhung KHONG chay (Status: $($svc.Status))"
Info "Thu chay: Start-Service 'com.docker.service'"
$results["Docker Service"] = $false
}
} else {
Warn "Khong tim thay docker service - co the la Docker Desktop dang dung standalone"
$results["Docker Service"] = $null
}
# =============================================================
# 3. DOCKER_HOST environment variable
# =============================================================
Title "3. DOCKER_HOST / Docker Socket"
Cmd "`$env:DOCKER_HOST"
$dockerHost = $env:DOCKER_HOST
if ($dockerHost) {
Info "DOCKER_HOST = $dockerHost"
$results["Docker Host"] = $true
} else {
Info "DOCKER_HOST chua duoc dat (dung default: npipe:////./pipe/docker_engine)"
$results["Docker Host"] = $true # default is fine on Windows
}
# Kiem tra named pipe
Cmd "Test-Path '//./pipe/docker_engine' ..."
$pipe = Test-Path "//./pipe/docker_engine"
if ($pipe) {
Pass "Docker named pipe ton tai - daemon co the ket noi"
} else {
Fail "Docker named pipe KHONG ton tai - daemon chua khoi dong"
Info "Hay doi Docker Desktop khoi dong xong roi thu lai"
$results["Docker Host"] = $false
}
# =============================================================
# 4. Docker daemon connectivity (docker ps)
# =============================================================
Title "4. Docker Daemon Connectivity"
Cmd "docker ps ..."
$dockerPs = docker ps 2>&1
$dockerExitCode = $LASTEXITCODE
if ($dockerExitCode -eq 0) {
Pass "Ket noi Docker daemon thanh cong"
$results["Docker Daemon"] = $true
} else {
Fail "Khong ket noi duoc Docker daemon"
Info "Loi: $dockerPs"
Info "Giai phap: Khoi dong lai Docker Desktop, doi ~30 giay, thu lai"
$results["Docker Daemon"] = $false
}
# =============================================================
# 5. List all running containers
# =============================================================
Title "5. Running Containers"
if ($results["Docker Daemon"]) {
Cmd "docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' ..."
$containers = docker ps --format "table {{.Names}}`t{{.Image}}`t{{.Status}}`t{{.Ports}}" 2>&1
if ($containers -match "NAMES") {
$lines = ($containers -split "`n") | Where-Object { $_ -ne "" }
$containerCount = $lines.Count - 1 # tru dong header
if ($containerCount -gt 0) {
Pass "$containerCount container dang chay:"
$containers | ForEach-Object { Write-Host " $_" -ForegroundColor White }
$results["Running Containers"] = $true
} else {
Warn "Khong co container nao dang chay"
$results["Running Containers"] = $false
}
}
} else {
Warn "Bo qua - Docker daemon chua ket noi duoc"
$results["Running Containers"] = $null
}
# =============================================================
# 6. PostgreSQL container check
# =============================================================
Title "6. PostgreSQL Container"
if ($results["Docker Daemon"]) {
# Tim container co ten chua "postgres" hoac "pg"
Cmd "docker ps -a --filter name=postgres ..."
$pgContainers = docker ps -a --format "{{.Names}}`t{{.Image}}`t{{.Status}}" 2>&1 |
Where-Object { $_ -match "postgres|pg" }
if ($pgContainers) {
$pgContainers | ForEach-Object {
$parts = $_ -split "`t"
$name = $parts[0]
$image = $parts[1]
$status = $parts[2]
if ($status -match "^Up") {
Pass "PostgreSQL container '$name' ($image) dang chay"
Pass "Status: $status"
$results["PostgreSQL Container"] = $true
$script:pgContainerName = $name
} else {
Fail "PostgreSQL container '$name' TON TAI nhung DUNG"
Info "Status: $status"
Info "Khoi dong lai: docker start $name"
$results["PostgreSQL Container"] = $false
$script:pgContainerName = $name
}
}
} else {
Fail "Khong tim thay PostgreSQL container nao"
Info "Tao container moi:"
Info " docker run -d --name postgres-dev -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:16"
$results["PostgreSQL Container"] = $false
$script:pgContainerName = $null
}
} else {
Warn "Bo qua - Docker daemon chua ket noi duoc"
$results["PostgreSQL Container"] = $null
}
# =============================================================
# 7. PostgreSQL connectivity test
# =============================================================
Title "7. PostgreSQL Connectivity"
if ($results["PostgreSQL Container"] -eq $true -and $script:pgContainerName) {
Cmd "docker exec $($script:pgContainerName) pg_isready ..."
$pgReady = docker exec $script:pgContainerName pg_isready 2>&1
$pgExitCode = $LASTEXITCODE
if ($pgExitCode -eq 0) {
Pass "PostgreSQL san sang nhan ket noi: $pgReady"
$results["PostgreSQL Connectivity"] = $true
# Thu ket noi bang psql
Cmd "docker exec $($script:pgContainerName) psql -U postgres -c '\l' ..."
$pgList = docker exec $script:pgContainerName psql -U postgres -c "\l" 2>&1
if ($LASTEXITCODE -eq 0) {
Pass "Ket noi psql thanh cong, danh sach database:"
$pgList | ForEach-Object { Write-Host " $_" -ForegroundColor White }
} else {
Warn "pg_isready OK nhung psql that bai (co the user khac): $pgList"
}
} else {
Fail "PostgreSQL CHUA san sang: $pgReady"
Info "Doi vai giay roi thu lai"
$results["PostgreSQL Connectivity"] = $false
}
} elseif ($results["PostgreSQL Container"] -eq $false) {
Warn "Bo qua - PostgreSQL container chua chay"
$results["PostgreSQL Connectivity"] = $null
} else {
Warn "Bo qua - Docker daemon chua ket noi duoc"
$results["PostgreSQL Connectivity"] = $null
}
# =============================================================
# SUMMARY REPORT
# =============================================================
Write-Host "`n" + ("=" * 55) -ForegroundColor Magenta
Write-Host " SUMMARY REPORT - Docker & PostgreSQL Health Check" -ForegroundColor Magenta
Write-Host ("=" * 55) -ForegroundColor Magenta
$allPass = $true
foreach ($check in $results.Keys) {
$val = $results[$check]
if ($val -eq $true) {
Write-Host (" [OK] {0,-35}" -f $check) -ForegroundColor Green
} elseif ($val -eq $false) {
Write-Host (" [!!] {0,-35} << Can fix" -f $check) -ForegroundColor Red
$allPass = $false
} else {
Write-Host (" [--] {0,-35} (skipped)" -f $check) -ForegroundColor Yellow
}
}
Write-Host ""
if ($allPass) {
Write-Host " Tat ca kiem tra PASS! Moi truong san sang." -ForegroundColor Green
Write-Host " Chay Quarkus: cd account-service && ./mvnw quarkus:dev" -ForegroundColor Cyan
} else {
Write-Host " CO MOT SO KIEM TRA THAT BAI. Xem huong dan o tren." -ForegroundColor Red
Write-Host ""
Write-Host " Giai phap nhanh:" -ForegroundColor Yellow
if (-not $results["Docker Desktop"]) {
Write-Host " 1. Mo Docker Desktop tu Start Menu" -ForegroundColor Yellow
}
if ($results["PostgreSQL Container"] -eq $false) {
Write-Host " 2. Chay: docker run -d --name postgres-dev -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:16" -ForegroundColor Yellow
}
if ($results["Docker Daemon"] -eq $false) {
Write-Host " 3. Doi Docker Desktop khoi dong xong, roi chay lai script nay" -ForegroundColor Yellow
}
}
Write-Host ("=" * 55) -ForegroundColor Magenta
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -23,5 +23,9 @@ public class AddMenuItem implements MenuItemInterface {
@NonNull
private Double price;
private Boolean available;
private String description;
private String imageUrl;
}
@@ -0,0 +1,17 @@
package com.drinkool.dtos;
import java.time.LocalTime;
import lombok.NoArgsConstructor;
import org.eclipse.microprofile.graphql.NonNull;
@NoArgsConstructor
public class CreateShift {
@NonNull
public LocalTime startTime;
@NonNull
public LocalTime endTime;
public Integer maxStaff;
}
@@ -0,0 +1,10 @@
package com.drinkool.dtos;
import java.util.UUID;
import org.eclipse.microprofile.graphql.NonNull;
public class RegisterShift {
@NonNull
public UUID shiftId;
}
@@ -26,5 +26,9 @@ public class UpdateMenuItem implements EntityInterface, MenuItemInterface {
Double price;
Boolean available;
String description;
String imageUrl;
}
@@ -27,6 +27,13 @@ public class EateryEntity extends BaseEntity {
)
public List<MenuItemEntity> menuItems = new ArrayList<>();
@OneToMany(
mappedBy = "eatery",
cascade = CascadeType.ALL,
orphanRemoval = true
)
public List<ShiftEntity> shifts = new ArrayList<>();
public EateryEntity() {}
@Transactional
@@ -20,10 +20,16 @@ public class MenuItemEntity extends BaseEntity implements MenuItemInterface {
@Column(nullable = false)
public Double price;
@Column(columnDefinition = "boolean default true")
public Boolean available;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "eatery_id")
public EateryEntity eatery;
@Column(columnDefinition = "TEXT default ''")
public String description;
@Column(nullable = true)
public String imageUrl;
@@ -0,0 +1,32 @@
package com.drinkool.entities;
import com.drinkool.lib.entities.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.LocalTime;
import java.util.UUID;
@Entity
@Table
public class ShiftEntity extends BaseEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "eatery_id")
public EateryEntity eatery;
@Column(nullable = true)
public String name;
@Column(nullable = false)
public LocalTime startTime;
@Column(nullable = false)
public LocalTime endTime;
@Column(nullable = true)
public Integer maxStaff;
}
@@ -0,0 +1,36 @@
package com.drinkool.entities;
import com.drinkool.lib.entities.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.util.List;
import java.util.UUID;
@Entity
@Table
public class ShiftRegistrationEntity extends BaseEntity {
@Column(nullable = false)
public UUID staffId;
@ManyToOne
public ShiftEntity shift;
public static long countByShift(UUID shiftId) {
return count("shift.id = ?1", shiftId);
}
public static List<ShiftRegistrationEntity> findOverlappingShifts(
UUID staffId,
ShiftEntity registratingShift
) {
return list(
"staffId = ?1 and shift.startTime < ?2 and shift.endTime > ?3",
staffId,
registratingShift.endTime,
registratingShift.startTime
);
}
}
@@ -42,33 +42,33 @@ public class EateryService {
EateryEntity eatery = EateryEntity.findById(id);
if (eatery == null) {
return Response.status(Response.Status.NOT_FOUND)
return Response.status(Response.Status.BAD_REQUEST)
.entity("NotFoundEatery")
.build();
}
return Response.ok().build();
return Response.ok(eatery.ownerId.toString()).build();
}
@GET
@Path("/{eateryId}/{menuItemId}")
public Response checkMenuItemExists(
public Response getMenuItemPrice(
@PathParam("eateryId") UUID eateryId,
@PathParam("menuItemId") UUID menuItemId
) {
long count = MenuItemEntity.find(
"id = ?2 and eatery.id = ?1",
eateryId,
menuItemId
).count();
MenuItemEntity menuItem = MenuItemEntity.find(
"id = ?1 and eatery.id = ?2",
menuItemId,
eateryId
).firstResult();
if (count == 0) {
return Response.status(Response.Status.NOT_FOUND)
if (menuItem == null) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("NotFoundMenuItem")
.build();
}
return Response.ok().build();
return Response.ok(menuItem.price).build();
}
@Incoming("manager-in")
@@ -0,0 +1,204 @@
package com.drinkool.services;
import com.drinkool.InternalValue;
import com.drinkool.Role;
import com.drinkool.dtos.CreateShift;
import com.drinkool.dtos.RegisterShift;
import com.drinkool.entities.EateryEntity;
import com.drinkool.entities.ShiftEntity;
import com.drinkool.entities.ShiftRegistrationEntity;
import io.vertx.core.http.HttpServerRequest;
import jakarta.annotation.security.RolesAllowed;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.eclipse.microprofile.graphql.*;
@GraphQLApi
@ApplicationScoped
public class ShiftService {
@Inject
HttpServerRequest request;
// --- QUERIES ---
@Query("allShifts")
@Description("Lấy danh sách tất cả các loại ca trực")
@RolesAllowed({ Role.Staff, Role.Manager })
public List<ShiftEntity> getAllShifts() throws GraphQLException {
String ownerId = request.getHeader(InternalValue.managerId);
if (ownerId == null || ownerId.isEmpty()) {
ownerId = request.getHeader(InternalValue.userId);
}
EateryEntity eatery = EateryEntity.findByOwnerId(ownerId);
return ShiftEntity.list("eatery", eatery);
}
@Query("myRegistrations")
@Description("Lấy danh sách ca trực mà nhân viên hiện tại đã đăng ký")
@RolesAllowed(Role.Staff)
public List<ShiftRegistrationEntity> getMyShifts() {
String userId = request.getHeader(InternalValue.userId);
return ShiftRegistrationEntity.list("staffId", UUID.fromString(userId));
}
@Query("allRegistrations")
@Description("Manager xem toàn bộ danh sách đăng ký của tất cả nhân viên")
@RolesAllowed(Role.Manager)
public List<ShiftRegistrationEntity> getAllRegistrations() {
return ShiftRegistrationEntity.listAll();
}
// --- MUTATIONS ---
@Mutation("registerShift")
@Description("Nhân viên đăng ký vào một ca trực cụ thể")
@RolesAllowed(Role.Staff)
@Transactional
public ShiftRegistrationEntity registerShift(
@Name("registration") RegisterShift registration
) throws GraphQLException {
String userIdStr = request.getHeader(InternalValue.userId);
String managerIdStr = request.getHeader(InternalValue.managerId);
UUID staffId = UUID.fromString(userIdStr);
EateryEntity eatery = EateryEntity.findByOwnerId(managerIdStr);
if (eatery == null) throw new GraphQLException("NotFoundEatery");
ShiftEntity shift = ShiftEntity.find(
"id = ?1 and eatery.id = ?2",
registration.shiftId,
eatery.id
).firstResult();
if (shift == null) throw new GraphQLException("NotFoundShift");
List<ShiftRegistrationEntity> overlappingShifts =
ShiftRegistrationEntity.findOverlappingShifts(staffId, shift);
if (!overlappingShifts.isEmpty()) {
String ids = overlappingShifts
.stream()
.map(reg -> reg.shift.id.toString())
.distinct()
.collect(Collectors.joining(", "));
throw new GraphQLException("OverlappingShift: " + ids);
}
long currentStaffCount = ShiftRegistrationEntity.countByShift(shift.id);
if (shift.maxStaff != null && currentStaffCount >= shift.maxStaff) {
throw new GraphQLException("FulledShift");
}
ShiftRegistrationEntity record = new ShiftRegistrationEntity();
record.staffId = staffId;
record.shift = shift;
record.persist();
return record;
}
@Mutation("createShift")
@Description("Quản lý tạo mới một loại ca trực")
@RolesAllowed(Role.Manager)
@Transactional
public ShiftEntity createShift(@Name("shiftInput") CreateShift input)
throws GraphQLException {
String ownerId = request.getHeader(InternalValue.userId);
EateryEntity eatery = EateryEntity.findByOwnerId(ownerId);
if (eatery == null) return null;
ShiftEntity shift = new ShiftEntity();
shift.eatery = eatery;
shift.startTime = input.startTime;
shift.endTime = input.endTime;
shift.maxStaff = input.maxStaff;
if (shift.endTime.isBefore(shift.startTime)) {
throw new GraphQLException("InvalidEndTime");
}
shift.persist();
return shift;
}
@Mutation("updateShift")
@Description("Quản lý cập nhật thông tin ca trực")
@RolesAllowed(Role.Manager)
@Transactional
public ShiftEntity updateShift(
@Name("id") UUID id,
@Name("shiftInput") CreateShift input
) throws GraphQLException {
ShiftEntity shift = ShiftEntity.findById(id);
if (shift == null) throw new GraphQLException("NotFoundShift");
String ownerId = request.getHeader(InternalValue.userId);
if (
!shift.eatery.ownerId.toString().equals(ownerId)
) throw new GraphQLException("InvalidShiftId");
shift.startTime = input.startTime;
shift.endTime = input.endTime;
shift.maxStaff = input.maxStaff;
if (shift.endTime.isBefore(shift.startTime)) {
throw new GraphQLException("InvalidEndTime");
}
return shift;
}
@Mutation("deleteShift")
@Description("Quản lý xóa một ca trực")
@RolesAllowed(Role.Manager)
@Transactional
public boolean deleteShift(@Name("id") UUID id) throws GraphQLException {
String ownerId = request.getHeader(InternalValue.userId);
EateryEntity eatery = EateryEntity.findByOwnerId(ownerId);
if (eatery == null) {
throw new GraphQLException("NotFoundEatery");
}
ShiftEntity shift = ShiftEntity.find(
"id = ?1 and eatery = ?2",
id,
eatery
).firstResult();
if (shift == null) {
throw new GraphQLException("NotFoundShiftOrAccessDenied");
}
long count = ShiftRegistrationEntity.count("shift.id", id);
if (count > 0) throw new GraphQLException(
"CannotDeleteShiftWithRegistrations"
);
return ShiftEntity.deleteById(id);
}
@Mutation("cancelRegistration")
@Description("Nhân viên hủy ca đã đăng ký")
@RolesAllowed(Role.Staff)
@Transactional
public boolean cancelRegistration(@Name("registrationId") UUID id)
throws GraphQLException {
String userId = request.getHeader(InternalValue.userId);
ShiftRegistrationEntity reg = ShiftRegistrationEntity.findById(id);
if (reg == null) throw new GraphQLException("RegistrationNotFound");
if (!reg.staffId.equals(UUID.fromString(userId))) {
throw new GraphQLException("NotYourRegistration");
}
reg.delete();
return true;
}
}
@@ -28,10 +28,12 @@ quarkus.native.additional-build-args=--future-defaults=all
# Kafka
%prod.mp.messaging.connector.smallrye-kafka.bootstrap.servers=${KAFKA_SERVICE_SERVICE_HOST:host.docker.internal}:9092
mp.messaging.incoming.manager-in.connector=smallrye-in-memory
## Create restaurant topic
mp.messaging.incoming.manager-in.connector=smallrye-kafka
mp.messaging.incoming.manager-in.topic=create-restaurant
mp.messaging.incoming.manager-in.auto.offset.reset=earliest
quarkus.messaging.kafka.serializer-generation.enabled=true
quarkus.messaging.kafka.serializer-generation.enabled=true
# Rest Client
quarkus.rest-client.account.url=http://account-service
@@ -88,6 +88,8 @@ public class EateryServiceTest {
new AddMenuItem(
faker.food().dish(),
faker.number().randomDouble(2, 10, 100),
true,
"",
""
)
).id;
@@ -0,0 +1,230 @@
package com.drinkool.services;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import com.drinkool.InternalValue;
import com.drinkool.Role;
import com.drinkool.entities.EateryEntity;
import com.drinkool.entities.ShiftEntity;
import com.drinkool.entities.ShiftRegistrationEntity;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.transaction.Transactional;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@QuarkusTest
public class ShiftServiceTest {
@BeforeEach
@Transactional
void setup() {
ShiftRegistrationEntity.deleteAll();
ShiftEntity.deleteAll();
}
// --- TEST QUERIES ---
@Test
void testGetAllShifts() {
UUID ownerId = createMockOwner();
EateryEntity eatery = createMockEatery(ownerId);
createMockShift("Ca Sáng", "08:00:00", "12:00:00", eatery);
given()
.header(InternalValue.role, Role.Manager)
.header(InternalValue.userId, ownerId)
.contentType("application/json")
.body("{ \"query\": \"{ allShifts { name startTime } }\" }")
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("data.allShifts", hasSize(1))
.body("data.allShifts[0].name", is("Ca Sáng"));
}
// --- TEST MUTATIONS ---
@Test
void testCreateShift_AsManager() {
String query = """
mutation Create($input: CreateShiftInput!)
{ createShift(shiftInput: $input) { id name } }""";
Map<String, Object> input = new HashMap<>();
input.put("name", "Ca Sáng");
input.put("startTime", "08:00:00");
input.put("endTime", "12:00:00");
input.put("maxStaff", 5);
Map<String, Object> body = new HashMap<>();
body.put("query", query);
body.put("variables", Map.of("input", input));
UUID ownerId = createMockOwner();
createMockEatery(ownerId);
given()
.contentType("application/json")
.header(InternalValue.role, Role.Manager)
.header(InternalValue.userId, ownerId)
.body(body)
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("data.createShift.name", is("Ca Sáng"));
}
@Test
void testRegisterShift_Success() {
UUID ownerId = createMockOwner();
EateryEntity eatery = createMockEatery(ownerId);
ShiftEntity shift = createMockShift(
"Ca Tối",
"18:00:00",
"22:00:00",
eatery
);
UUID staffId = UUID.randomUUID();
String mutation = String.format(
"mutation { registerShift(registration: { shiftId: \\\"%s\\\" }) { id staffId } }",
shift.id
);
given()
.contentType("application/json")
.header(InternalValue.role, Role.Staff)
.header(InternalValue.userId, staffId.toString())
.header(InternalValue.managerId, ownerId.toString())
.body("{ \"query\": \"" + mutation + "\" }")
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("data.registerShift.staffId", is(staffId.toString()));
}
@Test
void testRegisterShift_Overlap_Fail() {
UUID ownerId = createMockOwner();
EateryEntity eatery = createMockEatery(ownerId);
UUID staffId = UUID.randomUUID();
// Tạo 2 ca bị trùng giờ nhau
ShiftEntity shift1 = createMockShift(
"Ca 1",
"08:00:00",
"12:00:00",
eatery
);
ShiftEntity shift2 = createMockShift(
"Ca 2",
"10:00:00",
"14:00:00",
eatery
);
// Đăng ký ca 1 trước
registerStaffToShift(staffId, shift1);
// Đăng ký ca 2 (sẽ bị overlap)
String mutation = String.format(
"mutation { registerShift(registration: { shiftId: \\\"%s\\\" }) { id } }",
shift2.id
);
given()
.contentType("application/json")
.header(InternalValue.userId, staffId.toString())
.header(InternalValue.managerId, ownerId.toString())
.header(InternalValue.role, Role.Staff)
.body("{ \"query\": \"" + mutation + "\" }")
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("errors", notNullValue())
.body("errors[0].message", containsString("OverlappingShift"));
}
@Test
void testDeleteShift_WithRegistrations_Fail() {
UUID ownerId = createMockOwner();
EateryEntity eatery = createMockEatery(ownerId);
ShiftEntity shift = createMockShift(
"Ca Xóa",
"08:00:00",
"12:00:00",
eatery
);
registerStaffToShift(UUID.randomUUID(), shift);
String mutation = String.format(
"mutation { deleteShift(id: \\\"%s\\\") }",
shift.id
);
given()
.header(InternalValue.userId, ownerId.toString())
.header(InternalValue.role, Role.Manager)
.contentType("application/json")
.body("{ \"query\": \"" + mutation + "\" }")
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("errors[0].message", is("CannotDeleteShiftWithRegistrations"));
}
// --- HELPER METHODS ---
@Transactional
ShiftEntity createMockShift(
String name,
String start,
String end,
EateryEntity eatery
) {
ShiftEntity shift = new ShiftEntity();
shift.eatery = eatery;
shift.name = name;
shift.startTime = LocalTime.parse(start);
shift.endTime = LocalTime.parse(end);
shift.maxStaff = 5;
shift.persist();
return shift;
}
@Transactional
void registerStaffToShift(UUID staffId, ShiftEntity shift) {
ShiftRegistrationEntity reg = new ShiftRegistrationEntity();
reg.staffId = staffId;
reg.shift = shift;
reg.persist();
}
@Transactional
public UUID createMockOwner() {
return UUID.randomUUID();
}
@Transactional
public EateryEntity createMockEatery(UUID ownerId) {
EateryEntity eatery = new EateryEntity();
eatery.name = "Nhà hàng " + ownerId.toString().substring(0, 5);
eatery.ownerId = ownerId;
eatery.persist();
EateryEntity.getEntityManager().flush();
return eatery;
}
}
+3 -3
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -71,7 +71,7 @@
<profiles>
<profile>
<id>push-python-image</id>
<id>push</id>
<activation>
<property>
<name>quarkus.container-image.push</name>
@@ -86,7 +86,7 @@
<executions>
<execution>
<id>docker-push-python</id>
<phase>install</phase>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
+7 -3
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -55,6 +55,10 @@
<version>${org.projectlombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-security</artifactId>
@@ -151,8 +155,8 @@
<configuration>
<argLine>@{argLine}</argLine>
<systemPropertyVariables>
<native.image.path
>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
<native.image.path>
${project.build.directory}/${project.build.finalName}-runner</native.image.path>
<java.util.logging.manager
>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
@@ -9,6 +9,9 @@ import jakarta.json.bind.Jsonb;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class GraphqlBase {
@@ -39,18 +42,25 @@ public abstract class GraphqlBase {
gqlRequest.variables
);
if (response.hasError()) {
return Response.status(400)
.entity(jsonb.toJson(response.getErrors()))
.build();
}
Map<String, Object> gqlBody = new HashMap<>();
return Response.ok(jsonb.toJson(response.getData()))
gqlBody.put("data", response.getData());
gqlBody.put("errors", response.getErrors());
return Response.ok(jsonb.toJson(gqlBody))
.type(MediaType.APPLICATION_JSON)
.build();
} catch (Exception e) {
e.printStackTrace();
return Response.serverError().entity("Lỗi kết nối tới service").build();
Map<String, Object> errorBody = new HashMap<>();
errorBody.put(
"errors",
List.of(Map.of("message", "Lỗi kết nối tới service: " + e.getMessage()))
);
return Response.serverError()
.type(MediaType.APPLICATION_JSON)
.entity(jsonb.toJson(errorBody))
.build();
}
}
}
@@ -11,6 +11,9 @@ quarkus.container-image.additional-tags=latest
quarkus.native.container-build=true
quarkus.native.remote-container-build=true
quarkus.native.additional-build-args=--future-defaults=all
quarkus.swagger-ui.always-include=false
quarkus.swagger-ui.request-interceptor=true
quarkus.swagger-ui.path=/api
# Rest Client
quarkus.rest-client.account.url=http://account-service
+1 -1
View File
@@ -14,7 +14,7 @@ spec:
spec:
containers:
- name: account-pod
image: git.demonkernel.io.vn/foodsurf/account-service:1.5.26
image: git.demonkernel.io.vn/foodsurf/account-service:1.5.30
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
+1 -1
View File
@@ -14,7 +14,7 @@ spec:
spec:
containers:
- name: cart-pod
image: git.demonkernel.io.vn/foodsurf/cart-service:1.5.26
image: git.demonkernel.io.vn/foodsurf/cart-service:1.5.30
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
+1 -1
View File
@@ -14,7 +14,7 @@ spec:
spec:
containers:
- name: eatery-pod
image: git.demonkernel.io.vn/foodsurf/eatery-service:1.5.26
image: git.demonkernel.io.vn/foodsurf/eatery-service:1.5.30
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
+1 -1
View File
@@ -14,7 +14,7 @@ spec:
spec:
containers:
- name: file-pod
image: git.demonkernel.io.vn/foodsurf/file-service:1.5.26
image: git.demonkernel.io.vn/foodsurf/file-service:1.5.30
imagePullPolicy: IfNotPresent
volumeMounts:
- name: file-volume
+1 -1
View File
@@ -14,7 +14,7 @@ spec:
spec:
containers:
- name: gateway-pod
image: git.demonkernel.io.vn/foodsurf/gateway-service:1.5.26
image: git.demonkernel.io.vn/foodsurf/gateway-service:1.5.30
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -6,4 +6,5 @@ public class InternalValue {
public static final String headerId = "X-Internal-";
public static final String userId = headerId + "UserId";
public static final String role = headerId + "Role";
public static final String managerId = headerId + "ManagerId";
}
@@ -5,6 +5,10 @@ public interface MenuItemInterface {
void setName(String x);
Double getPrice();
void setPrice(Double x);
Boolean getAvailable();
void setAvailable(Boolean x);
String getImageUrl();
void setImageUrl(String x);
String getDescription();
void setDescription(String x);
}
@@ -3,4 +3,6 @@ package com.drinkool.lib.dtos;
public class ManagerSignup extends Signup {
public String eateryName;
public String bankAccount;
}
+1 -1
View File
@@ -7,7 +7,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.26</version>
<version>1.5.30</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>25</maven.compiler.source>
+1
View File
@@ -1,4 +1,5 @@
mvn clean package -DskipTests \
-Dquarkus.swagger-ui.always-include=true \
-Dquarkus.container-image.push=false \
-Dquarkus.container-image.registry=git.demonkernel.io.vn \
"$@"