This commit is contained in:
che
2026-07-27 10:51:18 +05:00
parent 560b3fe44e
commit c1b24206b9
13 changed files with 405 additions and 226 deletions
+124 -14
View File
@@ -9,6 +9,7 @@ use che_tauri::{
TauriApi,
};
use tauri::Manager;
use tauri_plugin_opener::OpenerExt;
use crate::sync::SyncContractsResult;
@@ -256,23 +257,76 @@ async fn sync_contracts(
}
#[tauri::command]
async fn load_application_file(local_path: String, scan_url: String) -> Result<Vec<u8>, ApiError> {
if !local_path.is_empty() {
match tokio::fs::metadata(&local_path).await {
Ok(metadata) if metadata.len() > 0 => {
return tokio::fs::read(&local_path)
async fn load_remote_file(
app: tauri::AppHandle,
api: tauri::State<'_, TauriApi>,
url: String,
) -> Result<Vec<u8>, ApiError> {
let path = cache_remote_file(&app, &api, &url).await?;
tokio::fs::read(path)
.await
.map_err(|error| ApiError::new("file_error", error.to_string()));
}
Ok(_) | Err(_) => {}
}
}
.map_err(|error| ApiError::new("file_error", error.to_string()))
}
if scan_url.is_empty() {
#[tauri::command]
async fn ensure_remote_file(
app: tauri::AppHandle,
api: tauri::State<'_, TauriApi>,
url: String,
) -> Result<String, ApiError> {
let path = cache_remote_file(&app, &api, &url).await?;
Ok(path.to_string_lossy().into_owned())
}
#[tauri::command]
async fn open_remote_file(
app: tauri::AppHandle,
api: tauri::State<'_, TauriApi>,
url: String,
) -> Result<(), ApiError> {
let path = cache_remote_file(&app, &api, &url).await?;
app.opener()
.open_path(path.to_string_lossy().into_owned(), None::<&str>)
.map_err(|error| ApiError::new("file_error", error.to_string()))
}
async fn cache_remote_file(
app: &tauri::AppHandle,
api: &tauri::State<'_, TauriApi>,
url: &str,
) -> Result<PathBuf, ApiError> {
if url.trim().is_empty() {
return Err(ApiError::new("file_error", "Файл недоступен"));
}
let response = reqwest::Client::new().get(&scan_url).send().await?;
let remote = api.state().remote_config().ok_or_else(|| {
ApiError::bad_request("load_remote_file requires [remote].base_url config")
})?;
let file_url = normalize_remote_file_url(&remote.base_url, url)?;
let relative_path = remote_file_cache_path(file_url.path())?;
let app_data_dir = app
.path()
.app_data_dir()
.map_err(|error| ApiError::new("file_error", error.to_string()))?;
let path = app_data_dir.join("remote_files").join(relative_path);
match tokio::fs::metadata(&path).await {
Ok(metadata) if metadata.len() > 0 => {
return Ok(path);
}
Ok(_) | Err(_) => {}
}
let token = api
.state()
.auth_token()
.ok_or_else(|| ApiError::new("not_authenticated", "authentication token is missing"))?;
let response = reqwest::Client::new()
.get(file_url)
.header(reqwest::header::AUTHORIZATION, format!("Token {token}"))
.send()
.await?;
if !response.status().is_success() {
return Err(ApiError::new(
"remote_error",
@@ -285,7 +339,61 @@ async fn load_application_file(local_path: String, scan_url: String) -> Result<V
return Err(ApiError::new("file_error", "Файл пустой"));
}
Ok(bytes.to_vec())
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|error| ApiError::new("file_error", error.to_string()))?;
}
tokio::fs::write(&path, &bytes)
.await
.map_err(|error| ApiError::new("file_error", error.to_string()))?;
Ok(path)
}
fn normalize_remote_file_url(base_url: &str, url: &str) -> Result<reqwest::Url, ApiError> {
if let Ok(parsed) = reqwest::Url::parse(url.trim()) {
return Ok(parsed);
}
let base = reqwest::Url::parse(&format!("{}/", base_url.trim_end_matches('/')))
.map_err(|error| ApiError::new("file_error", error.to_string()))?;
base.join(url.trim_start_matches('/'))
.map_err(|error| ApiError::new("file_error", error.to_string()))
}
fn remote_file_cache_path(url_path: &str) -> Result<PathBuf, ApiError> {
let mut path = PathBuf::new();
for segment in url_path.split('/') {
if segment.is_empty() || segment == "." || segment == ".." {
continue;
}
path.push(sanitize_path_segment(segment));
}
if path.as_os_str().is_empty() {
Err(ApiError::new("file_error", "URL не содержит имя файла"))
} else {
Ok(path)
}
}
fn sanitize_path_segment(segment: &str) -> String {
let sanitized = segment
.chars()
.map(|character| match character {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
_ => character,
})
.collect::<String>();
if sanitized.is_empty() {
"file".to_string()
} else {
sanitized
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
@@ -323,7 +431,9 @@ pub fn run() {
reset_app_settings,
current_employee,
sync_contracts,
load_application_file
load_remote_file,
ensure_remote_file,
open_remote_file
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
+3 -73
View File
@@ -158,7 +158,7 @@ struct RemoteEmployee {
pub async fn sync_contracts(
api: &TauriApi,
app_data_dir: PathBuf,
_app_data_dir: PathBuf,
) -> Result<SyncContractsResult, ApiError> {
let state = api.state();
let token = state
@@ -205,12 +205,9 @@ pub async fn sync_contracts(
fetch_contract_detail(&client, &token, &remote.base_url, contract.id).await?;
for application in &detail.contractapplicationfile_set {
let local_path =
download_application_file(&client, &token, &app_data_dir, application).await?;
upsert_contract_application_file(api, contract.id, application, &local_path)
.await?;
upsert_contract_application_file(api, contract.id, application, "").await?;
applications += 1;
if !local_path.is_empty() {
if !application.scan.is_empty() {
files_downloaded += 1;
}
}
@@ -324,69 +321,6 @@ async fn fetch_contract_detail(
Ok(response.json::<RemoteContractDetail>().await?)
}
async fn download_application_file(
client: &reqwest::Client,
token: &str,
app_data_dir: &PathBuf,
application: &RemoteContractApplicationFile,
) -> Result<String, ApiError> {
if application.scan.is_empty() {
return Ok(String::new());
}
let directory = application_download_dir(app_data_dir);
tokio::fs::create_dir_all(&directory)
.await
.map_err(file_error)?;
let file_name = format!(
"{}_{}",
application.id,
sanitize_file_name(&application.scan_name)
);
let path = directory.join(file_name);
let response = client
.get(&application.scan)
.header(reqwest::header::AUTHORIZATION, format!("Token {token}"))
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let detail = response.text().await.unwrap_or_default();
return Err(ApiError::new(
"remote_error",
format!("file download failed with {status}: {detail}"),
));
}
let bytes = response.bytes().await?;
tokio::fs::write(&path, bytes).await.map_err(file_error)?;
Ok(path.to_string_lossy().into_owned())
}
fn application_download_dir(app_data_dir: &PathBuf) -> PathBuf {
app_data_dir.join("contract_applications")
}
fn sanitize_file_name(file_name: &str) -> String {
let sanitized = file_name
.chars()
.map(|character| match character {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
_ => character,
})
.collect::<String>();
if sanitized.is_empty() {
"application_file".to_string()
} else {
sanitized
}
}
async fn upsert_contract_dependencies(
api: &TauriApi,
contract: &RemoteContract,
@@ -604,7 +538,3 @@ async fn upsert_contract_application_file(
fn database_error(error: sqlx::Error) -> ApiError {
ApiError::new("database_error", error.to_string())
}
fn file_error(error: impl std::fmt::Display) -> ApiError {
ApiError::new("file_error", error.to_string())
}
@@ -55,6 +55,7 @@ watch(search, (value) => {
<van-button size="small" type="primary" plain @click="selectCategory(0)">Все</van-button>
</div>
<div class="entity-popup-body">
<van-search v-model="search" placeholder="Поиск по категории" />
<van-loading v-if="loading" class="entity-state" type="spinner">Загрузка...</van-loading>
@@ -78,13 +79,18 @@ watch(search, (value) => {
<van-empty v-if="categories.length === 0" description="Категории не найдены" />
</template>
</div>
</van-popup>
</template>
<style scoped>
.entity-popup {
min-height: 55vh;
padding: 18px 0 28px;
display: flex;
flex-direction: column;
height: 70vh;
max-height: 70vh;
overflow: hidden;
padding: 18px 0 16px;
}
.entity-popup-header {
@@ -106,6 +112,12 @@ watch(search, (value) => {
padding: 36px 0;
}
.entity-popup-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.entity-select {
display: flex;
align-items: center;
@@ -58,6 +58,7 @@ watch(search, (value) => {
<van-button size="small" type="primary" plain @click="selectCounterparty(0)">Все</van-button>
</div>
<div class="counterparty-popup-body">
<van-search v-model="search" placeholder="Поиск по имени" />
<van-loading v-if="loading" class="counterparty-state" type="spinner">Загрузка...</van-loading>
@@ -85,13 +86,18 @@ watch(search, (value) => {
<van-empty v-if="counterparties.length === 0" description="Контрагенты не найдены" />
</template>
</div>
</van-popup>
</template>
<style scoped>
.counterparty-popup {
min-height: 55vh;
padding: 18px 0 28px;
display: flex;
flex-direction: column;
height: 70vh;
max-height: 70vh;
overflow: hidden;
padding: 18px 0 16px;
}
.counterparty-popup-header {
@@ -113,6 +119,12 @@ watch(search, (value) => {
padding: 36px 0;
}
.counterparty-popup-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.counterparty-select {
display: flex;
align-items: center;
+14 -2
View File
@@ -53,6 +53,7 @@ watch(search, (value) => {
<van-button size="small" type="primary" plain @click="selectFrc(0)">Все</van-button>
</div>
<div class="entity-popup-body">
<van-search v-model="search" placeholder="Поиск по названию" />
<van-loading v-if="loading" class="entity-state" type="spinner">Загрузка...</van-loading>
@@ -76,13 +77,18 @@ watch(search, (value) => {
<van-empty v-if="frcs.length === 0" description="ФРЦ не найдены" />
</template>
</div>
</van-popup>
</template>
<style scoped>
.entity-popup {
min-height: 55vh;
padding: 18px 0 28px;
display: flex;
flex-direction: column;
height: 70vh;
max-height: 70vh;
overflow: hidden;
padding: 18px 0 16px;
}
.entity-popup-header {
@@ -104,6 +110,12 @@ watch(search, (value) => {
padding: 36px 0;
}
.entity-popup-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.entity-select {
display: flex;
align-items: center;
+9 -11
View File
@@ -7,10 +7,9 @@ import {
type PDFDocumentProxy,
type RenderTask,
} from "pdfjs-dist";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, ref, shallowRef, watch } from "vue";
const props = defineProps<{
localPath: string;
scanUrl: string;
title: string;
}>();
@@ -23,7 +22,7 @@ GlobalWorkerOptions.workerSrc = new URL(
).toString();
const canvasRef = ref<HTMLCanvasElement | null>(null);
const pdfDocument = ref<PDFDocumentProxy | null>(null);
const pdfDocument = shallowRef<PDFDocumentProxy | null>(null);
const loading = ref(false);
const error = ref("");
const pageNumber = ref(1);
@@ -41,19 +40,17 @@ async function loadDocument() {
loading.value = true;
error.value = "";
let task: PDFDocumentLoadingTask | null = null;
try {
const bytes = await invoke<number[]>("load_application_file", {
localPath: props.localPath,
scanUrl: props.scanUrl,
const bytes = await invoke<number[]>("load_remote_file", {
url: props.scanUrl,
});
if (!bytes.length) {
throw new Error("Файл пустой");
}
task = getDocument({ data: new Uint8Array(bytes) });
const task = getDocument({ data: new Uint8Array(bytes) });
loadingTask = task;
const document = await task.promise;
@@ -66,12 +63,13 @@ async function loadDocument() {
pageCount.value = document.numPages;
pageNumber.value = 1;
scale.value = 1.1;
loading.value = false;
await nextTick();
await renderPage();
} catch (err) {
error.value = err instanceof Error ? err.message : "Не удалось открыть PDF";
} finally {
loading.value = false;
if (task && loadingTask === task) {
if (loadingTask) {
loadingTask = null;
}
}
@@ -156,7 +154,7 @@ async function zoomOut() {
await renderPage();
}
watch([show, () => props.localPath, () => props.scanUrl], async ([visible]) => {
watch([show, () => props.scanUrl], async ([visible]) => {
if (visible) {
await nextTick();
await loadDocument();
@@ -57,6 +57,7 @@ watch(search, (value) => {
<van-button size="small" type="primary" plain @click="selectProject(0)">Все</van-button>
</div>
<div class="entity-popup-body">
<van-search v-model="search" placeholder="Поиск по проекту" />
<van-loading v-if="loading" class="entity-state" type="spinner">Загрузка...</van-loading>
@@ -80,13 +81,18 @@ watch(search, (value) => {
<van-empty v-if="projects.length === 0" description="Проекты не найдены" />
</template>
</div>
</van-popup>
</template>
<style scoped>
.entity-popup {
min-height: 55vh;
padding: 18px 0 28px;
display: flex;
flex-direction: column;
height: 70vh;
max-height: 70vh;
overflow: hidden;
padding: 18px 0 16px;
}
.entity-popup-header {
@@ -108,6 +114,12 @@ watch(search, (value) => {
padding: 36px 0;
}
.entity-popup-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.entity-select {
display: flex;
align-items: center;
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { openPath, openUrl } from "@tauri-apps/plugin-opener";
import { invoke } from "@tauri-apps/api/core";
import { openUrl } from "@tauri-apps/plugin-opener";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showToast } from "vant";
@@ -173,14 +174,16 @@ function formatMoney(value: unknown) {
}).format(amount);
}
async function openApplicationFile(localPath: string) {
if (!localPath) {
async function openApplicationFile(scanUrl: string) {
if (!scanUrl) {
showToast("Файл не скачан");
return;
}
try {
await openPath(localPath);
await invoke("open_remote_file", {
url: scanUrl,
});
} catch (err) {
showToast(errorMessage(err, "Не удалось открыть файл"));
}
@@ -209,6 +212,10 @@ function openPdfPreview(file: ContractApplicationFile) {
}
function errorMessage(err: unknown, fallback: string) {
if (typeof err === "object" && err && "detail" in err) {
return String((err as { detail: unknown }).detail);
}
if (err instanceof Error) {
return err.message;
}
@@ -435,7 +442,7 @@ onMounted(() => {
size="small"
type="primary"
plain
:disabled="!file.local_path"
:disabled="!file.scan_url"
@click="openPdfPreview(file)"
>
Просмотр
@@ -443,8 +450,8 @@ onMounted(() => {
<van-button
size="small"
plain
:disabled="!file.local_path"
@click="openApplicationFile(file.local_path)"
:disabled="!file.scan_url"
@click="openApplicationFile(file.scan_url)"
>
Открыть
</van-button>
@@ -507,7 +514,6 @@ onMounted(() => {
<PdfPreview
v-model:show="pdfPreviewVisible"
:local-path="pdfPreviewFile?.local_path ?? ''"
:scan-url="pdfPreviewFile?.scan_url ?? ''"
:title="pdfPreviewTitle"
/>
@@ -2,6 +2,7 @@
import { computed, ref, watch } from "vue";
import { employeeApi } from "../../../generated/api";
import type { EmployeeListParams } from "../../../generated/models";
import RemoteImage from "../../../shared/components/RemoteImage.vue";
import { useModelApi } from "../../../shared/composables/useModelApi";
const PAGE_SIZE = 20;
@@ -58,6 +59,7 @@ watch(search, (value) => {
<van-button size="small" type="primary" plain @click="selectEmployee(0)">Не указан</van-button>
</div>
<div class="employee-popup-body">
<van-search v-model="search" placeholder="Поиск по имени" />
<van-loading v-if="loading" class="employee-state" type="spinner">Загрузка...</van-loading>
@@ -74,7 +76,7 @@ watch(search, (value) => {
@click="selectEmployee(employee.id)"
>
<template #icon>
<van-image class="employee-avatar" round width="36" height="36" :src="employee.avatar_small ?? ''" />
<RemoteImage class="employee-avatar" round width="36" height="36" :src="employee.avatar_small" />
</template>
<template #right-icon>
<van-icon v-if="selectedEmployeeId === employee.id" name="success" color="#1989fa" />
@@ -84,13 +86,18 @@ watch(search, (value) => {
<van-empty v-if="employees.length === 0" description="Сотрудники не найдены" />
</template>
</div>
</van-popup>
</template>
<style scoped>
.employee-popup {
min-height: 55vh;
padding: 18px 0 28px;
display: flex;
flex-direction: column;
height: 70vh;
max-height: 70vh;
overflow: hidden;
padding: 18px 0 16px;
}
.employee-popup-header {
@@ -116,6 +123,12 @@ watch(search, (value) => {
padding: 36px 0;
}
.employee-popup-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.employee-select {
display: flex;
align-items: center;
+2 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { Task } from "../../../generated/models";
import RemoteImage from "../../../shared/components/RemoteImage.vue";
type TaskItem = Task;
@@ -25,7 +26,7 @@ const emit = defineEmits<{
@click="emit('open', `/tasks/${props.item.id}`)"
>
<template #icon>
<van-image
<RemoteImage
class="task-avatar"
round
width="36"
+2 -1
View File
@@ -2,6 +2,7 @@
import { computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { taskApi } from "../../../generated/api";
import RemoteImage from "../../../shared/components/RemoteImage.vue";
import { useModelApi } from "../../../shared/composables/useModelApi";
const route = useRoute();
@@ -93,7 +94,7 @@ onMounted(() => {
<div v-else class="message-list">
<article v-for="message in task.message_set" :key="message.id" class="message-item">
<van-image class="message-avatar" round width="40" height="40" :src="message.author.avatar_small ?? ''" />
<RemoteImage class="message-avatar" round width="40" height="40" :src="message.author.avatar_small" />
<div class="message-bubble">
<div class="message-author">{{ personName(message.author) }}</div>
<div class="message-text">{{ message.text }}</div>
+15
View File
@@ -0,0 +1,15 @@
<script setup lang="ts">
import { computed } from "vue";
import { useRemoteFileUrl } from "../composables/useRemoteFileUrl";
const props = defineProps<{
src?: string | null;
}>();
const sourceUrl = computed(() => props.src);
const { objectUrl } = useRemoteFileUrl(sourceUrl);
</script>
<template>
<van-image v-bind="$attrs" :src="objectUrl" />
</template>
@@ -0,0 +1,57 @@
import { invoke } from "@tauri-apps/api/core";
import { onBeforeUnmount, ref, watch, type Ref } from "vue";
export function useRemoteFileUrl(sourceUrl: Ref<string | null | undefined>) {
const objectUrl = ref("");
const loading = ref(false);
const error = ref("");
let loadId = 0;
async function load(url: string | null | undefined) {
const currentLoadId = ++loadId;
revokeObjectUrl();
error.value = "";
if (!url) {
loading.value = false;
return;
}
loading.value = true;
try {
const bytes = await invoke<number[]>("load_remote_file", { url });
if (currentLoadId !== loadId) {
return;
}
objectUrl.value = URL.createObjectURL(new Blob([new Uint8Array(bytes)]));
} catch (err) {
if (currentLoadId !== loadId) {
return;
}
error.value = err instanceof Error ? err.message : "Не удалось загрузить файл";
} finally {
if (currentLoadId === loadId) {
loading.value = false;
}
}
}
function revokeObjectUrl() {
if (objectUrl.value) {
URL.revokeObjectURL(objectUrl.value);
objectUrl.value = "";
}
}
watch(sourceUrl, (url) => void load(url), { immediate: true });
onBeforeUnmount(revokeObjectUrl);
return {
objectUrl,
loading,
error,
};
}