Compare commits

52 Commits

Author SHA1 Message Date
a6847f2661 Fixed the column names in CSV export. 2026-02-23 13:28:13 +01:00
3431e281c3 CSV import: Added "AGA"-> "erarbeitet", "ja"-> "bezahlt" and "teils"-> "teils/teils" replacements for ShareType values to support the new spreadsheet entries. 2026-02-23 13:27:53 +01:00
d800ecfed7 The calculation of how many harvest shares are expected in total. 2026-02-21 22:54:59 +01:00
6b383b8f55 Added more model tests and fixed the calculations for nPlacedBiddings, biddingSum and totalSharesWithBiddings if there are conflicting entries (shareType: "erarbeitet" but a bidding is placed). 2026-02-21 22:53:29 +01:00
85afc9b329 Converted non critical qCritical() calls into qInfo() calls. 2026-02-21 19:38:35 +01:00
f3e2dbf309 Added two simple tests for the table model. 2026-02-21 19:37:36 +01:00
2021830239 Setting the server URL for displaying the users bidding link on program start from settings. Doesn't get updated after settings have been changed. 2026-02-21 12:37:26 +01:00
74470ba605 Defaulting the bidding type to "" in new item dialog. 2026-02-21 12:27:15 +01:00
6cd205506f If no authToken is stored in settings but email and password are on startup the log_in route is triggered to receive a new token. This token will be used to access a protected API. 2026-02-20 16:44:58 +01:00
064da850c4 Clicking the sendInvite button triggers a post request to the server to send a bidding invite via mail. 2026-02-19 20:54:24 +01:00
06589e5a09 Cleaning up TableModel::updateBiddings function 2026-02-19 13:20:07 +01:00
d381e1ab8c Merging received bidding into the model. 2026-02-19 13:10:55 +01:00
440333b589 Routing the received biddings to the model. Just debug outputs there yet. 2026-02-19 11:18:46 +01:00
21b8de96d8 Minor refactoring to move JSON processing into JsonParser. 2026-02-19 11:02:10 +01:00
4519a2de3f Added missing #include to core file. 2026-02-19 10:59:39 +01:00
369addac44 Fixed the hard coded server url to login a user per access token. 2026-02-19 10:57:27 +01:00
f34e1521c4 Merge branch 'feature/onlineUserAccounts' into develop 2026-02-19 10:16:16 +01:00
7d31ac8806 When receiving online user credentials insert them into the model. 2026-02-19 09:10:06 +01:00
faf01d6e15 Online account can now be created from the EditItemDialog. The response isn't processed properly yet. 2026-02-18 11:24:40 +01:00
7a8859843e Added onlineID and accessUrl widgets to the edit item dialog layout. No functionality yet. 2026-02-17 11:42:29 +01:00
f1a436ead0 Added ShareType changes to the conditions to emit nExpectedBiddingsChanged. 2026-02-17 11:38:38 +01:00
25bfc196a1 Counting "bezahlt" & "teils/teils" share type explicitly for expected biddings, instead of the absence of values (emptiness, "erarbeitet"). 2026-02-17 10:13:01 +01:00
bfb8e43c34 Disabling the progress status bar if more biddings are placed than expected. (Easy way to indicate a problem in the GUI). 2026-02-17 09:05:45 +01:00
c38bacc387 Merge branch 'feature/modelSummary' into develop 2026-02-17 08:18:57 +01:00
546d6ea3ef Added two skips in calculation of amount of expected biddings (depending on share type & share amount). 2026-02-16 19:00:06 +01:00
06e96916ed Fixed a crash bug when the application is quit. Because of intertwining shared pointer and the Qt ownership of child objects the model and the model summary were tried to be destroyed two times. 2026-02-16 18:50:44 +01:00
1e64dda701 Migrated old visualization of the bidding round statuses with donut charts from the legacy BeetRound project. 2026-02-16 18:48:05 +01:00
f8201ead71 Added a placeholder for the configuration of the monthly financial need. 2026-02-16 11:46:01 +01:00
f200fff99e Added a second bound property (nExpectedBiddings) & cleaned up the code a little. 2026-02-16 09:24:58 +01:00
dac9ac46f2 Added a ModelSummary class to make the overview over the model content accessible via QProperty system & a SummaryWidget to show this information. Only property rowCount as a proof of concept. Other properties will follow. 2026-02-15 16:36:13 +01:00
b28a35280c Merge branch 'feature/biddingRoundControl' into develop 2026-02-15 09:39:46 +01:00
5afdbd6dd9 Cosmetic source code refactoring. 2026-02-14 10:19:53 +01:00
29f913c532 Using the proper GetBiddingsOfHighestRound request on fetchCurrentBiddings again. 2026-02-14 10:18:37 +01:00
bb5e894557 Adding optional QVariant data argument to sendGetRequest to pass it to the server. Using hard coded sendGetRequest(GetBiddingsOfSpecificRound, 2) in fetchCurrentBiddings action to test this. 2026-02-14 10:17:31 +01:00
6e51aee3a5 Fetching current biddings from server menu. No extracting biddings from the response and merging into the model yet. 2026-02-14 10:02:00 +01:00
cfd3031cf9 Bidding round control communicating with the server. 2026-02-13 20:24:48 +01:00
ba4f95eb2d Added two minor refactoring todos. 2026-02-13 17:56:05 +01:00
a4d2815947 Added an "Event" tab with a BiddingRoundControl class in it. No connections of signals and slots yet. 2026-02-13 16:12:03 +01:00
bea89a2a16 Setting the column 0 to a width of 30 on startup. 2026-02-12 09:59:13 +01:00
f148ef9cba Not displaying 0 values for int and double columns in table view, but still using a SpinBox delegate when editing. 2026-02-10 11:52:35 +01:00
bdc8075324 Added support of optional header names when importing CSV file. 2026-02-10 11:04:26 +01:00
e157d4399d NewItemDialog content is now reset after accept() & using a default value of 1 for share amount. 2026-02-08 10:36:08 +01:00
572f0f266e Added ComboBoxDelegate class and using it as delegate for type columns in table view. 2026-02-08 10:34:47 +01:00
40a0815501 Added data(FullNameRole) implementation and minor refactoring. 2026-02-07 19:42:22 +01:00
c6d6b18ab3 Added roles for BeetRound purpose. 2026-02-07 19:41:02 +01:00
2fcd69df5f Renamed core subproject into BeetRoundCore. 2026-02-05 18:58:46 +01:00
455c6ef3bd Renamed widgets subproject into BeetRoundWidgets. 2026-02-05 18:48:13 +01:00
22adf36aa9 Adjusted the about text, the README and the CHANGELOG for the BeetRound project. 2026-02-05 18:45:31 +01:00
7edd6b9aa0 "Fixed" the failing test. 2026-02-05 18:44:25 +01:00
3146eceec2 Renamed UI and umbrella project to fit BeetRound project. 2026-02-05 13:58:42 +01:00
acca7140d9 Added submodule for the 3rd party libraries rapidcsv and Qt-QrCodeGenerator. 2026-02-04 19:30:11 +01:00
b24bda2d95 Initial commit based on GenericQtClient v0.3.0 2026-02-04 19:02:41 +01:00
97 changed files with 7074 additions and 0 deletions

10
.clang-format Normal file
View File

@ -0,0 +1,10 @@
BasedOnStyle: Chromium
ColumnLimit: 100
AllowShortLoopsOnASingleLine: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
BreakConstructorInitializersBeforeComma: true
AlignConsecutiveAssignments: true
AllowShortFunctionsOnASingleLine: true
BraceWrapping:
AfterControlStatement: Always
InsertBraces: true

84
.gitignore vendored Normal file
View File

