Initial commit

This commit is contained in:
2023-03-28 08:37:35 +02:00
commit 7a929eb757
22 changed files with 1128 additions and 0 deletions

74
.gitignore vendored Normal file
View File

@@ -0,0 +1,74 @@
# This file is used to ignore files which are generated
# ----------------------------------------------------------------------------
*~
*.autosave
*.a
*.core
*.moc
*.o
*.obj
*.orig
*.rej
*.so
*.so.*
*_pch.h.cpp
*_resource.rc
*.qm
.#*
*.*#
core
!core/
tags
.DS_Store
.directory
*.debug
Makefile*
*.prl
*.app
moc_*.cpp
ui_*.h
qrc_*.cpp
Thumbs.db
*.res
*.rc
/.qmake.cache
/.qmake.stash
# qtcreator generated files
*.pro.user*
CMakeLists.txt.user*
# xemacs temporary files
*.flc
# Vim temporary files
.*.swp
# Visual Studio generated files
*.ib_pdb_index
*.idb
*.ilk
*.pdb
*.sln
*.suo
*.vcproj
*vcproj.*.*.user
*.ncb
*.sdf
*.opensdf
*.vcxproj
*vcxproj.*
# MinGW generated files
*.Debug
*.Release
# Python byte code
*.pyc
# Binaries
# --------
*.dll
*.exe

76
CMakeLists.txt Normal file
View File

@@ -0,0 +1,76 @@
cmake_minimum_required(VERSION 3.14)
project(beerlog VERSION 0.1 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Quick WebSockets LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Quick WebSockets LinguistTools)
set(TS_FILES beerlog_ru_RU.ts)
set(PROJECT_SOURCES
main.cpp
qml.qrc
models/summarymodel.h models/summarymodel.cpp
models/usersmodel.h models/usersmodel.cpp
services/beerservice.h services/beerservice.cpp
services/settingsservice.h services/settingsservice.cpp
${TS_FILES}
)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(beerlog
MANUAL_FINALIZATION
${PROJECT_SOURCES}
)
# Define target properties for Android with Qt 6 as:
# set_property(TARGET beerlog APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
# ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
else()
if(ANDROID)
add_library(beerlog SHARED
${PROJECT_SOURCES}
)
# Define properties for Android with Qt 5 after find_package() calls as:
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
else()
add_executable(beerlog
${PROJECT_SOURCES}
)
endif()
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
endif()
qt_add_translations(beerlog TS_FILES beerlog_ru_RU.ts)
target_link_libraries(beerlog
PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick Qt${QT_VERSION_MAJOR}::WebSockets)
set_target_properties(beerlog PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
#install(TARGETS beerlog
# BUNDLE DESTINATION .
# LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
if(QT_VERSION_MAJOR EQUAL 6)
qt_import_qml_plugins(beerlog)
qt_finalize_executable(beerlog)
endif()

View File

@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.ded.beerlog" android:installLocation="auto" android:versionCode="0.0.1" android:versionName="-- %%INSERT_VERSION_NAME%% --">
<!-- %%INSERT_PERMISSIONS -->
<!-- %%INSERT_FEATURES -->
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true"/>
<application android:name="org.qtproject.qt.android.bindings.QtApplication" android:extractNativeLibs="true" android:hardwareAccelerated="true" android:label="BeerLog" android:requestLegacyExternalStorage="true" android:allowNativeHeapPointerTagging="false">
<activity android:name="org.qtproject.qt.android.bindings.QtActivity" android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation|mcc|mnc|density" android:label="BeerLog" android:launchMode="singleTop" android:screenOrientation="unspecified">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.lib_name" android:value="-- %%INSERT_APP_LIB_NAME%% --"/>
<meta-data android:name="android.app.arguments" android:value="-- %%INSERT_APP_ARGUMENTS%% --"/>
<meta-data android:name="android.app.extract_android_style" android:value="minimal"/>
</activity>
</application>
</manifest>

78
android/build.gradle Normal file
View File

@@ -0,0 +1,78 @@
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.2'
}
}
repositories {
google()
mavenCentral()
}
apply plugin: 'com.android.application'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}
android {
/*******************************************************
* The following variables:
* - androidBuildToolsVersion,
* - androidCompileSdkVersion
* - qtAndroidDir - holds the path to qt android files
* needed to build any Qt application
* on Android.
*
* are defined in gradle.properties file. This file is
* updated by QtCreator and androiddeployqt tools.
* Changing them manually might break the compilation!
*******************************************************/
compileSdkVersion androidCompileSdkVersion.toInteger()
buildToolsVersion androidBuildToolsVersion
ndkVersion androidNdkVersion
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = [qtAndroidDir + '/src', 'src', 'java']
aidl.srcDirs = [qtAndroidDir + '/src', 'src', 'aidl']
res.srcDirs = [qtAndroidDir + '/res', 'res']
resources.srcDirs = ['resources']
renderscript.srcDirs = ['src']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
}
}
tasks.withType(JavaCompile) {
options.incremental = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
abortOnError false
}
// Do not compress Qt binary resources file
aaptOptions {
noCompress 'rcc'
}
defaultConfig {
resConfig "en"
minSdkVersion qtMinSdkVersion
targetSdkVersion qtTargetSdkVersion
ndk.abiFilters = qtTargetAbiList.split(",")
}
}

