Skip to content

Commit

Permalink
feat: добавить disabled для кнопок удаления заметок
Browse files Browse the repository at this point in the history
- Дефолтно кнопки удаления заметки теперь заблокированы
- В начале отображения логов, теперь отображаеться размер файла в киллобайтах
  • Loading branch information
A-V-tor committed Oct 1, 2023
1 parent fb299af commit c7d44c7
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
- по пути `project/adminpanel/static/admin/js` создать файл `.env.json` по аналогии с `env.json.example`
```
{
"notesUrl": "http://localhost:5000/all-notes", // ендпоинт заметок
"notesUrl": "http://localhost:5000/api/all-notes", // ендпоинт заметок
"botLogsUrl": "http://localhost:5000/api/bot-logs",
"flaskLogsUrl": "http://localhost:5000/api/flask-logs",
"authorizationKey": "1234567" // ключ для для запросов к API # должен совпадать со знчением "AUTHORIZATION_KEY"
Expand Down
4 changes: 2 additions & 2 deletions project/adminpanel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def logout():
def pageNot(error):
date = datetime.now()
logger.error(
f'{date} !!! Запрос с ip {request.access_route[0]} на не существующий адрес {request.url}\n'
f'{date} Запрос с ip {request.access_route[0]} на не существующий адрес {request.url}\n'
)
return 'Адрес не существует'

Expand All @@ -123,7 +123,7 @@ def pageNot(error):
def notAllowed(error):
date = datetime.now()
logger.error(
f'{date} !!! Запрос с ip {request.access_route[0]} на запрещенный адрес {request.url}\n'
f'{date} ❗️ Запрос с ip {request.access_route[0]} на запрещенный адрес {request.url}\n'
)
return redirect('https://www.google.com/')

Expand Down
7 changes: 5 additions & 2 deletions project/adminpanel/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def all_notes():
try:
id_ = request.get_json()['id']
db.delete(all_notes[int(id_) - 1])
db.commit()
return {'message': 'Entry successfully deleted'}, 200

except Exception as e:
Expand Down Expand Up @@ -56,6 +57,7 @@ def get_flask_logs():
return {'message': 'No access'}, 405

try:
size_kb = os.path.getsize('flask-logs.log') * 0.001
with open('flask-logs.log') as f:
lines = f.readlines()

Expand All @@ -64,7 +66,7 @@ def get_flask_logs():

# преобразуем обратно в строку
reversed_content = ''.join(reversed_lines)
return reversed_content
return str(size_kb) + ' Килобайт\n\n' + reversed_content
except FileNotFoundError:
return 'Файл не найден'

Expand All @@ -79,10 +81,11 @@ def get_bot_logs():
return {'message': 'No access'}, 405

try:
size_kb = os.path.getsize('bot.log') * 0.001
with open('bot.log') as f:
lines = f.readlines()
reversed_lines = reversed(lines)
reversed_content = ''.join(reversed_lines)
return reversed_content
return str(size_kb) + ' Килобайт\n\n' + reversed_content
except FileNotFoundError:
return 'Файл не найден'
43 changes: 43 additions & 0 deletions project/adminpanel/static/admin/css/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ a:focus {
position: relative;
transition-duration: 300ms; /* анимация */
}

.switch-btn::after {
content: "";
height: 36px; /* высота кнопки */
Expand All @@ -109,14 +110,56 @@ a:focus {
position: absolute;
z-index: 1;
}

.switch-on {
background: #fff;
box-shadow: inset 0 0 10px 0 #999999; /* тень */
}

.switch-on::after {
left: 30px;
background: #31A0EA;
}

.switch-btn-2 {
display: inline-block;
width: 40px; /* ширина переключателя */
height: 14px; /* высота переключателя */
border-radius: 12px; /* радиус скругления */
background: #bfbfbf; /* цвет фона */
z-index: 0;
margin: 0;
padding: 0;
border: none;
cursor: pointer;
position: relative;
transition-duration: 300ms; /* анимация */
}

.switch-btn-2::after {
content: "";
height: 25px; /* высота кнопки */
width: 25px; /* ширина кнопки */
border-radius: 18px; /* радиус кнопки */
background: grey; /* цвет кнопки */
top: -7px; /* положение кнопки по вертикали относительно основы */
left: -6px; /* положение кнопки по горизонтали относительно основы */
transition-duration: 300ms; /* анимация */
box-shadow: 0 0 10px 0 #999999; /* тень */
position: absolute;
z-index: 1;
}

.switch-on-2{
background: #fff;
box-shadow: inset 0 0 10px 0 #999999; /* тень */
}

.switch-on-2::after {
left: 30px;
background: #E70A0A;
}

.position-switch {bottom: 4%;right: 10%;position: absolute;}


30 changes: 28 additions & 2 deletions project/adminpanel/static/admin/js/script-admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ const App = {
valueForNote: '',
notes: [],
notesUrl: json.notesUrl,
authorizationKey: json.authorizationKey
authorizationKey: json.authorizationKey,
getBt: true,
activeButtons: [], // массив булевых для блокировки кнопок
buttonClasses: [] // классы для отображения переключателя блокировки кнопки "Удалить"
}
},
created() {
// запрос списка заметок
this.get_data_notes().then((data) => {
this.notes = data;
this.fillListBtDisabled()
}).catch((error) => {
console.error('Ошибка при получении данных:', error);
});
Expand Down Expand Up @@ -73,6 +77,7 @@ const App = {
},
async delNote(indx) {
this.notes.splice(indx++, 1)
this.makeSwitchDisabled(indx-1)
try {
const res = await fetch(this.notesUrl, {
method: 'DELETE',
Expand Down Expand Up @@ -120,7 +125,28 @@ const App = {
} catch (error) {
return []; // Возвращаем пустой массив в случае ошибки
}
},
},
makeSwitchDisabled(indx) {
// переключение доступности кнопки "Удалить"
if (this.buttonClasses[indx] === 'switch-on-2') {
this.buttonClasses[indx] = '' // отображение блокировки
} else {
this.buttonClasses[indx] = 'switch-on-2' // отображение доступности взаимодействия
}
if (this.activeButtons[indx]) {
this.activeButtons[indx] = false; // Открываем кнопку

} else {
this.activeButtons[indx] = true; // Закрываем кнопку

}
},
fillListBtDisabled() {
// заполнить массив изначально заблокированными свойствами
for (let i = 0; i < this.notes.length; i++) {
this.activeButtons[i] = true; // Изначально все кнопки закрыты
}
}

},

Expand Down
4 changes: 3 additions & 1 deletion project/adminpanel/templates/admin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@
<div v-html="note"></div>
<button :class="getNoteButtonClasses(note)"
type="button"
v-on:click="delNote(indx)">
v-on:click="delNote(indx)"
:disabled="activeButtons[indx]">
удалить
</button>
<div class="position-switch switch-btn-2" :class="buttonClasses[indx]" v-on:click="makeSwitchDisabled(indx)"></div>
</li>
</ul>
</div>
Expand Down
2 changes: 1 addition & 1 deletion project/telegram/expense_journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ async def get_expenses_for_day(callback: types.CallbackQuery):

msg = mytable
except TypeError as e:
logger.exception(f'Ошибка- журнал пуст: {str(e)}')
logger.exception(f'Ошибка- журнал пуст')
msg = 'Журнал пуст!'
except Exception as e:
logger.exception(f'Ошибка: {str(e)}')
Expand Down

0 comments on commit c7d44c7

Please sign in to comment.