@ -0,0 +1,84 @@
# 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*
*.qbs.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
# Directories with generated files
.moc/
.obj/
.pch/
.rcc/
.uic/
/build*/
_build*/
_output/*

6
.gitmodules vendored Normal file
View File

@ -0,0 +1,6 @@
[submodule "libs/3rdParty/rapidcsv"]
path = libs/3rdParty/rapidcsv
url = https://github.com/d99kris/rapidcsv.git
[submodule "libs/3rdParty/Qt-QrCodeGenerator"]
path = libs/3rdParty/Qt-QrCodeGenerator
url = https://github.com/alex-spataru/Qt-QrCodeGenerator.git

2
ApplicationConfig.h.in Normal file
View File

@ -0,0 +1,2 @@
#define APPLICATION_NAME "${PROJECT_NAME}"
#define APPLICATION_VERSION "${PROJECT_VERSION}"

5
CHANGELOG.md Normal file
View File

@ -0,0 +1,5 @@
# Changelog
## 0.1.0 - 2026-02-05
Initial release of BeetRound. Based on GenericQtClient v0.3.0 and adjusted the project name to the use case.

56
CMakeLists.txt Normal file
View File

@ -0,0 +1,56 @@
cmake_minimum_required(VERSION 3.16)
set(TARGET_APP "BeetRound")
project(${TARGET_APP} VERSION 0.1.0 LANGUAGES CXX)
enable_testing()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_subdirectory(libs/BeetRoundCore)
set (CORE_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/BeetRoundCore)
### 3rd party libraries
add_subdirectory(libs/3rdParty/Qt-QrCodeGenerator)
set (QR_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/3rdParty/Qt-QrCodeGenerator)
configure_file(ApplicationConfig.h.in ApplicationConfig.h)
#Frontend applications
add_subdirectory(UIs/BeetRoundWidgets)
### Tests
add_subdirectory(tests/GenericCoreTests)
### Qt installer
set(PACKAGE_FOLDER "beetRound")
set(UBERSPACE_ASTEROID "...")
set(TARGET_PACKAGE "org.working_copy.${PACKAGE_FOLDER}")
set(CONFIG_REPO_URL ".../${PACKAGE_FOLDER}")
set(PUSH_REPO_URL "${UBERSPACE_ASTEROID}:/home/${UBERSPACE_ASTEROID}/html/${PACKAGE_FOLDER}")
string(TIMESTAMP CURRENT_DATE "%Y-%m-%d")
set(PLATFORM "linux")
set(BASH_COMMAND)
### quick fix for config.xml.in and installscript.qs.in:
set(ApplicationsDir @ApplicationsDir@)
set(TargetDir @TargetDir@)
set(DesktopDir @DesktopDir@)
set(HomeDir @HomeDir@)
### end of quick fix
configure_file(installer/config/config.xml.in installer/config/config.xml)
configure_file(installer/packages/defaultPackage/meta/package.xml.in installer/packages/${TARGET_PACKAGE}/meta/package.xml)
configure_file(installer/packages/defaultPackage/meta/installscript.qs.in installer/packages/${TARGET_PACKAGE}/meta/installscript.qs)
# configure_file(installer/packages/defaultPackage/meta/license.txt.in installer/packages/${TARGET_PACKAGE}/meta/license.txt)
# add_custom_command(
# OUTPUT installer/config/config.xml
# COMMAND ${BASH_COMMAND} ${CMAKE_CURRENT_SOURCE_DIR}/installer/script.sh ${PROJECT_VERSION} linux ${TARGET_APP} ${TARGET_PACKAGE}
# )
# add_custom_target(installer ALL
# DEPENDS installer/config/config.xml
# )

232
LICENSE Normal file
View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
GenericQtClient
Copyright (C) 2025 bent
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
GenericQtClient Copyright (C) 2025 bent
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

9
README.md Normal file
View File

@ -0,0 +1,9 @@
# BeetRound
BeetRound is a software project to manage the yearly crop share auction (german: Bietrunde) of a Community-supported agriculture (CSA, german: Solidarische Landwirtschaft (SoLaWi)).
This is the management application. The project also includes a web server where the participants can submit their biddings.
Further information will follow…
This project is currently tailored for one specific CSA and will be expanded to broader use after the coming crop share auction in february.

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US"></TS>

View File

@ -0,0 +1,100 @@
cmake_minimum_required(VERSION 3.16)
set(TARGET_APP "BeetRound-Widgets")
project(${TARGET_APP} VERSION 0.1.0 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 Widgets LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets LinguistTools Charts)
set(TS_FILES ${TARGET_APP}_en_US.ts)
set(PROJECT_SOURCES
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
${TS_FILES}
)
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(${TARGET_APP}
MANUAL_FINALIZATION
${PROJECT_SOURCES}
utils/messagehandler.h
assets/icons.qrc
dialogs/abstractdialog.h dialogs/abstractdialog.cpp
dialogs/newitemdialog.h dialogs/newitemdialog.cpp
dialogs/edititemdialog.h dialogs/edititemdialog.cpp
dialogs/settingsdialog.h dialogs/settingsdialog.cpp
views/itemdetailmapper.h views/itemdetailmapper.cpp
widgets/comboboxdelegate.h widgets/comboboxdelegate.cpp
widgets/spinboxdelegate.h widgets/spinboxdelegate.cpp
widgets/biddingroundcontrol.h widgets/biddingroundcontrol.cpp
widgets/summarywidget.h widgets/summarywidget.cpp
widgets/biddingroundstatuswidget.h widgets/biddingroundstatuswidget.cpp
widgets/biddingroundprogresslayout.h widgets/biddingroundprogresslayout.cpp
)
# Define target properties for Android with Qt 6 as:
# set_property(TARGET ${TARGET_APP} 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(${TARGET_APP} 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(${TARGET_APP}
${PROJECT_SOURCES}
)
endif()
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Charts)
target_include_directories(${TARGET_APP} PRIVATE ${CORE_LIB_DIR}/)
target_link_libraries(${TARGET_APP} PRIVATE BeetRoundCore)
target_include_directories(${TARGET_APP} PRIVATE ${QR_LIB_DIR}/src)
target_link_libraries(${TARGET_APP} PRIVATE qrcode)
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
# If you are developing for iOS or macOS you should consider setting an
# explicit, fixed bundle identifier manually though.
if(${QT_VERSION} VERSION_LESS 6.1.0)
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.${TARGET_APP})
endif()
set_target_properties(${TARGET_APP} PROPERTIES
${BUNDLE_ID_OPTION}
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
include(GNUInstallDirs)
install(TARGETS ${TARGET_APP}
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(${TARGET_APP})
endif()

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,7 @@
<RCC>
<qresource prefix="/">
<file>software-application.png</file>
<file>feature.png</file>
<file>no-picture-taking.png</file>
</qresource>
</RCC>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,5 @@
software-application.png:
https://www.flaticon.com/free-icon/software-application_5063917
feature.png:
https://www.flaticon.com/free-icon/feature_1085784

View File

@ -0,0 +1,51 @@
#include "abstractdialog.h"
#include <QDialogButtonBox>
#include <QGuiApplication>
#include <QLabel>
#include <QScreen>
#include <QVBoxLayout>
AbstractDialog::AbstractDialog(QDialogButtonBox::StandardButtons buttons, QWidget* parent)
: QDialog(parent) {
setWindowTitle(tr("Dialog does what?..."));
setModal(true);
m_buttonBox = new QDialogButtonBox(buttons, this);
connect(m_buttonBox, &QDialogButtonBox::accepted, this, &AbstractDialog::accept);
connect(m_buttonBox, &QDialogButtonBox::rejected, this, &AbstractDialog::reject);
m_contentContainer = new QLabel("content", this);
m_outerLayout = new QVBoxLayout;
m_outerLayout->addWidget(m_contentContainer);
m_outerLayout->addWidget(m_buttonBox);
setLayout(m_outerLayout);
}
void AbstractDialog::show() {
centerInParent();
QWidget::show();
}
void AbstractDialog::accept() { QDialog::accept(); }
void AbstractDialog::reject() { QDialog::reject(); }
void AbstractDialog::centerInParent() {
// BUG the centering in the parent doesn't work the first time (and the later ones seem off too)
QWidget* parent = parentWidget();
if (parent) {
auto parentRect = parent->geometry();
move(parentRect.center() - rect().center());
} else {
QRect screenGeometry = QGuiApplication::screens().at(0)->geometry();
int x = (screenGeometry.width() - width()) / 2;
int y = (screenGeometry.height() - height()) / 2;
move(x, y);
}
}
void AbstractDialog::closeEvent(QCloseEvent* event) { QWidget::closeEvent(event); }

View File

@ -0,0 +1,33 @@
#ifndef ABSTRACTDIALOG_H
#define ABSTRACTDIALOG_H
#include <QDialog>
#include <QDialogButtonBox>
class QGridLayout;
class QVBoxLayout;
class AbstractDialog : public QDialog {
Q_OBJECT
public:
AbstractDialog(QDialogButtonBox::StandardButtons buttons, QWidget* parent = nullptr);
virtual void createContent() = 0;
/// QDialog interface
public slots:
void show();
void accept() override;
void reject() override;
protected:
void centerInParent();
protected:
QWidget* m_contentContainer;
QVBoxLayout* m_outerLayout;
QDialogButtonBox* m_buttonBox = nullptr;
void closeEvent(QCloseEvent* event) override;
};
#endif // ABSTRACTDIALOG_H

View File

@ -0,0 +1,45 @@
#include "edititemdialog.h"
#include <QDialogButtonBox>
#include <QLabel>
#include <QVBoxLayout>
#include "../views/itemdetailmapper.h"
EditItemDialog::EditItemDialog(QTableView* tableView, QWidget* parent)
: AbstractDialog(QDialogButtonBox::Ok, parent)
, m_tableView(tableView) {}
void EditItemDialog::createContent() {
if (m_contentContainer) {
delete m_contentContainer;
}
setWindowTitle(tr("Edit item..."));
m_contentContainer = new QWidget(this);
QHBoxLayout* innerLayout = new QHBoxLayout();
m_contentContainer->setLayout(innerLayout);
m_detailMapper = new ItemDetailMapper(this);
m_detailMapper->setModelMappings(m_tableView);
innerLayout->addWidget(m_detailMapper);
m_outerLayout->insertWidget(0, m_contentContainer);
/// online user stuff
connect(m_detailMapper, &ItemDetailMapper::createOnlineAccountTriggered, this,
&EditItemDialog::createOnlineAccountTriggered);
connect(m_detailMapper, &ItemDetailMapper::sendInviteMailTriggered, this,
&EditItemDialog::sendInviteMailTriggered);
}
void EditItemDialog::accept() {
m_detailMapper->submit();
QDialog::accept();
}
void EditItemDialog::reject() {
m_detailMapper->revert();
QDialog::reject();
}

View File

@ -0,0 +1,35 @@
#ifndef EDITITEMDIALOG_H
#define EDITITEMDIALOG_H
#include "abstractdialog.h"
class QDoubleSpinBox;
class QLineEdit;
class QSpinBox;
class QLabel;
class QTableView;
class ItemDetailMapper;
class EditItemDialog : public AbstractDialog {
Q_OBJECT
public:
EditItemDialog(QTableView* tableView, QWidget* parent = nullptr);
/// AbstractDialog interface
void createContent() override;
signals:
void createOnlineAccountTriggered(const QString& mailAddress);
void sendInviteMailTriggered(const QString& mailAddress);
public slots:
void accept() override;
void reject() override;
private:
QTableView* m_tableView = nullptr;
ItemDetailMapper* m_detailMapper;
};
#endif // EDITITEMDIALOG_H

View File

@ -0,0 +1,149 @@
#include "newitemdialog.h"
#include <QGridLayout>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QSpinBox>
#include <QStringListModel>
#include "formats/jsonparser.h"
#include "model/metadata.h"
NewItemDialog::NewItemDialog(QWidget* parent)
: AbstractDialog(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, parent) {}
void NewItemDialog::createContent() {
if (m_contentContainer) {
delete m_contentContainer;
}
setWindowTitle(tr("New item..."));
m_contentContainer = new QWidget(this);
// REFACTOR use a data structure for input widgets which can be iterated through
// using a factory which iterates through the roles from metadata.h
// and create the input widgets based on the data type of this role
m_numberLabel = new QLabel(GET_HEADER_FOR_COLUMN(0));
m_numberBox = new QSpinBox();
m_numberBox->setMaximum(1000);
m_lastNameLabel = new QLabel(GET_HEADER_FOR_COLUMN(1));
m_lastNameEdit = new QLineEdit();
m_lastNameLabel->setBuddy(m_lastNameEdit);
m_firstNameLabel = new QLabel(GET_HEADER_FOR_COLUMN(2));
m_firstNameEdit = new QLineEdit();
m_firstNameLabel->setBuddy(m_firstNameEdit);
m_shareTypeLabel = new QLabel(GET_HEADER_FOR_COLUMN(3));
m_shareTypeBox = new QComboBox();
m_shareTypeLabel->setBuddy(m_shareTypeBox);
m_shareTypeModel = new QStringListModel(SHARE_TYPES, this);
m_shareTypeBox->setModel(m_shareTypeModel);
m_amountLabel = new QLabel(GET_HEADER_FOR_COLUMN(4));
m_amountSpinBox = new QDoubleSpinBox();
m_amountLabel->setBuddy(m_amountSpinBox);
m_amountSpinBox->setValue(1.0);
m_biddingTypeLabel = new QLabel(GET_HEADER_FOR_COLUMN(5));
m_biddingTypeBox = new QComboBox();
m_biddingTypeLabel->setBuddy(m_biddingTypeBox);
m_biddingTypeModel = new QStringListModel(BIDDING_TYPES, this);
m_biddingTypeBox->setModel(m_biddingTypeModel);
m_bidding1Label = new QLabel(GET_HEADER_FOR_COLUMN(6));
m_bidding1SpinBox = new QSpinBox();
m_bidding1SpinBox->setMaximum(500);
m_bidding2Label = new QLabel(GET_HEADER_FOR_COLUMN(7));
m_bidding2SpinBox = new QSpinBox();
m_bidding2SpinBox->setMaximum(500);
m_bidding3Label = new QLabel(GET_HEADER_FOR_COLUMN(8));
m_bidding3SpinBox = new QSpinBox();
m_bidding3SpinBox->setMaximum(500);
m_depotWish1Label = new QLabel(GET_HEADER_FOR_COLUMN(9));
m_depotWish1Edit = new QLineEdit();
m_depotWish1Label->setBuddy(m_depotWish1Edit);
m_depotWish2Label = new QLabel(GET_HEADER_FOR_COLUMN(10));
m_depotWish2Edit = new QLineEdit();
m_depotWish2Label->setBuddy(m_depotWish2Edit);
m_mailLabel = new QLabel(GET_HEADER_FOR_COLUMN(11));
m_mailEdit = new QLineEdit();
m_mailEdit->setMinimumWidth(200);
m_mailLabel->setBuddy(m_mailEdit);
/// layouting
QGridLayout* layout = new QGridLayout();
layout->addWidget(m_numberLabel, 0, 0, 1, 1);
layout->addWidget(m_numberBox, 0, 1, 1, 1);
layout->addWidget(m_lastNameLabel, 1, 0, 1, 1);
layout->addWidget(m_lastNameEdit, 1, 1, 1, 1);
layout->addWidget(m_firstNameLabel, 2, 0, 1, 1);
layout->addWidget(m_firstNameEdit, 2, 1, 1, 1);
layout->addWidget(m_shareTypeLabel, 3, 0, 1, 1);
layout->addWidget(m_shareTypeBox, 3, 1, 1, 1);
layout->addWidget(m_amountLabel, 4, 0, 1, 1);
layout->addWidget(m_amountSpinBox, 4, 1, 1, 1);
layout->addWidget(m_biddingTypeLabel, 5, 0, 1, 1);
layout->addWidget(m_biddingTypeBox, 5, 1, 1, 1);
layout->addWidget(m_bidding1Label, 6, 0, 1, 1);
layout->addWidget(m_bidding1SpinBox, 6, 1, 1, 1);
layout->addWidget(m_bidding2Label, 7, 0, 1, 1);
layout->addWidget(m_bidding2SpinBox, 7, 1, 1, 1);
layout->addWidget(m_bidding3Label, 8, 0, 1, 1);
layout->addWidget(m_bidding3SpinBox, 8, 1, 1, 1);
layout->addWidget(m_depotWish1Label, 9, 0, 1, 1);
layout->addWidget(m_depotWish1Edit, 9, 1, 1, 1);
layout->addWidget(m_depotWish2Label, 10, 0, 1, 1);
layout->addWidget(m_depotWish2Edit, 10, 1, 1, 1);
layout->addWidget(m_mailLabel, 11, 0, 1, 1);
layout->addWidget(m_mailEdit, 11, 1, 1, 1);
m_contentContainer->setLayout(layout);
m_outerLayout->insertWidget(0, m_contentContainer);
}
void NewItemDialog::accept() {
ModelItemValues itemValues;
// TODO (after refactoring data structure for input widgets) use iteration through the relevant
// roles and their input widgets
// itemValues.insert(LastNameRole, m_nameEdit->text());
itemValues.insert(GET_ROLE_FOR_COLUMN(0), m_numberBox->value());
itemValues.insert(GET_ROLE_FOR_COLUMN(1), m_lastNameEdit->text());
itemValues.insert(GET_ROLE_FOR_COLUMN(2), m_firstNameEdit->text());
itemValues.insert(GET_ROLE_FOR_COLUMN(3), m_shareTypeBox->currentText());
itemValues.insert(GET_ROLE_FOR_COLUMN(4), m_amountSpinBox->value());
itemValues.insert(GET_ROLE_FOR_COLUMN(5), m_biddingTypeBox->currentText());
itemValues.insert(GET_ROLE_FOR_COLUMN(6), m_bidding1SpinBox->value());
itemValues.insert(GET_ROLE_FOR_COLUMN(7), m_bidding2SpinBox->value());
itemValues.insert(GET_ROLE_FOR_COLUMN(8), m_bidding3SpinBox->value());
itemValues.insert(GET_ROLE_FOR_COLUMN(9), m_depotWish1Edit->text());
itemValues.insert(GET_ROLE_FOR_COLUMN(10), m_depotWish2Edit->text());
itemValues.insert(GET_ROLE_FOR_COLUMN(11), m_mailEdit->text());
const QByteArray jsonDoc = JsonParser::itemValuesListToJson({itemValues}, ITEMS_KEY_STRING);
emit addItems(jsonDoc);
resetContent();
AbstractDialog::accept();
}
void NewItemDialog::resetContent() {
m_numberBox->setValue(0);
m_lastNameEdit->setText("");
m_firstNameEdit->setText("");
m_shareTypeBox->setCurrentIndex(0);
m_amountSpinBox->setValue(1);
m_biddingTypeBox->setCurrentIndex(4);
m_bidding1SpinBox->setValue(0);
m_bidding2SpinBox->setValue(0);
m_bidding3SpinBox->setValue(0);
m_depotWish1Edit->setText("");
m_depotWish2Edit->setText("");
m_mailEdit->setText("");
}

View File

@ -0,0 +1,68 @@
#ifndef NEWITEMDIALOG_H
#define NEWITEMDIALOG_H
#include "abstractdialog.h"
#include <QComboBox>
class QStringListModel;
class QDoubleSpinBox;
class QLineEdit;
class QSpinBox;
class QLabel;
class NewItemDialog : public AbstractDialog {
Q_OBJECT
public:
NewItemDialog(QWidget* parent = nullptr);
void createContent() override;
signals:
void addItems(const QByteArray& jsonDoc);
public slots:
void accept() override;
// void reject() override;
private:
QLabel* m_numberLabel;
QSpinBox* m_numberBox;
QLabel* m_lastNameLabel;
QLineEdit* m_lastNameEdit;
QLabel* m_firstNameLabel;
QLineEdit* m_firstNameEdit;
QLabel* m_shareTypeLabel;
QComboBox* m_shareTypeBox;
QStringListModel* m_shareTypeModel = nullptr;
QLabel* m_amountLabel;
QDoubleSpinBox* m_amountSpinBox;
QLabel* m_biddingTypeLabel;
QComboBox* m_biddingTypeBox;
QStringListModel* m_biddingTypeModel = nullptr;
QLabel* m_bidding1Label;
QSpinBox* m_bidding1SpinBox;
QLabel* m_bidding2Label;
QSpinBox* m_bidding2SpinBox;
QLabel* m_bidding3Label;
QSpinBox* m_bidding3SpinBox;
QLabel* m_depotWish1Label;
QLineEdit* m_depotWish1Edit;
QLabel* m_depotWish2Label;
QLineEdit* m_depotWish2Edit;
QLabel* m_mailLabel;
QLineEdit* m_mailEdit;
void resetContent();
};
#endif // NEWITEMDIALOG_H

View File

@ -0,0 +1,63 @@
#include "settingsdialog.h"
#include <QCoreApplication>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QTabWidget>
SettingsDialog::SettingsDialog(QWidget* parent)
: AbstractDialog(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, parent) {}
void SettingsDialog::createContent() {
if (m_contentContainer) {
delete m_contentContainer;
}
const QString dialogTitle = tr("Settings - ");
const QString applicationName = QCoreApplication::applicationName();
setWindowTitle(dialogTitle + applicationName);
setModal(true);
setGeometry(0, 0, 350, 250);
QGridLayout* serverLayout = new QGridLayout();
QLabel* urlLabel = new QLabel("Server URL:");
m_urlEdit = new QLineEdit();
serverLayout->addWidget(urlLabel, 0, 0);
serverLayout->addWidget(m_urlEdit, 0, 1);
QLabel* emailLabel = new QLabel("Email:");
m_emailEdit = new QLineEdit();
// m_emailEdit->setEnabled(false);
serverLayout->addWidget(emailLabel, 1, 0);
serverLayout->addWidget(m_emailEdit, 1, 1);
QLabel* passwordLabel = new QLabel("Password:");
m_passwordEdit = new QLineEdit();
// m_passwordEdit->setEnabled(false);
m_passwordEdit->setEchoMode(QLineEdit::Password);
serverLayout->addWidget(passwordLabel, 2, 0);
serverLayout->addWidget(m_passwordEdit, 2, 1);
QWidget* serverTab = new QWidget();
serverTab->setLayout(serverLayout);
QTabWidget* widget = new QTabWidget();
widget->addTab(serverTab, "Server");
m_contentContainer = widget;
m_outerLayout->insertWidget(0, m_contentContainer);
}
void SettingsDialog::fillContent(const QVariantMap& settings) {
m_urlEdit->setText(settings.value("url").toString());
m_emailEdit->setText(settings.value("email").toString());
m_passwordEdit->setText(settings.value("password").toString());
}
QVariantMap SettingsDialog::getSettings() const {
QVariantMap result;
result.insert("url", m_urlEdit->text());
result.insert("email", m_emailEdit->text());
result.insert("password", m_passwordEdit->text());
return result;
}

View File

@ -0,0 +1,23 @@
#ifndef SETTINGSDIALOG_H
#define SETTINGSDIALOG_H
#include "abstractdialog.h"
class QLineEdit;
class SettingsDialog : public AbstractDialog {
Q_OBJECT
public:
SettingsDialog(QWidget* parent = nullptr);
void createContent() override;
void fillContent(const QVariantMap& settings);
QVariantMap getSettings() const;
private:
QLineEdit* m_urlEdit = nullptr;
QLineEdit* m_emailEdit = nullptr;
QLineEdit* m_passwordEdit = nullptr;
};
#endif // SETTINGSDIALOG_H

View File

@ -0,0 +1,29 @@
#include "mainwindow.h"
#include <QApplication>
#include <QLocale>
#include <QTranslator>
#ifdef QT_DEBUG
#include "utils/messagehandler.h"
#endif
int main(int argc, char* argv[]) {
#ifdef QT_DEBUG
qInstallMessageHandler(consoleHandlerColoredVerboseInDarkTheme);
#endif
QApplication a(argc, argv);
QTranslator translator;
const QStringList uiLanguages = QLocale::system().uiLanguages();
for (const QString& locale : uiLanguages) {
const QString baseName = "GenericWidgets_" + QLocale(locale).name();
if (translator.load(":/i18n/" + baseName)) {
a.installTranslator(&translator);
break;
}
}
MainWindow w;
w.show();
return a.exec();
}

View File

@ -0,0 +1,576 @@
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QCloseEvent>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QStandardPaths>
#include <QUndoStack>
#include <QUndoView>
#include "../../ApplicationConfig.h"
#include "dialogs/edititemdialog.h"
#include "dialogs/newitemdialog.h"
#include "dialogs/settingsdialog.h"
#include "genericcore.h"
#include "model/generalsortfiltermodel.h"
#include "model/metadata.h"
#include "model/tablemodel.h"
#include "widgets/biddingroundcontrol.h"
#include "widgets/comboboxdelegate.h"
#include "widgets/spinboxdelegate.h"
#include "widgets/summarywidget.h"
static int intColumnWidth = 30;
static QStandardPaths::StandardLocation standardLocation = QStandardPaths::HomeLocation;
static QString updateTextClean = "Do you want to update the application now?";
static QString updateTextDirty = "Do you want to save the tasks & update the application now?";
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow) {
ui->setupUi(this);
m_core = std::make_unique<GenericCore>();
setWindowTitle(QCoreApplication::applicationName() + " [*]");
/// application icon
const QString iconString = "://feature.png";
#ifdef QT_DEBUG
QPixmap pixmap = QPixmap(iconString);
QTransform transform = QTransform();
transform.rotate(180);
QPixmap rotated = pixmap.transformed(transform);
setWindowIcon(QIcon(rotated));
#else
setWindowIcon(QIcon(iconString));
#endif
const QVariantMap settings = m_core->getSettings("GUI");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("windowState").toByteArray());
setupModelViews();
createActions();
createHelpMenu();
createGuiDialogs();
connect(m_core.get(), &GenericCore::displayStatusMessage, this,
&MainWindow::displayStatusMessage);
connect(this, &MainWindow::displayStatusMessage, this, &MainWindow::showStatusMessage);
connect(this, &MainWindow::checkForUpdates, this,
&MainWindow::on_actionCheck_for_update_triggered, Qt::QueuedConnection);
// connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this,
// &MainWindow::onSelectionChanged);
connect(ui->tableView->selectionModel(), &QItemSelectionModel::currentChanged, this,
&MainWindow::onCurrentChanged);
onSelectionChanged(QItemSelection(), QItemSelection());
onCurrentChanged(QModelIndex(), QModelIndex());
setupEventTab();
// #ifndef QT_DEBUG
initServerConnection();
// #endif
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::closeEvent(QCloseEvent* event) {
if (isWindowModified()) {
QMessageBox msgBox;
msgBox.setWindowTitle(windowTitle() + " - Save dialog");
msgBox.setText("The document has been modified.");
msgBox.setInformativeText("Do you want to save your changes?");
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Save);
int ret = msgBox.exec();
switch (ret) {
case QMessageBox::Save:
emit saveItems();
event->accept();
break;
case QMessageBox::Discard:
event->accept();
break;
case QMessageBox::Cancel:
event->ignore();
break;
default:
/// should never be reached
qCritical() << "unexpected switch case in closeEvent:" << ret;
event->ignore();
break;
}
} else {
event->accept();
}
if (event->isAccepted()) {
qInfo() << "Saving GUI settings...";
m_core->applySettings({{"geometry", saveGeometry()}, {"windowState", saveState()}}, "GUI");
}
}
void MainWindow::showStatusMessage(const QString text) {
qInfo() << text;
ui->statusbar->showMessage(text);
}
void MainWindow::onCurrentChanged(const QModelIndex& current, const QModelIndex& previous) {
// Q_UNUSED(current);
Q_UNUSED(previous);
// QItemSelection localSelection = ui->tableView->selectionModel()->selection();
if (current == QModelIndex()) {
// qDebug() << "Nothing selected. Disabling delete action";
m_deleteItemAct->setEnabled(false);
} else {
// qDebug() << "Something selected. Enabling delete action";
m_deleteItemAct->setEnabled(true);
}
}
void MainWindow::onSelectionChanged(const QItemSelection& selected,
const QItemSelection& deselected) {
Q_UNUSED(selected);
Q_UNUSED(deselected);
QItemSelection localSelection = ui->tableView->selectionModel()->selection();
if (localSelection.empty()) {
// qDebug() << "Nothing selected. Disabling delete action";
m_deleteItemAct->setEnabled(false);
} else {
// qDebug() << "Something selected. Enabling delete action";
m_deleteItemAct->setEnabled(true);
}
}
void MainWindow::onAboutClicked() {
const QString applicationName = APPLICATION_NAME;
const QString titlePrefix = tr("About ");
// TODO read the about text from a rich text / markdown somewhere else.
const QString aboutText =
tr(QString("<b>%1 v%2</b> is a software project to manage the yearly crop share "
"auction (german: Bietrunde) of a Community-supported agriculture (CSA, german: "
"Solidarische Landwirtschaft (SoLaWi))."
"<br><br><a href=\"https://working-copy.org/\">Working-Copy_Collective website</a>"
"<br><br><a href=\"mailto:support@working-copy.org\">Mail to support</a>"
"<br><br>It uses the <a href=\"https://qt.io\">Qt Framework</a>.")
.arg(applicationName)
.arg(APPLICATION_VERSION)
.toLatin1());
QMessageBox::about(this, titlePrefix + applicationName, aboutText);
}
void MainWindow::on_actionCheck_for_update_triggered() {
showStatusMessage("Checking for update...");
const bool updateAvailable = m_core->isApplicationUpdateAvailable();
if (updateAvailable) {
const QString text = isWindowModified() ? updateTextDirty : updateTextClean;
const QMessageBox::StandardButton clickedButton = QMessageBox::question(
this, tr("Update available."), text, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (clickedButton == QMessageBox::Yes) {
m_core->triggerApplicationUpdate(true);
close();
}
}
}
void MainWindow::openNewItemDialog() {
showStatusMessage(tr("Invoked 'Edit|New Item'"));
m_newItemDialog->show();
}
void MainWindow::openEditItemDialog() {
showStatusMessage(tr("Invoked 'Edit|Edit Item'"));
m_editItemDialog->show();
}
void MainWindow::deleteCurrentItem() {
showStatusMessage(tr("Invoked 'Edit|Delete Item'"));
// QItemSelection localSelection = ui->tableView->selectionModel()->selection();
const QModelIndex currentIndex = ui->tableView->selectionModel()->currentIndex();
if (currentIndex == QModelIndex()) {
qDebug() << "No current item. Nothing to remove.";
} else {
m_proxyModel->removeRows(currentIndex.row(), 1);
}
}
void MainWindow::deleteSelectedtItems() {
showStatusMessage(tr("Invoked 'Edit|Delete Item'"));
QItemSelection localSelection = ui->tableView->selectionModel()->selection();
if (localSelection.empty()) {
qDebug() << "No items selected. Nothing to remove.";
} else {
for (QList<QItemSelectionRange>::reverse_iterator iter = localSelection.rbegin(),
rend = localSelection.rend();
iter != rend; ++iter) {
// qInfo() << "iter:" << *iter;
// const QModelIndex parentIndex = iter->parent();
const int topRow = iter->top();
const int bottomRow = iter->bottom();
const int nRows = bottomRow - topRow + 1;
m_proxyModel->removeRows(topRow, nRows);
}
}
}
void MainWindow::onCleanStateChanged(bool clean) {
qInfo() << "Slot onCleanStateChanged triggered: clean:" << clean;
setWindowModified(!clean);
if (!clean) {
ui->statusbar->clearMessage();
}
}
void MainWindow::onShowUndoViewToggled(bool checked) {
// qInfo() << "Slot onShowUndoViewToggled toggled: checked:" << checked;
// m_undoView->setVisible(checked);
/// workaround until m_showUndoViewAction is checkable
qInfo() << "Slot onShowUndoViewToggled triggered, toggleing undo view...";
Q_UNUSED(checked);
if (m_modelUndoView->isVisible()) {
m_modelUndoView->setVisible(false);
} else {
m_modelUndoView->setVisible(true);
}
}
void MainWindow::saveItems() {
showStatusMessage(tr("Invoked 'File|Save'"));
m_core->saveItems();
}
void MainWindow::importCSV() {
showStatusMessage(tr("Invoked 'File|Import CSV'"));
const QString csvFilePath = QFileDialog::getOpenFileName(
this, tr("Import CSV"), QStandardPaths::standardLocations(standardLocation).first(),
tr("CSV Files (*.csv)"));
if (QFileInfo::exists(csvFilePath)) {
m_core->importCSVFile(csvFilePath);
showStatusMessage(tr("Imported CSV file."));
} else {
qWarning() << "Selected CSV file path doesn't exist. Doing nothing...";
showStatusMessage(tr("Could't find CSV file!"));
}
}
void MainWindow::exportCSV() {
showStatusMessage(tr("Invoked 'File|Export'"));
const QString filter = tr("CSV Files (*.csv)");
const QString location = QStandardPaths::standardLocations(standardLocation).first();
QFileDialog dialog(this, "Export CSV File", location, "Comma-separated file (*.csv)");
dialog.setDefaultSuffix(".csv");
dialog.setAcceptMode(QFileDialog::AcceptSave);
if (dialog.exec()) {
const QString csvFilePath = dialog.selectedFiles().first();
const bool successful = m_core->exportCSVFile(csvFilePath);
if (successful) {
const QString message = QString(tr("CSV exported to: %1")).arg(csvFilePath);
showStatusMessage(message);
}
} else {
qWarning() << "Selected CSV file path doesn't exist. Doing nothing...";
}
}
void MainWindow::findItems() {
showStatusMessage(tr("Invoked 'Edit|Find items'"));
bool ok;
QString text = QInputDialog::getText(this, tr("Find items"), tr("Enter the text to search for:"),
QLineEdit::Normal, "", &ok);
if (ok && !text.isEmpty()) {
const QItemSelection itemsToSelect = m_proxyModel->findItems(text);
if (itemsToSelect.empty()) {
ui->tableView->setCurrentIndex(QModelIndex());
ui->tableView->selectionModel()->select(QModelIndex(), QItemSelectionModel::ClearAndSelect);
} else {
ui->tableView->setCurrentIndex(itemsToSelect.first().topLeft());
ui->tableView->selectionModel()->select(itemsToSelect, QItemSelectionModel::ClearAndSelect);
}
}
}
void MainWindow::fetchCurrentBiddings() {
showStatusMessage(tr("Invoked 'Server|Fetch current biddings'"));
emit m_core->sendGetRequest(GetBiddingsOfHighestRound);
}
void MainWindow::execSettingsDialog() {
showStatusMessage(tr("Invoked 'Tools|Settings'"));
QVariantMap oldSettings = m_core->getSettings("Server");
// SettingsDialog* settingsDialog = new SettingsDialog(settingMap, this);
SettingsDialog* settingsDialog = new SettingsDialog(this);
settingsDialog->createContent();
settingsDialog->fillContent(oldSettings);
int returnCode = settingsDialog->exec();
if (returnCode == QDialog::Accepted) {
qDebug() << "Settings dialog accepted, writing settings...";
const QVariantMap settings = settingsDialog->getSettings();
m_core->applySettings(settings, "Server");
// TODO use signal-slot connection Core::syncServerSetupChanged(bool enabled) ->
// MainWindow::onSyncServerSetupChanged(bool enabled)
// enableDisableServerActions();
} else {
qDebug() << "Settings dialog rejected";
}
delete settingsDialog;
}
void MainWindow::setupModelViews() {
// m_tableModel = m_core->getModel();
// ui->tableView->setModel(m_tableModel.get());
m_proxyModel = m_core->getSortFilterModel();
/// setting number delegates to combo boxes
SpinboxDelegate* spinboxDelegate = new SpinboxDelegate(this);
ui->tableView->setItemDelegateForColumn(0, spinboxDelegate);
ui->tableView->setItemDelegateForColumn(4, spinboxDelegate);
ui->tableView->setItemDelegateForColumn(6, spinboxDelegate);
ui->tableView->setItemDelegateForColumn(7, spinboxDelegate);
ui->tableView->setItemDelegateForColumn(8, spinboxDelegate);
/// setting type delegates to combo boxes
ComboboxDelegate* shareTypeDelegate = new ComboboxDelegate(SHARE_TYPES, this);
ComboboxDelegate* biddingTypeDelegate = new ComboboxDelegate(BIDDING_TYPES, this);
ui->tableView->setItemDelegateForColumn(3, shareTypeDelegate);
ui->tableView->setItemDelegateForColumn(5, biddingTypeDelegate);
ui->tableView->setModel((QAbstractItemModel*)m_proxyModel.get());
ui->tableView->setSortingEnabled(true);
ui->tableView->setColumnWidth(0, intColumnWidth);
m_modelSummary = m_core->getModelSummary();
}
void MainWindow::createActions() {
// TODO add generic menu actions (file/new, edit/cut, ...)
createFileActions();
createUndoActions();
createEditActions();
createServerActions();
createToolsActions();
}
void MainWindow::createFileActions() {
m_newFileAct = make_unique<QAction>(tr("&New File"), this);
m_newFileAct->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));
m_newFileAct->setStatusTip(tr("Create a new file"));
// connect(m_newAct, &QAction::triggered, this, &MainWindow::newFile);
m_newFileAct->setEnabled(false);
ui->menu_File->addAction(m_newFileAct.get());
m_openAct = make_unique<QAction>(tr("&Open..."), this);
m_openAct->setShortcuts(QKeySequence::Open);
m_openAct->setStatusTip(tr("Open an existing file"));
// connect(m_openAct, &QAction::triggered, this, &MainWindow::open);
m_openAct->setEnabled(false);
ui->menu_File->addAction(m_openAct.get());
m_saveAct = make_unique<QAction>(tr("&Save"), this);
m_saveAct->setShortcuts(QKeySequence::Save);
m_saveAct->setStatusTip(tr("Save the document to disk"));
connect(m_saveAct.get(), &QAction::triggered, this, &MainWindow::saveItems);
ui->menu_File->addAction(m_saveAct.get());
ui->menu_File->addSeparator();
m_importAct = make_unique<QAction>(tr("&Import CSV..."), this);
m_importAct->setStatusTip(tr("Import an existing CSV file"));
connect(m_importAct.get(), &QAction::triggered, this, &MainWindow::importCSV);
ui->menu_File->addAction(m_importAct.get());
m_exportAct = make_unique<QAction>(tr("&Export CSV..."), this);
m_exportAct->setStatusTip(tr("Export content to a CSV document to disk"));
connect(m_exportAct.get(), &QAction::triggered, this, &MainWindow::exportCSV);
ui->menu_File->addAction(m_exportAct.get());
ui->menu_File->addSeparator();
m_printAct = make_unique<QAction>(tr("&Print..."), this);
m_printAct->setShortcuts(QKeySequence::Print);
m_printAct->setStatusTip(tr("Print the document"));
// connect(m_printAct, &QAction::triggered, this, &MainWindow::print);
m_printAct->setEnabled(false);
ui->menu_File->addAction(m_printAct.get());
ui->menu_File->addSeparator();
m_exitAct = make_unique<QAction>(tr("E&xit"), this);
m_exitAct->setShortcuts(QKeySequence::Quit);
m_exitAct->setStatusTip(tr("Exit the application"));
connect(m_exitAct.get(), &QAction::triggered, this, &QWidget::close);
ui->menu_File->addAction(m_exitAct.get());
}
void MainWindow::createUndoActions() {
if (!m_core) {
qCritical() << "No core instance set, aborting...";
return;
}
m_modelUndoStack = m_core->getModelUndoStack();
connect(m_modelUndoStack, &QUndoStack::cleanChanged, this, &MainWindow::onCleanStateChanged);
m_undoAct.reset(m_modelUndoStack->createUndoAction(this, tr("&Undo")));
m_undoAct->setShortcuts(QKeySequence::Undo);
m_undoAct->setStatusTip(tr("Undo the last operation"));
ui->menu_Edit->addAction(m_undoAct.get());
m_redoAct.reset(m_modelUndoStack->createRedoAction(this, tr("&Redo")));
m_redoAct->setShortcuts(QKeySequence::Redo);
m_redoAct->setStatusTip(tr("Redo the last operation"));
ui->menu_Edit->addAction(m_redoAct.get());
m_modelUndoView = make_unique<QUndoView>(m_modelUndoStack);
m_modelUndoView->setWindowTitle(tr("Undo list"));
m_modelUndoView->setAttribute(Qt::WA_QuitOnClose, false);
m_modelUndoView->setMinimumSize(450, 600);
m_showModelUndoViewAct = make_unique<QAction>(tr("Show undo/redo window"), this);
m_showModelUndoViewAct->setStatusTip(tr("Opens a window displaying the items on the undo stack"));
// TODO showUndoViewAction should be checkable
// m_showUndoViewAction->setCheckable(true);
// connect(m_showUndoViewAction, &QAction::toggled, this, &MainWindow::onShowUndoViewToggled);
connect(m_showModelUndoViewAct.get(), &QAction::triggered, this,
&MainWindow::onShowUndoViewToggled);
ui->menu_View->addAction(m_showModelUndoViewAct.get());
}
void MainWindow::createEditActions() {
m_cutAct = make_unique<QAction>(tr("Cu&t"), this);
m_cutAct->setShortcuts(QKeySequence::Cut);
m_cutAct->setStatusTip(
tr("Cut the current selection's contents to the "
"clipboard"));
// connect(m_cutAct, &QAction::triggered, this, &MainWindow::cut);
m_cutAct->setEnabled(false);
ui->menu_Edit->addAction(m_cutAct.get());
m_copyAct = make_unique<QAction>(tr("&Copy"), this);
m_copyAct->setShortcuts(QKeySequence::Copy);
m_copyAct->setStatusTip(
tr("Copy the current selection's contents to the "
"clipboard"));
// connect(m_copyAct, &QAction::triggered, this, &MainWindow::copy);
m_copyAct->setEnabled(false);
ui->menu_Edit->addAction(m_copyAct.get());
m_pasteAct = make_unique<QAction>(tr("&Paste"), this);
m_pasteAct->setShortcuts(QKeySequence::Paste);
m_pasteAct->setStatusTip(
tr("Paste the clipboard's contents into the current "
"selection"));
// connect(m_pasteAct, &QAction::triggered, this, &MainWindow::paste);
m_pasteAct->setEnabled(false);
ui->menu_Edit->addAction(m_pasteAct.get());
ui->menu_Edit->addSeparator();
m_openNewItemDialogAct = make_unique<QAction>(tr("&New item"), this);
m_openNewItemDialogAct->setShortcut(QKeySequence::New);
m_openNewItemDialogAct->setStatusTip(tr("Opens a dialog to add a new item"));
connect(m_openNewItemDialogAct.get(), &QAction::triggered, this, &MainWindow::openNewItemDialog);
ui->menu_Edit->addAction(m_openNewItemDialogAct.get());
m_openEditItemDialogAct = make_unique<QAction>(tr("&Edit item"), this);
m_openEditItemDialogAct->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_E));
m_openEditItemDialogAct->setStatusTip(tr("Opens a edit dialog for the current item"));
connect(m_openEditItemDialogAct.get(), &QAction::triggered, this,
&MainWindow::openEditItemDialog);
ui->menu_Edit->addAction(m_openEditItemDialogAct.get());
m_deleteItemAct = make_unique<QAction>(tr("&Delete item(s)"), this);
m_deleteItemAct->setShortcut(QKeySequence::Delete);
m_deleteItemAct->setStatusTip(tr("Delete currently selected item(s)"));
// connect(m_deleteItemAct.get(), &QAction::triggered, this, &MainWindow::deleteSelectedtItems);
connect(m_deleteItemAct.get(), &QAction::triggered, this, &MainWindow::deleteCurrentItem);
ui->menu_Edit->addAction(m_deleteItemAct.get());
ui->menu_Edit->addSeparator();
m_findItemAct = make_unique<QAction>(tr("&Find item(s)"), this);
m_findItemAct->setShortcuts(QKeySequence::Find);
m_findItemAct->setStatusTip(tr("Opens a dialog to find item(s) by containing text"));
connect(m_findItemAct.get(), &QAction::triggered, this, &MainWindow::findItems);
ui->menu_Edit->addAction(m_findItemAct.get());
}
void MainWindow::createServerActions() {
m_fetchCurrentBiddingsAct = make_unique<QAction>(tr("&Fetch biddings"), this);
m_fetchCurrentBiddingsAct->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Down));
m_fetchCurrentBiddingsAct->setStatusTip(tr("Fetches all biddings of the current round"));
connect(m_fetchCurrentBiddingsAct.get(), &QAction::triggered, this,
&MainWindow::fetchCurrentBiddings);
ui->menu_Server->addAction(m_fetchCurrentBiddingsAct.get());
}
void MainWindow::createToolsActions() {
QMenu* menu = ui->menu_Tools;
QAction* settingsAct = menu->addAction(tr("&Settings"), this, &MainWindow::execSettingsDialog);
settingsAct->setStatusTip(tr("Opens a dialog to configure applications settings."));
}
void MainWindow::createHelpMenu() {
QMenu* helpMenu = ui->menu_Help;
helpMenu->addSeparator();
QAction* aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::onAboutClicked);
aboutAct->setStatusTip(tr("Show the application's About box"));
QAction* aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
}
void MainWindow::createGuiDialogs() {
/// new item dialog
m_newItemDialog = make_unique<NewItemDialog>(this);
m_newItemDialog->createContent();
connect(m_newItemDialog.get(), &NewItemDialog::addItems, m_proxyModel.get(),
&GeneralSortFilterModel::appendItems);
/// edit item dialog
m_editItemDialog = make_unique<EditItemDialog>(ui->tableView, this);
m_editItemDialog->createContent();
}
void MainWindow::setupEventTab() {
QWidget* containerWidget = new QWidget();
QVBoxLayout* containerLayout = new QVBoxLayout(containerWidget);
m_biddingRoundControl = make_unique<BiddingRoundControl>();
containerLayout->addWidget(m_biddingRoundControl.get());
/// requests
connect(m_biddingRoundControl.get(), &BiddingRoundControl::sendGetRequest, m_core.get(),
&GenericCore::sendGetRequest);
/// responses
connect(m_core.get(), &GenericCore::currentBiddingRoundChanged, m_biddingRoundControl.get(),
&BiddingRoundControl::onCurrentBiddingRoundChanged);
SummaryWidget* summaryWidget = new SummaryWidget(m_modelSummary, this);
containerLayout->addWidget(summaryWidget);
ui->tabWidget->insertTab(0, containerWidget, "Event (&1)");
}
void MainWindow::initServerConnection() {
connect(m_editItemDialog.get(), &EditItemDialog::createOnlineAccountTriggered, m_core.get(),
&GenericCore::onCreateOnlineAccountTriggered);
connect(m_editItemDialog.get(), &EditItemDialog::sendInviteMailTriggered, m_core.get(),
&GenericCore::onSendInviteMailTriggered);
emit m_core->loginAndStoreAuthToken();
}

View File

@ -0,0 +1,126 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QItemSelection>
#include <QMainWindow>
QT_BEGIN_NAMESPACE
class QUndoStack;
class QUndoView;
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class GenericCore;
class TableModel;
class GeneralSortFilterModel;
class ModelSummary;
class NewItemDialog;
class EditItemDialog;
class BiddingRoundControl;
using namespace std;
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr);
~MainWindow();
signals:
void displayStatusMessage(QString message);
void checkForUpdates();
protected:
void closeEvent(QCloseEvent* event) override;
private slots:
void showStatusMessage(const QString text);
void onCurrentChanged(const QModelIndex& current, const QModelIndex& previous);
void onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
void onAboutClicked();
void on_actionCheck_for_update_triggered();
/// slots for menu actions
void openNewItemDialog();
void openEditItemDialog();
void deleteCurrentItem();
void deleteSelectedtItems();
void onCleanStateChanged(bool clean);
void onShowUndoViewToggled(bool checked);
/// 'File' slots
void saveItems();
void importCSV();
void exportCSV();
/// 'Edit' slots
void findItems();
/// 'Server' slots
void fetchCurrentBiddings();
/// 'Tools' slots
void execSettingsDialog();
private:
Ui::MainWindow* ui;
unique_ptr<GenericCore> m_core;
shared_ptr<GeneralSortFilterModel> m_proxyModel;
shared_ptr<ModelSummary> m_modelSummary;
QUndoStack* m_modelUndoStack;
unique_ptr<QUndoView> m_modelUndoView;
unique_ptr<BiddingRoundControl> m_biddingRoundControl;
/// File actions
unique_ptr<QAction> m_newFileAct;
unique_ptr<QAction> m_openAct;
unique_ptr<QAction> m_saveAct;
unique_ptr<QAction> m_importAct;
unique_ptr<QAction> m_exportAct;
unique_ptr<QAction> m_printAct;
unique_ptr<QAction> m_exitAct;
/// Edit actions
unique_ptr<QAction> m_undoAct;
unique_ptr<QAction> m_redoAct;
unique_ptr<QAction> m_cutAct;
unique_ptr<QAction> m_copyAct;
unique_ptr<QAction> m_pasteAct;
unique_ptr<QAction> m_openNewItemDialogAct;
unique_ptr<QAction> m_openEditItemDialogAct;
unique_ptr<QAction> m_deleteItemAct;
unique_ptr<QAction> m_findItemAct;
/// Server actions
unique_ptr<QAction> m_fetchCurrentBiddingsAct;
/// View actions
unique_ptr<QAction> m_showModelUndoViewAct;
/// Dialogs
unique_ptr<NewItemDialog> m_newItemDialog;
unique_ptr<EditItemDialog> m_editItemDialog;
/// Setup functions
void setupModelViews();
void createActions();
void createFileActions();
void createUndoActions();
void createEditActions();
void createServerActions();
void createToolsActions();
void createHelpMenu();
void createGuiDialogs();
void setupEventTab();
void initServerConnection();
};
#endif // MAINWINDOW_H

View File

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>GenericQtClient</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab_user">
<attribute name="title">
<string>Mitglieder (&amp;2)</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QTableView" name="tableView"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>22</height>
</rect>
</property>
<widget class="QMenu" name="menu_File">
<property name="title">
<string>&amp;File</string>
</property>
</widget>
<widget class="QMenu" name="menu_Edit">
<property name="title">
<string>&amp;Edit</string>
</property>
</widget>
<widget class="QMenu" name="menu_View">
<property name="title">
<string>&amp;View</string>
</property>
</widget>
<widget class="QMenu" name="menu_Help">
<property name="title">
<string>&amp;Help</string>
</property>
<addaction name="actionCheck_for_update"/>
</widget>
<widget class="QMenu" name="menu_Server">
<property name="title">
<string>&amp;Server</string>
</property>
</widget>
<widget class="QMenu" name="menu_Tools">
<property name="title">
<string>&amp;Tools</string>
</property>
</widget>
<addaction name="menu_File"/>
<addaction name="menu_Edit"/>
<addaction name="menu_View"/>
<addaction name="menu_Server"/>
<addaction name="menu_Tools"/>
<addaction name="menu_Help"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="actionCheck_for_update">
<property name="text">
<string>Check for &amp;update</string>
</property>
</action>
</widget>
<resources/>
<connections/>
<slots>
<slot>onPushButtonClicked()</slot>
</slots>
</ui>

View File

@ -0,0 +1,164 @@
#ifndef MESSAGEHANDLER_H
#define MESSAGEHANDLER_H
/**
* Color and formatting codes
* @see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
*/
#include <QObject>
// qSetMessagePattern("%{file}(%{line}): %{message}");
// qSetMessagePattern("%{type}(%{line}):\t%{message}");
// qSetMessagePattern("%{type}%{file}(%{line}):\t%{message}");
void consoleHandlerColoredVerbose(QtMsgType type,
const QMessageLogContext& context,
const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
// context.line, context.function, localMsg.constData()); // bold
fprintf(stderr, "\033[107;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
abort();
}
}
void consoleHandlerColoredVerboseInDarkTheme(QtMsgType type,
const QMessageLogContext& context,
const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
// context.line, context.function, localMsg.constData()); // bold
fprintf(stderr, "\033[107;37mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
context.function, localMsg.constData());
abort();
}
}
void consoleHandlerColored(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "\033[1;30mDebug: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtInfoMsg:
fprintf(stderr, "\033[0;30mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtWarningMsg:
fprintf(stderr, "\033[1;33mWarning: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtCriticalMsg:
fprintf(stderr, "\033[31mCritical: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
break;
case QtFatalMsg:
fprintf(stderr, "\033[31mFatal: (%s:%u) \t%s\n\033[0m", context.file, context.line,
localMsg.constData());
abort();
}
}
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
context.function);
abort();
}
}
#ifdef Q_OS_ANDROID
#include <android/log.h>
const char* const applicationName = "Pensieve";
void androidMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
QString report = msg;
if (context.file && !QString(context.file).isEmpty()) {
report += " in file ";
report += QString(context.file);
report += " line ";
report += QString::number(context.line);
}
if (context.function && !QString(context.function).isEmpty()) {
report += +" function ";
report += QString(context.function);
}
const char* const local = report.toLocal8Bit().constData();
switch (type) {
case QtDebugMsg:
__android_log_write(ANDROID_LOG_DEBUG, applicationName, local);
break;
case QtInfoMsg:
__android_log_write(ANDROID_LOG_INFO, applicationName, local);
break;
case QtWarningMsg:
__android_log_write(ANDROID_LOG_WARN, applicationName, local);
break;
case QtCriticalMsg:
__android_log_write(ANDROID_LOG_ERROR, applicationName, local);
break;
case QtFatalMsg:
default:
__android_log_write(ANDROID_LOG_FATAL, applicationName, local);
abort();
}
}
#endif
#endif // MESSAGEHANDLER_H