14
android/gradle.properties Normal file
View File

@@ -0,0 +1,14 @@
# Project-wide Gradle settings.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2500m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# Enable building projects in parallel
org.gradle.parallel=true
# Gradle caching allows reusing the build artifacts from a previous
# build with the same inputs. However, over time, the cache size will
# grow. Uncomment the following line to enable it.
#org.gradle.caching=true

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
android/gradlew vendored Normal file
View File

@@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,20 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<!-- DO NOT EDIT THIS: This file is populated automatically by the deployment tool. -->
<array name="bundled_libs">
<!-- %%INSERT_EXTRA_LIBS%% -->
</array>
<array name="qt_libs">
<!-- %%INSERT_QT_LIBS%% -->
</array>
<array name="load_local_libs">
<!-- %%INSERT_LOCAL_LIBS%% -->
</array>
<string name="static_init_classes"><!-- %%INSERT_INIT_CLASSES%% --></string>
<string name="use_local_qt_libs"><!-- %%USE_LOCAL_QT_LIBS%% --></string>
<string name="bundle_local_qt_libs"><!-- %%BUNDLE_LOCAL_QT_LIBS%% --></string>
</resources>

34
beerlog_ru_RU.ts Normal file
View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
<name>main</name>
<message>
<location filename="main.qml" line="13"/>
<source>Beer Log</source>
<translation></translation>
</message>
<message>
<location filename="main.qml" line="19"/>
<source></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="main.qml" line="28"/>
<source></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Summary: %1 р.</source>
<translation type="vanished">Итого: %1 р.</translation>
</message>
<message>
<source>Order</source>
<translation type="vanished">Заказать</translation>
</message>
<message>
<source>Ordered %1 items. Amount: %2 р.</source>
<translation type="vanished">Заказано %1 позиций на сумму %2 р.</translation>
</message>
</context>
</TS>

44
main.cpp Normal file
View File

@@ -0,0 +1,44 @@
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QLocale>
#include <QTranslator>
#include <QQmlContext>
#include "models/summarymodel.h"
#include "models/usersmodel.h"
#include "services/beerservice.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QTranslator translator;
const QStringList uiLanguages = QLocale::system().uiLanguages();
for (const QString &locale : uiLanguages) {
const QString baseName = "beerlog_" + QLocale(locale).name();
if (translator.load(":/i18n/" + baseName)) {
app.installTranslator(&translator);
break;
}
}
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.rootContext()->setContextProperty("beerService", new BeerService(&engine));
qmlRegisterType<SummaryModel>("ru.ded.beerlog", 1, 0, "SummaryModel");
qmlRegisterType<UsersModel>("ru.ded.beerlog", 1, 0, "UsersModel");
engine.load(url);
return app.exec();
}

63
main.qml Normal file
View File

@@ -0,0 +1,63 @@
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtWebSockets
import ru.ded.beerlog 1.0
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Beer Log")
header: ToolBar {
RowLayout {
anchors.fill: parent
ToolButton {
text: qsTr("")
onClicked: stack.pop()
}
ToolButton {
text: usersModel.selectedUserName
Layout.fillWidth: true
onClicked: usersMenu.open()
}
ToolButton {
text: qsTr("⋮")
onClicked: menu.open()
}
}
Menu {
id: usersMenu
Repeater {
model: usersModel.users
MenuItem {
text: modelData.name
onClicked: {
usersModel.selectedUser = modelData.id
}
}
}
}
}
UsersModel {
id: usersModel
Component.onCompleted: {
beerService.connectSrv(selectedUser)
beerService.connectListener(usersModel)
beerService.sendCommand("users", "get")
}
onSelectedUserChanged: {
beerService.connectSrv(selectedUser)
}
}
}

39
models/summarymodel.cpp Normal file
View File

