Skip to content

Commit

Permalink
Заготовка магазина и рабочие фильтры
Browse files Browse the repository at this point in the history
  • Loading branch information
Zamelane committed Dec 3, 2024
1 parent aa4f2bd commit 2a0c89b
Show file tree
Hide file tree
Showing 30 changed files with 675 additions and 260 deletions.
2 changes: 2 additions & 0 deletions apps/api/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,5 @@ package-lock.json
# IDE files
/.idea

#uploads
src/uploads/avatars
3 changes: 3 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
"dependencies": {
"@diary-spo/crypto": "workspace:*",
"@elysiajs/cors": "^1.1.1",
"@elysiajs/static": "^1.1.1",
"@types/cli-progress": "^3.11.6",
"@types/node-telegram-bot-api": "^0.64.7",
"cache-manager": "^5.7.6",
"cli-progress": "^3.12.0",
"elysia": "1.1.21",
"elysia-compression": "^0.0.7",
"elysia-helmet": "^2.0.0",
Expand Down
108 changes: 108 additions & 0 deletions apps/api/src/helpers/syncDatabaseForDecorations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import {AvatarModel} from "../models/Avatar";
import {readdir} from "node:fs/promises";
import cliProgress from "cli-progress"
import {AvatarTagModel} from "../models/AvatarTag";
import {TagModel} from "../models/Tag";

const pathToDecorationsFile = 'src/uploads/decorations.json'
const pathToAvatars = 'src/uploads/avatars'

interface Content {
avatars: AvatarContent[]
}

interface AvatarContent {
isAnimated: boolean
filename: string
tags: string[]
price: number
}

export const syncDatabaseForDecorations = async () => {
console.log('Обновляю декорации в базе данных...')

let progress = 0
const progressBar = new cliProgress.SingleBar({
format: ' {bar} | {filename} | {value}/{total}'
}, cliProgress.Presets.shades_classic)

const file = Bun.file(pathToDecorationsFile)

if (!await file.exists()) {
console.log('Файл декораций не найден. Пропускаю ...')
return
}

const contents: Content = await file.json()
const avatarFiles = await readdir(pathToAvatars)

progressBar.start(avatarFiles.length, progress)

for (const avatarFile of avatarFiles) {
progressBar.increment(1, {filename: avatarFile})
const avatarToSave = {
filename: avatarFile,
isAnimated: avatarFile.endsWith('.gif'),
price: 1000
}

let tags: string[] = []

// Пробуем найти, переопределена ли цена и статус анимации
for (const avatarInfo of contents.avatars) {
if (avatarInfo.filename !== avatarFile)
continue
avatarToSave.isAnimated = avatarInfo.isAnimated
avatarToSave.price = avatarInfo.price
tags = avatarInfo.tags
break
}

// Находим или создаём модель
const avatarModel = await AvatarModel.findOrCreate({
where: {
filename: avatarFile,
},
defaults: avatarToSave
})

// Проверяем наличие тегов
if (!tags)
await AvatarTagModel.destroy({
where: {
avatarId: avatarModel[0].id
}
})
else
for (const tag of tags) {
const tagModel = await TagModel.findOrCreate({
where: {
value: tag
},
defaults: {
value: tag
}
})
await AvatarTagModel.findOrCreate({
where: {
avatarId: avatarModel[0].id,
tagId: tagModel[0].id
},
defaults: {
avatarId: avatarModel[0].id,
tagId: tagModel[0].id
}
})
}

// Если создана - то завершаем цикл
if (avatarModel[1])
continue

await avatarModel[0].update(avatarToSave)
}

progressBar.stop()

console.log('Обновил все декорации')
}
8 changes: 8 additions & 0 deletions apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { getTimezone } from './config/getTimeZone'
import { routes } from './routes'

import './models/relations'
import staticPlugin from "@elysiajs/static";
import {syncDatabaseForDecorations} from "./helpers/syncDatabaseForDecorations";

// настраиваем сервер...
const port = Bun.env.PORT ?? 3003
Expand Down Expand Up @@ -53,6 +55,10 @@ const app = new Elysia()
contentSecurityPolicy: false
})
)
.use(staticPlugin({
assets: 'src/uploads',
prefix: 'uploads'
}))
.use(routes)
.listen(port)