View File

@ -0,0 +1,315 @@
#include "itemdetailmapper.h"
#include <data/settingshandler.h>
#include <QAbstractItemModel>
#include <QComboBox>
#include <QDataWidgetMapper>
#include <QGridLayout>
#include <QJsonArray>
#include <QJsonObject>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QStringListModel>
#include <QTableView>
#include "model/metadata.h"
ItemDetailMapper::ItemDetailMapper(QWidget* parent)
: QWidget{parent}
, m_qrCodeDisplay(new QLabel("QR Code")) {
/// model mapping
m_mapper = std::make_unique<QDataWidgetMapper>(this);
/// BUG: If multiple columns are changed not all changes are applied.
/// Multiple changes are set individually by calling setData().
/// Probably due to a conflicting dataChanged signal for too many roles&columns the data of
/// the remaining columns is reset before setData is called.
/// And a manual submit would also create multiple undo steps anyway.
/// Workaround: ManualSubmit -> AutoSubmit
// m_mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
m_mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
/// model mapping buttons
m_nextButton = new QPushButton(tr("Ne&xt"));
m_previousButton = new QPushButton(tr("&Previous"));
connect(m_previousButton, &QAbstractButton::clicked, this, &ItemDetailMapper::toPrevious);
connect(m_nextButton, &QAbstractButton::clicked, this, &ItemDetailMapper::toNext);
/// the individual widgets
// REFACTOR deduce types from meta data & use a factory
/// left layout
m_numberLabel = new QLabel(GET_HEADER_FOR_COLUMN(0));
m_numberBox = new QSpinBox();
m_numberBox->setMaximum(1000);
m_lastNameLabel = new QLabel(GET_HEADER_FOR_COLUMN(1));
m_lastNameEdit = new QLineEdit();
m_lastNameLabel->setBuddy(m_lastNameEdit);
m_firstNameLabel = new QLabel(GET_HEADER_FOR_COLUMN(2));
m_firstNameEdit = new QLineEdit();
m_firstNameLabel->setBuddy(m_firstNameEdit);
m_shareTypeLabel = new QLabel(GET_HEADER_FOR_COLUMN(3));
m_shareTypeBox = new QComboBox();
m_shareTypeLabel->setBuddy(m_shareTypeBox);
m_shareTypeModel = new QStringListModel(SHARE_TYPES, this);
m_shareTypeBox->setModel(m_shareTypeModel);
m_amountLabel = new QLabel(GET_HEADER_FOR_COLUMN(4));
m_amountSpinBox = new QDoubleSpinBox();
m_amountLabel->setBuddy(m_amountSpinBox);
m_biddingTypeLabel = new QLabel(GET_HEADER_FOR_COLUMN(5));
m_biddingTypeBox = new QComboBox();
m_biddingTypeLabel->setBuddy(m_biddingTypeBox);
m_biddingTypeModel = new QStringListModel(BIDDING_TYPES, this);
m_biddingTypeBox->setModel(m_biddingTypeModel);
m_bidding1Label = new QLabel(GET_HEADER_FOR_COLUMN(6));
m_bidding1SpinBox = new QSpinBox();
m_bidding1SpinBox->setMaximum(500);
m_bidding2Label = new QLabel(GET_HEADER_FOR_COLUMN(7));
m_bidding2SpinBox = new QSpinBox();
m_bidding2SpinBox->setMaximum(500);
m_bidding3Label = new QLabel(GET_HEADER_FOR_COLUMN(8));
m_bidding3SpinBox = new QSpinBox();
m_bidding3SpinBox->setMaximum(500);
m_depotWish1Label = new QLabel(GET_HEADER_FOR_COLUMN(9));
m_depotWish1Edit = new QLineEdit();
m_depotWish1Label->setBuddy(m_depotWish1Edit);
m_depotWish2Label = new QLabel(GET_HEADER_FOR_COLUMN(10));
m_depotWish2Edit = new QLineEdit();
m_depotWish2Label->setBuddy(m_depotWish2Edit);
m_mailLabel = new QLabel(GET_HEADER_FOR_COLUMN(11));
m_mailEdit = new QLineEdit();
m_mailEdit->setMinimumWidth(200);
m_mailLabel->setBuddy(m_mailEdit);
/// right layout
m_createOnlineAccountButton = new QPushButton(tr("&Create account"));
m_sendInviteMailButton = new QPushButton(tr("&Send invite"));
m_onlineIdLabel = new QLabel(GET_HEADER_FOR_COLUMN(12));
m_onlineIdDisplay = new QLineEdit();
m_onlineIdDisplay->setReadOnly(true);
m_onlineIdLabel->setBuddy(m_onlineIdDisplay);
m_accessCodeLabel = new QLabel(GET_HEADER_FOR_COLUMN(13));
m_accessCodeDisplay = new QLineEdit();
m_accessCodeDisplay->setReadOnly(true);
m_accessCodeLabel->setBuddy(m_onlineIdDisplay);
updateQRCode();
connect(this, &ItemDetailMapper::contentChanged, this, &ItemDetailMapper::updateQRCode);
m_accessUrlDisplay = new QLineEdit();
m_accessUrlDisplay->setReadOnly(true);
QGridLayout* leftLayout = new QGridLayout();
leftLayout->addWidget(m_numberLabel, 0, 0, 1, 1);
leftLayout->addWidget(m_numberBox, 0, 1, 1, 1);
leftLayout->addWidget(m_lastNameLabel, 1, 0, 1, 1);
leftLayout->addWidget(m_lastNameEdit, 1, 1, 1, 1);
leftLayout->addWidget(m_firstNameLabel, 2, 0, 1, 1);
leftLayout->addWidget(m_firstNameEdit, 2, 1, 1, 1);
leftLayout->addWidget(m_shareTypeLabel, 3, 0, 1, 1);
leftLayout->addWidget(m_shareTypeBox, 3, 1, 1, 1);
leftLayout->addWidget(m_amountLabel, 4, 0, 1, 1);
leftLayout->addWidget(m_amountSpinBox, 4, 1, 1, 1);
leftLayout->addWidget(m_biddingTypeLabel, 5, 0, 1, 1);
leftLayout->addWidget(m_biddingTypeBox, 5, 1, 1, 1);
leftLayout->addWidget(m_bidding1Label, 6, 0, 1, 1);
leftLayout->addWidget(m_bidding1SpinBox, 6, 1, 1, 1);
leftLayout->addWidget(m_bidding2Label, 7, 0, 1, 1);
leftLayout->addWidget(m_bidding2SpinBox, 7, 1, 1, 1);
leftLayout->addWidget(m_bidding3Label, 8, 0, 1, 1);
leftLayout->addWidget(m_bidding3SpinBox, 8, 1, 1, 1);
leftLayout->addWidget(m_depotWish1Label, 9, 0, 1, 1);
leftLayout->addWidget(m_depotWish1Edit, 9, 1, 1, 1);
leftLayout->addWidget(m_depotWish2Label, 10, 0, 1, 1);
leftLayout->addWidget(m_depotWish2Edit, 10, 1, 1, 1);
leftLayout->addWidget(m_mailLabel, 11, 0, 1, 1);
leftLayout->addWidget(m_mailEdit, 11, 1, 1, 1);
leftLayout->addWidget(m_previousButton, 12, 0, 1, 1);
leftLayout->addWidget(m_nextButton, 12, 1, 1, 1);
/// right layout
QVBoxLayout* rightLayout = new QVBoxLayout;
QHBoxLayout* onlineAccountControlLayout = new QHBoxLayout;
onlineAccountControlLayout->addWidget(m_createOnlineAccountButton);
onlineAccountControlLayout->addWidget(m_sendInviteMailButton);
rightLayout->addLayout(onlineAccountControlLayout);
QGridLayout* rightGridLayout = new QGridLayout();
rightGridLayout->addWidget(m_onlineIdLabel, 0, 0, 1, 1);
rightGridLayout->addWidget(m_onlineIdDisplay, 0, 1, 1, 1);
rightGridLayout->addWidget(m_accessCodeLabel, 1, 0, 1, 1);
rightGridLayout->addWidget(m_accessCodeDisplay, 1, 1, 1, 1);
rightGridLayout->addWidget(m_qrCodeDisplay, 2, 0, 6, 2);
rightGridLayout->addWidget(m_accessUrlDisplay, 9, 0, 1, 2);
rightLayout->addLayout(rightGridLayout);
QHBoxLayout* outerLayout = new QHBoxLayout;
outerLayout->addLayout(leftLayout);
outerLayout->addLayout(rightLayout);
setLayout(outerLayout);
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
const QString urlValue = serverSettings.value("url").toString();
m_serverUrl = urlValue;
/// online user account
connect(m_mailEdit, &QLineEdit::textChanged, this, &ItemDetailMapper::onMailEditChanged);
connect(m_onlineIdDisplay, &QLineEdit::textChanged, this, &ItemDetailMapper::onOnlineIDChanged);
connect(m_accessCodeDisplay, &QLineEdit::textChanged, this,
&ItemDetailMapper::onAccessCodeChanged);
connect(m_createOnlineAccountButton, &QAbstractButton::clicked, this,
&ItemDetailMapper::onCreateOnlineAccountTriggered);
connect(m_sendInviteMailButton, &QAbstractButton::clicked, this,
&ItemDetailMapper::onSendInviteMailTriggered);
}
void ItemDetailMapper::setModelMappings(QTableView* tableView) {
qDebug() << "Setting model...";
m_tableView = tableView;
m_model = tableView->model();
m_selectionModel = tableView->selectionModel();
m_mapper->setModel(m_model);
m_mapper->addMapping(m_numberBox, 0);
m_mapper->addMapping(m_lastNameEdit, 1);
m_mapper->addMapping(m_firstNameEdit, 2);
m_mapper->addMapping(m_shareTypeBox, 3, "currentText");
m_mapper->addMapping(m_amountSpinBox, 4);
m_mapper->addMapping(m_biddingTypeBox, 5, "currentText");
m_mapper->addMapping(m_bidding1SpinBox, 6);
m_mapper->addMapping(m_bidding2SpinBox, 7);
m_mapper->addMapping(m_bidding3SpinBox, 8);
m_mapper->addMapping(m_depotWish1Edit, 9);
m_mapper->addMapping(m_depotWish2Edit, 10);
m_mapper->addMapping(m_mailEdit, 11);
m_mapper->addMapping(m_onlineIdDisplay, 12);
m_mapper->addMapping(m_accessCodeDisplay, 13);
m_mapper->setCurrentIndex(m_selectionModel->currentIndex().row());
connect(m_model, &QAbstractItemModel::rowsInserted, this, &ItemDetailMapper::rowsInserted);
connect(m_model, &QAbstractItemModel::rowsRemoved, this, &ItemDetailMapper::rowsRemoved);
connect(m_selectionModel, &QItemSelectionModel::currentChanged, this,
&ItemDetailMapper::onCurrentIndexChanged);
updateButtons(m_selectionModel->currentIndex().row());
}
bool ItemDetailMapper::submit() { return m_mapper->submit(); }
void ItemDetailMapper::revert() { m_mapper->revert(); }
void ItemDetailMapper::rowsInserted(const QModelIndex& parent, int start, int end) {
updateButtons(m_mapper->currentIndex());
}
void ItemDetailMapper::rowsRemoved(const QModelIndex& parent, int start, int end) {
if (m_model->rowCount() == 0) {
setEnabled(false);
// m_nameEdit->clear();
// m_descriptionEdit->clear();
// m_infoEdit->clear();
// m_amountBox->clear();
// m_factorBox->clear();
}
updateButtons(m_mapper->currentIndex());
}
void ItemDetailMapper::toPrevious() {
int currentRow = m_selectionModel->currentIndex().row();
QModelIndex previousIndex = m_selectionModel->currentIndex().siblingAtRow(currentRow - 1);
if (previousIndex.isValid()) {
m_selectionModel->setCurrentIndex(previousIndex, QItemSelectionModel::ClearAndSelect);
}
}
void ItemDetailMapper::toNext() {
int currentRow = m_selectionModel->currentIndex().row();
QModelIndex nextIndex = m_selectionModel->currentIndex().siblingAtRow(currentRow + 1);
if (nextIndex.isValid()) {
m_selectionModel->setCurrentIndex(nextIndex, QItemSelectionModel::ClearAndSelect);
}
}
void ItemDetailMapper::updateButtons(int row) {
m_previousButton->setEnabled(row > 0);
m_nextButton->setEnabled(row < m_model->rowCount() - 1);
}
void ItemDetailMapper::onCurrentIndexChanged(const QModelIndex& current,
const QModelIndex& /*previous*/) {
if (!isEnabled()) {
setEnabled(true);
}
m_mapper->setCurrentModelIndex(current);
updateButtons(current.row());
}
void ItemDetailMapper::updateQRCode(const QString text) {
QImage unscaledImage;
if (text.isEmpty()) {
unscaledImage = QImage("://no-picture-taking.png");
} else {
unscaledImage = m_generator.generateQr(text);
}
QImage image = unscaledImage.scaled(250, 250);
m_qrCodeDisplay->setPixmap(QPixmap::fromImage(image));
m_qrCodeDisplay->setToolTip(text);
}
void ItemDetailMapper::onMailEditChanged(const QString& text) {
if (text.isEmpty()) {
m_createOnlineAccountButton->setEnabled(false);
m_sendInviteMailButton->setEnabled(false);
} else {
onOnlineIDChanged(m_onlineIdDisplay->text());
onAccessCodeChanged(m_accessCodeDisplay->text());
}
}
void ItemDetailMapper::onOnlineIDChanged(const QString& text) {
if (text.isEmpty()) {
m_createOnlineAccountButton->setEnabled(true);
m_sendInviteMailButton->setEnabled(false);
} else {
m_createOnlineAccountButton->setEnabled(false);
m_sendInviteMailButton->setEnabled(true);
}
}
void ItemDetailMapper::onAccessCodeChanged(const QString& accessCode) {
if (accessCode.isEmpty()) {
m_sendInviteMailButton->setEnabled(false);
m_accessUrlDisplay->setText("");
updateQRCode("");
} else {
m_sendInviteMailButton->setEnabled(true);
const QString accessUrl = m_serverUrl + "/log_in/" + accessCode;
// const QString accessUrl = "https://bietrunde.das-gruene-zebra.de/log_in/" + text;
m_accessUrlDisplay->setText(accessUrl);
updateQRCode(accessUrl);
}
}
void ItemDetailMapper::onCreateOnlineAccountTriggered() {
emit createOnlineAccountTriggered(m_mailEdit->text());
}
void ItemDetailMapper::onSendInviteMailTriggered() {
emit sendInviteMailTriggered(m_mailEdit->text());
}

View File

@ -0,0 +1,117 @@
#ifndef ITEMDETAILMAPPER_H
#define ITEMDETAILMAPPER_H
#include <QDataWidgetMapper>
#include <QWidget>
class QLabel;
class QLineEdit;
class QComboBox;
class QDoubleSpinBox;
class QSpinBox;
class QPushButton;
class QAbstractItemModel;
class QItemSelectionModel;
class QStringListModel;
class QTableView;
#include "QrCodeGenerator.h"
class ItemDetailMapper : public QWidget {
Q_OBJECT
public:
explicit ItemDetailMapper(QWidget* parent = nullptr);
void setModelMappings(QTableView* tableView);
bool submit();
void revert();
signals:
void contentChanged(const QString text);
void createOnlineAccountTriggered(const QString& mailAddress);
void sendInviteMailTriggered(const QString& mailAddress);
private slots:
void rowsInserted(const QModelIndex& parent, int start, int end);
void rowsRemoved(const QModelIndex& parent, int start, int end);
void toPrevious();
void toNext();
void updateButtons(int row);
void onCurrentIndexChanged(const QModelIndex& current, const QModelIndex& previous);
void updateQRCode(const QString text = "");
void onMailEditChanged(const QString& text);
void onOnlineIDChanged(const QString& text);
void onAccessCodeChanged(const QString& accessCode);
void onCreateOnlineAccountTriggered();
void onSendInviteMailTriggered();
private:
/// *** members ***
/// Model stuff
QTableView* m_tableView = nullptr;
QAbstractItemModel* m_model = nullptr;
QItemSelectionModel* m_selectionModel = nullptr;
std::unique_ptr<QDataWidgetMapper> m_mapper;
QString m_serverUrl;
/// *** GUI elements ***
/// left layout
QLabel* m_numberLabel;
QSpinBox* m_numberBox;
QLabel* m_lastNameLabel;
QLineEdit* m_lastNameEdit;
QLabel* m_firstNameLabel;
QLineEdit* m_firstNameEdit;
QLabel* m_shareTypeLabel;
QComboBox* m_shareTypeBox;
QStringListModel* m_shareTypeModel = nullptr;
QLabel* m_amountLabel;
QDoubleSpinBox* m_amountSpinBox;
QLabel* m_biddingTypeLabel;
QComboBox* m_biddingTypeBox;
QStringListModel* m_biddingTypeModel = nullptr;
QLabel* m_bidding1Label;
QSpinBox* m_bidding1SpinBox;
QLabel* m_bidding2Label;
QSpinBox* m_bidding2SpinBox;
QLabel* m_bidding3Label;
QSpinBox* m_bidding3SpinBox;
QLabel* m_depotWish1Label;
QLineEdit* m_depotWish1Edit;
QLabel* m_depotWish2Label;
QLineEdit* m_depotWish2Edit;
QLabel* m_mailLabel;
QLineEdit* m_mailEdit;
/// right layout
QPushButton* m_createOnlineAccountButton = nullptr;
QPushButton* m_sendInviteMailButton = nullptr;
QLabel* m_onlineIdLabel;
QLineEdit* m_onlineIdDisplay = nullptr;
QLabel* m_accessCodeLabel;
QLineEdit* m_accessCodeDisplay = nullptr;
QLabel* m_qrCodeDisplay = nullptr;
QrCodeGenerator m_generator;
QLineEdit* m_accessUrlDisplay = nullptr;
/// *** Model mapper stuff ***
QPushButton* m_nextButton;
QPushButton* m_previousButton;
};
#endif // ITEMDETAILMAPPER_H

View File

@ -0,0 +1,67 @@
#include "biddingroundcontrol.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
BiddingRoundControl::BiddingRoundControl(QWidget* parent)
: QWidget{parent} {
m_layout = new QHBoxLayout(this);
m_title = new QLabel("Bidding round control:");
m_status = new QLabel("(No round started yet.)");
m_newRoundButton = new QPushButton("Start new round");
m_restartRoundButton = new QPushButton("Restart last round");
m_stopRoundButton = new QPushButton("Stop round");
m_refreshRoundButton = new QPushButton("Refresh");
m_newRoundButton->setEnabled(false);
m_restartRoundButton->setEnabled(false);
m_stopRoundButton->setEnabled(false);
m_layout->addWidget(m_title);
m_layout->addWidget(m_status);
m_layout->addWidget(m_newRoundButton);
m_layout->addWidget(m_restartRoundButton);
m_layout->addWidget(m_stopRoundButton);
m_layout->addWidget(m_refreshRoundButton);
connect(m_newRoundButton, &QPushButton::clicked, this,
&BiddingRoundControl::onStartNewRoundTriggered);
connect(m_restartRoundButton, &QPushButton::clicked, this,
&BiddingRoundControl::onRestartLastRoundTriggered);
connect(m_stopRoundButton, &QPushButton::clicked, this,
&BiddingRoundControl::onStopCurrentRoundTriggered);
connect(m_refreshRoundButton, &QPushButton::clicked, this,
&BiddingRoundControl::onRefreshCurrentRoundTriggered);
}
void BiddingRoundControl::onRefreshCurrentRoundTriggered() {
emit sendGetRequest(GetCurrentBiddingRound);
}
void BiddingRoundControl::onStartNewRoundTriggered() { emit sendGetRequest(StartNewBiddingRound); }
void BiddingRoundControl::onRestartLastRoundTriggered() {
emit sendGetRequest(RestartLastBiddingRound);
}
void BiddingRoundControl::onStopCurrentRoundTriggered() {
emit sendGetRequest(StopCurrentBiddingRound);
}
void BiddingRoundControl::onCurrentBiddingRoundChanged(int roundNumber, bool isActive) {
QString text = QString::number(roundNumber);
if (isActive) {
text.append(" (active)");
m_newRoundButton->setEnabled(false);
m_restartRoundButton->setEnabled(false);
m_stopRoundButton->setEnabled(true);
} else {
text.append(" (stopped)");
m_newRoundButton->setEnabled(true);
m_restartRoundButton->setEnabled(roundNumber > 0);
m_stopRoundButton->setEnabled(false);
}
m_status->setText(text);
}

View File

