refactor: вся основа кода в отдельной папке
This commit is contained in:
159
R/modules/global_options.R
Normal file
159
R/modules/global_options.R
Normal file
@@ -0,0 +1,159 @@
|
||||
#' @export
|
||||
#' @description костыли для упрощения работы себе
|
||||
set_global_options = function(
|
||||
SYMBOL_DELIM = "; ",
|
||||
APP.DEBUG = FALSE,
|
||||
shiny.host = "127.0.0.1",
|
||||
shiny.port = 1338,
|
||||
...
|
||||
) {
|
||||
|
||||
config_params_to_check <- c(
|
||||
"form_app_version",
|
||||
"form_id",
|
||||
"form_name",
|
||||
"form_app_configure_path",
|
||||
"form_auth_enabled",
|
||||
"form_schemes"
|
||||
)
|
||||
|
||||
expected_params_in_config <- config_params_to_check %in% names(config::get())
|
||||
if (!all(expected_params_in_config)) {
|
||||
cli::cli_abort(c(
|
||||
"Необходимо добавить в файл конфига {.file config.yml} следующие параметры:",
|
||||
paste0(config_params_to_check[!expected_params_in_config], ":")
|
||||
))
|
||||
}
|
||||
|
||||
options(
|
||||
SYMBOL_DELIM = SYMBOL_DELIM,
|
||||
# form.db_path = config::get("form_db_path"),
|
||||
APP.DEBUG = APP.DEBUG,
|
||||
# APP.FILE_DB = APP.FILE_DB,
|
||||
shiny.host = shiny.host,
|
||||
shiny.port = shiny.port,
|
||||
...
|
||||
)
|
||||
}
|
||||
|
||||
#' @export
|
||||
AUTH_ENABLED <- config::get("form_auth_enabled")
|
||||
|
||||
#' @export
|
||||
check_and_init_scheme = function() {
|
||||
|
||||
cli::cli_inform(c("*" = "проверка схемы..."))
|
||||
|
||||
options(box.path = here::here())
|
||||
box::use(R/modules/db[local_db_backup])
|
||||
|
||||
# список файлов, изменение которых, приведут к переинициализиации схемы
|
||||
files_to_watch <- c(
|
||||
"config.yml",
|
||||
"R/modules/scheme_generator.R",
|
||||
"R/modules/utils.R"
|
||||
)
|
||||
|
||||
# проверка существования отслеживаемых файлов
|
||||
if (!all(file.exists(files_to_watch))) {
|
||||
cli::cli_abort("проверка схем: {files_to_watch[!file.exists(files_to_watch)]} is not exists")
|
||||
}
|
||||
|
||||
scheme_names <- names(config::get()$form_schemes)
|
||||
scheme_file <- paste0(config::get("form_app_configure_path"), "/schemas/", scheme_names, ".xlsx")
|
||||
scheme_file <- stats::setNames(scheme_file, scheme_names)
|
||||
|
||||
if (!all(file.exists(scheme_file))) {
|
||||
cli::cli_abort(c("Отсутствуют файлы схем для следующих наименований:", paste("-", names(scheme_file)[!file.exists(scheme_file)])))
|
||||
}
|
||||
|
||||
db_files <- paste0(config::get("form_app_configure_path"), "/db/", scheme_names, ".sqlite")
|
||||
|
||||
hash_file <- "temp/schema_hash.rds"
|
||||
|
||||
#
|
||||
exist_hash <- tools::md5sum(c(scheme_file, files_to_watch))
|
||||
|
||||
# если первый запуск (нет файла с кешем) инициализация схемы
|
||||
if (!file.exists(hash_file) | !file.exists("temp/scheme.rds") | !all(file.exists(db_files))) {
|
||||
|
||||
init_scheme(scheme_file)
|
||||
|
||||
# в ином случае - проверяем кэш
|
||||
} else {
|
||||
|
||||
saved_hash <- readRDS(hash_file)
|
||||
|
||||
# если данные были изменены проводим реинициализацию таблицы и схемы
|
||||
if (!all(exist_hash == saved_hash)) {
|
||||
|
||||
cli::cli_inform(c(">" = "Данные схем были изменены..."))
|
||||
init_scheme(scheme_file)
|
||||
|
||||
} else {
|
||||
cli::cli_alert_success("изменений нет")
|
||||
}
|
||||
}
|
||||
|
||||
# MAKING BACKUPS
|
||||
if (Sys.getenv("FORM_APP_LOCAL_DB_BACKUP_PATH") != "") {
|
||||
cli::cli_inform(c("*" = "создание бэкапов баз данных..."))
|
||||
purrr::walk(scheme_names, local_db_backup)
|
||||
|
||||
}
|
||||
|
||||
# перезаписываем файл
|
||||
if (!dir.exists("temp")) dir.create("temp")
|
||||
saveRDS(exist_hash, hash_file)
|
||||
}
|
||||
|
||||
init_scheme = function(scheme_file) {
|
||||
|
||||
options(box.path = here::here())
|
||||
box::use(
|
||||
R/modules/db,
|
||||
R/modules/scheme_generator[scheme_R6]
|
||||
)
|
||||
|
||||
db_path <- fs::path(config::get("form_app_configure_path"), "db")
|
||||
if (!dir.exists(db_path)) dir.create(db_path)
|
||||
|
||||
cli::cli_h1("Инициализация схемы")
|
||||
|
||||
schms <- purrr::map2(
|
||||
.x = scheme_file,
|
||||
.y = names(scheme_file),
|
||||
\(x, y) {
|
||||
|
||||
con <- db$make_db_connection(y)
|
||||
on.exit(db$close_db_connection(con), add = TRUE)
|
||||
|
||||
# новый объект
|
||||
schm <- scheme_R6$new(x)
|
||||
|
||||
# проверка схемы с существующей базой данных и инициализация таблиц
|
||||
db$check_if_table_is_exist_and_init_if_not(schm, con)
|
||||
|
||||
# удаление орфанных записей
|
||||
|
||||
db$db_clean_orphans(schm = schm, con = con)
|
||||
schm
|
||||
}
|
||||
)
|
||||
|
||||
# проверка на наличие дублирующихся названий вложенных таблиц
|
||||
nested_tables_ids <- purrr::map(
|
||||
names(schms),
|
||||
\(x) schms[[x]]$nested_tables_names
|
||||
)
|
||||
|
||||
nested_tables_ids <- unlist(nested_tables_ids)
|
||||
tab <- table(nested_tables_ids)
|
||||
|
||||
# если встречается хоть одно значение несколько раз - начать истошно кричать (могут возникнуть пробемы при вызове всплывающих окон в формах)
|
||||
if (!all(!tab > 1)) {
|
||||
cli::cli_abort(c("В одной или нескольких схемах наименования вложенных форм совпадают:", paste("-", names(tab)[tab > 1])))
|
||||
}
|
||||
|
||||
saveRDS(schms, "temp/scheme.rds")
|
||||
}
|
||||
Reference in New Issue
Block a user