impemented pagination from roese utils

main
alex 2023-10-13 09:00:11 +02:00
parent 6340cfc391
commit 9a8530dbfd
15 changed files with 52 additions and 75 deletions

4
go.mod
View File

@ -3,7 +3,7 @@ module jannex/admin-dashboard-backend
go 1.21.0 go 1.21.0
require ( require (
git.ex.umbach.dev/Alex/roese-utils v1.0.10 git.ex.umbach.dev/Alex/roese-utils v1.0.11
github.com/gofiber/fiber/v2 v2.49.2 github.com/gofiber/fiber/v2 v2.49.2
github.com/gofiber/websocket/v2 v2.1.6 github.com/gofiber/websocket/v2 v2.1.6
github.com/google/uuid v1.3.1 github.com/google/uuid v1.3.1
@ -12,7 +12,7 @@ require (
github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee github.com/savsgio/gotils v0.0.0-20230208104028-c358bd845dee
golang.org/x/crypto v0.7.0 golang.org/x/crypto v0.7.0
gorm.io/driver/mysql v1.5.0 gorm.io/driver/mysql v1.5.0
gorm.io/gorm v1.25.0 gorm.io/gorm v1.25.5
) )
require ( require (

16
go.sum
View File

@ -1,13 +1,5 @@
git.ex.umbach.dev/Alex/roese-utils v1.0.6 h1:dqel8hRA+7IEwxPN1ld88UQu+ZnccECwWuwRbXDdh3U= git.ex.umbach.dev/Alex/roese-utils v1.0.11 h1:iPrVktpUG0WYLTexoI3iJqi/KojaB5Cs0hCF/GFs92c=
git.ex.umbach.dev/Alex/roese-utils v1.0.6/go.mod h1:tjq6m6lNFo0TzAvq8jHhlK48IGxi+SrlrQwf9WYg408= git.ex.umbach.dev/Alex/roese-utils v1.0.11/go.mod h1:mov3ZaoSu+GBQU1uXN/AfSK6MF3/3WxUk38Tb6IKxbI=
git.ex.umbach.dev/Alex/roese-utils v1.0.7 h1:eLw6u1ibPeG6zd702Q3Ge8VebABiz0KQJkzr3Rp++HM=
git.ex.umbach.dev/Alex/roese-utils v1.0.7/go.mod h1:tjq6m6lNFo0TzAvq8jHhlK48IGxi+SrlrQwf9WYg408=
git.ex.umbach.dev/Alex/roese-utils v1.0.8 h1:ph18N52R9UsJ0AsJW95W6afa9qKlMDMh60xE4wlfFi8=
git.ex.umbach.dev/Alex/roese-utils v1.0.8/go.mod h1:tjq6m6lNFo0TzAvq8jHhlK48IGxi+SrlrQwf9WYg408=
git.ex.umbach.dev/Alex/roese-utils v1.0.9 h1:MshCYgFc22t4h9KjfE4hvuHbUcrqkbzxC3J4nqGoyuk=
git.ex.umbach.dev/Alex/roese-utils v1.0.9/go.mod h1:tjq6m6lNFo0TzAvq8jHhlK48IGxi+SrlrQwf9WYg408=
git.ex.umbach.dev/Alex/roese-utils v1.0.10 h1:pAtvtWrDSuVKGyusKPG093+DsnNc2ek/6k/9Qgz7acE=
git.ex.umbach.dev/Alex/roese-utils v1.0.10/go.mod h1:tjq6m6lNFo0TzAvq8jHhlK48IGxi+SrlrQwf9WYg408=
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
@ -92,5 +84,5 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.0 h1:6hSAT5QcyIaty0jfnff0z0CLDjyRgZ8mlMHLqSt7uXM= gorm.io/driver/mysql v1.5.0 h1:6hSAT5QcyIaty0jfnff0z0CLDjyRgZ8mlMHLqSt7uXM=
gorm.io/driver/mysql v1.5.0/go.mod h1:FFla/fJuCvyTi7rJQd27qlNX2v3L6deTR1GgTjSOLPo= gorm.io/driver/mysql v1.5.0/go.mod h1:FFla/fJuCvyTi7rJQd27qlNX2v3L6deTR1GgTjSOLPo=
gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.0 h1:+KtYtb2roDz14EQe4bla8CbQlmb9dN3VejSai3lprfU= gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=

View File

@ -6,7 +6,9 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')
from libs.robots import rex from libs.robots import rex
rexRobot = rex.Rex("B24", "Drucker leeren") rexRobot = rex.Rex("test", "Drucker leeren")
# rexRobot.moveToXYZ(1, 2, 3) # rexRobot.moveToXYZ(1, 2, 3)
rexRobot.move_to_x(5) rexRobot.move_to_x(5)
rexRobot.finish()

View File

@ -6,17 +6,18 @@ class Rex:
""" """
This class represents a rex robot. This class represents a rex robot.
""" """
def __init__(self, rexName, jobName): def __init__(self, robotName, jobName, address='http://localhost:50055'):
self.rexName = rexName self.robotName = robotName
self.jobId = uuid.uuid4().__str__() self.jobId = uuid.uuid4().__str__()
self.jobName = jobName self.jobName = jobName
self.address = address
self.x = 0 self.x = 0
self.y = 0 self.y = 0
self.z = 0 self.z = 0
self.connectedModule = 0 self.connectedModule = 0
def _request_data(self): def _request_data(self):
return {'robotName': self.rexName, 'jobid': self.jobId, 'jobName': self.jobName} return {'robotName': self.robotName, 'jobId': self.jobId, 'jobName': self.jobName}
def _post_request(self, json): def _post_request(self, json):
obj = {} obj = {}
@ -24,7 +25,9 @@ class Rex:
obj = self._request_data() obj = self._request_data()
obj['task'] = json obj['task'] = json
res = requests.post('http://localhost:50055/v1/control/0', json=obj) res = requests.post(self.address + '/v1/control/1', json=obj)
print("status code", res.status_code)
def move_to_x(self, x): def move_to_x(self, x):
""" """
@ -54,23 +57,25 @@ class Rex:
self.y = y self.y = y
self.z = z self.z = z
print('Robot: ' + self.rexName + ' moved to (' + str(self.x) + ', ' + str(self.y) + ')') print('Robot: ' + self.robotName + ' moved to (' + str(self.x) + ', ' + str(self.y) + ')')
# requests.post('http://localhost:50055/v1/control/move', json={'x': self.x, 'y': self.y, 'z': self.z})
self._post_request({'x': self.x, 'y': self.y, 'z': self.z}) self._post_request({'x': self.x, 'y': self.y, 'z': self.z})
def change_connected_module(self, module): def change_connected_module(self, module):
""" """
Change the connected module. Change the connected module.
""" """
print('Robot: ' + self.rexName + ' changed connected module to ' + str(module)) print('Robot: ' + self.robotName + ' changed connected module to ' + str(module))
def finish(): def finish(self):
""" """
Finish the robot. Finish the robot.
This will update the robot status to free. This will update the robot status to free.
""" """
print('Robot finished') print('Robot finished')
# TODO: request to the server to finish the robot and update the robot status to free # TODO: request to the server to finish the robot and update the robot status to free
res = requests.post(self.address + '/v1/control/1/finish', json={'robotName': self.robotName, 'jobId': self.jobId})
print("status code", res.status_code)

View File

@ -72,7 +72,7 @@ INVEX_API_TOKEN=api_token`)
config.LoadConfig() config.LoadConfig()
rslogger.InitLogger(config.Cfg.Debug, config.Cfg.ColorizedOutput, config.Cfg.LogManagerServerUrl) rslogger.InitLogger(false, config.Cfg.ColorizedOutput, config.Cfg.LogManagerServerUrl)
if os.Getenv("DOCKER") != "" { if os.Getenv("DOCKER") != "" {
fmt.Println("Waiting for mariadb docker") fmt.Println("Waiting for mariadb docker")

View File

@ -13,6 +13,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -111,10 +112,10 @@ func CreateEquipmentDocumentation(c *fiber.Ctx, body structs.CreateEquipmentDocu
return c.JSON(fiber.Map{"message": "ok"}) return c.JSON(fiber.Map{"message": "ok"})
} }
func GetEquipmentDocumentations(stockItemId string, query structs.PageQuery, c *fiber.Ctx) error { func GetEquipmentDocumentations(stockItemId string, query rspagination.PageQuery, c *fiber.Ctx) error {
var documentations []structs.EquipmentDocumentation var documentations []structs.EquipmentDocumentation
utils.DbPageQuery(query, rspagination.DbPageQuery(database.DB, query,
utils.EquipmentDocumentationsPaginationLimit, utils.EquipmentDocumentationsPaginationLimit,
&documentations, &documentations,
"created_at DESC", "created_at DESC",
@ -135,7 +136,7 @@ func GetEquipmentDocumentations(stockItemId string, query structs.PageQuery, c *
return c.SendStatus(fiber.StatusInternalServerError) return c.SendStatus(fiber.StatusInternalServerError)
} }
} else { } else {
totalPages = utils.GetTotalPages(utils.EquipmentDocumentationsPaginationLimit, totalPages = rspagination.GetTotalPages(database.DB, utils.EquipmentDocumentationsPaginationLimit,
&documentations, &documentations,
"stock_item_id = ?", "stock_item_id = ?",
stockItemId) stockItemId)

View File

@ -18,6 +18,7 @@ import (
"strings" "strings"
"time" "time"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"git.ex.umbach.dev/Alex/roese-utils/rsutils" "git.ex.umbach.dev/Alex/roese-utils/rsutils"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -736,10 +737,10 @@ func updateGroupTaskSteps(groupTaskStep structs.GroupTaskSteps, category string)
}) })
} }
func GetAllGroupTasks(category string, query structs.PageQuery) []structs.GroupTasks { func GetAllGroupTasks(category string, query rspagination.PageQuery) []structs.GroupTasks {
var groupTasks []structs.GroupTasks var groupTasks []structs.GroupTasks
utils.DbPageQuery(query, rspagination.DbPageQuery(database.DB, query,
utils.GroupTasksPaginationLimit, utils.GroupTasksPaginationLimit,
&groupTasks, &groupTasks,
"started_at DESC", "started_at DESC",
@ -861,7 +862,7 @@ func StartGroupTask(userId string, groupTask structs.GroupTasks) {
TotalPages int TotalPages int
}{ }{
GroupTask: groupTask, GroupTask: groupTask,
TotalPages: utils.GetTotalPages(utils.GroupTasksPaginationLimit, TotalPages: rspagination.GetTotalPages(database.DB, utils.GroupTasksPaginationLimit,
[]structs.GroupTasks{}, []structs.GroupTasks{},
"category = ?", "category = ?",
groupTask.Category), groupTask.Category),

View File

@ -7,6 +7,7 @@ import (
"jannex/admin-dashboard-backend/socketclients" "jannex/admin-dashboard-backend/socketclients"
"time" "time"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/google/uuid" "github.com/google/uuid"
) )
@ -19,10 +20,10 @@ func GetTotalNotifications(userId string) int {
return int(totalNotifications) return int(totalNotifications)
} }
func GetNotifications(query structs.PageQuery, userId string) []structs.Notification { func GetNotifications(query rspagination.PageQuery, userId string) []structs.Notification {
var notifications []structs.Notification var notifications []structs.Notification
utils.DbPageQuery(query, rspagination.DbPageQuery(database.DB, query,
utils.NotificationsPaginationLimit, utils.NotificationsPaginationLimit,
&notifications, &notifications,
"created_at DESC", "created_at DESC",
@ -93,7 +94,7 @@ func AddNotification(c *fiber.Ctx, body structs.AddNotificationRequest) error {
TotalPages int TotalPages int
}{ }{
Notification: notify, Notification: notify,
TotalPages: utils.GetTotalPages(utils.NotificationsPaginationLimit, TotalPages: rspagination.GetTotalPages(database.DB, utils.NotificationsPaginationLimit,
[]structs.Notification{}, []structs.Notification{},
"user_id = ?", "user_id = ?",
userId), userId),

View File

@ -1,5 +0,0 @@
package structs
type PageQuery struct {
Page int
}

View File

@ -202,6 +202,8 @@ const (
PermissionUserProfileApiKeys = "user_profile.api_keys" PermissionUserProfileApiKeys = "user_profile.api_keys"
_consoles = "consoles." _consoles = "consoles."
PermissionConsolesView = _consoles + "view" PermissionConsolesView = _consoles + "view"
PermissionRoboticsView = "robotics.view"
) )
var SystemPermissions = []string{ var SystemPermissions = []string{
@ -226,6 +228,7 @@ var SystemPermissions = []string{
PermissionAdminAreaManageRemoveLogManagerServerConnection, PermissionAdminAreaManageRemoveLogManagerServerConnection,
PermissionUserProfileApiKeys, PermissionUserProfileApiKeys,
PermissionConsolesView, PermissionConsolesView,
PermissionRoboticsView,
} }
var DynamicGroupTasksPermissions = []string{ var DynamicGroupTasksPermissions = []string{

View File

@ -1,14 +1,10 @@
package utils package utils
import ( import (
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/structs"
"math"
"time" "time"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"gorm.io/gorm"
) )
func GetXAuhorizationHeader(c *fiber.Ctx) string { func GetXAuhorizationHeader(c *fiber.Ctx) string {
@ -33,27 +29,3 @@ func IsPasswordLengthValid(password string) bool {
return true return true
} }
// GetTotalPages returns total pages for pagination
// Example whereQuery = "stock_item_id = ?" and args = stockItemId is Where("stock_item_id = ?", stockItemId)
func GetTotalPages(paginationLimit int, any interface{}, whereQuery interface{}, args ...interface{}) int {
var totalPages int64
database.DB.Model(any).
Where(whereQuery, args).
Count(&totalPages)
return int(math.Ceil(float64(totalPages) / float64(paginationLimit)))
}
func GetPageOffset(page int, paginationLimit int) int {
return (page - 1) * paginationLimit
}
func DbPageQuery(query structs.PageQuery, paginationLimit int, result any, orderBy, whereQuery interface{}, args ...interface{}) *gorm.DB {
return database.DB.Limit(paginationLimit).
Offset(GetPageOffset(query.Page, paginationLimit)).
Where(whereQuery, args).
Order(orderBy).
Find(result)
}

View File

@ -6,6 +6,7 @@ import (
"jannex/admin-dashboard-backend/modules/utils" "jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients" "jannex/admin-dashboard-backend/socketclients"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"git.ex.umbach.dev/Alex/roese-utils/rsutils" "git.ex.umbach.dev/Alex/roese-utils/rsutils"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
@ -91,7 +92,7 @@ func GetEquipmentDocumentations(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusBadRequest) return c.SendStatus(fiber.StatusBadRequest)
} }
var query structs.PageQuery var query rspagination.PageQuery
if err := rsutils.QueryParserHelper(c, &query); err != nil { if err := rsutils.QueryParserHelper(c, &query); err != nil {
return c.SendStatus(fiber.StatusBadRequest) return c.SendStatus(fiber.StatusBadRequest)

View File

@ -3,11 +3,13 @@ package grouptasks
import ( import (
"encoding/json" "encoding/json"
"jannex/admin-dashboard-backend/modules/cache" "jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/grouptasks" "jannex/admin-dashboard-backend/modules/grouptasks"
"jannex/admin-dashboard-backend/modules/structs" "jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils" "jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients" "jannex/admin-dashboard-backend/socketclients"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"git.ex.umbach.dev/Alex/roese-utils/rsutils" "git.ex.umbach.dev/Alex/roese-utils/rsutils"
"git.ex.umbach.dev/Alex/roese-utils/rsvalidator" "git.ex.umbach.dev/Alex/roese-utils/rsvalidator"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
@ -55,7 +57,7 @@ func GetGroupTasks(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusUnauthorized) return c.SendStatus(fiber.StatusUnauthorized)
} }
var query structs.PageQuery var query rspagination.PageQuery
if err := c.QueryParser(&query); err != nil { if err := c.QueryParser(&query); err != nil {
return c.SendStatus(fiber.StatusBadRequest) return c.SendStatus(fiber.StatusBadRequest)
@ -72,7 +74,7 @@ func GetGroupTasks(c *fiber.Ctx) error {
return c.JSON(structs.GroupTasksResponse{ return c.JSON(structs.GroupTasksResponse{
CategoryGroup: categoryGroup, CategoryGroup: categoryGroup,
GroupTasks: grouptasks.GetAllGroupTasks(params.Category, query), GroupTasks: grouptasks.GetAllGroupTasks(params.Category, query),
TotalPages: utils.GetTotalPages(utils.GroupTasksPaginationLimit, TotalPages: rspagination.GetTotalPages(database.DB, utils.GroupTasksPaginationLimit,
[]structs.GroupTasks{}, []structs.GroupTasks{},
"category = ?", "category = ?",
params.Category), params.Category),

View File

@ -1,10 +1,12 @@
package notification package notification
import ( import (
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/notification" "jannex/admin-dashboard-backend/modules/notification"
"jannex/admin-dashboard-backend/modules/structs" "jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils" "jannex/admin-dashboard-backend/modules/utils"
"git.ex.umbach.dev/Alex/roese-utils/rspagination"
"git.ex.umbach.dev/Alex/roese-utils/rsutils" "git.ex.umbach.dev/Alex/roese-utils/rsutils"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
@ -71,7 +73,7 @@ func GetNotifications(c *fiber.Ctx) error {
// '500': // '500':
// description: Failed to get notifications // description: Failed to get notifications
var query structs.PageQuery var query rspagination.PageQuery
if err := rsutils.QueryParserHelper(c, &query); err != nil { if err := rsutils.QueryParserHelper(c, &query); err != nil {
return c.SendStatus(fiber.StatusBadRequest) return c.SendStatus(fiber.StatusBadRequest)
@ -81,7 +83,7 @@ func GetNotifications(c *fiber.Ctx) error {
return c.JSON(structs.NotificationsResponse{ return c.JSON(structs.NotificationsResponse{
Notifications: notification.GetNotifications(query, userId), Notifications: notification.GetNotifications(query, userId),
TotalPages: utils.GetTotalPages(utils.NotificationsPaginationLimit, TotalPages: rspagination.GetTotalPages(database.DB, utils.NotificationsPaginationLimit,
[]structs.Notification{}, []structs.Notification{},
"user_id = ?", "user_id = ?",
userId), userId),