@ -0,0 +1,39 @@
#ifndef BIDDINGROUNDCONTROL_H
#define BIDDINGROUNDCONTROL_H
#include <QWidget>
#include "model/metadata.h"
class QPushButton;
class QLabel;
class QHBoxLayout;
class BiddingRoundControl : public QWidget {
Q_OBJECT
public:
explicit BiddingRoundControl(QWidget* parent = nullptr);
signals:
void sendGetRequest(GetRequestTypes type, QVariant data = QVariant());
public slots:
/// button slots
void onRefreshCurrentRoundTriggered();
void onStartNewRoundTriggered();
void onRestartLastRoundTriggered();
void onStopCurrentRoundTriggered();
/// event slots
void onCurrentBiddingRoundChanged(int roundNumber, bool isActive);
private:
QHBoxLayout* m_layout = nullptr;
QLabel* m_title = nullptr;
QLabel* m_status = nullptr;
QPushButton* m_newRoundButton = nullptr;
QPushButton* m_restartRoundButton = nullptr;
QPushButton* m_stopRoundButton = nullptr;
QPushButton* m_refreshRoundButton = nullptr;
};
#endif // BIDDINGROUNDCONTROL_H

View File

@ -0,0 +1,56 @@
#include "biddingroundprogresslayout.h"
#include <QLabel>
#include <QProgressBar>
BiddingRoundProgressLayout::BiddingRoundProgressLayout(const int nCurrentBiddings,
const int nExpectedBiddings,
QWidget* parent)
: QHBoxLayout(parent)
, m_nCurrentBiddings(nCurrentBiddings)
, m_nExpectedBiddings(nExpectedBiddings) {
QLabel* nBidsText = new QLabel("Abgegeben:");
addWidget(nBidsText);
m_nBiddingsLabel = new QLabel(QString::number(m_nCurrentBiddings));
addWidget(m_nBiddingsLabel);
QLabel* nExpectedText = new QLabel("Erwartet:");
addWidget(nExpectedText);
m_nExpectedBiddingLabel = new QLabel(QString::number(m_nExpectedBiddings));
addWidget(m_nExpectedBiddingLabel);
m_biddingRoundProgressBar = new QProgressBar(parent);
m_biddingRoundProgressBar->setMinimum(0);
m_biddingRoundProgressBar->setMaximum(m_nExpectedBiddings);
m_biddingRoundProgressBar->setValue(m_nCurrentBiddings);
addWidget(m_biddingRoundProgressBar);
updateEnabledStatus();
}
void BiddingRoundProgressLayout::setCurrentBiddings(const int value) {
m_nCurrentBiddings = value;
const QString bidCountString = QString::number(value);
m_nBiddingsLabel->setText(bidCountString);
m_biddingRoundProgressBar->setValue(value);
updateEnabledStatus();
}
void BiddingRoundProgressLayout::setExpectedBiddings(const int value) {
m_nExpectedBiddings = value;
const QString expectedBiddingsString = QString::number(value);
m_nExpectedBiddingLabel->setText(expectedBiddingsString);
m_biddingRoundProgressBar->setMaximum(value);
updateEnabledStatus();
}
void BiddingRoundProgressLayout::updateEnabledStatus() {
if (m_nCurrentBiddings > m_nExpectedBiddings) {
m_biddingRoundProgressBar->setEnabled(false);
} else {
m_biddingRoundProgressBar->setEnabled(true);
}
}

View File

@ -0,0 +1,30 @@
#ifndef BIDDINGROUNDPROGRESSLAYOUT_H
#define BIDDINGROUNDPROGRESSLAYOUT_H
#include <QHBoxLayout>
class QLabel;
class QProgressBar;
class BiddingRoundProgressLayout : public QHBoxLayout {
Q_OBJECT
public:
BiddingRoundProgressLayout(const int nCurrentBiddings,
const int nExpectedBiddings,
QWidget* parent = nullptr);
void setCurrentBiddings(const int value);
void setExpectedBiddings(const int value);
private:
int m_nCurrentBiddings;
int m_nExpectedBiddings;
QLabel* m_nBiddingsLabel = nullptr;
QLabel* m_nExpectedBiddingLabel = nullptr;
QProgressBar* m_biddingRoundProgressBar = nullptr;
void updateEnabledStatus();
};
#endif // BIDDINGROUNDPROGRESSLAYOUT_H

View File

@ -0,0 +1,110 @@
#include "biddingroundstatuswidget.h"
#include <QChartView>
#include <QLabel>
#include <QPieSeries>
#include <QVBoxLayout>
BiddingRoundStatusWidget::BiddingRoundStatusWidget(const QString& title,
const int placedBiddings,
const int expectedBiddings,
const int financialNeed,
const int currentSum,
const qreal currentAverage,
QWidget* parent)
: QWidget{parent}
, m_title(title)
, m_financialNeed(financialNeed)
, m_currentSum(currentSum) {
m_moneyDonutSeries = new QPieSeries();
m_moneyDonutSeries->setHoleSize(0.35);
const QString sumText = QString("Summe: %1 €").arg(currentSum);
m_sumSlice = m_moneyDonutSeries->append(sumText, currentSum);
m_sumSlice->setLabelVisible();
const int currentGap = m_financialNeed - currentSum;
const QString gapText = QString("offen: %1 €").arg(currentGap);
m_gapSlice = m_moneyDonutSeries->append(gapText, currentGap);
m_gapSlice->setLabelVisible();
m_chartView = new QChartView();
m_chartView->setMinimumWidth(100);
// m_chartView->setMaximumWidth(500);
m_chartView->setRenderHint(QPainter::Antialiasing);
m_chartView->chart()->setTitle(m_title);
m_chartView->chart()->addSeries(m_moneyDonutSeries);
m_chartView->chart()->legend()->setAlignment(Qt::AlignBottom);
m_chartView->chart()->setTheme(QChart::ChartThemeBlueCerulean);
m_chartView->chart()->legend()->setFont(QFont("Arial", 8));
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(m_chartView, 5);
QBoxLayout* progressLayout = createProgressLayout(placedBiddings, expectedBiddings);
layout->addLayout(progressLayout);
/// bidding average
QHBoxLayout* averageLayout = new QHBoxLayout();
m_biddingAverageDescription = new QLabel("Durchschnittsgebot: ");
const QString currencyString = createCurrencyString(currentAverage);
m_biddingAverageValue = new QLabel(currencyString);
averageLayout->addWidget(m_biddingAverageDescription);
averageLayout->addWidget(m_biddingAverageValue);
layout->addLayout(averageLayout);
setLayout(layout);
}
void BiddingRoundStatusWidget::onExpectedBiddingsChanged(const int nExpected) {
m_biddingRoundProgress->setExpectedBiddings(nExpected);
}
void BiddingRoundStatusWidget::onNPlacedBiddingsChanged(const int nPlaced) {
m_biddingRoundProgress->setCurrentBiddings(nPlaced);
}
void BiddingRoundStatusWidget::onBiddingSumChanged(const int sum) {
m_currentSum = sum;
updateDonutChart();
}
void BiddingRoundStatusWidget::onBiddingAverageChanged(const qreal average) {
if (m_biddingAverageValue) {
m_biddingAverageValue->setText(createCurrencyString(average));
}
}
void BiddingRoundStatusWidget::onFinancialNeedChanged(const int financialNeed) {
m_financialNeed = financialNeed;
updateDonutChart();
}
QBoxLayout* BiddingRoundStatusWidget::createProgressLayout(const int nPlaced, const int nExpected) {
QVBoxLayout* progressLayout = new QVBoxLayout();
m_biddingRoundProgress = new BiddingRoundProgressLayout(nPlaced, nExpected);
progressLayout->addLayout(m_biddingRoundProgress);
return progressLayout;
}
void BiddingRoundStatusWidget::updateDonutChart() {
int currentGap;
if (m_currentSum < m_financialNeed) {
currentGap = m_financialNeed - m_currentSum;
} else {
currentGap = 0;
}
const QString sumText = QString("Summe: %1 €").arg(m_currentSum);
m_sumSlice->setValue(m_currentSum);
m_sumSlice->setLabel(sumText);
const QString gapText = QString("offen: %1 €").arg(currentGap);
m_gapSlice->setValue(currentGap);
m_gapSlice->setLabel(gapText);
const bool gapLabelVisible = currentGap != 0;
m_gapSlice->setLabelVisible(gapLabelVisible);
}
QString BiddingRoundStatusWidget::createCurrencyString(const qreal value) const {
return QString::number(value) + "";
}

View File

@ -0,0 +1,53 @@
#ifndef BIDDINGROUNDSTATUSWIDGET_H
#define BIDDINGROUNDSTATUSWIDGET_H
#include "biddingroundprogresslayout.h"
#include <QWidget>
class QBoxLayout;
class QChartView;
class QPieSeries;
class QPieSlice;
class BiddingRoundStatusWidget : public QWidget {
Q_OBJECT
public:
explicit BiddingRoundStatusWidget(const QString& title,
const int placedBiddings,
const int expectedBiddings,
const int financialNeed,
const int currentSum,
const qreal currentAverage,
QWidget* parent = nullptr);
public slots:
void onExpectedBiddingsChanged(const int nExpected);
void onNPlacedBiddingsChanged(const int nPlaced);
void onBiddingSumChanged(const int sum);
void onBiddingAverageChanged(const qreal average);
void onFinancialNeedChanged(const int financialNeed);
signals:
private:
QString m_title;
int m_financialNeed;
int m_currentSum;
QChartView* m_chartView = nullptr;
QPieSeries* m_moneyDonutSeries = nullptr;
QPieSlice* m_sumSlice = nullptr;
QPieSlice* m_gapSlice = nullptr;
QLabel* m_biddingAverageDescription = nullptr;
QLabel* m_biddingAverageValue = nullptr;
BiddingRoundProgressLayout* m_biddingRoundProgress = nullptr;
QBoxLayout* createProgressLayout(const int nPlaced, const int nExpected);
void updateDonutChart();
QString createCurrencyString(const qreal value) const;
};
#endif // BIDDINGROUNDSTATUSWIDGET_H

View File

@ -0,0 +1,66 @@
#include "comboboxdelegate.h"
#include <QComboBox>
#include <QStringListModel>
#include "model/metadata.h"
ComboboxDelegate::ComboboxDelegate(const QStringList items, QObject* parent)
: QStyledItemDelegate(parent)
, m_types(new QStringListModel(items)) {}
void ComboboxDelegate::paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const {
QStyledItemDelegate::paint(painter, option, index);
}
QSize ComboboxDelegate::sizeHint(const QStyleOptionViewItem& option,
const QModelIndex& index) const {
return QStyledItemDelegate::sizeHint(option, index);
}
QWidget* ComboboxDelegate::createEditor(QWidget* parent,
const QStyleOptionViewItem& /*option*/,
const QModelIndex& /*index*/) const {
QComboBox* editor = new QComboBox(parent);
editor->setModel(m_types);
return editor;
// return QStyledItemDelegate::createEditor(parent, option, index);
}
void ComboboxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const {
/// Get the value via index of the Model
const QAbstractItemModel* localModel = index.model();
const QString headerText = localModel->headerData(index.column(), Qt::Horizontal).toString();
const UserRoles role = GET_ROLE_FOR_COLUMN(index.column());
const bool isShareType = SHARE_TYPE_ROLES.contains(role);
const bool isBiddingType = BIDDING_TYPE_ROLES.contains(role);
/// Put the value into the SpinBox
if (isShareType) {
const QString valueString = index.model()->data(index, ShareTypeRole).toString();
int value = SHARE_TYPES.indexOf(valueString);
QComboBox* combobox = static_cast<QComboBox*>(editor);
combobox->setCurrentIndex(value);
// QStyledItemDelegate::setEditorData(editor, index);
} else if (isBiddingType) {
const QString valueString = index.model()->data(index, BiddingTypeRole).toString();
int value = BIDDING_TYPES.indexOf(valueString);
// Put the value into the SpinBox
QComboBox* combobox = static_cast<QComboBox*>(editor);
combobox->setCurrentIndex(value);
// QStyledItemDelegate::setEditorData(editor, index);
} else {
qCritical() << "Could not find the correct type role for index:" << index << "!!!";
QComboBox* combobox = static_cast<QComboBox*>(editor);
combobox->setCurrentIndex(-1);
}
}
void ComboboxDelegate::setModelData(QWidget* editor,
QAbstractItemModel* model,
const QModelIndex& index) const {
QStyledItemDelegate::setModelData(editor, model, index);
}

View File

@ -0,0 +1,31 @@
#ifndef COMBOBOXDELEGATE_H
#define COMBOBOXDELEGATE_H
#include <QStyledItemDelegate>
class QStringListModel;
class ComboboxDelegate : public QStyledItemDelegate {
// TODO move source code files into subfolder "widgets/delegate"
Q_OBJECT
public:
explicit ComboboxDelegate(const QStringList items, QObject* parent = nullptr);
/// QAbstractItemDelegate interface
public:
void paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const override;
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override;
QWidget* createEditor(QWidget* parent,
const QStyleOptionViewItem& option,
const QModelIndex&) const override;
void setEditorData(QWidget* editor, const QModelIndex& index) const override;
void setModelData(QWidget* editor,
QAbstractItemModel* model,
const QModelIndex& index) const override;
private:
QStringListModel* m_types = nullptr;
};
#endif // COMBOBOXDELEGATE_H

View File

@ -0,0 +1,69 @@
#include "spinboxdelegate.h"
#include <QSpinBox>
#include "model/metadata.h"
SpinboxDelegate::SpinboxDelegate(QObject* parent)
: QStyledItemDelegate(parent) {}
void SpinboxDelegate::paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const {
QStyledItemDelegate::paint(painter, option, index);
}
QSize SpinboxDelegate::sizeHint(const QStyleOptionViewItem& option,
const QModelIndex& index) const {
return QStyledItemDelegate::sizeHint(option, index);
}
QWidget* SpinboxDelegate::createEditor(QWidget* parent,
const QStyleOptionViewItem& option,
const QModelIndex& index) const {
const QAbstractItemModel* localModel = index.model();
QString headerText = localModel->headerData(index.column(), Qt::Horizontal).toString();
const UserRoles role = GET_ROLE_FOR_COLUMN(index.column());
const bool isInt = INT_ROLES.contains(role);
if (isInt) {
QSpinBox* editor = new QSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(23000);
return editor;
} else {
QDoubleSpinBox* editor = new QDoubleSpinBox(parent);
editor->setMinimum(0);
editor->setMaximum(23000);
return editor;
}
// return QStyledItemDelegate::createEditor(parent, option, index);
}
void SpinboxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const {
// Get the value via index of the Model
const QAbstractItemModel* localModel = index.model();
QString headerText = localModel->headerData(index.column(), Qt::Horizontal).toString();
const UserRoles role = GET_ROLE_FOR_COLUMN(index.column());
const bool isInt = INT_ROLES.contains(role);
if (isInt) {
int value = index.model()->data(index, Qt::EditRole).toInt();
// Put the value into the SpinBox
QSpinBox* spinbox = static_cast<QSpinBox*>(editor);
spinbox->setValue(value);
} else {
// Put the value into the SpinBox
qreal value = index.model()->data(index, Qt::EditRole).toReal();
QDoubleSpinBox* spinbox = static_cast<QDoubleSpinBox*>(editor);
spinbox->setValue(value);
}
// QStyledItemDelegate::setEditorData(editor, index);
}
void SpinboxDelegate::setModelData(QWidget* editor,
QAbstractItemModel* model,
const QModelIndex& index) const {
QStyledItemDelegate::setModelData(editor, model, index);
}

View File