@@ -0,0 +1,39 @@
#include "summarymodel.h"
QVariantList SummaryModel::items() const
{
return m_items.values();
}
float SummaryModel::sum() const
{
float res = 0.0;
for (auto it = m_items.constBegin(); it != m_items.constEnd(); ++it) {
QVariantMap item = it.value().toMap();
int count = item.value("count", 0).toInt();
float price = item.value("cost", 0.0).toFloat();
res += count * price;
}
return res;
}
void SummaryModel::setItemCount(QVariantMap item, int count)
{
QString id = item.value("id", QString()).toString();
if (count) {
item["count"] = count;
m_items[id] = item;
} else {
m_items.remove(id);
}
emit itemsChanged();
}
void SummaryModel::clear()
{
m_items.clear();
emit itemsChanged();
}

28
models/summarymodel.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef SUMMARYMODEL_H
#define SUMMARYMODEL_H
#include <QObject>
#include <QVariantMap>
class SummaryModel : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariantList items READ items NOTIFY itemsChanged)
Q_PROPERTY(float sum READ sum NOTIFY itemsChanged)
public:
QVariantList items() const;
float sum() const;
Q_INVOKABLE void setItemCount(QVariantMap item, int count);
Q_INVOKABLE void clear();
signals:
void itemsChanged();
private:
QVariantMap m_items;
};
#endif // SUMMARYMODEL_H

80
models/usersmodel.cpp Normal file
View File

@@ -0,0 +1,80 @@
#include "usersmodel.h"
UsersModel::UsersModel(QObject *parent)
: QObject{parent}
{
setSelectedUser(m_settings.value("selected_user").toString());
}
void UsersModel::created(const QVariant &data)
{
modified(data);
}
void UsersModel::modified(const QVariant &data)
{
QVariantMap user = data.toMap();
m_users[user.value("id").toString()] = user;
emit usersChanged();
emit selectedUserNameChanged();
}
void UsersModel::deleted(const QVariant &data)
{
QString userId = data.toString();
m_users.remove(userId);
emit usersChanged();
emit selectedUserNameChanged();
}
void UsersModel::received(const QVariant &data)
{
m_users = data.toMap();
emit usersChanged();
emit selectedUserNameChanged();
}
void UsersModel::connected(const QVariant &data)
{
qInfo() << data.toMap().value("name").toString() << "connected";
}
void UsersModel::disconnected(const QVariant &data)
{
qInfo() << data.toMap().value("name").toString() << "disconnected";
}
QString UsersModel::entity() const
{
return QStringLiteral("users");
}
QVariantList UsersModel::users() const
{
return m_users.values();
}
QString UsersModel::selectedUser() const
{
return m_selectedUser;
}
void UsersModel::setSelectedUser(const QString &newSelectedUser)
{
if (m_selectedUser == newSelectedUser) {
return;
}
m_selectedUser = newSelectedUser;
m_settings.setValue("selected_user", m_selectedUser);
emit selectedUserChanged();
emit selectedUserNameChanged();
}
QString UsersModel::selectedUserName() const
{
return m_users.value(m_selectedUser).toMap().value("name").toString();
}

47
models/usersmodel.h Normal file
View File

@@ -0,0 +1,47 @@
#ifndef USERSMODEL_H
#define USERSMODEL_H
#include <QObject>
#include <QVariantMap>
#include "services/settingsservice.h"
class UsersModel : public QObject
{
Q_OBJECT
Q_PROPERTY(QString entity READ entity CONSTANT)
Q_PROPERTY(QVariantList users READ users NOTIFY usersChanged)
Q_PROPERTY(QString selectedUser READ selectedUser WRITE setSelectedUser NOTIFY selectedUserChanged)
Q_PROPERTY(QString selectedUserName READ selectedUserName NOTIFY selectedUserNameChanged)
public:
explicit UsersModel(QObject *parent = nullptr);
QString entity() const;
QVariantList users() const;
QString selectedUser() const;
void setSelectedUser(const QString &newSelectedUser);
QString selectedUserName() const;
public slots:
void created(const QVariant &data);
void modified(const QVariant &data);
void deleted(const QVariant &data);
void received(const QVariant &data);
void connected(const QVariant &data);
void disconnected(const QVariant &data);
signals:
void usersChanged();
void selectedUserChanged();
void selectedUserNameChanged();
private:
QVariantMap m_users;
QString m_selectedUser;
SettingsService m_settings;
};
#endif // USERSMODEL_H

6
qml.qrc Normal file
View File

@@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file>main.qml</file>
<file>beerlog_ru_RU.qm</file>
</qresource>
</RCC>

122
services/beerservice.cpp Normal file
View File