Expand All @@ -69,6 +75,8 @@ console.log(
}.`
)

await syncDatabaseForDecorations()

export type App = typeof app
const workerURL = new URL('worker', import.meta.url).href
new Worker(workerURL)
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/models/Avatar/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './model'
42 changes: 42 additions & 0 deletions apps/api/src/models/Avatar/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { DataTypes } from 'sequelize'

import { cache, enableCache, sequelize } from '@db'

import { SPOModel } from '../SPO'
import type { IModelPrototype } from '../types'

// REMOVE IT
// ?
export type AvatarModelType = {
id: bigint
filename: string
price: number
isAnimated: boolean
}

export type IAvatarModelType = IModelPrototype<AvatarModelType, 'id'>

const avatarModel = sequelize.define<IAvatarModelType>('avatar', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true
},
filename: {
type: DataTypes.STRING(35),
allowNull: false
},
price: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 1000
},
isAnimated: {
type: DataTypes.BOOLEAN,
allowNull: false
}
})

export const AvatarModel = enableCache
? cache.init<IAvatarModelType>(avatarModel)
: avatarModel
1 change: 1 addition & 0 deletions apps/api/src/models/AvatarTag/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './model'
40 changes: 40 additions & 0 deletions apps/api/src/models/AvatarTag/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { DataTypes } from 'sequelize'

import { cache, enableCache, sequelize } from '@db'

import { SPOModel } from '../SPO'
import type {IModelPrototype, IModelPrototypeNoId} from '../types'
import {AvatarModel} from "../Avatar";
import {TagModel} from "../Tag";

// REMOVE IT
// ?
export type AvatarTagModelType = {
avatarId: bigint
tagId: bigint
}

export type IAvatarTagModelType = IModelPrototypeNoId<AvatarTagModelType>

const avatarTagModel = sequelize.define<IAvatarTagModelType>('avatarTag', {
avatarId: {
type: DataTypes.BIGINT,
primaryKey: true,
allowNull: false,
references: {
model: AvatarModel
}
},
tagId: {
type: DataTypes.BIGINT,
primaryKey: true,
allowNull: false,
references: {
model: TagModel
}
}
})

export const AvatarTagModel = enableCache
? cache.init<IAvatarTagModelType>(avatarTagModel)
: avatarTagModel
9 changes: 9 additions & 0 deletions apps/api/src/models/DiaryUser/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { formatDate } from '@utils'

import { GroupModel } from '../Group'
import type { IModelPrototype } from '../types'
import {AvatarModel} from "../Avatar";

// REMOVE IT
// ?
Expand All @@ -26,6 +27,7 @@ export type DiaryUserModelType = {
termStartDate?: Nullable<string>
isAdmin: boolean
idFromDiary: number
avatarId: bigint
}

export type IDiaryUserModel = IModelPrototype<DiaryUserModelType, 'id'>
Expand Down Expand Up @@ -125,6 +127,13 @@ export const DiaryUserModel = sequelize.define<IDiaryUserModel>('diaryUser', {
defaultValue: false,
comment: 'Признак администратора'
},
avatarId: {
type: DataTypes.BIGINT,
allowNull: true,
references: {
model: AvatarModel
}
},
idFromDiary: {
type: DataTypes.INTEGER,
allowNull: false,
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/models/Tag/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './model'
33 changes: 33 additions & 0 deletions apps/api/src/models/Tag/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DataTypes } from 'sequelize'

import { cache, enableCache, sequelize } from '@db'

import { SPOModel } from '../SPO'
import type { IModelPrototype } from '../types'
import {AvatarModel} from "../Avatar";

// REMOVE IT
// ?
export type TagModelType = {
id: bigint
value: string
}

export type ITagModelType = IModelPrototype<TagModelType, 'id'>

const tagModel = sequelize.define<ITagModelType>('tag', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
value: {
type: DataTypes.STRING,
allowNull: false
}
})

export const TagModel = enableCache
? cache.init<ITagModelType>(tagModel)
: tagModel
1 change: 1 addition & 0 deletions apps/api/src/models/UserAvatar/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './model'
38 changes: 38 additions & 0 deletions apps/api/src/models/UserAvatar/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { DataTypes } from 'sequelize'

import { cache, enableCache, sequelize } from '@db'

import { SPOModel } from '../SPO'
import type {IModelPrototype, IModelPrototypeNoId} from '../types'
import {AvatarModel} from "../Avatar";
import {DiaryUserModel} from "../DiaryUser";

// REMOVE IT
// ?
export type UserAvatarModelType = {
avatarId: bigint
diaryUserId: bigint
}

export type IUserAvatarModelType = IModelPrototypeNoId<UserAvatarModelType>

const userAvatarModel = sequelize.define<IUserAvatarModelType>('userAvatar', {
avatarId: {
type: DataTypes.BIGINT,
references: {
model: AvatarModel
},
allowNull: false
},
diaryUserId: {
type: DataTypes.BIGINT,
references: {
model: DiaryUserModel
},
allowNull: false
}
})

export const UserAvatarModel = enableCache
? cache.init<IUserAvatarModelType>(userAvatarModel)
: userAvatarModel
23 changes: 22 additions & 1 deletion apps/api/src/models/relations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import { TermSubjectExaminationTypeModel } from './TermSubjectExaminationType'
import { TermTypeModel } from './TermType'
import { TermUserModel } from './TermUser'
import { ThemeModel } from './Theme'
import {AvatarModel} from "./Avatar";
import {UserAvatarModel} from "./UserAvatar";
import {AvatarTagModel} from "./AvatarTag";
import {TagModel} from "./Tag";

// SPO <--->> Group
SPOModel.hasMany(GroupModel)
Expand Down Expand Up @@ -193,10 +197,27 @@ TermSubjectModel.belongsTo(TeacherModel)
DiaryUserModel.hasMany(TermSubjectModel)
TermSubjectModel.belongsTo(DiaryUserModel)

// DiaryUser <-->> Subscribe
DiaryUserModel.hasMany(SubscribeModel)
SubscribeModel.belongsTo(DiaryUserModel)

// Avatar <-->> UserAvatar
AvatarModel.hasMany(UserAvatarModel)
UserAvatarModel.belongsTo(AvatarModel)

// Avatar <-->> DiaryUser
AvatarModel.hasMany(DiaryUserModel)
DiaryUserModel.belongsTo(AvatarModel)

// Avatar <-->> AvatarTag
AvatarModel.hasMany(AvatarTagModel)
AvatarTagModel.belongsTo(AvatarModel)

// Tag <-->> AvatarTag
TagModel.hasMany(AvatarTagModel)
AvatarTagModel.belongsTo(TagModel)

if (forceSyncDatabase) {
console.log('Syncing database...')
await sequelize.sync({ alter: true })
await sequelize.sync()
}
Loading

0 comments on commit 2a0c89b

Please sign in to comment.