@ -0,0 +1,27 @@
#ifndef SPINBOXDELEGATE_H
#define SPINBOXDELEGATE_H
#include <QStyledItemDelegate>
class SpinboxDelegate : public QStyledItemDelegate {
// TODO move source code files into subfolder "widgets/delegate"
Q_OBJECT
public:
explicit SpinboxDelegate(QObject* parent = nullptr);
/// QAbstractItemDelegate interface
public:
void paint(QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const override;
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override;
QWidget* createEditor(QWidget* parent,
const QStyleOptionViewItem& option,
const QModelIndex& index) const override;
void setEditorData(QWidget* editor, const QModelIndex& index) const override;
void setModelData(QWidget* editor,
QAbstractItemModel* model,
const QModelIndex& index) const override;
};
#endif // SPINBOXDELEGATE_H

View File

@ -0,0 +1,166 @@
#include "summarywidget.h"
#include "biddingroundstatuswidget.h"
#include <QLabel>
#include <QProperty>
#include <QSpinBox>
#include <QVBoxLayout>
#include <model/modelsummary.h>
SummaryWidget::SummaryWidget(std::shared_ptr<ModelSummary> modelSummary, QWidget* parent)
: QWidget{parent}
, m_modelSummary(modelSummary) {
/// Layouting
QVBoxLayout* mainLayout = new QVBoxLayout(this);
/// monthly need
QHBoxLayout* footerLayout = new QHBoxLayout();
QLabel* nTotalSharesLabel = new QLabel("Erwartete Ernteanteile:");
const qreal expectedShares = m_modelSummary->nTotalExpectedShares();
m_nTotalExpectedShares = new QLabel(QString::number(expectedShares));
QLabel* financialNeedLabel = new QLabel("monatlicher Finanzbedarf:");
m_financialNeedBox = new QSpinBox();
m_financialNeedBox->setMaximum(50000);
m_financialNeedBox->setValue(m_financialNeed);
connect(m_financialNeedBox, &QSpinBox::valueChanged, this,
&SummaryWidget::onFinancialNeedChanged);
footerLayout->addWidget(nTotalSharesLabel);
footerLayout->addWidget(m_nTotalExpectedShares);
footerLayout->addStretch(1);
footerLayout->addWidget(financialNeedLabel);
footerLayout->addWidget(m_financialNeedBox);
footerLayout->addStretch(1);
QBoxLayout* roundsLayout = createBiddingOverviewLayout();
mainLayout->addLayout(roundsLayout);
mainLayout->addLayout(footerLayout);
mainLayout->setSpacing(50);
setLayout(mainLayout);
setupConnections();
}
void SummaryWidget::onFinancialNeedChanged(int newFinancialNeed) {
m_biddingStatus1->onFinancialNeedChanged(newFinancialNeed);
m_biddingStatus2->onFinancialNeedChanged(newFinancialNeed);
m_biddingStatus3->onFinancialNeedChanged(newFinancialNeed);
}
void SummaryWidget::onNExpectedBiddingChanged(int newNExpected) {
m_biddingStatus1->onExpectedBiddingsChanged(newNExpected);
m_biddingStatus2->onExpectedBiddingsChanged(newNExpected);
m_biddingStatus3->onExpectedBiddingsChanged(newNExpected);
}
void SummaryWidget::onNTotalExpectedSharesChanged(qreal newNExpected) {
const QString expectedSharesString = QString::number(newNExpected);
m_nTotalExpectedShares->setText(expectedSharesString);
}
void SummaryWidget::onNPlacedBiddingsChanged(const int roundNumber) {
switch (roundNumber) {
case 1:
m_biddingStatus1->onNPlacedBiddingsChanged(m_modelSummary->nPlacedBiddings1());
break;
case 2:
m_biddingStatus2->onNPlacedBiddingsChanged(m_modelSummary->nPlacedBiddings2());
break;
case 3:
m_biddingStatus3->onNPlacedBiddingsChanged(m_modelSummary->nPlacedBiddings3());
break;
default:
qWarning() << "Unknown round number:" << roundNumber;
break;
}
}
void SummaryWidget::onBiddingSumChanged(const int roundNumber) {
switch (roundNumber) {
case 1:
m_biddingStatus1->onBiddingSumChanged(m_modelSummary->biddingSum1());
break;
case 2:
m_biddingStatus2->onBiddingSumChanged(m_modelSummary->biddingSum2());
break;
case 3:
m_biddingStatus3->onBiddingSumChanged(m_modelSummary->biddingSum3());
break;
default:
qWarning() << "Unknown round number:" << roundNumber;
break;
}
}
void SummaryWidget::onBiddingAverageChanged(const int roundNumber) {
switch (roundNumber) {
case 1:
m_biddingStatus1->onBiddingAverageChanged(m_modelSummary->biddingAverage1());
break;
case 2:
m_biddingStatus2->onBiddingAverageChanged(m_modelSummary->biddingAverage2());
break;
case 3:
m_biddingStatus3->onBiddingAverageChanged(m_modelSummary->biddingAverage3());
break;
default:
qWarning() << "Unknown round number:" << roundNumber;
break;
}
}
QBoxLayout* SummaryWidget::createBiddingOverviewLayout() {
QHBoxLayout* layout = new QHBoxLayout();
const int expectedBiddings = m_modelSummary->nExpectedBiddings();
/// bidding round 1
const int placedBiddings1 = m_modelSummary->nPlacedBiddings1();
const int biddingSum1 = m_modelSummary->biddingSum1();
const qreal biddingAverage1 = m_modelSummary->biddingAverage1();
m_biddingStatus1 =
make_unique<BiddingRoundStatusWidget>("Bietrunde 1", placedBiddings1, expectedBiddings,
m_financialNeed, biddingSum1, biddingAverage1);
/// bidding round 2
const int placedBiddings2 = m_modelSummary->nPlacedBiddings2();
const int biddingSum2 = m_modelSummary->biddingSum2();
const qreal biddingAverage2 = m_modelSummary->biddingAverage2();
m_biddingStatus2 =
make_unique<BiddingRoundStatusWidget>("Bietrunde 2", placedBiddings2, expectedBiddings,
m_financialNeed, biddingSum2, biddingAverage2);
/// bidding round 3
const int placedBiddings3 = m_modelSummary->nPlacedBiddings3();
const int biddingSum3 = m_modelSummary->biddingSum3();
const qreal biddingAverage3 = m_modelSummary->biddingAverage3();
m_biddingStatus3 =
make_unique<BiddingRoundStatusWidget>("Bietrunde 3", placedBiddings3, expectedBiddings,
m_financialNeed, biddingSum3, biddingAverage3);
layout->addWidget(m_biddingStatus1.get());
layout->addWidget(m_biddingStatus2.get());
layout->addWidget(m_biddingStatus3.get());
return layout;
}
void SummaryWidget::setupConnections() {
// TODO figure out how to encapsulate each property binding into a dedicated function:
// "bindProperty(&bindable, &signal, &getter, widget)"
QObject::connect(m_modelSummary.get(), &ModelSummary::nExpectedBiddingsChanged,
[&]() { onNExpectedBiddingChanged(m_modelSummary->nExpectedBiddings()); });
QObject::connect(m_modelSummary.get(), &ModelSummary::nTotalExpectedSharesChanged, this, [&]() {
onNTotalExpectedSharesChanged(m_modelSummary->nTotalExpectedShares());
});
QObject::connect(m_modelSummary.get(), &ModelSummary::nPlacedBiddingsChanged, this,
&SummaryWidget::onNPlacedBiddingsChanged);
QObject::connect(m_modelSummary.get(), &ModelSummary::biddingSumChanged, this,
&SummaryWidget::onBiddingSumChanged);
QObject::connect(m_modelSummary.get(), &ModelSummary::biddingAverageChanged, this,
&SummaryWidget::onBiddingAverageChanged);
}

View File

@ -0,0 +1,47 @@
#ifndef SUMMARYWIDGET_H
#define SUMMARYWIDGET_H
#include <QWidget>
class BiddingRoundStatusWidget;
class ModelSummary;
class QLabel;
class QSpinBox;
class QBoxLayout;
class SummaryWidget : public QWidget {
Q_OBJECT
public:
explicit SummaryWidget(std::shared_ptr<ModelSummary> modelSummary, QWidget* parent = nullptr);
private slots:
void onFinancialNeedChanged(int newFinancialNeed);
void onNExpectedBiddingChanged(int newNExpected);
void onNTotalExpectedSharesChanged(qreal newNExpected);
void onNPlacedBiddingsChanged(const int roundNumber);
void onBiddingSumChanged(const int roundNumber);
void onBiddingAverageChanged(const int roundNumber);
private:
std::shared_ptr<ModelSummary> m_modelSummary;
std::unique_ptr<BiddingRoundStatusWidget> m_biddingStatus1;
std::unique_ptr<BiddingRoundStatusWidget> m_biddingStatus2;
std::unique_ptr<BiddingRoundStatusWidget> m_biddingStatus3;
// TODO read from settings (maybe via model/core; maybe set in constructor)
const int m_financialNeed = 13942;
QSpinBox* m_financialNeedBox = nullptr;
QLabel* m_nTotalExpectedShares = nullptr;
QLabel* m_rowCountValueLabel;
QLabel* m_nExpectedBiddingsValueLabel;
/// functions
QBoxLayout* createBiddingOverviewLayout();
void setupConnections();
};
#endif // SUMMARYWIDGET_H

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
assets/icons/feature.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

7
assets/icons/icons.qrc Normal file
View File

@ -0,0 +1,7 @@
<RCC>
<qresource prefix="/">
<file>software-application.png</file>
<file>feature.png</file>
<file>no-picture-taking.png</file>
</qresource>
</RCC>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

5
assets/icons/urls.txt Normal file
View File

@ -0,0 +1,5 @@
software-application.png:
https://www.flaticon.com/free-icon/software-application_5063917
feature.png:
https://www.flaticon.com/free-icon/feature_1085784

4
installer/.env Normal file
View File

@ -0,0 +1,4 @@
# ssh url of the packages directory of the repo
PROJECT_FOLDER=""
export CONFIG_REPO_URL="/${PROJECT_FOLDER}"
export PUSH_REPO_URL="/${PROJECT_FOLDER}"

52
installer/build.sh Executable file
View File

@ -0,0 +1,52 @@
#!/bin/bash
echo amount of arguments: $#
if [[ $# -ne 4 ]]; then
echo "Build script has to be called with exactly two arguments."
echo "The version number (Major.Minor.Patch) as its first argument."
echo "... and the OS (linux, windows or macos) as the second argument"
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
echo "Aborting..."
exit 1
fi
VERSION=$1
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
if [[ $VERSION =~ $regex ]]; then
echo "Version accepted: $VERSION"
else
echo "Version '$VERSION' is not acceptable. Aborting..."
exit 1
fi
PLATFORM=$2
# TODO refactor this to use something like PLATFORMS.contains(PLATFORM)
if [[ $PLATFORM == linux ]]; then
echo "OS: $PLATFORM"
elif [[ $PLATFORM == windows ]]; then
echo "OS: $PLATFORM"
elif [[ $PLATFORM == macos ]]; then
echo "OS: $PLATFORM"
else
echo "Platform '$PLATFORM' is not acceptable. Aborting..."
exit 1
fi
#if [[ ! -e .env ]]; then
# echo "File .env not found. Aborting..."
# exit 1
#fi
#echo "Sourcing .env file..."
#source .env
echo "calling the compile-executable.sh..."
./compile-executable.sh $1 $2 $3 $4
echo "calling the create-installer.sh..."
./create-installer.sh $1 $2 $3 $4
echo "calling the deployToRepo.sh..."
./deployToRepo.sh $1 $2 $3 $4
cd ${OLD_PWD}

59
installer/compile-executable.sh Executable file
View File

@ -0,0 +1,59 @@
#!/bin/bash
echo amount of arguments: $#
if [[ $# -ne 4 ]]; then
echo "Build script has to be called with exactly two arguments."
echo "The version number (Major.Minor.Patch) as its first argument."
echo "... and the OS (linux, windows or macos) as the second argument"
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
echo "Aborting..."
exit 1
fi
VERSION=$1
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
if [[ $VERSION =~ $regex ]]; then
echo "Version accepted: $VERSION"
else
echo "Version '$VERSION' is not acceptable. Aborting..."
exit 1
fi
PLATFORM=$2
# TODO refactor this to use something like PLATFORMS.contains(PLATFORM)
if [[ $PLATFORM == linux ]]; then
echo "OS: $PLATFORM"
#QMAKE_EXE="qmake"
COMPILER_EXE="make"
elif [[ $PLATFORM == windows ]]; then
echo "OS: $PLATFORM"
#QMAKE_EXE="$QMAKE_LOCATION/qmake"
#COMPILER_EXE="$MINGWROOT/bin/mingw32-make"
elif [[ $PLATFORM == macos ]]; then
echo "OS: $PLATFORM"
#QMAKE_EXE="qmake"
COMPILER_EXE="make"
else
echo "Platform '$PLATFORM' is not acceptable. Aborting..."
exit 1
fi
echo "Starting build ..."
OLD_PWD=$(pwd)
BUILD_DIR="_build"
echo "starting in: ${OLD_PWD}"
# if [[ -e $BUILD_DIR/$TARGET ]]; then
# echo "old build dir has old content, cleaning the build directory..."
# rm -r $BUILD_DIR/*
# fi
cd $BUILD_DIR
echo "Building in $(pwd) ..."
echo "Building whole project..."
echo "Running CMake..."
cmake -DCMAKE_BUILD_TYPE=Release ../../
echo "Compiling..."
$COMPILER_EXE

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<Installer>
<Name>${PROJECT_NAME}</Name>
<Version>1.0.0</Version>
<Title>${PROJECT_NAME} Installer</Title>
<Publisher>Working-Copy Collective</Publisher>
<StartMenuDir>Utilities</StartMenuDir>
<TargetDir>@ApplicationsDir@/${PROJECT_NAME}</TargetDir>
<RemoteRepositories>
<Repository>
<Url>${CONFIG_REPO_URL}/${PLATFORM}/packages</Url>
<Enabled>1</Enabled>
<DisplayName>The ${PROJECT_NAME} repository</DisplayName>
</Repository>
</RemoteRepositories>
</Installer>

112
installer/create-installer.sh Executable file
View File

@ -0,0 +1,112 @@
#!/bin/bash
if [[ $# -ne 4 ]]; then
echo "Build script has to be called with exactly two arguments."
echo "The version number (Major.Minor.Patch) as its first argument."
echo "... and the OS (linux, windows or macos) as the second argument"
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
echo "Aborting..."
exit 1
fi
VERSION=$1
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
if [[ $VERSION =~ $regex ]]; then
echo "Version accepted: $VERSION"
else
echo "Version '$VERSION' is not acceptable. Aborting..."
exit 1
fi
PLATFORM=$2
TARGET=$3
EXECUTABLE="$TARGET-Widgets"
BUILD_PREFIX="_build/UIs/GenericWidgets"
# TODO refactor this to use PLATFORMS.contains(PLATFORM)
if [[ $PLATFORM == linux ]]; then
echo "OS: $PLATFORM"
BUILD_DIR=$BUILD_PREFIX
elif [[ $PLATFORM == windows ]]; then
echo "OS: $PLATFORM"
BUILD_DIR="$BUILD_PREFIX/release"
elif [[ $PLATFORM == macos ]]; then
echo "OS: $PLATFORM"
BUILD_DIR=$BUILD_PREFIX
else
echo "Version '$PLATFORM' is not acceptable. Aborting..."
exit 1
fi
#if [[ ! -e .env ]]; then
# echo "File .env not found. Aborting..."
# exit 1
#fi
#echo "Sourcing .env file..."
#source .env
PACKAGENAME=$4
INSTALLER_DIR="_build/installer"
PKG_DATA_DIR="$INSTALLER_DIR/packages/$PACKAGENAME/data"
PKG_META_DIR="$INSTALLER_DIR/packages/$PACKAGENAME/meta"
ASSET_DIR="../assets/icons"
OUTPUT_DIR="../_output/installer"
if [[ -e $PKG_DATA_DIR/$TARGET ]]; then
echo "old $TARGET exe exists, cleaning the package data directory..."
rm -r $PKG_DATA_DIR/*
fi
if [[ ! -d $PKG_DATA_DIR ]]; then
echo "creating package data folder..."
mkdir -p $PKG_DATA_DIR
fi
mv $INSTALLER_DIR/packages/meta $PKG_META_DIR
echo "copying executable..."
if [[ $PLATFORM == macos ]]; then
cp -r $BUILD_DIR/$EXECUTABLE.app $PKG_DATA_DIR/$TARGET.app
else
cp $BUILD_DIR/$EXECUTABLE $PKG_DATA_DIR/$TARGET
fi
echo "copying assets..."
cp $ASSET_DIR/$TARGET.png $PKG_DATA_DIR/$TARGET.png
echo "copying license..."
cp ../LICENSE $PKG_META_DIR/license.txt
### Platform dependencies
echo "Applying platform dependencies..."
INSTALLER_APPENDIX="installer"
if [[ $PLATFORM == linux ]]; then
echo "Linux..."
# echo "Patching the config.xml"
# sed -i "s/<PLATFORM>/$PLATFORM/g" config/config.xml
elif [[ $PLATFORM == windows ]]; then
echo "Windows..."
cd $PKG_DATA_DIR
echo "Copying OpenSSL dlls..."
cp /c/Qt/Tools/OpenSSL/Win_x64/bin/libcrypto-1_1-x64.dll .
cp /c/Qt/Tools/OpenSSL/Win_x64/bin/libssl-1_1-x64.dll .
echo "Calling windeployqt..."
$QMAKE_LOCATION/windeployqt $TARGET.exe
cd -
# echo "Patching the config.xml"
# sed -i "s/<PLATFORM>/$PLATFORM/g" config/config.xml
elif [[ $PLATFORM == macos ]]; then
echo "MacOS..."
echo "Calling macdeployqt..."
INSTALLER_APPENDIX="installer.dmg"
cd $PKG_DATA_DIR
macdeployqt $TARGET.app
cd -
# echo "Patching the config.xml..."
# sed -i '' "s/<PLATFORM>/$PLATFORM/g" config/config.xml
fi
echo "running binarycreator..."
#echo "$QIF_LOCATION/binarycreator"
binarycreator -n -c $INSTALLER_DIR/config/config.xml -p $INSTALLER_DIR/packages $OUTPUT_DIR/$TARGET-$PLATFORM-$VERSION-$INSTALLER_APPENDIX-online
binarycreator -f -c $INSTALLER_DIR/config/config.xml -p $INSTALLER_DIR/packages $OUTPUT_DIR/$TARGET-$PLATFORM-$VERSION-$INSTALLER_APPENDIX-offline

44
installer/deployToRepo.sh Executable file
View File

@ -0,0 +1,44 @@
#!/bin/bash
echo amount of arguments: $#
if [[ $# -ne 4 ]]; then
echo "Build script has to be called with exactly two arguments."
echo "The version number (Major.Minor.Patch) as its first argument."
echo "... and the OS (linux, windows or macos) as the second argument"
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
echo "Aborting..."
exit 1
fi
VERSION=$1
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
if [[ $VERSION =~ $regex ]]; then
echo "Version accepted: $VERSION"
else
echo "Version '$VERSION' is not acceptable. Aborting..."
exit 1
fi
if [[ ! -e .env ]]; then
exit 1
fi
echo "Sourcing .env file..."
source .env
PACKAGENAME=$4
PLATFORM=$2
PACKAGE_DIR="_build/installer/packages"
OUTPUT_DIR="../_output/repository"
echo "executing repo-gen..."
repogen --update -p $PACKAGE_DIR $OUTPUT_DIR
if [[ $PUSH_REPO_URL != "" ]]; then
echo "pushing package data to repo..."
echo "PUSH_REPO_URL: $PUSH_REPO_URL"
scp -r $OUTPUT_DIR/* $PUSH_REPO_URL/$PLATFORM/packages/
fi
cd ${OLD_PWD}

View File

@ -0,0 +1,24 @@
function Component() {}
Component.prototype.isDefault = function() {
return true;
}
Component.prototype.createOperations = function() {
try {
component.createOperations();
} catch (e) {
print(e);
}
if (installer.value("os") === "win")
{
component.addOperation("CreateShortcut", "@TargetDir@/${PROJECT_NAME}.exe", "@DesktopDir@/${PROJECT_NAME}.lnk");
}
if (installer.value("os") === "x11")
{
component.addOperation("CreateDesktopEntry", "/usr/share/applications/${PROJECT_NAME}.desktop", "Version=1.0\nType=Application\nTerminal=false\nCategories=Utility\nExec=@TargetDir@/${PROJECT_NAME}\nName=${PROJECT_NAME}\nIcon=@TargetDir@/${PROJECT_NAME}.png\nName[en_US]=${PROJECT_NAME}");
//component.addElevatedOperation("Copy", "/usr/share/applications/${PROJECT_NAME}.desktop", "@HomeDir@/Desktop/${PROJECT_NAME}.desktop");
}
}

View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
GenericQtClient
Copyright (C) 2025 bent
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
GenericQtClient Copyright (C) 2025 bent
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package>
<DisplayName>The application itself</DisplayName>
<Description>Installs the ${PROJECT_NAME} executable.</Description>
<Version>${PROJECT_VERSION}</Version>
<ReleaseDate>${CURRENT_DATE}</ReleaseDate>
<Licenses>
<License name="GNU General Public License Agreement" file="license.txt" />
</Licenses>
<ForcedInstallation>true</ForcedInstallation>
<Default>script</Default>
<Script>installscript.qs</Script>
</Package>

1
libs/3rdParty/rapidcsv vendored Submodule

Submodule libs/3rdParty/rapidcsv added at 3aa768a4ad

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US"></TS>

View File

@ -0,0 +1,57 @@
cmake_minimum_required(VERSION 3.16)
set(TARGET_APP "BeetRoundCore")
project(${TARGET_APP} VERSION 0.1.0 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 REQUIRED COMPONENTS Core LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools Gui)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Network)
configure_file(CoreConfig.h.in CoreConfig.h)
set(TS_FILES ${TARGET_APP}_en_US.ts)
add_library(${TARGET_APP} STATIC
genericcore.cpp
genericcore.h
${TS_FILES}
constants.h
structs.h
data/settingshandler.h data/settingshandler.cpp
data/filehandler.h data/filehandler.cpp
formats/jsonparser.h formats/jsonparser.cpp
formats/csvparser.h formats/csvparser.cpp
model/metadata.h
model/tablemodel.h model/tablemodel.cpp
model/modelitem.h model/modelitem.cpp
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
model/modelsummary.h model/modelsummary.cpp
model/commands/insertrowscommand.h model/commands/insertrowscommand.cpp
model/commands/removerowscommand.h model/commands/removerowscommand.cpp
model/commands/edititemcommand.h model/commands/edititemcommand.cpp
network/apiroutes.h
network/servercommunicator.h network/servercommunicator.cpp
# 3rd party libraries
../3rdParty/rapidcsv/src/rapidcsv.h
)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui)
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Test)
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Network)
target_compile_definitions(${TARGET_APP} PRIVATE ${TARGET_APP}_LIBRARY)
if(COMMAND qt_create_translation)
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
else()
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
endif()

View File

@ -0,0 +1,2 @@
#define CORE_NAME "${PROJECT_NAME}"
#define CORE_VERSION "${PROJECT_VERSION}"

View File

@ -0,0 +1,15 @@
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <QString>
/// Platform dependent
#ifdef Q_OS_LINUX
static const QString UPDATER_EXE = "maintenancetool";
#elif defined(Q_OS_MAC)
static const QString UPDATER_EXE = "maintenancetool.app/Contents/MacOS/maintenancetool";
#elif defined(Q_OS_WIN)
static const QString UPDATER_EXE = "maintenancetool.exe";
#endif
#endif // CONSTANTS_H

View File

@ -0,0 +1,89 @@
#include "filehandler.h"
#include <QDebug>
#include <QDir>
#include <QJsonDocument>
#include <QStandardPaths>
#include "../formats/csvparser.h"
bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName) {
qDebug() << "saving file...";
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
qDebug() << path;
QDir dir;
if (!dir.exists(path)) {
dir.mkpath(path);
}
// qDebug() << path + fileName;
const QString filePath = path + '/' + fileName;
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qWarning() << "can't open file";
return false;
}
QTextStream out(&file);
out.setEncoding(QStringConverter::Utf8);
out << doc.toJson(QJsonDocument::Indented);
return true;
}
QByteArray FileHandler::loadJSONDataFromFile(const QString fileName) {
QFile file;
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
file.setFileName(path + "/" + fileName);
QPair<QString, QByteArray> fileContent = getFileContent(path + "/" + fileName);
return fileContent.second;
}
QList<ModelItemValues> FileHandler::getItemValuesFromCSVFile(const QString& filePath) {
QList<ModelItemValues> result;
QFile file;
file.setFileName(filePath);
if (file.exists()) {
result = CsvParser::getItemsFromCSVFile(filePath);
}
return result;
}
bool FileHandler::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
return CsvParser::exportToCSVFile(rows, filePath);
}
FileHandler::FileHandler() {}
/** Tries to open the file specified by the file path & returns the content
* @brief FileHandler::getFileContent
* @param filePath
* @return Returns an error string (empty if successful) and the file content
*/
QPair<QString, QByteArray> FileHandler::getFileContent(const QString& filePath) {
QString errorString = "";
QByteArray fileContent;
QFile file;
file.setFileName(filePath);
if (file.exists()) {
qDebug() << "File found, reading content...";
const bool successfulOpened = file.open(QIODevice::ReadOnly | QIODevice::Text);
if (successfulOpened) {
// TODO learn and decide on the differences between "readAll" and using
// streams
fileContent = file.readAll();
file.close();
} else {
errorString = "File could not be opened!";
qWarning() << errorString;
}
} else {
errorString = "File not found. Returning empty result...";
qInfo() << errorString;
}
const QPair<QString, QByteArray> result(errorString, fileContent);
return result;
}

View File

@ -0,0 +1,28 @@
#ifndef FILEHANDLER_H
#define FILEHANDLER_H
#include <QVariant>
typedef QMap<int, QVariant> ModelItemValues;
class QJsonDocument;
class QString;
class QByteArray;
class FileHandler {
public:
/// JSON
static bool saveToFile(const QJsonDocument& doc, const QString& fileName);
static QByteArray loadJSONDataFromFile(const QString fileName);
/// CSV
static QList<ModelItemValues> getItemValuesFromCSVFile(const QString& filePath);
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
private:
explicit FileHandler();
static QPair<QString, QByteArray> getFileContent(const QString& filePath);
};
#endif // FILEHANDLER_H

View File

@ -0,0 +1,43 @@
#include "settingshandler.h"
#include <QSettings>
QVariantMap SettingsHandler::getSettings(QString group) {
QSettings settings;
QVariantMap result;
if (!group.isEmpty()) {
settings.beginGroup(group);
}
foreach (QString key, settings.allKeys()) {
result.insert(key, settings.value(key));
}
if (!group.isEmpty()) {
settings.endGroup();
}
return result;
}
void SettingsHandler::saveSettings(QVariantMap settingMap, QString group) {
qInfo() << "saving settings...";
QSettings settings;
if (!group.isEmpty()) {
settings.beginGroup(group);
}
foreach (QString key, settingMap.keys()) {
// qDebug() << "saving:" << key << "-" << settingMap.value(key);
settings.setValue(key, settingMap.value(key));
}
if (!group.isEmpty()) {
settings.endGroup();
}
settings.sync();
}
SettingsHandler::SettingsHandler() {}

View File

@ -0,0 +1,15 @@
#ifndef SETTINGSHANDLER_H
#define SETTINGSHANDLER_H
#include <QVariantMap>
class SettingsHandler {
public:
static QVariantMap getSettings(QString group = "");
static void saveSettings(QVariantMap settingMap, QString group = "");
private:
SettingsHandler();
};
#endif // SETTINGSHANDLER_H

View File

@ -0,0 +1,179 @@
#include "csvparser.h"
#include <QHash>
#include <QLocale>
#include <QVariant>
#include "../../3rdParty/rapidcsv/src/rapidcsv.h"
#include "../model/metadata.h"
using namespace rapidcsv;
QList<ModelItemValues> CsvParser::getItemsFromCSVFile(const QString& fileName) {
Document doc(fileName.toStdString());
const bool isCompatible = isCsvCompatible(doc);
if (isCompatible) {
const QList<ModelItemValues> result = createListItemsFromCsvEntries(doc);
return result;
} else {
return QList<ModelItemValues>();
}
}
bool CsvParser::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
Document doc(std::string(), LabelParams(0, -1));
// const QList<QString> headerNames = GET_HEADER_NAMES();
const int columnCount = USER_FACING_ROLES.size();
for (int column = 0; column < columnCount; ++column) {
const UserRoles role = GET_ROLE_FOR_COLUMN(column);
std::string columnName = ROLE_NAMES.value(role).toStdString();
doc.SetColumnName(column, columnName);
}
for (int row = 0; row < rows.size(); ++row) {
QStringList rowValues = rows.at(row);
std::vector<std::string> rowValueStrings;
for (int column = 0; column < rowValues.size(); ++column) {
rowValueStrings.push_back(rowValues.at(column).toStdString());
}
doc.InsertRow(row, rowValueStrings);
}
doc.Save(filePath.toStdString());
return true;
}
CsvParser::CsvParser() {}
/** A CSV file is compatible if the following is true:
* - there is a CSV column for every column in the table model
* (except there are optional columns defined in the model)
* @brief CsvParser::isCsvCompatible
* @param doc
* @return
*/
bool CsvParser::isCsvCompatible(const rapidcsv::Document& doc) {
qInfo() << "Checking CSV document for compatiblity...";
const std::vector<std::string> columnNames = doc.GetColumnNames();
for (const QString& headerName : GET_HEADER_NAMES()) {
if (OPTIONAL_CSV_HEADERS.contains(headerName)) {
/// no need to have a column for the optional values
continue;
}
/// these column must be found in CSV document
bool isHeaderNameFound = false;
if (std::find(columnNames.begin(), columnNames.end(), headerName) != columnNames.end()) {
qDebug() << QString("Header found in column names: %1").arg(headerName);
} else {
const QString errorString =
QString("Couldn't find header name '%1' in CSV file. Aborting...").arg(headerName);
qWarning() << errorString;
return false;
}
}
return true;
}
QList<ModelItemValues> CsvParser::createListItemsFromCsvEntries(const rapidcsv::Document& doc) {
QList<ModelItemValues> result;
const int rowCount = doc.GetRowCount();
const QList<QString> headerNames = GET_HEADER_NAMES();
/// get the values for all columns
QHash<QString, std::vector<std::string>> columnValueMap = extractColumnValues(headerNames, doc);
/// get item values for each row
for (int row = 0; row < rowCount; ++row) {
const ModelItemValues itemValues = getItemValuesForRow(headerNames, columnValueMap, row);
result.append(itemValues);
}
return result;
}
QHash<QString, std::vector<std::string>> CsvParser::extractColumnValues(
const QList<QString> headerNames,
const rapidcsv::Document& doc) {
QHash<QString, std::vector<std::string>> columnValueMap;
for (const QString& columnName : headerNames) {
if (OPTIONAL_CSV_HEADERS.contains(columnName)) {
const std::vector<std::string> columnNames = doc.GetColumnNames();
int columnIdx = doc.GetColumnIdx(columnName.toStdString());
if (columnIdx == -1) {
continue;
}
}
const std::vector<std::string> columnValues =
doc.GetColumn<std::string>(columnName.toStdString());
columnValueMap.insert(columnName, columnValues);
}
return columnValueMap;
}
ModelItemValues CsvParser::getItemValuesForRow(
const QList<QString>& headerNames,
const QHash<QString, std::vector<std::string>>& columnValueMap,
const int row) {
ModelItemValues result;
for (const QString& columnName : headerNames) {
if (!columnValueMap.contains(columnName)) {
continue;
}
int role = ROLE_NAMES.key(columnName.toLatin1());
std::string valueString = columnValueMap.value(columnName).at(row);
QVariant value = parseItemValue(role, valueString);
if (value.isValid()) {
result[role] = value;
}
}
return result;
}
QVariant CsvParser::parseItemValue(const int role, const std::string& valueString) {
QVariant result;
if (STRING_ROLES.contains(role)) {
if (role == ShareTypeRole) {
if (valueString == "AGA") {
result = "erarbeitet";
} else if (valueString == "ja") {
result = "bezahlt";
} else if (valueString == "teils") {
result = "teils/teils";
} else {
result = "";
}
} else {
/// string values
result = QString::fromStdString(valueString);
}
} else if (INT_ROLES.contains(role)) {
/// int values
/// GetColumn<int> crashed (probably because of the empty values)
/// so the strings will be processed later
const QString intAsString = QString::fromStdString(valueString);
result = intAsString.toInt();
} else if (DOUBLE_ROLES.contains(role)) {
/// double values
const QString doubleAsString = QString::fromStdString(valueString);
double doubleValue;
if (doubleAsString.contains(',')) {
QLocale german(QLocale::German);
doubleValue = german.toDouble(doubleAsString);
} else {
doubleValue = doubleAsString.toDouble();
}
result = doubleValue;
// } else if (typeColumns.contains(columnName)) {
// // TODO validate string is allowed
// values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row));
} else {
/// no type recognized for column
QString errorString = QString("Couldn't find value type for role '%1'").arg(role);
qCritical() << errorString;
}
return result;
}

View File

@ -0,0 +1,32 @@
#ifndef CSVPARSER_H
#define CSVPARSER_H
#include <QString>
typedef QMap<int, QVariant> ModelItemValues;
namespace rapidcsv {
class Document;
}
class CsvParser {
public:
static QList<ModelItemValues> getItemsFromCSVFile(const QString& fileName);
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
private:
explicit CsvParser();
static bool isCsvCompatible(const rapidcsv::Document& doc);
static QList<ModelItemValues> createListItemsFromCsvEntries(const rapidcsv::Document& doc);
static QHash<QString, std::vector<std::string>> extractColumnValues(
const QList<QString> headerNames,
const rapidcsv::Document& doc);
static ModelItemValues getItemValuesForRow(
const QList<QString>& headerNames,
const QHash<QString, std::vector<std::string>>& columnValueMap,
const int row);
static QVariant parseItemValue(const int role, const std::string& valueString);
};
#endif // CSVPARSER_H

View File

@ -0,0 +1,171 @@
#include "jsonparser.h"
#include <QJsonArray>
#include <QJsonObject>
#include "../model/metadata.h"
#include "../structs.h"
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
const QString& rootValueName) {
QList<ModelItemValues> result;
if (jsonData.isEmpty()) {
return result;
}
// TODO tidy up the following code and encapsulate into functions;
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
/// case one: json value name in plural -> should contain an array of items
if (rootValueName == ITEMS_KEY_STRING) {
QJsonArray itemArray = extractItemArray(doc, rootValueName);
foreach (QJsonValue value, itemArray) {
QJsonObject itemJsonObject = value.toObject();
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
result.append(values);
}
}
/// case two: json value name in singular -> should contain an object of one item
if (rootValueName == ITEM_KEY_STRING) {
QJsonObject rootObject = doc.object();
QJsonObject itemJsonObject = rootObject.value(rootValueName).toObject();
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
result.append(values);
}
return result;
}
QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
const QString& objectName) {
QJsonDocument jsonDoc;
QJsonObject rootObject;
QJsonArray itemArray;
for (const ModelItemValues& itemValues : itemValuesList) {
QJsonObject itemObject;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant value = itemValues.value(role);
if (STRING_ROLES.contains(role)) {
itemObject.insert(roleName, value.toString());
} else if (INT_ROLES.contains(role)) {
itemObject.insert(roleName, value.toInt());
} else if (DOUBLE_ROLES.contains(role)) {
itemObject.insert(roleName, value.toDouble());
} else {
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
}
}
itemArray.append(itemObject);
}
rootObject.insert(objectName, itemArray);
jsonDoc.setObject(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact);
}
QByteArray JsonParser::toJsonDoc(const QHash<QString, QVariant>& values,
const QString& objectName) {
QJsonDocument jsonDoc;
QJsonObject rootObject;
QJsonObject itemObject;
QHashIterator<QString, QVariant> i(values);
while (i.hasNext()) {
i.next();
const QString key = i.key();
const QVariant value = i.value();
itemObject.insert(key, value.toString());
}
rootObject.insert(objectName, itemObject);
jsonDoc.setObject(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact);
}
ModelItemValues JsonParser::serverUserCredentialsToItemValues(const QJsonDocument& jsonDoc) {
ModelItemValues values;
const QJsonObject rootObject = jsonDoc["data"].toObject();
const QString emailAddress = rootObject["email"].toString();
const QString uuid = rootObject["id"].toString();
const QString token = rootObject["token"].toString();
values.insert(MailRole, emailAddress);
values.insert(OnlineIdRole, uuid);
values.insert(AccessCodeRole, token);
return values;
}
QList<bidding> JsonParser::extractBiddings(const QJsonDocument& jsonDoc) {
QList<bidding> result;
if (jsonDoc.isEmpty()) {
return result;
}
QJsonArray itemArray = JsonParser::extractItemArray(jsonDoc, "data");
foreach (QJsonValue value, itemArray) {
// REFACTOR implement & use "JsonParser::parseServerResponse(const QJsonObject& object,
// QHash<QString, int> entries)"
QJsonObject itemJsonObject = value.toObject();
bidding values{.userId = itemJsonObject.value("user_id").toString(),
.biddingRound = itemJsonObject.value("bidding_round").toInt(),
.amount = itemJsonObject.value("amount").toInt(),
.depotWishOne = itemJsonObject.value("depot_wish_one").toString(),
.depotWishTwo = itemJsonObject.value("depot_wish_two").toString()};
result.append(values);
}
return result;
}
QJsonArray JsonParser::extractItemArray(const QJsonDocument& doc, const QString& objectName) {
QJsonArray itemArray;
if (objectName.isEmpty()) {
itemArray = doc.array();
} else {
QJsonObject rootObject = doc.object();
itemArray = rootObject.value(objectName).toArray();
}
return itemArray;
}
ModelItemValues JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
ModelItemValues values;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, role);
values.insert(keyValuePair.first, keyValuePair.second);
}
return values;
}
JsonParser::JsonParser() {}
pair<int, QVariant> JsonParser::getKeyValuePair(const QJsonObject& itemJsonObject, const int role) {
QVariant result;
const QJsonValue jsonValue = itemJsonObject[ROLE_NAMES.value(role)];
if (STRING_ROLES.contains(role)) {
result = jsonValue.toString();
} else if (INT_ROLES.contains(role)) {
result = jsonValue.toInt();
} else if (DOUBLE_ROLES.contains(role)) {
result = jsonValue.toDouble();
} else {
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
}
return pair<int, QVariant>(role, result);
}

View File

@ -0,0 +1,41 @@
#ifndef JSONPARSER_H
#define JSONPARSER_H
#include <QVariant>
class QJsonObject;
class QString;
class QByteArray;
class QJsonArray;
typedef QMap<int, QVariant> ModelItemValues;
class bidding;
using namespace std;
class JsonParser {
public:
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
const QString& rootValueName = "");
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
const QString& objectName = "");
static QByteArray toJsonDoc(const QHash<QString, QVariant>& Values,
const QString& objectName = "");
static ModelItemValues serverUserCredentialsToItemValues(const QJsonDocument& jsonDoc);
static QList<bidding> extractBiddings(const QJsonDocument& jsonDoc);
// static ModelItemValues parseServerResponse(const QJsonDocument& jsonDoc,
// QHash<QString, int> entries);
// static ModelItemValues parseServerResponse(const QJsonObject& object,
// QHash<QString, int> entries);
static QJsonArray extractItemArray(const QJsonDocument& doc, const QString& objectName);
static ModelItemValues jsonObjectToItemValues(const QJsonObject& itemJsonObject);
private:
explicit JsonParser();
static pair<int, QVariant> getKeyValuePair(const QJsonObject& itemJsonObject, const int role);
};
#endif // JSONPARSER_H