@@ -0,0 +1,122 @@
#include "beerservice.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardPaths>
#include <QFile>
#include <QDebug>
namespace {
constexpr auto GuestUserId = "2641ffe8cd4311eda27f0242ac120002";
}
BeerService::BeerService(QObject *parent)
: QObject{parent}
{
restoreStash();
connect(&m_socket, &QWebSocket::textMessageReceived, this, [this](QString message) {
QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(message.toLocal8Bit(), &err);
if (err.error != QJsonParseError::NoError) {
qWarning() << "Json parse error:" << err.errorString() << message;
return;
}
QString entity = doc.object().value("entity").toString();
const QList<QObject *> listeners = m_listeners.values(entity);
for (QObject *listener : listeners) {
QString event = doc.object().value("event").toString();
QVariant data = doc.object().value("data").toVariant();
QMetaObject::invokeMethod(listener, event.toLatin1(), Qt::QueuedConnection, Q_ARG(QVariant, data));
}
});
connect(&m_socket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, [this](QAbstractSocket::SocketError error) {
qInfo() << error << m_socket.errorString();
});
connect(&m_socket, &QWebSocket::connected, this, [this]() {
while (!m_commandStash.isEmpty()) {
sendCommand(m_commandStash.takeFirst().toMap());
}
});
}
BeerService::~BeerService()
{
saveStash();
m_socket.close();
}
void BeerService::connectSrv(const QString &userId)
{
if (QAbstractSocket::ConnectedState == m_socket.state()) {
m_socket.close();
}
QNetworkRequest request(QUrl("ws://195.133.196.161:8000"));
QString authString = QString("%1:pass").arg(userId.isEmpty() ? GuestUserId : userId);
request.setRawHeader("Authorization", "Basic " + authString.toLatin1().toBase64());
m_socket.open(request);
}
void BeerService::sendCommand(const QString &entity, const QString &action, const QVariantMap &data)
{
sendCommand(QVariantMap {
{ "entity", entity },
{ "action", action },
{ "data", data }
});
}
void BeerService::connectListener(QObject *listener)
{
QString entity = listener->property("entity").toString();
m_listeners.insert(entity, listener);
}
QString BeerService::stashFileName() const
{
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/command.stash";
}
void BeerService::saveStash() const
{
if (m_commandStash.isEmpty()) {
return;
}
QFile stash(stashFileName());
if (stash.open(QIODevice::WriteOnly)) {
stash.write(QJsonDocument::fromVariant(m_commandStash).toJson(QJsonDocument::Compact));
stash.close();
} else {
qWarning() << stash.errorString();
}
}
void BeerService::restoreStash()
{
QFile stash(stashFileName());
if (stash.open(QIODevice::ReadOnly)) {
QJsonDocument doc = QJsonDocument::fromJson(stash.readAll());
m_commandStash = doc.array().toVariantList();
stash.close();
} else {
qWarning() << stash.errorString();
}
}
void BeerService::sendCommand(const QVariantMap &command)
{
if (QAbstractSocket::ConnectedState == m_socket.state()) {
QJsonDocument doc = QJsonDocument::fromVariant(command);
m_socket.sendTextMessage(doc.toJson(QJsonDocument::Compact));
} else {
m_commandStash << command;
}
}

31
services/beerservice.h Normal file
View File

@@ -0,0 +1,31 @@
#ifndef BEERSERVICE_H
#define BEERSERVICE_H
#include <QObject>
#include <QtWebSockets/QWebSocket>
class BeerService : public QObject
{
Q_OBJECT
public:
explicit BeerService(QObject *parent = nullptr);
~BeerService();
Q_INVOKABLE void connectSrv(const QString &userId = QString());
Q_INVOKABLE void sendCommand(const QString &entity, const QString &action, const QVariantMap &data = QVariantMap());
Q_INVOKABLE void connectListener(QObject *listener);
private:
QString stashFileName() const;
void saveStash() const;
void restoreStash();
void sendCommand(const QVariantMap &command);
QMultiMap<QString, QObject *> m_listeners;
QWebSocket m_socket;
QVariantList m_commandStash;
};
#endif // BEERSERVICE_H

View File

@@ -0,0 +1,11 @@
#include "settingsservice.h"
QVariant SettingsService::value(const QString &key, const QVariant &defaultValue) const
{
return m_settings.value(key, defaultValue);
}
void SettingsService::setValue(const QString &key, const QVariant &value)
{
m_settings.setValue(key, value);
}

View File

@@ -0,0 +1,16 @@
#ifndef SETTINGSSERVICE_H
#define SETTINGSSERVICE_H
#include <QSettings>
class SettingsService
{
public:
QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const;
void setValue(const QString &key, const QVariant &value);
private:
QSettings m_settings = QSettings("DedSoft", "BeerLog");
};
#endif // SETTINGSSERVICE_H