View File

@ -0,0 +1,268 @@
#include "genericcore.h"
#include <QAbstractItemModelTester>
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QJsonDocument>
#include <QProcess>
#include <QSettings>
#include <QString>
#include <QtGui/QUndoStack>
#include "../../ApplicationConfig.h"
#include "CoreConfig.h"
#include "constants.h"
#include "data/filehandler.h"
#include "data/settingshandler.h"
#include "formats/jsonparser.h"
#include "model/generalsortfiltermodel.h"
#include "model/metadata.h"
#include "model/modelsummary.h"
#include "model/tablemodel.h"
#include "network/servercommunicator.h"
GenericCore::GenericCore() {
qDebug() << "Creating core...";
QCoreApplication::setOrganizationName("Working-Copy Collective");
QCoreApplication::setOrganizationDomain("working-copy.org");
#ifdef QT_DEBUG
QCoreApplication::setApplicationName(QString(APPLICATION_NAME) + "-dev");
#else
QCoreApplication::setApplicationName(QString(APPLICATION_NAME));
#endif
// TODO let the model own its undo stack (& use TableModel::getUndoStack() if necessary)
m_modelUndoStack = new QUndoStack(this);
setupModels();
setupServerConfiguration();
}
GenericCore::~GenericCore() { qDebug() << "Destroying core..."; }
QString GenericCore::toString() const {
return QString("%1 (Version %2)").arg(CORE_NAME).arg(CORE_VERSION);
}
void GenericCore::sayHello() const { qDebug() << "Hello from the core!"; }
bool GenericCore::isApplicationUpdateAvailable() {
QProcess process;
const QString programmString = getMaintenanceToolFilePath();
const QStringList checkArgs("--checkupdates");
process.start(programmString, checkArgs);
process.waitForFinished();
const int exitCode = process.exitCode();
if (process.error() != QProcess::UnknownError) {
qDebug() << "Error checking for updates";
emit displayStatusMessage("Error checking for updates");
return false;
}
QByteArray data = process.readAllStandardOutput();
QSettings settings;
settings.beginGroup("Application");
settings.setValue("lastCheckForUpdate", QDateTime::currentDateTimeUtc());
settings.endGroup();
settings.sync();
if (data.isEmpty() || data.contains("currently no updates")) {
qInfo() << "No updates available";
emit displayStatusMessage("No updates available.");
return false;
}
return true;
}
void GenericCore::triggerApplicationUpdate(const bool saveChanges) {
if (saveChanges && !m_modelUndoStack->isClean()) {
saveItems();
}
QStringList args("--start-updater");
QString toolFilePath = getMaintenanceToolFilePath();
QProcess::startDetached(toolFilePath, args);
}
QUndoStack* GenericCore::getModelUndoStack() const { return m_modelUndoStack; }
std::shared_ptr<TableModel> GenericCore::getModel() const { return m_mainModel; }
std::shared_ptr<GeneralSortFilterModel> GenericCore::getSortFilterModel() const {
return m_sortFilterModel;
}
shared_ptr<ModelSummary> GenericCore::getModelSummary() const { return m_modelSummary; }
/**
* Save items to default file (in standard location).
* @brief GenericCore::saveItems Saves item fo file.
*/
void GenericCore::saveItems() {
qDebug() << "saving items...";
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
const bool successfulSave = FileHandler::saveToFile(doc, ITEMS_FILE_NAME);
if (successfulSave) {
m_modelUndoStack->setClean();
emit displayStatusMessage(QString("Items saved."));
} else {
emit displayStatusMessage(QString("Error: Items couldn't be saved."));
}
}
void GenericCore::importCSVFile(const QString& filePath) {
qInfo() << "importing items from CSV...";
qDebug() << "filePath:" << filePath;
const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath);
// TODO inform UI on errors
if (itemValuesList.isEmpty()) {
qDebug() << "No items found. Doing nothing...";
return;
}
// qDebug() << "CSV file content:" << itemValuesList;
m_mainModel->insertItems(m_mainModel->rowCount(), itemValuesList);
}
bool GenericCore::exportCSVFile(const QString& filePath) {
qInfo() << "exporting items to CSV...";
qDebug() << "filePath:" << filePath;
const QList<QStringList> itemsAsStringLists = m_mainModel->getItemsAsStringLists();
return FileHandler::exportToCSVFile(itemsAsStringLists, filePath);
}
QVariantMap GenericCore::getSettings(QString group) const {
return SettingsHandler::getSettings(group);
}
void GenericCore::applySettings(QVariantMap settingMap, QString group) {
SettingsHandler::saveSettings(settingMap, group);
if (group == "Server") {
setupServerConfiguration();
}
}
bool GenericCore::isSyncServerSetup() const {
if (m_serverCommunicator) {
return true;
} else {
return false;
}
}
void GenericCore::onLoginSuccessful() {
qInfo() << "Login successful.";
emit displayStatusMessage("Login successful.");
emit sendGetRequest(GetCurrentBiddingRound);
}
void GenericCore::onBiddingsChanged(const QList<bidding> biddings) {
qInfo() << "onBiddingsChanged: biddings:" << biddings.count();
// NEXT merge biddings into model
m_mainModel->updateBiddings(biddings);
}
void GenericCore::onCreateOnlineAccountTriggered(const QString& mailAddress) {
qInfo() << "Creating online account for:" << mailAddress;
QHash<QString, QVariant> hash;
hash.insert("email", mailAddress);
const QByteArray jsonDoc = JsonParser::toJsonDoc(hash, "user");
emit sendPostRequest(RegisterUser, jsonDoc);
}
void GenericCore::onOnlineUserAccountReceived(const QString mailAddress,
const QString uuid,
const QString accessToken) {
m_mainModel->setOnlineCredentials(mailAddress, uuid, accessToken);
const QString message = QString("Online credentials received for: %1").arg(mailAddress);
emit displayStatusMessage(message);
}
void GenericCore::onSendInviteMailTriggered(const QString& mailAddress) {
qInfo() << "Sending invite mail to:" << mailAddress;
const QString serverUrl = m_serverCommunicator->getUserLoginUrl();
const QJsonDocument mailInviteJsonDoc = m_mainModel->getMailInviteJsonDoc(mailAddress, serverUrl);
emit sendPostRequest(MailInvite, mailInviteJsonDoc.toJson());
}
void GenericCore::setupModels() {
m_mainModel = make_shared<TableModel>(m_modelUndoStack);
m_sortFilterModel = make_shared<GeneralSortFilterModel>(m_mainModel);
m_modelSummary = make_shared<ModelSummary>(m_mainModel);
/// QAbstractItemModelTester
#ifdef QT_DEBUG
m_mainModelTester = make_unique<QAbstractItemModelTester>(
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
#else
m_mainModelTester = make_unique<QAbstractItemModelTester>(
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
#endif
initModelData();
}
/**
* Initializing model with data. Tries to read items from default file. Generating example items as
* fallback.
* @brief GenericCore::initModelData
*/
void GenericCore::initModelData() {
qInfo() << "Trying to read model data from file...";
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEMS_FILE_NAME);
// qDebug() << "jsonDoc:" << jsonDoc;
// TODO decide on lack of file(s) (config, data) if example items should be generated
// (see welcome wizard)
if (jsonDoc.isEmpty()) {
qDebug() << "No item content in file. Generating example items...";
const QByteArray exampleItems = m_mainModel->generateExampleItems();
m_mainModel->insertItems(0, exampleItems);
} else {
qDebug() << "Item in file found.";
m_mainModel->insertItems(0, jsonDoc);
}
m_modelUndoStack->clear();
}
QString GenericCore::getMaintenanceToolFilePath() const {
QString applicationDirPath = QCoreApplication::applicationDirPath();
/// setting the applicationDirPath hard coded to test update feature from IDE
#ifdef QT_DEBUG
applicationDirPath = QString("/opt/%1").arg(APPLICATION_NAME);
#endif
#ifdef Q_OS_MAC
applicationDirPath.append("/../../..");
#endif
const QString filePath = applicationDirPath + "/" + UPDATER_EXE;
return filePath;
}
void GenericCore::setupServerConfiguration() {
m_serverCommunicator = make_unique<ServerCommunicator>(this);
applyServerConfiguration();
}
void GenericCore::applyServerConfiguration() {
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
const QString urlValue = serverSettings.value("url").toString();
if (!urlValue.isEmpty()) {
const QString emailValue = serverSettings.value("email").toString();
const QString passwordValue = serverSettings.value("password").toString();
const QString authToken = serverSettings.value("token").toString();
m_serverCommunicator->setServerConfiguration(urlValue, emailValue, passwordValue, authToken);
}
}

View File

@ -0,0 +1,95 @@
#ifndef GENERICCORE_H
#define GENERICCORE_H
#include <QObject>
#include <QVariant>
#include "model/metadata.h"
#include "structs.h"
class QUndoStack;
class QAbstractItemModel;
class QAbstractItemModelTester;
class QString;
class TableModel;
class GeneralSortFilterModel;
class ModelSummary;
class ServerCommunicator;
using namespace std;
class GenericCore : public QObject {
Q_OBJECT
public:
GenericCore();
~GenericCore();
QString toString() const;
void sayHello() const;
bool isApplicationUpdateAvailable();
void triggerApplicationUpdate(const bool saveChanges);
QUndoStack* getModelUndoStack() const;
shared_ptr<TableModel> getModel() const;
shared_ptr<GeneralSortFilterModel> getSortFilterModel() const;
shared_ptr<ModelSummary> getModelSummary() const;
void saveItems();
void importCSVFile(const QString& filePath);
bool exportCSVFile(const QString& filePath);
QVariantMap getSettings(QString group = "") const;
void applySettings(QVariantMap settingMap, QString group = "");
bool isSyncServerSetup() const;
public slots:
void onLoginSuccessful();
void onBiddingsChanged(const QList<bidding> biddings);
void onCreateOnlineAccountTriggered(const QString& mailAddress);
void onOnlineUserAccountReceived(const QString mailAddress,
const QString uuid,
const QString accessToken);
void onSendInviteMailTriggered(const QString& mailAddress);
signals:
void displayStatusMessage(QString message);
/// *** server communication ***
void loginAndStoreAuthToken();
/// request signals
void sendGetRequest(GetRequestTypes type, QVariant data = QVariant());
void sendPostRequest(PostRequestTypes type, QByteArray data);
/// response signals
void currentBiddingRoundChanged(int round, bool isRunning);
/// deprecated signals
void fetchItemsFromServer();
void postItemToServer(const QByteArray& jsonData);
void deleteItemFromServer(const QString& id);
private:
QUndoStack* m_modelUndoStack;
shared_ptr<TableModel> m_mainModel;
shared_ptr<GeneralSortFilterModel> m_sortFilterModel;
shared_ptr<ModelSummary> m_modelSummary;
unique_ptr<QAbstractItemModelTester> m_mainModelTester;
unique_ptr<QAbstractItemModelTester> m_proxyModelTester;
void setupModels();
void initModelData();
QString getMaintenanceToolFilePath() const;
/// Network communication
unique_ptr<ServerCommunicator> m_serverCommunicator;
void setupServerConfiguration();
void applyServerConfiguration();
};
#endif // GENERICCORE_H

View File

@ -0,0 +1,75 @@
#include "edititemcommand.h"
#include <QDebug>
#include "../metadata.h"
#include "../tablemodel.h"
EditItemCommand::EditItemCommand(TableModel* model,
const QModelIndex& index,
QMap<int, QVariant>& changedValues,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_model(model)
, m_row(index.row()) {
qInfo() << "New EditCommand...";
QString commandText;
if (changedValues.size() == 1) {
qDebug() << "Only one value to change. Using more specific command text...";
const int role = changedValues.firstKey();
const QVariant value = changedValues.first();
QString roleName = model->roleNames().value(role);
if (USER_FACING_ROLES.contains(role)) {
commandText = QString("Setting '%1' of item '%2' to '%3'")
.arg(roleName)
.arg(index.data(DEFAULT_ROLE).toString())
.arg(value.toString());
} else {
qWarning() << "Role didn't match! Using a generic command text...";
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
}
} else {
qDebug() << "More than one value to change. Using a generic command text...";
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
}
setText(commandText);
m_newValues = changedValues;
/// storing old values for undo step
m_oldValues = getOldValues(index, changedValues);
}
void EditItemCommand::undo() {
qDebug() << "Undoing the EditCommand...";
m_model->execEditItemData(m_row, m_oldValues);
}
void EditItemCommand::redo() {
qDebug() << "(Re-)doing the EditCommand...";
m_model->execEditItemData(m_row, m_newValues);
}
const QMap<int, QVariant> EditItemCommand::getOldValues(
const QModelIndex& index,
const QMap<int, QVariant>& changedValues) const {
QMap<int, QVariant> result;
QMap<int, QVariant>::const_iterator i;
for (i = changedValues.constBegin(); i != changedValues.constEnd(); ++i) {
const int role = i.key();
const QVariant newValue = i.value();
const QVariant oldValue = index.data(role);
// TODO check if role is a editable role?
if (oldValue != newValue) {
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
result.insert(role, oldValue);
} else {
qInfo() << "oldValue is already the same as newValue:" << oldValue;
}
}
// QVariant oldModifiedDate = index.data(ModifiedDateUTCRole);
// result.insert(ModifiedDateUTCRole, oldModifiedDate);
return result;
}

View File

@ -0,0 +1,33 @@
#ifndef EDITITEMCOMMAND_H
#define EDITITEMCOMMAND_H
#include <QMap>
#include <QUndoCommand>
class TableModel;
class EditItemCommand : public QUndoCommand {
public:
// TODO don't use simple pointer to model
/// Using simple pointer to model because there was a crash when closing the application with an
/// unclean undo stack
EditItemCommand(TableModel* model,
const QModelIndex& index,
QMap<int, QVariant>& changedValues,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo();
void redo();
private:
TableModel* m_model = nullptr;
const int m_row;
QMap<int, QVariant> m_oldValues;
QMap<int, QVariant> m_newValues;
/// private functions
const QMap<int, QVariant> getOldValues(const QModelIndex& index,
const QMap<int, QVariant>& changedValues) const;
};
#endif // EDITITEMCOMMAND_H

View File

@ -0,0 +1,33 @@
#include "insertrowscommand.h"
#include <QDebug>
#include "../tablemodel.h"
InsertRowsCommand::InsertRowsCommand(TableModel* model,
int startRow,
QList<ModelItemValues> valueList,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_tableModel(model)
, m_startRow(startRow)
, m_valueList(valueList) {
qInfo() << "New InsertCommand...";
const QString commandText =
QString("inserting %1 item(s) on row %2").arg(valueList.length()).arg(startRow);
setText(commandText);
}
void InsertRowsCommand::undo() {
qDebug() << "Undoing the InsertCommand...";
if (m_tableModel) {
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
}
}
void InsertRowsCommand::redo() {
qDebug() << "(Re-)doing the InsertCommand...";
if (m_tableModel) {
m_tableModel->execInsertItems(m_startRow, m_valueList);
}
}

View File

@ -0,0 +1,30 @@
#ifndef INSERTROWSCOMMAND_H
#define INSERTROWSCOMMAND_H
#include <QUndoCommand>
typedef QMap<int, QVariant> ModelItemValues;
class TableModel;
class InsertRowsCommand : public QUndoCommand {
public:
// TODO don't use simple pointer to model
/// Using simple pointer to model because there was a crash when closing the application with an
/// unclean undo stack
InsertRowsCommand(TableModel* model,
int startRow,
QList<ModelItemValues> valueList,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo() override;
void redo() override;
private:
TableModel* m_tableModel;
const int m_startRow;
const QList<ModelItemValues> m_valueList;
};
#endif // INSERTROWSCOMMAND_H

View File

@ -0,0 +1,41 @@
#include "removerowscommand.h"
#include <QDebug>
#include "../tablemodel.h"
RemoveRowsCommand::RemoveRowsCommand(TableModel* model,
const int startRow,
const int nRows,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_tableModel(model)
, m_startRow(startRow) {
qInfo() << "New RemoveCommand...";
const QString commandText =
QString("removing %1 item(s) on position %2").arg(nRows).arg(startRow);
setText(commandText);
for (int row = 0; row < nRows; ++row) {
const int rowPosition = startRow + row;
QModelIndex index = m_tableModel->index(rowPosition, 0);
ModelItemValues values = m_tableModel->getItemValues(index);
m_valueList.append(values);
}
}
void RemoveRowsCommand::undo() {
qDebug() << "Undoing the RemoveCommand...";
if (m_tableModel) {
m_tableModel->execInsertItems(m_startRow, m_valueList);
}
}
void RemoveRowsCommand::redo() {
qDebug() << "(Re-)doing the RemoveCommand...";
if (m_tableModel) {
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
}
}

View File

@ -0,0 +1,30 @@
#ifndef REMOVEROWSCOMMAND_H
#define REMOVEROWSCOMMAND_H
#include <QUndoCommand>
class TableModel;
typedef QMap<int, QVariant> ModelItemValues;
class RemoveRowsCommand : public QUndoCommand {
public:
// TODO don't use simple pointer to model
/// Using simple pointer to model because there was a crash when closing the application with an
/// unclean undo stack
RemoveRowsCommand(TableModel* model,
const int startRow,
const int nRows,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo() override;
void redo() override;
private:
TableModel* m_tableModel;
const int m_startRow;
QList<ModelItemValues> m_valueList;
};
#endif // REMOVEROWSCOMMAND_H

View File

@ -0,0 +1,105 @@
#include "generalsortfiltermodel.h"
#include "metadata.h"
#include <QItemSelection>
GeneralSortFilterModel::GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel)
: QSortFilterProxyModel{sourceModel.get()}
, m_tableModel(sourceModel) {
setSourceModel(sourceModel.get());
m_collator.setNumericMode(true);
}
QItemSelection GeneralSortFilterModel::findItems(const QString& text) const {
QItemSelection result;
for (int i = 0; i < rowCount(); ++i) {
const QModelIndex localIndex = index(i, 0);
if (indexContainsText(localIndex, text)) {
result.select(localIndex, index(i, columnCount() - 1)); /// select entire row
}
}
return result;
}
QString GeneralSortFilterModel::getUuid(const QModelIndex& itemIndex) const {
return data(itemIndex, OnlineIdRole).toString();
}
QByteArray GeneralSortFilterModel::jsonDataForServer(const QModelIndex& proxyIndex) {
const QModelIndex sourceIndex = mapToSource(proxyIndex);
return m_tableModel->jsonDataForServer(sourceIndex);
}
void GeneralSortFilterModel::appendItems(const QByteArray& jsonDoc) {
m_tableModel->appendItems(jsonDoc);
}
bool GeneralSortFilterModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
const QModelIndex proxyIndex = index(firstRow, 0, parentIndex);
const QModelIndex sourceIndex = mapToSource(proxyIndex);
return m_tableModel->removeRows(sourceIndex.row(), nRows, sourceIndex.parent());
}
bool GeneralSortFilterModel::lessThan(const QModelIndex& source_left,
const QModelIndex& source_right) const {
if (source_left.column() != source_right.column()) {
return false;
}
QAbstractItemModel* localSourceModel = sourceModel();
const int role = GET_ROLE_FOR_COLUMN(source_left.column());
const QVariant leftData = localSourceModel->data(source_left);
const QVariant rightData = localSourceModel->data(source_right);
const bool isText = STRING_ROLES.contains(role);
if (isText) {
const QString leftString = leftData.toString();
const QString rightString = rightData.toString();
return m_collator.compare(leftString, rightString) > 0;
}
const bool isInt = INT_ROLES.contains(role);
if (isInt) {
const int leftInt = leftData.toInt();
const int rightInt = rightData.toInt();
return leftInt > rightInt;
}
const bool isDouble = DOUBLE_ROLES.contains(role);
if (isDouble) {
const int leftInt = leftData.toDouble();
const int rightInt = rightData.toDouble();
return leftInt > rightInt;
}
return false;
}
bool GeneralSortFilterModel::indexContainsText(const QModelIndex& index,
const QString& text) const {
// iterate over USER_FACING_ROLES and call roleDataContainsText(...);
// ...for each until text is found or no more roles to check;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const bool isTextFound = roleDataContainsText(index, role, text);
if (isTextFound) {
// qInfo() << "Text is found in role:" << role;
return true;
// } else {
// qDebug() << QString("Can't find text in role %1. Continuing search...").arg(role);
}
}
// qWarning() << "Text not found in any role. Returning false...";
return false;
}
bool GeneralSortFilterModel::roleDataContainsText(const QModelIndex& index,
const int role,
const QString& text) const {
const QString dataString = index.data(role).toString();
if (dataString.contains(text, Qt::CaseInsensitive)) {
return true;
} else {
return false;
}
}

View File

@ -0,0 +1,39 @@
#ifndef GENERALSORTFILTERMODEL_H
#define GENERALSORTFILTERMODEL_H
#include <QCollator>
#include <QSortFilterProxyModel>
#include "tablemodel.h"
class GeneralSortFilterModel : public QSortFilterProxyModel {
Q_OBJECT
public:
explicit GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel = nullptr);
/** Returns a QItemSelection with all ModelIndexes which contain the given text.
* @brief Returns QItemSelection containing all successful ModelIndex results
* @param text To search for
* @return QItemSelection containing all successful ModelIndex results
*/
QItemSelection findItems(const QString& text) const;
QString getUuid(const QModelIndex& itemIndex) const;
QByteArray jsonDataForServer(const QModelIndex& proxyIndex);
public slots:
void appendItems(const QByteArray& jsonDoc);
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
/// QSortFilterProxyModel interface
protected:
bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
private:
std::shared_ptr<TableModel> m_tableModel;
QCollator m_collator; /// for sorting
bool indexContainsText(const QModelIndex& index, const QString& text) const;
bool roleDataContainsText(const QModelIndex& index, const int role, const QString& text) const;
};
#endif // GENERALSORTFILTERMODEL_H

View File

@ -0,0 +1,162 @@
#ifndef METADATA_H
#define METADATA_H
#include <QDebug>
#include <QHash>
#include <QList>
#include <QString>
// TODO add namespace
/// model data
enum UserRoles {
LastNameRole = Qt::UserRole + 1,
FirstNameRole,
MembershipNumberRole,
Bidding1Role,
Bidding2Role,
Bidding3Role,
DepotWish1Role,
DepotWish2Role,
ShareAmountRole,
MailRole,
ShareTypeRole,
BiddingTypeRole,
OnlineIdRole,
AccessCodeRole,
// read-only (calculated)
FullNameRole,
FactoredBiddingRole,
ToStringRole,
JsonObjectRole
};
static UserRoles DEFAULT_ROLE = FullNameRole;
// TODO ?rename USER_FACING_ROLES -> MAIN_ROLES ?
static QList<UserRoles> USER_FACING_ROLES = {
LastNameRole, FirstNameRole, MembershipNumberRole, Bidding1Role, Bidding2Role,
Bidding3Role, DepotWish1Role, DepotWish2Role, ShareAmountRole, MailRole,
ShareTypeRole, BiddingTypeRole, OnlineIdRole, AccessCodeRole};
static QHash<int, QByteArray> ROLE_NAMES = {{MembershipNumberRole, "Mitglieds-nr."},
{LastNameRole, "Name"},
{FirstNameRole, "Vorname"},
{Bidding1Role, "Gebot 1"},
{Bidding2Role, "Gebot 2"},
{Bidding3Role, "Gebot 3"},
{DepotWish1Role, "Wunsch 1"},
{DepotWish2Role, "Wunsch 2"},
{ShareAmountRole, "Anzahl"},
{MailRole, "Mail"},
{ShareTypeRole, "Art"},
{BiddingTypeRole, "Bietart"},
{OnlineIdRole, "Online ID"},
{AccessCodeRole, "Access Code"},
{FactoredBiddingRole, "factoredBidding"}};
static const QList<QString> SHARE_TYPES = {"bezahlt", "teils/teils", "erarbeitet", ""};
static const QList<QString> BIDDING_TYPES = {"paper", "digital", "online", "offline", ""};
static QList<UserRoles> STRING_ROLES = {LastNameRole, FirstNameRole, DepotWish1Role,
DepotWish2Role, MailRole, ShareTypeRole,
BiddingTypeRole, OnlineIdRole, AccessCodeRole};
static QList<UserRoles> INT_ROLES = {
MembershipNumberRole,
Bidding1Role,
Bidding2Role,
Bidding3Role,
};
static QList<UserRoles> DOUBLE_ROLES = {
ShareAmountRole,
};
static const QList<UserRoles> TYPE_ROLES = {ShareTypeRole, BiddingTypeRole};
static const QList<UserRoles> SHARE_TYPE_ROLES = {ShareTypeRole};
static const QList<UserRoles> BIDDING_TYPE_ROLES = {BiddingTypeRole};
static const QStringList OPTIONAL_CSV_HEADERS = {"Bietart", "Online ID", "Access Code"};
/// JSON keys
static const QString ITEMS_KEY_STRING = "items";
static const QString ITEM_KEY_STRING = "item";
/// file naming
static const QString ITEMS_FILE_NAME = ITEMS_KEY_STRING + ".json";
/// server communication
enum GetRequestTypes {
GetCurrentBiddingRound,
StartNewBiddingRound,
RestartLastBiddingRound,
StopCurrentBiddingRound,
GetBiddingsOfSpecificRound,
GetBiddingsOfHighestRound
};
enum PostRequestTypes { LogInAdmin, RegisterUser, MailInvite };
/// functions
static UserRoles GET_ROLE_FOR_COLUMN(const int column) {
switch (column) {
case 0:
return MembershipNumberRole;
break;
case 1:
return LastNameRole;
break;
case 2:
return FirstNameRole;
break;
case 3:
return ShareTypeRole;
break;
case 4:
return ShareAmountRole;
break;
case 5:
return BiddingTypeRole;
break;
case 6:
return Bidding1Role;
break;
case 7:
return Bidding2Role;
break;
case 8:
return Bidding3Role;
break;
case 9:
return DepotWish1Role;
break;
case 10:
return DepotWish2Role;
break;
case 11:
return MailRole;
break;
case 12:
return OnlineIdRole;
break;
case 13:
return AccessCodeRole;
break;
default:
qWarning() << QString("No role found for column %1! Returning 'FullNameRole'...").arg(column);
return FullNameRole;
break;
}
}
static QList<QString> GET_HEADER_NAMES() {
QList<QString> result;
for (const UserRoles& role : USER_FACING_ROLES) {
const QString headerName = ROLE_NAMES.value(role);
result.append(headerName);
}
return result;
}
static QString GET_HEADER_FOR_COLUMN(const int column) {
const UserRoles role = GET_ROLE_FOR_COLUMN(column);
const QString headerName = ROLE_NAMES.value(role);
return headerName;
}
#endif // METADATA_H

View File

@ -0,0 +1,113 @@
#include "modelitem.h"
#include "metadata.h"
#include <QJsonObject>
#include <QJsonValue>
ModelItem::ModelItem(const ModelItemValues values)
: m_values(values) {}
QVariant ModelItem::data(int role) const {
switch (role) {
case FullNameRole:
return fullName();
break;
case ToStringRole:
return toString();
break;
case JsonObjectRole:
return toJsonObject();
break;
case MembershipNumberRole:
case ShareAmountRole:
case Bidding1Role:
case Bidding2Role:
case Bidding3Role:
return getValueButReplaceZeroValueWithEmptyString(role);
break;
default:
return m_values.value(role);
}
}
bool ModelItem::setData(const QVariant& value, int role) {
bool valueChanged = false;
if (m_values.contains(role)) {
if (m_values.value(role) != value) {
valueChanged = true;
}
}
m_values[role] = value;
return valueChanged;
}
bool ModelItem::setItemData(const QMap<int, QVariant>& changedValues) {
bool valueChanged = false;
QMap<int, QVariant>::const_iterator citer = changedValues.constBegin();
while (citer != changedValues.constEnd()) {
const int role = citer.key();
const QVariant value = citer.value();
if (m_values.contains(role)) {
if (m_values.value(role) != value) {
valueChanged = true;
}
}
m_values[role] = value;
citer++;
}
return valueChanged;
}
QString ModelItem::fullName() const {
return QString("%1 %2").arg(data(FirstNameRole).toString(), data(LastNameRole).toString());
}
QString ModelItem::toString() const {
QString result;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant value = data(role);
result.append(QString("%1: %2\n").arg(roleName, value.toString()));
}
return result;
}
QJsonObject ModelItem::toJsonObject() const {
QJsonObject itemObject;
// TODO add UUID and dates (entry, modification, end)
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant value = data(role);
if (STRING_ROLES.contains(role)) {
itemObject.insert(roleName, value.toString());
} else if (INT_ROLES.contains(role)) {
itemObject.insert(roleName, value.toInt());
} else if (DOUBLE_ROLES.contains(role)) {
itemObject.insert(roleName, value.toDouble());
} else {
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
}
}
return itemObject;
}
QVariant ModelItem::getValueButReplaceZeroValueWithEmptyString(const int role) const {
QVariant localValue = m_values.value(role, QVariant());
if (localValue == 0) {
return QVariant();
} else {
return localValue;
}
}

View File

@ -0,0 +1,27 @@
#ifndef MODELITEM_H
#define MODELITEM_H
#include <QVariant>
typedef QMap<int, QVariant> ModelItemValues;
class ModelItem {
public:
ModelItem(const ModelItemValues values);
QVariant data(int role) const;
bool setData(const QVariant& value, int role);
// TODO change return value to list of changed roles
bool setItemData(const QMap<int, QVariant>& changedValues);
QString fullName() const;
QString toString() const;
QJsonObject toJsonObject() const;
private:
ModelItemValues m_values;
QVariant getValueButReplaceZeroValueWithEmptyString(const int role) const;
};
#endif // MODELITEM_H

View File

@ -0,0 +1,48 @@
#include "modelsummary.h"
#include "tablemodel.h"
ModelSummary::ModelSummary(std::shared_ptr<TableModel> model, QObject* parent)
: QObject(parent)
, m_model(model) {
Q_ASSERT(model);
connect(m_model.get(), &TableModel::rowCountChanged, this, &ModelSummary::rowCountChanged);
// TODO ? use existing model signals (dataChanged(role),...) instead of special signals
connect(m_model.get(), &TableModel::nExpectedBiddingsChanged, this,
&ModelSummary::nExpectedBiddingsChanged);
connect(m_model.get(), &TableModel::nTotalExpectedSharesChanged, this,
&ModelSummary::nTotalExpectedSharesChanged);
connect(m_model.get(), &TableModel::nPlacedBiddingsChanged, this,
&ModelSummary::nPlacedBiddingsChanged);
connect(m_model.get(), &TableModel::biddingSumChanged, this, &ModelSummary::biddingSumChanged);
connect(m_model.get(), &TableModel::biddingAverageChanged, this,
&ModelSummary::biddingAverageChanged);
}
ModelSummary::~ModelSummary() {}
int ModelSummary::rowCount() const {
const int nRows = m_model->rowCount();
return nRows;
}
QBindable<int> ModelSummary::bindableRowCount() {
m_rowCount = m_model->rowCount();
return &m_rowCount;
}
qreal ModelSummary::nTotalExpectedShares() const { return m_model->nTotalExpectedShares(); }
int ModelSummary::nExpectedBiddings() const { return m_model->nExpectedBiddings(); }
int ModelSummary::nPlacedBiddings1() const { return m_model->nPlacedBiddings1(); }
int ModelSummary::nPlacedBiddings2() const { return m_model->nPlacedBiddings2(); }
int ModelSummary::nPlacedBiddings3() const { return m_model->nPlacedBiddings3(); }
int ModelSummary::biddingSum1() const { return m_model->biddingSum1(); }
int ModelSummary::biddingSum2() const { return m_model->biddingSum2(); }
int ModelSummary::biddingSum3() const { return m_model->biddingSum3(); }
qreal ModelSummary::biddingAverage1() const { return m_model->biddingAverage1(); }
qreal ModelSummary::biddingAverage2() const { return m_model->biddingAverage2(); }
qreal ModelSummary::biddingAverage3() const { return m_model->biddingAverage3(); }

View File

@ -0,0 +1,52 @@
#ifndef MODELSUMMARY_H
#define MODELSUMMARY_H
#include <QObject>
#include <QProperty>
class TableModel;
using namespace std;
class ModelSummary : public QObject {
Q_OBJECT
Q_PROPERTY(int rowCount READ rowCount NOTIFY rowCountChanged BINDABLE bindableRowCount)
public:
ModelSummary(shared_ptr<TableModel> model, QObject* parent = nullptr);
~ModelSummary();
int rowCount() const;
QBindable<int> bindableRowCount();
qreal nTotalExpectedShares() const;
int nExpectedBiddings() const;
int nPlacedBiddings1() const;
int nPlacedBiddings2() const;
int nPlacedBiddings3() const;
int biddingSum1() const;
int biddingSum2() const;
int biddingSum3() const;
qreal biddingAverage1() const;
qreal biddingAverage2() const;
qreal biddingAverage3() const;
signals:
void rowCountChanged();
void nExpectedBiddingsChanged();
void nTotalExpectedSharesChanged();
void nPlacedBiddingsChanged(const int roundNumber);
void biddingSumChanged(const int roundNumber);
void biddingAverageChanged(const int roundNumber);
private:
shared_ptr<TableModel> m_model;
Q_OBJECT_BINDABLE_PROPERTY(ModelSummary, int, m_rowCount, &ModelSummary::rowCountChanged);
};
#endif // MODELSUMMARY_H

View File

@ -0,0 +1,739 @@
#include "tablemodel.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include "../formats/jsonparser.h"
#include "../structs.h"
#include "commands/edititemcommand.h"
#include "commands/insertrowscommand.h"
#include "commands/removerowscommand.h"
#include "metadata.h"
#include "modelitem.h"
QByteArray TableModel::generateExampleItems() {
QJsonDocument doc = QJsonDocument();
QJsonObject rootObject;
QJsonArray array;
// TODO use JsonParser for the item generation
for (int row = 0; row < 5; ++row) {
QJsonObject itemObject;
// itemObject.insert("uuid", m_uuid.toString());
// itemObject.insert("entryDateUTC", m_entryDateUTC.toString(Qt::ISODate));
itemObject.insert(ROLE_NAMES.value(MembershipNumberRole), row);
itemObject.insert(ROLE_NAMES.value(LastNameRole), QString("Nachname%1").arg(row));
itemObject.insert(ROLE_NAMES.value(FirstNameRole), QString("Vorname%1").arg(row));
itemObject.insert(ROLE_NAMES.value(Bidding1Role), 100 + row);
itemObject.insert(ROLE_NAMES.value(DepotWish1Role), QString("Depot X%1").arg(row));
itemObject.insert(ROLE_NAMES.value(DepotWish2Role), QString("Depot Y%1").arg(row));
itemObject.insert(ROLE_NAMES.value(MailRole),
QString("%1@%2.com")
.arg(itemObject.value(ROLE_NAMES.value(FirstNameRole)).toString(),
itemObject.value(ROLE_NAMES.value(LastNameRole)).toString()));
itemObject.insert(ROLE_NAMES.value(ShareAmountRole), 1);
itemObject.insert(ROLE_NAMES.value(ShareTypeRole), SHARE_TYPES.at(row % 3));
itemObject.insert(ROLE_NAMES.value(BiddingTypeRole), BIDDING_TYPES.at(row % 4));
// itemObject.insert(ROLE_NAMES.value(FactorRole), row * 1.1);
array.append(itemObject);
}
rootObject.insert(ITEMS_KEY_STRING, array);
doc.setObject(rootObject);
return doc.toJson();
}
TableModel::TableModel(QUndoStack* undoStack, QObject* parent)
: QAbstractTableModel{parent}
, m_undoStack(undoStack) {
connect(this, &TableModel::rowsInserted, this, &TableModel::onRowCountChanged);
connect(this, &TableModel::rowsRemoved, this, &TableModel::onRowCountChanged);
}
Qt::ItemFlags TableModel::flags(const QModelIndex& index) const {
if (!index.isValid()) {
return QAbstractTableModel::flags(index);
}
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
int TableModel::rowCount(const QModelIndex& parent) const {
if (parent.isValid()) {
return 0; /// no children
}
return m_items.size();
}
int TableModel::columnCount(const QModelIndex& parent) const {
if (parent.isValid()) {
return 0; /// no children
}
return USER_FACING_ROLES.size();
}
QVariant TableModel::data(const QModelIndex& index, int role) const {
const int row = index.row();
const int column = index.column();
if (!index.isValid()) {
return QVariant();
}
if (row >= rowCount(QModelIndex()) || column >= columnCount(QModelIndex())) {
return QVariant();
}
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return m_items.at(row)->data(roleForColumn);
case Qt::ToolTipRole:
return m_items.at(index.row())->data(ToStringRole);
break;
case MembershipNumberRole:
case LastNameRole:
case FirstNameRole:
case FullNameRole:
case Bidding1Role:
case Bidding2Role:
case Bidding3Role:
case DepotWish1Role:
case DepotWish2Role:
case ShareAmountRole:
case MailRole:
case ShareTypeRole:
case BiddingTypeRole:
case OnlineIdRole:
case AccessCodeRole:
case ToStringRole:
case JsonObjectRole:
return m_items.at(row)->data(role);
}
return QVariant();
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (role == Qt::DisplayRole) {
if (orientation == Qt::Horizontal) {
const int columnRole = GET_ROLE_FOR_COLUMN(section);
const QString headerName = ROLE_NAMES.value(columnRole);
return QString("%1").arg(headerName);
} else {
return QString("%1").arg(section);
}
}
return QVariant();
}
bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) {
if (role == Qt::EditRole && checkIndex(index)) {
const int column = index.column();
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
return setItemData(index, {{roleForColumn, value}});
}
return false;
}
bool TableModel::setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) {
if (!checkIndex(index)) {
return false;
}
// if (isRoleReadOnly(roleForColumn)) {
// return false;
// }
QMap<int, QVariant> changedValues = onlyChangedValues(index, roles);
if (changedValues.size() > 0) {
EditItemCommand* editCommand = new EditItemCommand(this, index, changedValues);
m_undoStack->push(editCommand);
return true;
}
return false;
}
ModelItemValues TableModel::getItemValues(const QModelIndex& index) const {
ModelItemValues values;
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
values.insert(role, data(index, role));
}
return values;
}
QJsonDocument TableModel::getAllItemsAsJsonDoc() const {
QJsonDocument doc = QJsonDocument();
QJsonObject rootObject;
QJsonArray array;
foreach (shared_ptr<ModelItem> item, m_items) {
QJsonObject itemObject = item->toJsonObject();
array.append(itemObject);
}
rootObject.insert(ITEMS_KEY_STRING, array);
doc.setObject(rootObject);
return doc;
}
QList<QStringList> TableModel::getItemsAsStringLists() const {
QList<QStringList> result;
foreach (shared_ptr<ModelItem> item, m_items) {
QStringList valueList;
for (int column = 0; column < columnCount(); ++column) {
QString value = item->data(GET_ROLE_FOR_COLUMN(column)).toString();
valueList.append(value);
}
result.append(valueList);
}
return result;
}
// TODO use item selection as parameter to wrap multiple items into JSON data structure
QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const {
const QJsonObject itemObject = data(currentIndex, JsonObjectRole).toJsonObject();
QJsonObject rootObject;
rootObject.insert(ITEM_KEY_STRING, itemObject);
const QJsonDocument jsonDoc(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact);
}
QString TableModel::updateItemsFromJson(const QByteArray& jsonData) {
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonData, ITEM_KEY_STRING);
int nChangedItems = 0;
for (const ModelItemValues& itemValues : valueList) {
bool updateHappened = updateItem(itemValues);
if (updateHappened) {
nChangedItems++;
}
}
return QString("Found and updated %1 item(s).").arg(nChangedItems);
}
bool TableModel::updateItem(const ModelItemValues& itemValues) {
QModelIndex foundIndex = searchItemIndex(itemValues);
qDebug() << "Search done!";
if (foundIndex == QModelIndex()) {
const QString errorMessage = "No matching item found!";
qWarning() << errorMessage;
return false;
} else {
qInfo() << "Item found!";
/// update existing item
setItemData(foundIndex, itemValues);
return true;
}
}
void TableModel::setOnlineCredentials(const QString& mail,
const QString& uuid,
const QString& token) {
QModelIndex itemIndex = getIndexByRoleValue(mail, MailRole);
setItemData(itemIndex, {{OnlineIdRole, uuid}, {AccessCodeRole, token}});
}
QJsonDocument TableModel::getMailInviteJsonDoc(const QString& mail,
const QString& serverUrl) const {
QJsonDocument doc = QJsonDocument();
QModelIndex index = getIndexByRoleValue(mail, MailRole);
if (index.isValid()) {
QJsonObject rootObject;
const QString user_id = data(index, OnlineIdRole).toString();
const QString email = data(index, MailRole).toString();
const QString name = data(index, FullNameRole).toString();
const QString token = data(index, AccessCodeRole).toString();
const QString accessUrl = serverUrl + "/" + token;
QJsonObject userObject;
userObject.insert("user_id", user_id);
userObject.insert("email", email);
userObject.insert("name", name);
userObject.insert("access_url", accessUrl);
rootObject.insert("user", userObject);
doc.setObject(rootObject);
}
return doc;
}
void TableModel::updateBiddings(const QList<bidding> biddings) {
QListIterator<bidding> i(biddings);
while (i.hasNext()) {
const bidding localBidding = i.next();
qInfo() << "Processing bidding:";
const int biddingRound = localBidding.biddingRound;
if (biddingRound == 0 || biddingRound > 3) {
qWarning() << "Bidding round exceeds valid bounds. Ignoring...";
continue;
}
const QString uuid = localBidding.userId;
const QModelIndex itemIndex = getIndexByRoleValue(localBidding.userId, OnlineIdRole);
if (itemIndex.isValid()) {
qInfo() << "Found Uuid for user:" << itemIndex.data(MailRole);
const QMap<int, QVariant> values = getItemValues(localBidding);
setItemData(itemIndex, values);
}
}
}
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
if (parentIndex != QModelIndex()) {
qWarning() << "Removing of child rows is not supported yet!";
return false;
}
const int lastRow = firstRow + nRows - 1;
if (firstRow < 0 || lastRow >= m_items.size()) {
qWarning() << "Trying to remove rows is out of bounds!";
return false;
}
RemoveRowsCommand* removeCommand = new RemoveRowsCommand(this, firstRow, nRows);
m_undoStack->push(removeCommand);
return true;
}
void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDoc, QModelIndex()); }
void TableModel::insertItems(int startPosition,
const QByteArray& jsonDoc,
const QModelIndex& parentIndex) {
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEMS_KEY_STRING);
if (valueList.empty()) {
/// don't try inserting if no values to insert
qDebug() << "No items found in JSON document. Not adding anything...";
return;
}
insertItems(startPosition, valueList, parentIndex);
}
void TableModel::insertItems(int startPosition,
const QList<ModelItemValues>& itemValuesList,
const QModelIndex& parentIndex) {
qInfo() << "Inserting item(s) into model...";
if (parentIndex != QModelIndex()) {
qWarning()
<< "Using invalid parent index (no child support for now)! Using root index as parent...";
}
if (startPosition == -1 || startPosition > m_items.size()) {
/// Appending item(s)
startPosition = m_items.size();
}
InsertRowsCommand* insertCommand = new InsertRowsCommand(this, startPosition, itemValuesList);
m_undoStack->push(insertCommand);
}
qreal TableModel::nTotalExpectedShares() const {
qreal result = 0;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
/// if BiddingTypeRole is not empty
const QString biddingType = (*i)->data(BiddingTypeRole).toString();
const qreal shareAmount = (*i)->data(ShareAmountRole).toReal();
if (biddingType.isEmpty() || shareAmount == 0.0) {
continue;
}
/// add amount
const QString shareType = (*i)->data(ShareTypeRole).toString();
if (shareType == "bezahlt") {
result += shareAmount;
} else if (shareType == "teils/teils") {
result += shareAmount / 2;
} else {
qInfo() << "Share type not 'bezahlt' nor 'teils/teils'. Will be ignored..";
qDebug() << "Share type:" << shareType;
}
}
qInfo() << "Biddings expected for " << result << "shares!";
return result;
}
int TableModel::nExpectedBiddings() const {
int result = 0;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
const QString biddingType = (*i)->data(BiddingTypeRole).toString();
if (biddingType.isEmpty()) {
continue;
}
const double shareAmount = (*i)->data(ShareAmountRole).toDouble();
if (shareAmount == 0.0) {
continue;
}
const QString shareType = (*i)->data(ShareTypeRole).toString();
if (shareType == "bezahlt" || shareType == "teils/teils") {
result++;
}
}
return result;
}
int TableModel::nPlacedBiddings1() const { return nPlacedBiddings(Bidding1Role); }
int TableModel::nPlacedBiddings2() const { return nPlacedBiddings(Bidding2Role); }
int TableModel::nPlacedBiddings3() const { return nPlacedBiddings(Bidding3Role); }
int TableModel::biddingSum1() const { return biddingSum(Bidding1Role); }
int TableModel::biddingSum2() const { return biddingSum(Bidding2Role); }
int TableModel::biddingSum3() const { return biddingSum(Bidding3Role); }
qreal TableModel::biddingAverage1() const {
const UserRoles biddingRole = Bidding1Role;
const qreal averageBidding = averageBiddingAmount(biddingRole);
qInfo() << "average calculation (1):" << averageBidding;
return averageBidding;
}
qreal TableModel::biddingAverage2() const {
const UserRoles biddingRole = Bidding2Role;
const qreal averageBidding = averageBiddingAmount(biddingRole);
qInfo() << "average calculation (2):" << averageBidding;
return averageBidding;
}
qreal TableModel::biddingAverage3() const {
const UserRoles biddingRole = Bidding3Role;
const qreal averageBidding = averageBiddingAmount(biddingRole);
qInfo() << "average calculation (3):" << averageBidding;
return averageBidding;
}
void TableModel::onRowCountChanged(const QModelIndex& parent, int first, int last) {
Q_UNUSED(first);
Q_UNUSED(last);
if (parent != QModelIndex()) {
return;
}
emit rowCountChanged();
emit nExpectedBiddingsChanged();
emit nTotalExpectedSharesChanged();
emit nPlacedBiddingsChanged(1);
emit nPlacedBiddingsChanged(2);
emit nPlacedBiddingsChanged(3);
emit biddingSumChanged(1);
emit biddingSumChanged(2);
emit biddingSumChanged(3);
emit biddingAverageChanged(1);
emit biddingAverageChanged(2);
emit biddingAverageChanged(3);
}
void TableModel::execInsertItems(const int firstRow, const QList<ModelItemValues> valueList) {
const int nRows = valueList.size();
qDebug() << "Inserting" << nRows << "items...";
const int lastRow = firstRow + nRows - 1;
beginInsertRows(QModelIndex(), firstRow, lastRow);
for (int row = 0; row < nRows; ++row) {
const int rowPosition = firstRow + row;
shared_ptr<ModelItem> item = make_unique<ModelItem>(valueList.at(row));
m_items.insert(rowPosition, std::move(item));
}
endInsertRows();
}
void TableModel::execRemoveItems(const int firstRow, const int nRows) {
const int lastRow = firstRow + nRows - 1;
beginRemoveRows(QModelIndex(), firstRow, lastRow);
m_items.remove(firstRow, nRows);
endRemoveRows();
}
void TableModel::execEditItemData(const int row, const QMap<int, QVariant>& changedValues) {
shared_ptr<ModelItem> item = m_items.at(row);
bool isDataChanged = item->setItemData(changedValues);
if (isDataChanged) {
/// FIXME due to the mapping from roles to the DisplayRole of different columns the complete
/// row is getting notified about (potential) data changes; dataChanged should be called only
/// for the affected columns
const QModelIndex firstIndex = this->index(row, 0);
const QModelIndex lastIndex = this->index(row, USER_FACING_ROLES.size() - 1);
QList<int> roles = changedValues.keys();
roles.insert(0, Qt::DisplayRole);
emit dataChanged(firstIndex, lastIndex, roles.toVector());
if (roles.contains(BiddingTypeRole) || roles.contains(ShareAmountRole) ||
roles.contains(ShareTypeRole)) {
emit nExpectedBiddingsChanged();
emit nTotalExpectedSharesChanged();
}
if (roles.contains(ShareAmountRole) || roles.contains(ShareTypeRole)) {
emit nPlacedBiddingsChanged(1);
emit nPlacedBiddingsChanged(2);
emit nPlacedBiddingsChanged(3);
emit biddingSumChanged(1);
emit biddingSumChanged(2);
emit biddingSumChanged(3);
emit biddingAverageChanged(1);
emit biddingAverageChanged(2);
emit biddingAverageChanged(3);
} else {
/// no changes to share amount or type, but maybe to the biddings:
if (roles.contains(Bidding1Role)) {
emit nPlacedBiddingsChanged(1);
emit biddingSumChanged(1);
emit biddingAverageChanged(1);
}
if (roles.contains(Bidding2Role)) {
emit nPlacedBiddingsChanged(2);
emit biddingSumChanged(2);
emit biddingAverageChanged(2);
}
if (roles.contains(Bidding3Role)) {
emit nPlacedBiddingsChanged(3);
emit biddingSumChanged(3);
emit biddingAverageChanged(3);
}
}
}
}
QMap<int, QVariant> TableModel::onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const {
QMap<int, QVariant> result;
QMap<int, QVariant>::const_iterator i;
for (i = roleValueMap.constBegin(); i != roleValueMap.constEnd(); ++i) {
const int role = i.key();
const QVariant newValue = i.value();
const QVariant oldValue = index.data(role);
// TODO check if role is a editable role?
if (oldValue != newValue) {
bool emptyValueIsEqualToZero = isEmptyValueEqualToZero(role);
if (emptyValueIsEqualToZero && oldValue == QVariant() && newValue == 0) {
qDebug() << "oldValue:" << oldValue << "& newValue:" << newValue
<< "mean the same. Ignoring...";
continue;
}
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
result.insert(role, newValue);
} else {
qInfo() << "oldValue is already the same as newValue:" << oldValue << "-> ignoring...";
}
}
return result;
}
bool TableModel::isEmptyValueEqualToZero(const int role) const {
if (INT_ROLES.contains(role)) {
return true;
} else if (DOUBLE_ROLES.contains(role)) {
return true;
} else {
return false;
}
}
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
// iterate over indexes to search item : see searchItem(...);
// for (const shared_ptr<ModelItem>& item : m_items) {
for (int row = 0; row < rowCount(); ++row) {
qDebug() << "Processing item at row" << row << "...";
QModelIndex itemIndex = index(row, 0);
if (isItemEqualToItemValues(itemIndex, givenItemValues)) {
qInfo() << "Found item at row" << row << "! Returning its index...";
return itemIndex;
}
}
qDebug() << "No matching item found. Returning empty pointer...";
return {};
}
bool TableModel::isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const {
/// do both have a UUID?
const UserRoles idRole = OnlineIdRole;
QVariant idOfItem = data(itemIndex, idRole);
QVariant given = givenItemValues.value(idRole);
if (idOfItem.isValid() && given.isValid()) {
/// are the UUIDs the same?
if (idOfItem.toString() == given.toString()) {
qInfo() << "UUIDs are the same.";
return true;
} else {
qDebug() << "UUIDs are NOT the same.";
return false;
}
} else {
/// are all other values the same? (for now only USER_FACING_ROLES are checked)
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant valueOfItem = data(itemIndex, role);
const QVariant givenValue = givenItemValues.value(role);
if (STRING_ROLES.contains(role)) {
if (valueOfItem.toString() != givenValue.toString()) {
return false;
}
} else if (INT_ROLES.contains(role)) {
if (valueOfItem.toInt() != givenValue.toInt()) {
return false;
}
} else if (DOUBLE_ROLES.contains(role)) {
if (valueOfItem.toDouble() != givenValue.toDouble()) {
return false;
}
} else {
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
}
}
return true;
}
}
int TableModel::nPlacedBiddings(const UserRoles biddingRole) const {
int result = 0;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
const QString biddingType = (*i)->data(BiddingTypeRole).toString();
const qreal shareAmount = (*i)->data(ShareAmountRole).toReal();
const QString shareType = (*i)->data(ShareTypeRole).toString();
if (biddingType.isEmpty() || shareAmount == 0.0) {
continue;
}
if (shareType == "erarbeitet" || shareType == "") {
continue;
}
int localBidding = (*i)->data(biddingRole).toInt();
if (localBidding > 0) {
result++;
}
}
return result;
}
int TableModel::biddingSum(const UserRoles biddingRole) const {
int result = 0;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
const QString biddingType = (*i)->data(BiddingTypeRole).toString();
const qreal shareAmount = (*i)->data(ShareAmountRole).toReal();
const QString shareType = (*i)->data(ShareTypeRole).toString();
if (biddingType.isEmpty() || shareAmount == 0.0) {
continue;
}
if (shareType == "erarbeitet" || shareType == "") {
continue;
}
result += (*i)->data(biddingRole).toInt();
}
return result;
}
qreal TableModel::averageBiddingAmount(const UserRoles biddingRole) const {
qInfo() << "Calculating average bidding for role:" << ROLE_NAMES.value(biddingRole);
const qreal localTotalSharesWithBiddings = totalSharesWithBiddings(biddingRole);
if (localTotalSharesWithBiddings <= 0) {
qInfo() << "No biddings found. Aborting calculation...";
return 0;
}
const qreal localTotalBiddingAmount = biddingSum(biddingRole);
const qreal alternateBiddingAverage = localTotalBiddingAmount / localTotalSharesWithBiddings;
qDebug() << "Total bidding amount:" << localTotalBiddingAmount;
qDebug() << "Total bidding shares:" << localTotalSharesWithBiddings;
return alternateBiddingAverage;
}
qreal TableModel::totalSharesWithBiddings(const UserRoles biddingRole) const {
qreal result = 0;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
const QString biddingType = (*i)->data(BiddingTypeRole).toString();
const qreal shareAmount = (*i)->data(ShareAmountRole).toReal();
if (biddingType.isEmpty() || shareAmount == 0.0) {
continue;
}
const int bidding = (*i)->data(biddingRole).toInt();
const QString shareType = (*i)->data(ShareTypeRole).toString();
const bool isValid = bidding != 0 && shareAmount != 0.0;
if (isValid) {
// qInfo() << "Including entry in bidding average calculation. MailRole:"
// << (*i)->data(MailRole);
// qreal bidForWholeShare = 0;
if (shareType == "bezahlt") {
result += shareAmount;
} else if (shareType == "teils/teils") {
result += shareAmount / 2;
} else {
qInfo() << "Share type not 'bezahlt' nor 'teils/teils'. Will be ignored..";
qDebug() << "Share type:" << shareType;
continue;
}
}
}
qInfo() << "Biddings exist for " << result << "shares!";
return result;
}
QModelIndex TableModel::getIndexByRoleValue(const QString& valueString, const int role) const {
const QString text =
QString("Searching list item with value '%1' for role '%2'").arg(valueString, role);
qInfo() << text;
int itemRow = -1;
for (auto i = m_items.begin(), end = m_items.end(); i != end; ++i) {
const QString mailValue = (*i)->data(role).toString();
qDebug() << "found value:" << mailValue;
if (valueString == mailValue) {
itemRow = i - m_items.constBegin();
qInfo() << "Found item at row:" << itemRow;
break;
} else {
qDebug() << "Not the right item. Continuing search...";
continue;
}
}
if (itemRow < 0 || itemRow >= m_items.length()) {
qWarning() << "Couldn't find item with:" << valueString << " matching role" << role
<< "- Returning...";
return QModelIndex();
}
const QModelIndex itemIndex = index(itemRow, 0);
return itemIndex;
}
QMap<int, QVariant> TableModel::getItemValues(const bidding bid) {
const int biddingRound = bid.biddingRound;
const int amount = bid.amount;
const QString depotWishOne = bid.depotWishOne;
const QString depotWishTwo = bid.depotWishTwo;
UserRoles biddingRole;
switch (biddingRound) {
case 1:
biddingRole = Bidding1Role;
break;
case 2:
biddingRole = Bidding2Role;
break;
case 3:
biddingRole = Bidding3Role;
break;
default:
break;
}
if (biddingRound == 1) {
return {{biddingRole, amount}, {DepotWish1Role, depotWishOne}, {DepotWish2Role, depotWishTwo}};
} else {
return {{biddingRole, amount}};
}
}

View File

@ -0,0 +1,121 @@
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
#include "metadata.h"
class bidding;
class QUndoStack;
class ModelItem;
using namespace std;
typedef QMap<int, QVariant> ModelItemValues;
class TableModel : public QAbstractTableModel {
Q_OBJECT
friend class InsertRowsCommand;
friend class RemoveRowsCommand;
friend class EditItemCommand;
public:
static QByteArray generateExampleItems();
explicit TableModel(QUndoStack* undoStack, QObject* parent = nullptr);
/// QAbstractItemModel interface
Qt::ItemFlags flags(const QModelIndex& index) const override;
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) override;
ModelItemValues getItemValues(const QModelIndex& index) const;
QJsonDocument getAllItemsAsJsonDoc() const;
QList<QStringList> getItemsAsStringLists() const;
QByteArray jsonDataForServer(const QModelIndex& currentIndex) const;
QString updateItemsFromJson(const QByteArray& jsonData);
bool updateItem(const ModelItemValues& itemValues);
void setOnlineCredentials(const QString& mail, const QString& uuid, const QString& token);
QJsonDocument getMailInviteJsonDoc(const QString& mail, const QString& serverUrl) const;
void updateBiddings(const QList<bidding> biddings);
public slots:
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
// override;
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
void appendItems(const QByteArray& jsonDoc);
void insertItems(int startPosition,
const QByteArray& jsonDoc,
const QModelIndex& parentIndex = QModelIndex());
void insertItems(int startPosition,
const QList<ModelItemValues>& itemValuesList,
const QModelIndex& parentIndex = QModelIndex());
/// property functions
qreal nTotalExpectedShares() const;
int nExpectedBiddings() const;
int nPlacedBiddings1() const;
int nPlacedBiddings2() const;
int nPlacedBiddings3() const;
int biddingSum1() const;
int biddingSum2() const;
int biddingSum3() const;
qreal biddingAverage1() const;
qreal biddingAverage2() const;
qreal biddingAverage3() const;
signals:
void rowCountChanged();
void nExpectedBiddingsChanged();
void nTotalExpectedSharesChanged();
void nPlacedBiddingsChanged(const int roundNumber);
void biddingSumChanged(const int roundNumber);
void biddingAverageChanged(const int roundNumber);
private slots:
void onRowCountChanged(const QModelIndex& parent, int first, int last);
private:
/// *** members ***
// TODO shared_ptr -> unique_ptr
QList<shared_ptr<ModelItem>> m_items;
QUndoStack* m_undoStack;
/// *** functions ***
/// undo/redo functions
void execInsertItems(const int firstRow, const QList<ModelItemValues> valueList);
void execRemoveItems(const int firstRow, const int nRows);
void execEditItemData(const int row, const QMap<int, QVariant>& changedValues);
/// misc functions
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const;
bool isEmptyValueEqualToZero(const int role) const;
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const;
int nPlacedBiddings(const UserRoles biddingRole) const;
int biddingSum(const UserRoles biddingRole) const;
qreal averageBiddingAmount(const UserRoles biddingRole) const;
qreal totalSharesWithBiddings(const UserRoles biddingRole) const;
QModelIndex getIndexByRoleValue(const QString& valueString, const int role) const;
QMap<int, QVariant> getItemValues(const bidding bid);
};
#endif // TABLEMODEL_H

View File

@ -0,0 +1,27 @@
#ifndef APIROUTES_H
#define APIROUTES_H
#include <QString>
// TODO add namespace
static const QString ROUTE_USER_LOG_IN = "/log_in";
static const QString apiPrefix = "/api/";
static const QString ROUTE_ITEMS = apiPrefix + "items";
static const QString ROUTE_ADMIN_LOG_IN = apiPrefix + "log_in";
static const QString ROUTE_REGISTER_USER = apiPrefix + "users";
static const QString ROUTE_MAIL_INVITE = apiPrefix + "invite";
static const QString ROUTE_BIDDINGROUNDS = apiPrefix + "bidding_rounds";
static const QString ROUTE_CURRENT_BIDDINGROUND = ROUTE_BIDDINGROUNDS + "/get_current";
static const QString ROUTE_START_BIDDINGROUND = ROUTE_BIDDINGROUNDS + "/start_new";
static const QString ROUTE_RESTART_BIDDINGROUND = ROUTE_BIDDINGROUNDS + "/restart";
static const QString ROUTE_STOP_BIDDINGROUND = ROUTE_BIDDINGROUNDS + "/stop";
static const QString ROUTE_GET_BIDDINGS_OF_SPECIFIC_ROUND = apiPrefix + "biddings_of_round";
static const QString ROUTE_GET_BIDDINGS_OF_HIGHEST_ROUND = apiPrefix + "biddings_of_highest_round";
#endif // APIROUTES_H

View File

@ -0,0 +1,321 @@
#include "servercommunicator.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QRestAccessManager>
#include <QRestReply>
#include "../formats/jsonparser.h"
#include "../genericcore.h"
#include "../structs.h"
#include "apiroutes.h"
#include "../data/settingshandler.h"
using namespace Qt::StringLiterals;
ServerCommunicator::ServerCommunicator(GenericCore* core)
: m_core(core)
, QObject{core} {
m_netManager.setAutoDeleteReplies(true);
m_restManager = std::make_shared<QRestAccessManager>(&m_netManager);
m_serviceApi = std::make_shared<QNetworkRequestFactory>();
connect(core, &GenericCore::loginAndStoreAuthToken, this, &ServerCommunicator::onLoginTriggered);
connect(this, &ServerCommunicator::loginSuccessful, core, &GenericCore::onLoginSuccessful);
connect(m_core, &GenericCore::sendGetRequest, this,
&ServerCommunicator::onSendGetRequestTriggered);
connect(m_core, &GenericCore::sendPostRequest, this,
&ServerCommunicator::onSendPostRequestTriggered);
connect(this, &ServerCommunicator::biddingsChanged, m_core, &GenericCore::onBiddingsChanged);
connect(this, &ServerCommunicator::onlineUserAccountReceived, m_core,
&GenericCore::onOnlineUserAccountReceived);
}
bool ServerCommunicator::sslSupported() const {
#if QT_CONFIG(ssl)
return QSslSocket::supportsSsl();
#else
return false;
#endif
}
QUrl ServerCommunicator::url() const { return m_serviceApi->baseUrl(); }
void ServerCommunicator::setUrl(const QUrl& url) {
if (m_serviceApi->baseUrl() == url) {
return;
}
m_serviceApi->setBaseUrl(url);
QHttpHeaders authenticationHeaders;
authenticationHeaders.append(QHttpHeaders::WellKnownHeader::ContentType, "application/json");
m_serviceApi->setCommonHeaders(authenticationHeaders);
emit urlChanged();
}
void ServerCommunicator::setServerConfiguration(const QString url,
const QString email,
const QString password,
const QString authToken) {
setUrl(url);
m_email = email;
m_password = password;
m_authToken = authToken;
if (!m_authToken.isEmpty()) {
m_serviceApi->setBearerToken(authToken.toLatin1());
}
}
QString ServerCommunicator::getUserLoginUrl() const {
const QString logInUrl = m_serviceApi->baseUrl().toString() + ROUTE_USER_LOG_IN;
return logInUrl;
}
void ServerCommunicator::onSendGetRequestTriggered(const GetRequestTypes type,
QVariant data = QVariant()) {
QString path;
switch (type) {
case GetCurrentBiddingRound:
path = ROUTE_CURRENT_BIDDINGROUND;
break;
case StartNewBiddingRound:
path = ROUTE_START_BIDDINGROUND;
break;
case RestartLastBiddingRound:
path = ROUTE_RESTART_BIDDINGROUND;
break;
case StopCurrentBiddingRound:
path = ROUTE_STOP_BIDDINGROUND;
break;
case GetBiddingsOfSpecificRound:
path = ROUTE_GET_BIDDINGS_OF_SPECIFIC_ROUND + "/" + data.toString();
break;
case GetBiddingsOfHighestRound:
path = ROUTE_GET_BIDDINGS_OF_HIGHEST_ROUND;
break;
default:
qWarning() << "No route found for GetRequestType:" << type;
break;
}
// TODO move into default case of switch statement?
if (path.isEmpty()) {
qDebug() << "Empty path -> Not sending a request.";
return;
}
m_serviceApi->setBearerToken(m_authToken.toLatin1());
const QNetworkRequest request = m_serviceApi->createRequest(path);
m_restManager->get(request, this, [this, type](QRestReply& reply) {
if (reply.isSuccess()) {
qInfo() << "Request successful.";
const QJsonDocument doc = reply.readJson().value();
onGetReplySuccessful(type, doc);
} else {
if (reply.hasError()) {
const QString errorString = reply.errorString();
qWarning() << "Network error:" << errorString;
onGetReplyFailure(type, errorString);
} else {
int statusCode = reply.httpStatus();
qWarning() << "Request not successful:" << statusCode;
onGetReplyFailure(type, QString("HTTP status code: %1").arg(statusCode));
}
}
});
}
void ServerCommunicator::onGetReplySuccessful(const GetRequestTypes type, const QJsonDocument doc) {
switch (type) {
case GetCurrentBiddingRound:
case StartNewBiddingRound:
case RestartLastBiddingRound:
case StopCurrentBiddingRound:
currentBiddingRoundChangedReply(doc);
break;
case GetBiddingsOfSpecificRound:
case GetBiddingsOfHighestRound:
currentBiddingsReply(doc);
break;
default:
qWarning() << "Can't match request type:" << type;
break;
}
}
void ServerCommunicator::onGetReplyFailure(const GetRequestTypes type, const QString errorString) {
const QString message =
QString("Request of type %1 returned: %2").arg(QString::number(type), errorString);
m_core->displayStatusMessage(message);
}
void ServerCommunicator::onSendPostRequestTriggered(const PostRequestTypes type,
const QByteArray data) {
QString path;
switch (type) {
case LogInAdmin:
path = ROUTE_ADMIN_LOG_IN;
break;
case RegisterUser:
path = ROUTE_REGISTER_USER;
break;
case MailInvite:
path = ROUTE_MAIL_INVITE;
break;
default:
qWarning() << "No route found for PostRequestType:" << type;
break;
}
// TODO move into default case of switch statement?
if (path.isEmpty()) {
qDebug() << "Empty path -> Not sending a request.";
return;
}
m_serviceApi->setBearerToken(m_authToken.toLatin1());
const QNetworkRequest request = m_serviceApi->createRequest(path);
m_restManager->post(request, data, this, [this, type](QRestReply& reply) {
if (reply.isSuccess()) {
int statusCode = reply.httpStatus();
qInfo() << "Request successful. Status code:" << statusCode;
const QJsonDocument doc = reply.readJson().value();
onPostReplySuccessful(type, doc);
} else {
if (reply.hasError()) {
const QString errorString = reply.errorString();
qWarning() << "Network error:" << errorString;
onPostReplyFailure(type, errorString);
} else {
int statusCode = reply.httpStatus();
qWarning() << "Request not successful:" << statusCode;
qInfo() << "Content:" << reply.readJson();
onPostReplyFailure(type, QString("HTTP status code: %1").arg(statusCode));
}
}
});
}
void ServerCommunicator::onPostReplySuccessful(const PostRequestTypes type,
const QJsonDocument doc) {
switch (type) {
case LogInAdmin:
qInfo() << "Admin successfully logged in:" << type;
handleLogInReply(doc);
break;
case RegisterUser:
qInfo() << "Register user successful:" << type;
onlineUserAccountReply(doc);
break;
case MailInvite:
qInfo() << "Mail invite successful sent:" << type;
mailInviteSentReply(doc);
break;
default:
qWarning() << "Can't match request type:" << type;
break;
}
}
void ServerCommunicator::onPostReplyFailure(const PostRequestTypes type,
const QString errorString) {
const QString message =
QString("Request of type %1 returned: %2").arg(QString::number(type), errorString);
// NEXT improve error message to the UI;
emit m_core->displayStatusMessage(message);
}
QByteArray ServerCommunicator::createLoginBody() {
QHash<QString, QVariant> values;
values.insert("email", m_email);
values.insert("password", m_password);
return JsonParser::toJsonDoc(values, "admin");
}
void ServerCommunicator::handleLogInReply(const QJsonDocument jsonDoc) {
QJsonObject rootObject = jsonDoc.object();
bool hasErrors = rootObject.contains(QString("errors"));
if (hasErrors) {
qCritical() << "Reply has error(s)!";
QString errorString = rootObject["errors"].toString();
emit m_core->displayStatusMessage(errorString);
} else {
qInfo() << "Reply has no error(s)!";
const QJsonObject dataObject = rootObject["data"].toObject();
const QString authToken = dataObject["token"].toString();
m_authToken = authToken;
SettingsHandler::saveSettings({{"token", authToken}}, "Server");
emit loginSuccessful();
emit m_core->displayStatusMessage("Successfully logged in.");
}
}
void ServerCommunicator::currentBiddingRoundChangedReply(const QJsonDocument jsonDoc) {
qInfo() << "Current bidding round received.";
// REFACTOR implement & use "JsonParser::parseServerResponse(const QJsonDocument& jsonDoc,
// QHash<QString, int> entries)" (generalized version of
// "serverUserCredentialsToItemValues")
const QJsonObject rootObject = jsonDoc["data"].toObject();
const int roundNumber = rootObject["round_number"].toInt();
const bool stopped = rootObject["stopped"].toBool();
const bool isActive = !stopped;
// NOTE ?use ServerCommunicator::currentBiddingRoundChanged signal instead of emiting a signal of
// the core directly?
emit m_core->currentBiddingRoundChanged(roundNumber, isActive);
}
void ServerCommunicator::currentBiddingsReply(const QJsonDocument jsonDoc) {
qInfo() << "currentBiddingsReply:" << jsonDoc;
const QList<bidding> biddings = JsonParser::extractBiddings(jsonDoc);
emit biddingsChanged(biddings);
}
void ServerCommunicator::onlineUserAccountReply(const QJsonDocument jsonDoc) {
qInfo() << "Online user account received.";
ModelItemValues values = JsonParser::serverUserCredentialsToItemValues(jsonDoc);
emit onlineUserAccountReceived(values[MailRole].toString(), values[OnlineIdRole].toString(),
values[AccessCodeRole].toString());
}
void ServerCommunicator::mailInviteSentReply(const QJsonDocument jsonDoc) {
qInfo() << "Invitation mail successfully sent.";
emit m_core->displayStatusMessage("Invitation mail successfully sent.");
}
void ServerCommunicator::onLoginTriggered() {
qInfo() << "Login triggered...";
if (m_email.isEmpty() || m_password.isEmpty()) {
emit m_core->displayStatusMessage(
"Missing email or password in settings! Not trying to log in.");
return;
}
if (m_authToken.isEmpty()) {
/// get new authToken
qInfo() << "Creating a new authToken!";
const QByteArray loginBody = createLoginBody();
onSendPostRequestTriggered(LogInAdmin, loginBody);
} else {
/// try authToken
qWarning() << "Validity check of token not implemented yet!!!";
qInfo() << "Assuming validity of token...";
emit loginSuccessful();
// TODO try validity of token and trigger log_in if not valid
// try default route to test access;
// if (access denied) {
// m_apiClient->sendAPIRequestPost(ROUTE_LOG_IN_ADMIN, );
// }
}
}

View File

@ -0,0 +1,82 @@
#ifndef SERVERCOMMUNICATOR_H
#define SERVERCOMMUNICATOR_H
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkRequestFactory>
#include <QObject>
#include <QRestAccessManager>
#include "../model/metadata.h"
class bidding;
class GenericCore;
class ServerCommunicator : public QObject {
Q_OBJECT
public:
explicit ServerCommunicator(GenericCore* core);
bool sslSupported() const;
QUrl url() const;
void setUrl(const QUrl& url);
void setServerConfiguration(const QString url,
const QString email,
const QString password,
const QString authToken);
QString getUserLoginUrl() const;
public slots:
void onLoginTriggered();
void onSendGetRequestTriggered(const GetRequestTypes type, QVariant data);
void onGetReplySuccessful(const GetRequestTypes type, const QJsonDocument doc);
void onGetReplyFailure(const GetRequestTypes type, const QString errorString);
void onSendPostRequestTriggered(const PostRequestTypes type, const QByteArray data);
void onPostReplySuccessful(const PostRequestTypes type, const QJsonDocument doc);
void onPostReplyFailure(const PostRequestTypes type, const QString errorString);
signals:
void urlChanged();
void itemsFetched(const QByteArray jsonDoc);
void itemsFetchFailure(const QString errorString);
void postRequestSuccessful(const QByteArray responseData);
void postRequestFailure(const QString errorString);
void deleteRequestSuccessful(const QByteArray responseData);
void deleteRequestFailure(const QString errorString);
void loginSuccessful();
void currentBiddingRoundChanged(int round, bool isRunning);
void biddingsChanged(QList<bidding> biddings);
void onlineUserAccountReceived(const QString mailAddress,
const QString uuid,
const QString accessToken);
private:
GenericCore* m_core = nullptr;
QNetworkAccessManager m_netManager;
std::shared_ptr<QRestAccessManager> m_restManager;
std::shared_ptr<QNetworkRequestFactory> m_serviceApi;
QString m_email;
QString m_password;
QString m_authToken;
QByteArray createLoginBody();
/// reply parser
void handleLogInReply(const QJsonDocument jsonDoc);
void currentBiddingRoundChangedReply(const QJsonDocument jsonDoc);
void currentBiddingsReply(const QJsonDocument jsonDoc);
void onlineUserAccountReply(const QJsonDocument jsonDoc);
void mailInviteSentReply(const QJsonDocument jsonDoc);
};
#endif // SERVERCOMMUNICATOR_H

View File

@ -0,0 +1,14 @@
#ifndef STRUCTS_H
#define STRUCTS_H
#include <QUuid>
struct bidding {
QString userId;
int biddingRound;
int amount;
QString depotWishOne;
QString depotWishTwo;
};
#endif // STRUCTS_H

View File

@ -0,0 +1,31 @@
include(FetchContent)
set(TARGET_APP "core_test")
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.17.0
)
FetchContent_MakeAvailable(googletest)
add_library(GTest::GTest INTERFACE IMPORTED)
target_link_libraries(GTest::GTest INTERFACE gtest_main)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools)
add_executable(${TARGET_APP} core_test.cpp
model_test.cpp)
target_include_directories(${TARGET_APP} PRIVATE ${CORE_LIB_DIR}/include)
target_link_libraries(${TARGET_APP}
PRIVATE
GTest::GTest
BeetRoundCore)
target_link_libraries(${TARGET_APP} PUBLIC Qt${QT_VERSION_MAJOR}::Core)
add_test(core_gtests ${TARGET_APP})

View File

@ -0,0 +1,26 @@
#include <gtest/gtest.h>
#include <QString>
#include "../../libs/BeetRoundCore/genericcore.h"
QT_BEGIN_NAMESPACE
inline void PrintTo(const QString& qString, ::std::ostream* os) { *os << qUtf8Printable(qString); }
QT_END_NAMESPACE
TEST(CoreTests, TestEqualString) {
const QString coreName("BeetRoundCore");
const QString coreVersion("0.1.0");
const auto expected = QString("%1 (Version %2)").arg(coreName).arg(coreVersion);
auto core = std::make_unique<GenericCore>();
const auto actual = core->toString();
// const auto actual = multiply(1, 1);
ASSERT_EQ(expected, actual);
}
TEST(CoreTests, TestNotEqualString) {
const QString expected = QString("Hello from the Core!");
auto core = std::make_unique<GenericCore>();
const QString actual = core->toString();
ASSERT_NE(expected, actual);
}

View File

@ -0,0 +1,131 @@
#include <gtest/gtest.h>
#include <QString>
#include <QtGui/QUndoCommand>
#include "../../libs/BeetRoundCore/model/tablemodel.h"
QT_BEGIN_NAMESPACE
inline void PrintTo(const QString& qString, ::std::ostream* os) { *os << qUtf8Printable(qString); }
QT_END_NAMESPACE
struct ModelTest : testing::Test {
std::shared_ptr<TableModel> model;
ModelTest() { model = make_shared<TableModel>(new QUndoStack()); }
virtual ~ModelTest() {}
};
struct ModelTestWithData : ModelTest {
ModelTestWithData() {
QList<ModelItemValues> itemList;
ModelItemValues itemValues1 = {{Bidding1Role, 100},
{ShareTypeRole, "bezahlt"},
{ShareAmountRole, 1},
{BiddingTypeRole, "digital"}};
itemList.append(itemValues1);
ModelItemValues itemValues2 = {{Bidding1Role, 100},
{ShareTypeRole, "bezahlt"},
{ShareAmountRole, 1},
{BiddingTypeRole, ""}};
itemList.append(itemValues2);
ModelItemValues itemValues3 = {{Bidding1Role, 50},
{ShareTypeRole, "teils/teils"},
{ShareAmountRole, 1},
{BiddingTypeRole, "paper"}};
itemList.append(itemValues3);
ModelItemValues itemValues4 = {{Bidding1Role, 50},
{ShareTypeRole, "bezahlt"},
{ShareAmountRole, 0.5},
{BiddingTypeRole, "paper"}};
itemList.append(itemValues4);
ModelItemValues itemValues5 = {{Bidding1Role, 100},
{ShareTypeRole, "erarbeitet"},
{ShareAmountRole, 1},
{BiddingTypeRole, "paper"}};
itemList.append(itemValues5);
ModelItemValues itemValues6 = {{Bidding1Role, 0},
{ShareTypeRole, "bezahlt"},
{ShareAmountRole, 1},
{BiddingTypeRole, "online"}};
itemList.append(itemValues6);
model->insertItems(0, itemList);
}
};
/// empty model
TEST_F(ModelTest, TestRowCountEmpty) {
const int expectedRowCount = 0;
const auto actualRowCount = model->rowCount();
ASSERT_EQ(expectedRowCount, actualRowCount);
}
TEST_F(ModelTest, TestBidding1Average) {
const int expected = 0;
const auto actualBidding1Average = model->biddingAverage1();
ASSERT_EQ(expected, actualBidding1Average);
}
TEST_F(ModelTest, ExpectedPlacedBiddings) {
const int expected = 0;
const auto expectedPlacedBiddings = model->nExpectedBiddings();
ASSERT_EQ(expected, expectedPlacedBiddings);
}
TEST_F(ModelTest, ExpectedTotalShareAmount) {
const int expected = 0;
const auto nTotalExpectedShares = model->nTotalExpectedShares();
ASSERT_EQ(expected, nTotalExpectedShares);
}
/// model with data
TEST_F(ModelTestWithData, TestRowCount) {
const int expected = 6;
const auto actual = model->rowCount();
ASSERT_EQ(expected, actual);
}
TEST_F(ModelTestWithData, TestBidding1Average) {
const qreal expected = 100;
const auto actual = model->biddingAverage1();
ASSERT_EQ(expected, actual);
}
TEST_F(ModelTestWithData, ExpectedPlacedBiddings) {
const int expected = 4;
const auto actual = model->nExpectedBiddings();
ASSERT_EQ(expected, actual);
}
TEST_F(ModelTestWithData, PlacedBiddings1) {
const int expected = 3;
const auto actual = model->nPlacedBiddings1();
ASSERT_EQ(expected, actual);
}
TEST_F(ModelTestWithData, NTotalExpectedShares) {
const qreal expected = 3;
const auto actual = model->nTotalExpectedShares();
ASSERT_EQ(expected, actual);
}

View File

@ -0,0 +1,8 @@
Name,Description,Info,Factor
Item 0,This is item 0,Info of item 0,0
Item 1,This is item 1,Info of item 1,1
Item 2,This is item 2,Info of item 2,2
Item 3,This is item 3,Info of item 3,3
Item 4,This is item 4,Info of item 4,4
Item 5,This is item 5,Info of item 5,5
Item 6,This is item 6,Info of item 6,6
1 Name Description Info Factor
2 Item 0 This is item 0 Info of item 0 0
3 Item 1 This is item 1 Info of item 1 1
4 Item 2 This is item 2 Info of item 2 2
5 Item 3 This is item 3 Info of item 3 3
6 Item 4 This is item 4 Info of item 4 4
7 Item 5 This is item 5 Info of item 5 5
8 Item 6 This is item 6 Info of item 6 6

View File

@ -0,0 +1,8 @@
Name,Description,Info,Amount,Factor
Item 0,This is item 0,Info of item 0,0,0
Item 1,This is item 1,Info of item 1,1,1
Item 2,This is item 2,Info of item 2,2,2
Item 3,This is item 3,Info of item 3,3,3
Item 4,This is item 4,Info of item 4,4,4
Item 5,This is item 5,Info of item 5,5,5
Item 6,This is item 6,Info of item 6,6,6
1 Name Description Info Amount Factor
2 Item 0 This is item 0 Info of item 0 0 0
3 Item 1 This is item 1 Info of item 1 1 1
4 Item 2 This is item 2 Info of item 2 2 2
5 Item 3 This is item 3 Info of item 3 3 3
6 Item 4 This is item 4 Info of item 4 4 4
7 Item 5 This is item 5 Info of item 5 5 5
8 Item 6 This is item 6 Info of item 6 6 6