4 Commits

Author SHA1 Message Date
henrique fe66b8aa8f Port to Paper 26.3 (2.1.0)
Built against paper-api 26.3.build.140-beta on Java 25, api-version 26.3,
version 2.1.0 so the jar reports the number Modrinth shows. Release notes
are in the 2.1.0 section of the Modrinth changelog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 16:41:55 +01:00
henrique cfc2efc9a5 Port to Paper 26.2 (2.0.0)
Snapshot of the 26.2 port published on Modrinth as 2.0.0 on 2026-08-06.
Built against paper-api 26.2.build.100-stable on Java 25. The changes had
only lived in the working tree on HPDebian (/root/mc-26.2/repos); this
commit records them as they were shipped. Details are in the 2.0.0 section
of the Modrinth changelog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 16:35:33 +01:00
henrique bc6e2296c6 Second+third review pass (2026-07-10/11): security and completeness fixes, public-release polish 2026-07-11 13:59:33 +01:00
henrique fe8dc78d0f Security hardening + GPL-3.0 license (audit 2026-07-04)
Applied fixes from a full security/bug audit (per-finding detail in the
maintainer's audit report): dupe/exploit/injection/thread-safety and
input-validation fixes as applicable to this plugin, plus build-portability
fixes (JDK path / dependency pins / path casing) where present.
Added GPL-3.0 LICENSE.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 15:17:13 +01:00
136 changed files with 1371 additions and 5902 deletions
Vendored
BIN
View File
Binary file not shown.
+27 -13
View File
@@ -1,17 +1,31 @@
# Maven build artifacts
# Build output
target/
dependency-reduced-pom.xml
# IDE files
.idea/
*.iml
.DS_Store
build/
.gradle/
out/
bin/
*.class
# OS files
Thumbs.db
.DS_Store
# Node (remnants of any old embedded web-panel)
node_modules/
package-lock.json
# ServerShop build artifacts
ServerShop/target/
ServerShop/dependency-reduced-pom.xml
# IDE / tooling
.idea/
*.iml
.vscode/
.claude/
.settings/
.classpath
.project
# OS
.DS_Store
Thumbs.db
# Local / logs
*.log
build_output.txt
dependency-reduced-pom.xml
run/
logs/
+26
View File
@@ -5,6 +5,32 @@ All notable changes to CommunityMarket will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.0] - 2026-10-01
Requires Minecraft 26.3 and Java 25. On 26.2 use 2.0.0; on 1.21.x use the 1.x release.
### Changed
- Built against Paper 26.3 on Java 25 and tested on Paper 26.3 build 140, which Paper still marks as beta: there was no stable 26.3 build when this was released. `api-version` is now `26.3`.
- The plugin now reports version 2.1.0. The 2.0.0 jar reported `1.0.0`.
- Checked against 26.3: no new item holds other items, so the container checks from 2.0.0 cover the new content unchanged.
## [2.0.0] - 2026-08-06
Requires Minecraft 26.2 and Java 25. This release does not run on 1.21.x; upgrade the server before installing it.
### Fixed
- Listing more than one stack could hand the buyer nothing. The quantity selector let a player list everything they held, so five stacks of dirt became a single count of 320, and from 26.1 a stack larger than its own maximum is read as empty. The purchase, the refund on a failed listing, the return on cancel or expiry, and claim storage were each a place where the player received an empty slot. Items are split into legal stacks before they are given or taken now, and every leftover is delivered instead of only the first.
- The same count rendered as a blank slot in Browse Market, My Listings and the quantity selector. Icon counts are clamped, and against the item's real maximum: items that stack to 16 or to 1 were treated as stacking to 64.
- Blacklisted materials and blacklisted name or lore keywords could be listed or auctioned inside a shulker box, a bundle or a loaded sulfur cube bucket, because only the outer item was checked. Every rule now applies to the container and to everything inside it, three levels deep, and listing and auction creation both run the same check before anything is written, so no path can skip it. A container holding ordinary items is still tradeable.
### Changed
- Built against Paper 26.2 on Java 25.
- Listings already stored with an oversized count keep it and are split when they are handed out, so no database migration is needed.
- Unchanged, and worth knowing before installing: CommunityMarket reads only Vault and EssentialsX economies. It has no MultiBank provider and disables itself when neither is present.
## [1.0.0] - 2026-01-15
### Added
+669 -17
View File
@@ -1,22 +1,674 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2026 Henrique
Copyright (C) 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.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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:
<program> Copyright (C) <year> <name of author>
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/licenses/why-not-lgpl.html>.
+23 -26
View File
@@ -1,43 +1,43 @@
# CommunityMarket
[![Modrinth Downloads](https://img.shields.io/modrinth/dt/communitymarket?logo=modrinth)](https://modrinth.com/plugin/communitymarket)
[![Modrinth Downloads](https://img.shields.io/modrinth/dt/carrageis-communitymarket?logo=modrinth)](https://modrinth.com/plugin/carrageis-communitymarket)
[![GitHub License](https://img.shields.io/github/license/henrique/CommunityMarket)](LICENSE)
A professional, production-ready **GUI-only marketplace plugin** for Minecraft Paper 1.21+.
Players can create fixed-price listings and auctions, browse, buy, bid, claim items, and withdraw earnings — all through intuitive GUIs. **No complex commands to learn!**
## ✨ Features
Features
### 🛒 Fixed-Price Market
Fixed-Price Market
- Create listings with custom prices and durations
- Browse paginated listings with sorting
- Safe atomic purchases to prevent double-buying
- Configurable taxes on sales
### 🔨 Auction System
Auction System
- Start auctions with minimum bid and optional buyout price
- **Anti-snipe protection** extends auction when bids arrive near the end
- Bid history and automatic outbid notifications
- Safe handling of auction endings and payouts
### 📦 Claim Storage
Claim Storage
- Items from expired listings go to claim storage
- Won auction items are safely delivered
- Handles full inventories gracefully
### 💰 Earnings Management
Earnings Management
- Pending earnings from sales accumulate
- Withdraw all earnings at once
- Complete transaction history
### 🔐 Admin Features (GUI-based)
Admin Features (GUI-based)
- View all listings and auctions
- Remove any listing or cancel auctions
- Force-end auctions
- Reload configuration in-game
### 🎮 Intuitive GUI Flow
Intuitive GUI Flow
The creation flow for listings and auctions:
1. **Main Menu** - Central hub for all actions
2. **Select Item** - Click an item from your inventory
@@ -45,7 +45,7 @@ The creation flow for listings and auctions:
4. **Settings** - Set price and duration with easy click-to-adjust controls
5. **Confirm** - Review and create your listing/auction
## 📋 Requirements
Requirements
| Requirement | Version |
|-------------|---------|
@@ -57,23 +57,23 @@ The creation flow for listings and auctions:
CommunityMarket supports two economy configurations:
1. **Vault + Economy Plugin** (Recommended)
- Install [Vault](https://modrinth.com/plugin/vault-2.0-economy-plugins)
- Install [VaultUnlocked](https://modrinth.com/plugin/vaultunlocked)
- Install an economy plugin: [EssentialsX](https://essentialsx.net/), CMI, or any Vault-compatible economy
2. **EssentialsX Standalone** (Fallback)
- Install [EssentialsX](https://essentialsx.net/) with economy enabled
- CommunityMarket will use EssentialsX directly if Vault is not present
## 📥 Installation
Installation
1. Download the latest `CommunityMarket-x.x.x.jar` from [Modrinth](https://modrinth.com/plugin/communitymarket)
1. Download the latest `CommunityMarket-x.x.x.jar` from [Modrinth](https://modrinth.com/plugin/carrageis-communitymarket)
2. Place it in your server's `plugins/` folder
3. Ensure you have an economy system installed (see above)
4. Start or restart your server
5. Edit `plugins/CommunityMarket/config.yml` as needed
6. Use `/market` to open the marketplace!
## 🎮 Commands
Commands
| Command | Alias | Description | Permission |
|---------|-------|-------------|------------|
@@ -81,7 +81,7 @@ CommunityMarket supports two economy configurations:
**That's it!** Everything else is done through GUIs.
## 🔒 Permissions
Permissions
| Permission | Description | Default |
|------------|-------------|---------|
@@ -94,11 +94,8 @@ CommunityMarket supports two economy configurations:
| `communitymarket.claim` | Claim items from storage | everyone |
| `communitymarket.withdraw` | Withdraw earnings | everyone |
| `communitymarket.admin` | Access admin functions | op |
| `communitymarket.admin.viewall` | View all listings/auctions | op |
| `communitymarket.admin.remove` | Remove any listing/auction | op |
| `communitymarket.admin.reload` | Reload configuration | op |
## ⚙️ Configuration
Configuration
### config.yml Highlights
@@ -148,7 +145,7 @@ gui:
Language files are located in `plugins/CommunityMarket/lang/` and can be customized.
## 🔧 Troubleshooting
Troubleshooting
### "No compatible economy provider found!"
@@ -156,7 +153,7 @@ This error appears when CommunityMarket cannot find an economy system.
**Solutions:**
1. **Install Vault + an economy plugin:**
- Download [Vault]([https://www.spigotmc.org/resources/vault.34315/](https://modrinth.com/plugin/vault-2.0-economy-plugins))
- Download [VaultUnlocked](https://modrinth.com/plugin/vaultunlocked)
- Download [EssentialsX](https://essentialsx.net/) or another economy plugin
- Restart your server
@@ -190,20 +187,20 @@ database:
password: your_password
```
## 📊 API
API
CommunityMarket does not currently provide a public API. If you need integration capabilities, please open an issue on GitHub.
## 🤝 Support
Support
- **Issues & Bug Reports:** [GitHub Issues](https://github.com/henrique/CommunityMarket/issues)
- **Feature Requests:** [GitHub Issues](https://github.com/henrique/CommunityMarket/issues)
- **Issues & Bug Reports:** [GitHub Issues](https://github.com/henriquescrrrr/carrageis-communitymarket/issues)
- **Feature Requests:** [GitHub Issues](https://github.com/henriquescrrrr/carrageis-communitymarket/issues)
## 📜 License
License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## 🙏 Credits
Credits
- Built for the Paper/Spigot community
- Uses [Vault](https://github.com/MilkBowl/VaultAPI) for economy integration
-166
View File
@@ -1,166 +0,0 @@
# ServerShop
A professional **server-run global market** plugin for **Paper/Purpur 1.21.1** servers. This plugin provides a GUI-driven shop where players can buy and sell all game items at configurable prices.
## Overview
ServerShop is designed to work alongside the [CommunityMarket](../README.md) player-to-player marketplace. It features a **large spread** between buy and sell prices, ensuring that player-to-player trading via CommunityMarket remains the preferred option for best deals.
### How the Spread Works
- **Buy Price**: What the server charges when selling to players (higher)
- **Sell Price**: What the server pays when buying from players (lower)
- **Default Spread**: 75% (`sellMultiplier = 0.25`)
For example, a Diamond with a buy price of `$100`:
- Server sells to player: **$100**
- Server buys from player: **$25** (100 × 0.25)
- Players trading via CommunityMarket might sell for **$60-80**, making it better for both buyer and seller
## Features
- **GUI-Only Interface**: All interactions through intuitive inventory GUIs
- **Category System**: Items organized into 10 categories (Blocks, Ores, Farming, Food, Mob Drops, Redstone, Decoration, Tools, Combat, Brewing, Misc)
- **Search**: Find items by name via chat input
- **Pagination**: Browse large categories with page navigation
- **Quantity Selection**: Adjust amounts with -32/-16/-8/-1/+1/+8/+16/+32 and MIN/MAX buttons
- **Sell Hand / Sell Inventory**: Quick-sell shortcuts from the main menu
- **Vault Economy**: Full integration with any Vault-compatible economy plugin
- **Multi-Language**: English (en_US) and Portuguese (pt_PT) included
- **Transaction Logging**: SQLite database for tracking all transactions
- **Anti-Exploit**: Comprehensive protection against item duplication and GUI exploits
- **Configurable Pricing**: Per-category multipliers, per-item overrides, buy/sell toggles
## Requirements
- **Paper** or **Purpur** 1.21.1+
- **Java 21**
- **Vault** + an economy provider (e.g., EssentialsX, CMI)
## Installation
1. Download the `ServerShop-1.0.0.jar`
2. Place it in your server's `plugins/` folder
3. Make sure **Vault** and an economy plugin are installed
4. Start/restart the server
5. Edit configuration files in `plugins/ServerShop/`
## Commands
| Command | Description | Permission |
|---------|-------------|------------|
| `/shop` | Opens the server shop GUI | `servershop.use` |
| `/servershop` | Alias for `/shop` | `servershop.use` |
| `/shop reload` | Reloads all configuration | `servershop.admin.reload` |
## Permissions
| Permission | Description | Default |
|------------|-------------|---------|
| `servershop.use` | Access the server shop | `true` |
| `servershop.buy` | Buy items from the shop | `true` |
| `servershop.sell` | Sell items to the shop | `true` |
| `servershop.sell.hand` | Use the "sell hand" feature | `true` |
| `servershop.sell.inventory` | Use the "sell inventory" feature | `true` |
| `servershop.admin` | Admin permissions | `op` |
| `servershop.admin.reload` | Reload configuration | `op` |
## Configuration
### config.yml
Main plugin settings including:
- Language selection
- Economy settings (symbol, decimal places, sell tax)
- Pricing defaults (global sell multiplier)
- Shop behavior (full inventory action, sell hand/inventory toggles)
- GUI settings (titles, filler items, sounds)
- Transaction logging
### prices.yml
Item pricing configuration with:
- **Categories**: Define categories with icon, sell multiplier, and item lists
- **Items**: Each item has a buy price; sell price is auto-calculated
- **Overrides**: Per-item buy/sell price overrides and enable/disable toggles
#### Adding/Editing Prices
```yaml
categories:
MyCategory:
icon: DIAMOND # Category icon material
sell-multiplier: 0.30 # Override global multiplier
buy-enabled: true
sell-enabled: true
items:
DIAMOND: 100.0 # Buy price = $100, Sell = $100 * 0.30 = $30
EMERALD: 50.0 # Buy price = $50, Sell = $50 * 0.30 = $15
```
#### Per-Item Overrides
```yaml
overrides:
ELYTRA:
sell: 500.0 # Override auto-calculated sell price
COMMAND_BLOCK:
buy-enabled: false # Cannot be purchased
sell-enabled: false # Cannot be sold
```
### Language Files
Located in `lang/en_US.yml` and `lang/pt_PT.yml`. All GUI labels and messages are fully customizable.
## Building from Source
```bash
cd ServerShop
mvn clean package
```
The compiled JAR will be in `ServerShop/target/`.
## Architecture
```
pt.henrique.servershop
├── ServerShop.java # Main plugin class
├── command/
│ └── ShopCommand.java # /shop command handler
├── config/
│ ├── ConfigManager.java # Main config (config.yml)
│ └── MessageManager.java # Language/message system
├── economy/
│ └── EconomyManager.java # Vault economy integration
├── pricing/
│ ├── PricingService.java # Price calculation & lookup
│ └── ItemPrice.java # Price data model
├── category/
│ ├── CategoryRegistry.java # Category management
│ └── ShopCategory.java # Category data model
├── gui/
│ ├── ShopGui.java # GUI interface
│ ├── GuiManager.java # GUI orchestration
│ ├── MainShopGui.java # Main menu
│ ├── CategoryGui.java # Category browser
│ ├── ItemDetailGui.java # Buy/sell detail view
│ └── SearchResultsGui.java # Search results
├── service/
│ └── ShopService.java # Buy/sell business logic
├── transaction/
│ └── TransactionLogger.java # SQLite transaction logging
├── listener/
│ └── GuiListener.java # Anti-exploit GUI listener
└── util/
├── ItemBuilder.java # Fluent ItemStack builder
└── TextUtil.java # Text formatting utilities
```
## Known Limitations
- **Special Items**: Enchanted books, potions, and other items with special metadata are excluded by default (configurable via `pricing.include-special-items`)
- **Dynamic Pricing**: v1.0 uses static, config-driven pricing only. Dynamic supply/demand pricing may be added in a future version
- **New Items**: Items added in future Minecraft updates will automatically fall into the "Misc" category if not explicitly configured
## License
MIT License - See [LICENSE](../LICENSE) for details.
-104
View File
@@ -1,104 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pt.henrique</groupId>
<artifactId>servershop</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>ServerShop</name>
<description>A server-run global market plugin for Paper/Purpur 1.21.1 with configurable pricing and GUI-driven UX</description>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<paper.version>1.21.1-R0.1-SNAPSHOT</paper.version>
</properties>
<repositories>
<!-- Paper Repository -->
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
<!-- Vault Repository -->
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<!-- Paper API -->
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>${paper.version}</version>
<scope>provided</scope>
</dependency>
<!-- Vault API for Economy -->
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
</dependency>
<!-- SQLite JDBC Driver -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.45.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.sqlite</pattern>
<shadedPattern>pt.henrique.servershop.libs.sqlite</shadedPattern>
</relocation>
</relocations>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
@@ -1,127 +0,0 @@
package pt.henrique.servershop;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
import pt.henrique.servershop.category.CategoryRegistry;
import pt.henrique.servershop.command.ShopCommand;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.economy.EconomyManager;
import pt.henrique.servershop.gui.GuiManager;
import pt.henrique.servershop.listener.GuiListener;
import pt.henrique.servershop.pricing.PricingService;
import pt.henrique.servershop.service.ShopService;
import pt.henrique.servershop.transaction.TransactionLogger;
/**
* ServerShop - A server-run global market plugin for Paper/Purpur 1.21.1.
* <p>
* Provides a GUI-driven shop where players can buy and sell all game items
* at configurable prices. Designed with a large spread between buy and sell
* prices to support the CommunityMarket player-to-player economy.
* </p>
*
* @author henrique
* @version 1.0.0
*/
public class ServerShop extends JavaPlugin {
private ConfigManager configManager;
private MessageManager messageManager;
private EconomyManager economyManager;
private CategoryRegistry categoryRegistry;
private PricingService pricingService;
private ShopService shopService;
private GuiManager guiManager;
private TransactionLogger transactionLogger;
@Override
public void onEnable() {
// 1. Configuration
configManager = new ConfigManager(this);
configManager.reload();
// 2. Language / Messages
messageManager = new MessageManager(this);
messageManager.reload();
// 3. Economy (Vault)
economyManager = new EconomyManager(this);
if (!economyManager.setupEconomy()) {
getLogger().severe("==============================================");
getLogger().severe(" ServerShop requires Vault + an economy plugin!");
getLogger().severe(" Plugin will be disabled.");
getLogger().severe("==============================================");
getServer().getPluginManager().disablePlugin(this);
return;
}
// 4. Categories
categoryRegistry = new CategoryRegistry(this);
categoryRegistry.reload();
// 5. Pricing
pricingService = new PricingService(this);
pricingService.reload();
// 6. Services
shopService = new ShopService(this);
// 7. Transaction Logging
transactionLogger = new TransactionLogger(this);
transactionLogger.initialize();
// 8. GUI Manager
guiManager = new GuiManager(this);
// 9. Register listeners
getServer().getPluginManager().registerEvents(guiManager, this);
getServer().getPluginManager().registerEvents(new GuiListener(this), this);
// 10. Register commands
ShopCommand shopCommand = new ShopCommand(this);
PluginCommand cmd = getCommand("shop");
if (cmd != null) {
cmd.setExecutor(shopCommand);
cmd.setTabCompleter(shopCommand);
}
getLogger().info("==============================================");
getLogger().info(" ServerShop v" + getDescription().getVersion() + " enabled!");
getLogger().info(" Categories: " + categoryRegistry.getCategories().size());
getLogger().info(" Items: " + pricingService.getAllPrices().size());
getLogger().info("==============================================");
}
@Override
public void onDisable() {
if (transactionLogger != null) {
transactionLogger.close();
}
getLogger().info("ServerShop disabled.");
}
/**
* Reloads all plugin configuration, prices, and language files.
*/
public void reloadPlugin() {
configManager.reload();
messageManager.reload();
categoryRegistry.reload();
pricingService.reload();
getLogger().info("ServerShop configuration reloaded.");
}
// ================================================================
// Service Accessors
// ================================================================
public ConfigManager getConfigManager() { return configManager; }
public MessageManager getMessageManager() { return messageManager; }
public EconomyManager getEconomyManager() { return economyManager; }
public CategoryRegistry getCategoryRegistry() { return categoryRegistry; }
public PricingService getPricingService() { return pricingService; }
public ShopService getShopService() { return shopService; }
public GuiManager getGuiManager() { return guiManager; }
public TransactionLogger getTransactionLogger() { return transactionLogger; }
}
@@ -1,138 +0,0 @@
package pt.henrique.servershop.category;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import pt.henrique.servershop.ServerShop;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
/**
* Registry that manages all shop categories and their item assignments.
* Loads from prices.yml and provides lookup methods.
*/
public class CategoryRegistry {
private final ServerShop plugin;
private final LinkedHashMap<String, ShopCategory> categories = new LinkedHashMap<>();
private final Map<Material, String> materialToCategory = new HashMap<>();
public CategoryRegistry(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Loads categories and item assignments from prices.yml.
*/
public void reload() {
categories.clear();
materialToCategory.clear();
File pricesFile = new File(plugin.getDataFolder(), "prices.yml");
if (!pricesFile.exists()) {
plugin.saveResource("prices.yml", false);
}
FileConfiguration pricesConfig = YamlConfiguration.loadConfiguration(pricesFile);
ConfigurationSection categoriesSection = pricesConfig.getConfigurationSection("categories");
if (categoriesSection == null) {
plugin.getLogger().severe("No 'categories' section found in prices.yml!");
return;
}
double globalMultiplier = plugin.getConfigManager().getDefaultSellMultiplier();
for (String categoryName : categoriesSection.getKeys(false)) {
ConfigurationSection catSection = categoriesSection.getConfigurationSection(categoryName);
if (catSection == null) continue;
// Parse category icon
Material icon;
try {
icon = Material.valueOf(catSection.getString("icon", "CHEST"));
} catch (IllegalArgumentException e) {
icon = Material.CHEST;
plugin.getLogger().warning("Invalid icon material for category " + categoryName);
}
double sellMultiplier = catSection.getDouble("sell-multiplier", globalMultiplier);
boolean buyEnabled = catSection.getBoolean("buy-enabled", true);
boolean sellEnabled = catSection.getBoolean("sell-enabled", true);
ShopCategory category = new ShopCategory(categoryName, icon, sellMultiplier, buyEnabled, sellEnabled);
// Parse items
ConfigurationSection itemsSection = catSection.getConfigurationSection("items");
if (itemsSection != null) {
for (String materialName : itemsSection.getKeys(false)) {
try {
Material material = Material.valueOf(materialName);
if (material.isAir()) continue;
category.addItem(material);
materialToCategory.put(material, categoryName);
} catch (IllegalArgumentException e) {
plugin.getLogger().log(Level.WARNING,
"Invalid material in category " + categoryName + ": " + materialName);
}
}
}
categories.put(categoryName, category);
}
plugin.getLogger().info("Loaded " + categories.size() + " categories with " +
materialToCategory.size() + " items.");
}
/**
* Gets all registered categories in order.
*
* @return unmodifiable collection of categories
*/
public Collection<ShopCategory> getCategories() {
return Collections.unmodifiableCollection(categories.values());
}
/**
* Gets a category by name.
*
* @param name the category name
* @return the category, or null if not found
*/
public ShopCategory getCategory(String name) {
return categories.get(name);
}
/**
* Gets the category name for a material.
*
* @param material the material
* @return the category name, or "Misc" if not found
*/
public String getCategoryForMaterial(Material material) {
return materialToCategory.getOrDefault(material, "Misc");
}
/**
* Checks if a material belongs to any category.
*
* @param material the material
* @return true if the material is registered
*/
public boolean hasMaterial(Material material) {
return materialToCategory.containsKey(material);
}
/**
* Gets all registered materials across all categories.
*
* @return set of registered materials
*/
public Set<Material> getAllMaterials() {
return Collections.unmodifiableSet(materialToCategory.keySet());
}
}
@@ -1,64 +0,0 @@
package pt.henrique.servershop.category;
import org.bukkit.Material;
import java.util.*;
/**
* Represents a shop category containing a set of items.
*/
public class ShopCategory {
private final String name;
private final Material icon;
private final double sellMultiplier;
private final boolean buyEnabled;
private final boolean sellEnabled;
private final List<Material> items;
/**
* Constructs a ShopCategory.
*
* @param name the display name of the category
* @param icon the material for the category icon
* @param sellMultiplier the sell multiplier for this category
* @param buyEnabled whether buying is enabled for this category
* @param sellEnabled whether selling is enabled for this category
*/
public ShopCategory(String name, Material icon, double sellMultiplier,
boolean buyEnabled, boolean sellEnabled) {
this.name = name;
this.icon = icon;
this.sellMultiplier = sellMultiplier;
this.buyEnabled = buyEnabled;
this.sellEnabled = sellEnabled;
this.items = new ArrayList<>();
}
public String getName() { return name; }
public Material getIcon() { return icon; }
public double getSellMultiplier() { return sellMultiplier; }
public boolean isBuyEnabled() { return buyEnabled; }
public boolean isSellEnabled() { return sellEnabled; }
public List<Material> getItems() { return Collections.unmodifiableList(items); }
/**
* Adds a material to this category.
*
* @param material the material to add
*/
public void addItem(Material material) {
if (!items.contains(material)) {
items.add(material);
}
}
/**
* Gets the number of items in this category.
*
* @return the item count
*/
public int getItemCount() {
return items.size();
}
}
@@ -1,74 +0,0 @@
package pt.henrique.servershop.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.config.MessageManager;
import java.util.Collections;
import java.util.List;
/**
* Handles the /shop (and /servershop) command.
* Players: opens the shop GUI.
* Admins: /shop reload to reload configuration.
*/
public class ShopCommand implements CommandExecutor, TabCompleter {
private final ServerShop plugin;
public ShopCommand(ServerShop plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
MessageManager msg = plugin.getMessageManager();
// Admin reload subcommand
if (args.length > 0 && args[0].equalsIgnoreCase("reload")) {
if (!sender.hasPermission("servershop.admin.reload")) {
sender.sendMessage(msg.getPrefixed("no-permission"));
return true;
}
plugin.reloadPlugin();
sender.sendMessage(msg.getPrefixed("reload-success"));
return true;
}
// Player-only for GUI
if (!(sender instanceof Player player)) {
sender.sendMessage(msg.getPrefixed("player-only"));
return true;
}
// Permission check
if (!player.hasPermission("servershop.use")) {
player.sendMessage(msg.getPrefixed("no-permission"));
return true;
}
// Economy check
if (!plugin.getEconomyManager().isAvailable()) {
player.sendMessage(msg.getPrefixed("economy-unavailable"));
return true;
}
// Open the main shop GUI
plugin.getGuiManager().openMainGui(player);
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 1 && sender.hasPermission("servershop.admin.reload")) {
if ("reload".startsWith(args[0].toLowerCase())) {
return List.of("reload");
}
}
return Collections.emptyList();
}
}
@@ -1,145 +0,0 @@
package pt.henrique.servershop.config;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import pt.henrique.servershop.ServerShop;
import java.io.File;
import java.util.logging.Level;
/**
* Manages the main plugin configuration (config.yml).
* Provides typed getters for all configuration values with sensible defaults.
*/
public class ConfigManager {
private final ServerShop plugin;
private FileConfiguration config;
// Cached values
private String language;
private String currencySymbol;
private int decimalPlaces;
private double sellTax;
private double defaultSellMultiplier;
private boolean includeSpecialItems;
private String fullInventoryAction;
private boolean enableSellHand;
private boolean enableSellInventory;
private int maxTransactionQuantity;
private String mainTitle;
private String categoryTitle;
private String detailTitle;
private String searchTitle;
private Material fillerMaterial;
private String fillerName;
private int itemsPerPage;
private boolean soundsEnabled;
private Sound openSound;
private Sound clickSound;
private Sound buySound;
private Sound sellSound;
private Sound errorSound;
private boolean loggingEnabled;
private String databaseFile;
public ConfigManager(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Loads or reloads the configuration from disk.
*/
public void reload() {
plugin.saveDefaultConfig();
plugin.reloadConfig();
config = plugin.getConfig();
loadSettings();
}
private void loadSettings() {
language = config.getString("language", "en_US");
currencySymbol = config.getString("economy.symbol", "$");
decimalPlaces = config.getInt("economy.decimal-places", 2);
sellTax = config.getDouble("economy.sell-tax", 0.0);
defaultSellMultiplier = config.getDouble("pricing.default-sell-multiplier", 0.25);
includeSpecialItems = config.getBoolean("pricing.include-special-items", false);
fullInventoryAction = config.getString("shop.full-inventory-action", "DROP");
enableSellHand = config.getBoolean("shop.enable-sell-hand", true);
enableSellInventory = config.getBoolean("shop.enable-sell-inventory", true);
maxTransactionQuantity = config.getInt("shop.max-transaction-quantity", 2304);
mainTitle = config.getString("gui.main-title", "&8Server Shop");
categoryTitle = config.getString("gui.category-title", "&8{category}");
detailTitle = config.getString("gui.detail-title", "&8Buy/Sell");
searchTitle = config.getString("gui.search-title", "&8Search: {query}");
fillerName = config.getString("gui.filler-name", " ");
itemsPerPage = config.getInt("gui.items-per-page", 28);
soundsEnabled = config.getBoolean("gui.sounds.enabled", true);
loggingEnabled = config.getBoolean("logging.enabled", true);
databaseFile = config.getString("logging.database-file", "transactions.db");
// Parse filler material safely
try {
fillerMaterial = Material.valueOf(config.getString("gui.filler-material", "GRAY_STAINED_GLASS_PANE"));
} catch (IllegalArgumentException e) {
fillerMaterial = Material.GRAY_STAINED_GLASS_PANE;
}
// Parse sounds safely
openSound = parseSound(config.getString("gui.sounds.open", "BLOCK_CHEST_OPEN"));
clickSound = parseSound(config.getString("gui.sounds.click", "UI_BUTTON_CLICK"));
buySound = parseSound(config.getString("gui.sounds.buy", "ENTITY_EXPERIENCE_ORB_PICKUP"));
sellSound = parseSound(config.getString("gui.sounds.sell", "ENTITY_EXPERIENCE_ORB_PICKUP"));
errorSound = parseSound(config.getString("gui.sounds.error", "ENTITY_VILLAGER_NO"));
}
private Sound parseSound(String name) {
try {
return Sound.valueOf(name);
} catch (IllegalArgumentException e) {
plugin.getLogger().log(Level.WARNING, "Invalid sound: " + name);
return null;
}
}
// ================================================================
// Getters
// ================================================================
public String getLanguage() { return language; }
public String getCurrencySymbol() { return currencySymbol; }
public int getDecimalPlaces() { return decimalPlaces; }
public double getSellTax() { return sellTax; }
public double getDefaultSellMultiplier() { return defaultSellMultiplier; }
public boolean isIncludeSpecialItems() { return includeSpecialItems; }
public String getFullInventoryAction() { return fullInventoryAction; }
public boolean isEnableSellHand() { return enableSellHand; }
public boolean isEnableSellInventory() { return enableSellInventory; }
public int getMaxTransactionQuantity() { return maxTransactionQuantity; }
public String getMainTitle() { return mainTitle; }
public String getCategoryTitle() { return categoryTitle; }
public String getDetailTitle() { return detailTitle; }
public String getSearchTitle() { return searchTitle; }
public Material getFillerMaterial() { return fillerMaterial; }
public String getFillerName() { return fillerName; }
public int getItemsPerPage() { return itemsPerPage; }
public boolean isSoundsEnabled() { return soundsEnabled; }
public Sound getOpenSound() { return openSound; }
public Sound getClickSound() { return clickSound; }
public Sound getBuySound() { return buySound; }
public Sound getSellSound() { return sellSound; }
public Sound getErrorSound() { return errorSound; }
public boolean isLoggingEnabled() { return loggingEnabled; }
public String getDatabaseFile() { return databaseFile; }
/**
* Whether to drop items when inventory is full (vs cancel purchase).
*
* @return true if items should be dropped
*/
public boolean isDropOnFullInventory() {
return "DROP".equalsIgnoreCase(fullInventoryAction);
}
}
@@ -1,178 +0,0 @@
package pt.henrique.servershop.config;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.util.TextUtil;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.Level;
/**
* Manages localized messages from language files.
* Supports placeholders with {key} syntax and Adventure component output.
*/
public class MessageManager {
private final ServerShop plugin;
private FileConfiguration langConfig;
private FileConfiguration fallbackConfig;
private final Map<String, String> cache = new HashMap<>();
public MessageManager(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Loads or reloads the language file based on config.
*/
public void reload() {
cache.clear();
String language = plugin.getConfigManager().getLanguage();
// Save language files from jar if they don't exist
saveLanguageFile("en_US");
saveLanguageFile("pt_PT");
// Load selected language
File langFile = new File(plugin.getDataFolder(), "lang/" + language + ".yml");
if (langFile.exists()) {
langConfig = YamlConfiguration.loadConfiguration(langFile);
} else {
plugin.getLogger().warning("Language file not found: " + language + ".yml, falling back to en_US");
langFile = new File(plugin.getDataFolder(), "lang/en_US.yml");
langConfig = YamlConfiguration.loadConfiguration(langFile);
}
// Load fallback (en_US from jar)
InputStream fallbackStream = plugin.getResource("lang/en_US.yml");
if (fallbackStream != null) {
fallbackConfig = YamlConfiguration.loadConfiguration(
new InputStreamReader(fallbackStream, StandardCharsets.UTF_8));
}
}
private void saveLanguageFile(String lang) {
File file = new File(plugin.getDataFolder(), "lang/" + lang + ".yml");
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
plugin.saveResource("lang/" + lang + ".yml", false);
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Could not save language file: " + lang + ".yml", e);
}
}
}
/**
* Gets a raw message string from the language file.
*
* @param path the config path
* @return the raw message string
*/
public String getRaw(String path) {
// Check cache first
String cached = cache.get(path);
if (cached != null) return cached;
String value = langConfig.getString(path);
if (value == null && fallbackConfig != null) {
value = fallbackConfig.getString(path);
}
if (value == null) {
value = "&cMissing message: " + path;
}
cache.put(path, value);
return value;
}
/**
* Gets a message with the plugin prefix.
*
* @param path the message path (under "messages.")
* @param replacements the placeholder replacements
* @return the formatted message string with prefix
*/
public String getPrefixed(String path, Map<String, String> replacements) {
String prefix = getRaw("prefix");
String message = getRaw("messages." + path);
return TextUtil.color(applyReplacements(prefix + message, replacements));
}
/**
* Gets a message with the plugin prefix (no placeholders).
*
* @param path the message path (under "messages.")
* @return the formatted message string with prefix
*/
public String getPrefixed(String path) {
return getPrefixed(path, Collections.emptyMap());
}
/**
* Gets a raw message with replacements applied.
*
* @param path the full config path
* @param replacements the placeholder replacements
* @return the formatted message string
*/
public String get(String path, Map<String, String> replacements) {
return TextUtil.color(applyReplacements(getRaw(path), replacements));
}
/**
* Gets a raw message.
*
* @param path the full config path
* @return the formatted message string
*/
public String get(String path) {
return TextUtil.color(getRaw(path));
}
/**
* Gets a list of strings from the language file.
*
* @param path the config path
* @return the list of strings
*/
public List<String> getList(String path) {
List<String> list = langConfig.getStringList(path);
if (list.isEmpty() && fallbackConfig != null) {
list = fallbackConfig.getStringList(path);
}
return list;
}
/**
* Gets a list of strings with replacements applied.
*
* @param path the config path
* @param replacements the placeholder replacements
* @return the processed list
*/
public List<String> getList(String path, Map<String, String> replacements) {
List<String> raw = getList(path);
List<String> result = new ArrayList<>();
for (String line : raw) {
result.add(TextUtil.color(applyReplacements(line, replacements)));
}
return result;
}
/**
* Applies placeholder replacements to a string.
*/
private String applyReplacements(String text, Map<String, String> replacements) {
if (replacements == null || replacements.isEmpty()) return text;
for (Map.Entry<String, String> entry : replacements.entrySet()) {
text = text.replace("{" + entry.getKey() + "}", entry.getValue());
}
return text;
}
}
@@ -1,139 +0,0 @@
package pt.henrique.servershop.economy;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import pt.henrique.servershop.ServerShop;
import java.util.logging.Level;
/**
* Manages Vault economy integration.
* Provides safe methods for balance checks, withdrawals, and deposits.
*/
public class EconomyManager {
private final ServerShop plugin;
private Economy economy;
public EconomyManager(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Attempts to set up the Vault economy provider.
*
* @return true if economy was successfully hooked
*/
public boolean setupEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
plugin.getLogger().severe("Vault not found! ServerShop requires Vault for economy.");
return false;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
plugin.getLogger().severe("No economy provider found! Install an economy plugin (e.g., EssentialsX, CMI).");
return false;
}
economy = rsp.getProvider();
plugin.getLogger().info("Hooked into economy: " + economy.getName());
return true;
}
/**
* Checks if the economy system is available.
*
* @return true if economy is ready
*/
public boolean isAvailable() {
return economy != null;
}
/**
* Gets a player's current balance.
*
* @param player the player
* @return the balance, or 0 if economy unavailable
*/
public double getBalance(Player player) {
if (economy == null) return 0;
try {
return economy.getBalance(player);
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error getting balance for " + player.getName(), e);
return 0;
}
}
/**
* Withdraws money from a player's account.
*
* @param player the player
* @param amount the amount to withdraw
* @return true if the withdrawal was successful
*/
public boolean withdraw(Player player, double amount) {
if (economy == null || amount <= 0) return false;
try {
EconomyResponse response = economy.withdrawPlayer(player, amount);
return response.transactionSuccess();
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error withdrawing from " + player.getName(), e);
return false;
}
}
/**
* Deposits money into a player's account.
*
* @param player the player
* @param amount the amount to deposit
* @return true if the deposit was successful
*/
public boolean deposit(Player player, double amount) {
if (economy == null || amount <= 0) return false;
try {
EconomyResponse response = economy.depositPlayer(player, amount);
return response.transactionSuccess();
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error depositing to " + player.getName(), e);
return false;
}
}
/**
* Checks if a player has enough money.
*
* @param player the player
* @param amount the amount to check
* @return true if the player has enough
*/
public boolean has(Player player, double amount) {
if (economy == null) return false;
try {
return economy.has(player, amount);
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error checking balance for " + player.getName(), e);
return false;
}
}
/**
* Formats a monetary amount using the economy provider's format.
*
* @param amount the amount
* @return the formatted string
*/
public String format(double amount) {
if (economy == null) return String.format("$%.2f", amount);
try {
return economy.format(amount);
} catch (Exception e) {
return String.format("$%.2f", amount);
}
}
}
@@ -1,219 +0,0 @@
package pt.henrique.servershop.gui;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.category.ShopCategory;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.pricing.ItemPrice;
import pt.henrique.servershop.util.ItemBuilder;
import pt.henrique.servershop.util.TextUtil;
import java.util.*;
/**
* GUI showing items within a specific category with pagination.
*/
public class CategoryGui implements ShopGui {
private final ServerShop plugin;
private final Player player;
private final ShopCategory category;
private final int page;
private final Inventory inventory;
private final List<Material> pagedItems;
// Layout: 4 rows of 7 items (slots 10-16, 19-25, 28-34, 37-43) = 28 items per page
private static final int[] ITEM_SLOTS = {
10, 11, 12, 13, 14, 15, 16,
19, 20, 21, 22, 23, 24, 25,
28, 29, 30, 31, 32, 33, 34,
37, 38, 39, 40, 41, 42, 43
};
private static final int BACK_SLOT = 45;
private static final int PREV_SLOT = 48;
private static final int INFO_SLOT = 49;
private static final int NEXT_SLOT = 50;
private static final int CLOSE_SLOT = 53;
public CategoryGui(ServerShop plugin, Player player, ShopCategory category, int page) {
this.plugin = plugin;
this.player = player;
this.category = category;
this.page = page;
// Calculate page items
List<Material> allItems = category.getItems();
int perPage = ITEM_SLOTS.length;
int start = page * perPage;
int end = Math.min(start + perPage, allItems.size());
this.pagedItems = (start < allItems.size()) ? allItems.subList(start, end) : List.of();
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
String title = msg.get("gui.titles.category", Map.of("category", category.getName()));
this.inventory = Bukkit.createInventory(this, 54, TextUtil.colorize(title));
buildGui();
}
private void buildGui() {
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
// Fill with filler
ItemStack filler = new ItemBuilder(config.getFillerMaterial())
.name(config.getFillerName()).hideFlags().build();
for (int i = 0; i < 54; i++) {
inventory.setItem(i, filler);
}
// Place items
for (int i = 0; i < pagedItems.size() && i < ITEM_SLOTS.length; i++) {
Material material = pagedItems.get(i);
ItemPrice price = plugin.getPricingService().getPrice(material);
if (price == null) continue;
String buyPriceStr = price.isBuyEnabled() ?
plugin.getEconomyManager().format(price.getBuyPrice()) : "N/A";
String sellPriceStr = price.isSellEnabled() ?
plugin.getEconomyManager().format(price.getSellPrice()) : "N/A";
String spreadStr = String.format("%.0f", price.getSpread());
Map<String, String> placeholders = Map.of(
"buy_price", buyPriceStr,
"sell_price", sellPriceStr,
"spread", spreadStr
);
String lorePath;
if (!price.isBuyEnabled() && !price.isSellEnabled()) {
lorePath = "gui.lore.both-disabled-lore";
} else if (!price.isBuyEnabled()) {
lorePath = "gui.lore.buy-disabled-lore";
} else if (!price.isSellEnabled()) {
lorePath = "gui.lore.sell-disabled-lore";
} else {
lorePath = "gui.lore.item-entry";
}
List<String> lore = msg.getList(lorePath, placeholders);
String displayName = "&f" + TextUtil.formatMaterialName(material.name());
ItemStack item = new ItemBuilder(material)
.name(displayName)
.loreStr(lore)
.hideFlags()
.build();
inventory.setItem(ITEM_SLOTS[i], item);
}
// Back button
ItemStack backButton = ItemBuilder.button(Material.ARROW,
msg.get("gui.buttons.back"),
msg.getList("gui.buttons.back-lore"));
inventory.setItem(BACK_SLOT, backButton);
// Previous page
int totalPages = getTotalPages();
if (page > 0) {
ItemStack prevButton = ItemBuilder.button(Material.PAPER,
msg.get("gui.buttons.previous-page"),
msg.getList("gui.buttons.previous-page-lore",
Map.of("page", String.valueOf(page))));
inventory.setItem(PREV_SLOT, prevButton);
}
// Info (page indicator)
ItemStack infoItem = new ItemBuilder(Material.BOOK)
.name("&bPage " + (page + 1) + " / " + Math.max(1, totalPages))
.loreStr("&7" + category.getItemCount() + " items")
.build();
inventory.setItem(INFO_SLOT, infoItem);
// Next page
if (page < totalPages - 1) {
ItemStack nextButton = ItemBuilder.button(Material.PAPER,
msg.get("gui.buttons.next-page"),
msg.getList("gui.buttons.next-page-lore",
Map.of("page", String.valueOf(page + 2))));
inventory.setItem(NEXT_SLOT, nextButton);
}
// Close button
ItemStack closeButton = ItemBuilder.button(Material.BARRIER,
msg.get("gui.buttons.close"),
msg.getList("gui.buttons.close-lore"));
inventory.setItem(CLOSE_SLOT, closeButton);
}
@Override
public void handleClick(InventoryClickEvent event, Player player) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 0 || slot >= 54) return;
ConfigManager config = plugin.getConfigManager();
GuiManager guiManager = plugin.getGuiManager();
// Check if clicked an item slot
for (int i = 0; i < ITEM_SLOTS.length && i < pagedItems.size(); i++) {
if (slot == ITEM_SLOTS[i]) {
Material material = pagedItems.get(i);
playSound(player, config.getClickSound());
guiManager.openItemDetailGui(player, material, category.getName());
return;
}
}
// Back to main menu
if (slot == BACK_SLOT) {
playSound(player, config.getClickSound());
guiManager.openMainGui(player);
return;
}
// Previous page
if (slot == PREV_SLOT && page > 0) {
playSound(player, config.getClickSound());
guiManager.openCategoryGui(player, category, page - 1);
return;
}
// Next page
if (slot == NEXT_SLOT && page < getTotalPages() - 1) {
playSound(player, config.getClickSound());
guiManager.openCategoryGui(player, category, page + 1);
return;
}
// Close
if (slot == CLOSE_SLOT) {
player.closeInventory();
}
}
private int getTotalPages() {
return Math.max(1, (int) Math.ceil((double) category.getItemCount() / ITEM_SLOTS.length));
}
private void playSound(Player player, Sound sound) {
if (plugin.getConfigManager().isSoundsEnabled() && sound != null) {
player.playSound(player.getLocation(), sound, 0.5f, 1.0f);
}
}
@Override
public Inventory getInventory() {
return inventory;
}
}
@@ -1,226 +0,0 @@
package pt.henrique.servershop.gui;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.category.ShopCategory;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.economy.EconomyManager;
import pt.henrique.servershop.pricing.ItemPrice;
import pt.henrique.servershop.service.ShopService;
import java.util.*;
/**
* Manages all GUI interactions and navigation.
* Acts as a facade for opening and coordinating shop screens.
*/
public class GuiManager implements Listener {
private final ServerShop plugin;
/** Players waiting to type a search query in chat. */
private final Set<UUID> searchPending = new HashSet<>();
public GuiManager(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Opens the main shop GUI for a player.
*
* @param player the player
*/
public void openMainGui(Player player) {
MainShopGui gui = new MainShopGui(plugin, player);
player.openInventory(gui.getInventory());
playOpenSound(player);
}
/**
* Opens a category page for a player.
*
* @param player the player
* @param category the category to display
* @param page the page number
*/
public void openCategoryGui(Player player, ShopCategory category, int page) {
CategoryGui gui = new CategoryGui(plugin, player, category, page);
player.openInventory(gui.getInventory());
}
/**
* Opens the item detail GUI for a specific material.
*
* @param player the player
* @param material the material to view
* @param fromCategory the category to return to
*/
public void openItemDetailGui(Player player, Material material, String fromCategory) {
ItemDetailGui gui = new ItemDetailGui(plugin, player, material, fromCategory);
player.openInventory(gui.getInventory());
}
/**
* Opens search results for a query.
*
* @param player the player
* @param query the search query
* @param page the page number
*/
public void openSearchResults(Player player, String query, int page) {
List<ItemPrice> results = plugin.getPricingService().search(query);
if (results.isEmpty()) {
MessageManager msg = plugin.getMessageManager();
player.sendMessage(msg.getPrefixed("search-no-results", Map.of("query", query)));
openMainGui(player);
return;
}
SearchResultsGui gui = new SearchResultsGui(plugin, player, query, page);
player.openInventory(gui.getInventory());
}
/**
* Initiates the search flow: closes inventory and asks player to type in chat.
*
* @param player the player
*/
public void openSearchInput(Player player) {
player.closeInventory();
searchPending.add(player.getUniqueId());
MessageManager msg = plugin.getMessageManager();
player.sendMessage(msg.getPrefixed("search-prompt"));
}
/**
* Handles chat messages for search input.
*/
@EventHandler(priority = EventPriority.LOW)
public void onChat(AsyncChatEvent event) {
Player player = event.getPlayer();
if (!searchPending.remove(player.getUniqueId())) return;
event.setCancelled(true);
String query = PlainTextComponentSerializer.plainText().serialize(event.message()).trim();
// Open search results on the main thread
Bukkit.getScheduler().runTask(plugin, () -> openSearchResults(player, query, 0));
}
/**
* Handles the "sell hand" action.
*/
public void handleSellHand(Player player) {
MessageManager msg = plugin.getMessageManager();
if (!player.hasPermission("servershop.sell.hand")) {
player.sendMessage(msg.getPrefixed("no-permission"));
return;
}
ItemStack held = player.getInventory().getItemInMainHand();
if (held.getType().isAir()) {
player.sendMessage(msg.getPrefixed("sell-hand-empty"));
return;
}
Material material = held.getType();
ItemPrice price = plugin.getPricingService().getPrice(material);
if (price == null || !price.isSellEnabled() || price.getSellPrice() <= 0) {
player.sendMessage(msg.getPrefixed("sell-hand-not-sellable"));
return;
}
int amount = held.getAmount();
ShopService.ShopResult result = plugin.getShopService().sell(player, material, amount);
player.sendMessage(msg.getPrefixed(result.messageKey(), result.placeholders()));
if (result.success()) {
playSound(player, plugin.getConfigManager().getSellSound());
} else {
playSound(player, plugin.getConfigManager().getErrorSound());
}
// Reopen main gui
Bukkit.getScheduler().runTaskLater(plugin, () -> openMainGui(player), 1L);
}
/**
* Handles the "sell inventory" action.
*/
public void handleSellInventory(Player player) {
MessageManager msg = plugin.getMessageManager();
EconomyManager economy = plugin.getEconomyManager();
if (!player.hasPermission("servershop.sell.inventory")) {
player.sendMessage(msg.getPrefixed("no-permission"));
return;
}
double totalEarnings = 0;
boolean soldAnything = false;
// Iterate through all inventory items
for (ItemStack item : player.getInventory().getContents()) {
if (item == null || item.getType().isAir()) continue;
Material material = item.getType();
ItemPrice price = plugin.getPricingService().getPrice(material);
if (price == null || !price.isSellEnabled() || price.getSellPrice() <= 0) continue;
int amount = item.getAmount();
double earnings = price.getSellPrice() * amount;
double tax = earnings * plugin.getConfigManager().getSellTax();
double net = earnings - tax;
// Remove the items
item.setAmount(0);
totalEarnings += net;
soldAnything = true;
// Log each material sale
plugin.getTransactionLogger().log(
player.getUniqueId(), player.getName(), material, amount, net,
pt.henrique.servershop.transaction.TransactionLogger.TransactionType.SELL
);
}
if (!soldAnything) {
player.sendMessage(msg.getPrefixed("sell-inventory-nothing"));
Bukkit.getScheduler().runTaskLater(plugin, () -> openMainGui(player), 1L);
return;
}
// Deposit total
economy.deposit(player, totalEarnings);
player.sendMessage(msg.getPrefixed("sell-inventory-success",
Map.of("price", economy.format(totalEarnings))));
playSound(player, plugin.getConfigManager().getSellSound());
// Reopen main gui
Bukkit.getScheduler().runTaskLater(plugin, () -> openMainGui(player), 1L);
}
/**
* Removes a player from the search pending set (e.g., on disconnect).
*/
public void cancelSearch(UUID uuid) {
searchPending.remove(uuid);
}
private void playOpenSound(Player player) {
playSound(player, plugin.getConfigManager().getOpenSound());
}
private void playSound(Player player, org.bukkit.Sound sound) {
if (plugin.getConfigManager().isSoundsEnabled() && sound != null) {
player.playSound(player.getLocation(), sound, 0.5f, 1.0f);
}
}
}
@@ -1,279 +0,0 @@
package pt.henrique.servershop.gui;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.economy.EconomyManager;
import pt.henrique.servershop.pricing.ItemPrice;
import pt.henrique.servershop.service.ShopService;
import pt.henrique.servershop.util.ItemBuilder;
import pt.henrique.servershop.util.TextUtil;
import java.util.*;
/**
* GUI for viewing item details with quantity selection and buy/sell buttons.
* Layout (54 slots):
* Row 1 (0-8): filler
* Row 2 (9-17): -32 -16 -8 -1 [ITEM+INFO] +1 +8 +16 +32
* Row 3 (18-26): filler with MIN/MAX
* Row 4 (27-35): filler
* Row 5 (36-44): back [BUY] filler [SELL] close
* Row 6 (45-53): filler
*/
public class ItemDetailGui implements ShopGui {
private final ServerShop plugin;
private final Player player;
private final Material material;
private final String fromCategory;
private final Inventory inventory;
private int quantity = 1;
// Slot constants
private static final int ITEM_INFO_SLOT = 13;
private static final int DEC_32_SLOT = 9;
private static final int DEC_16_SLOT = 10;
private static final int DEC_8_SLOT = 11;
private static final int DEC_1_SLOT = 12;
private static final int INC_1_SLOT = 14;
private static final int INC_8_SLOT = 15;
private static final int INC_16_SLOT = 16;
private static final int INC_32_SLOT = 17;
private static final int MIN_SLOT = 21;
private static final int MAX_SLOT = 23;
private static final int BACK_SLOT = 36;
private static final int BUY_SLOT = 39;
private static final int SELL_SLOT = 41;
private static final int CLOSE_SLOT = 44;
public ItemDetailGui(ServerShop plugin, Player player, Material material, String fromCategory) {
this.plugin = plugin;
this.player = player;
this.material = material;
this.fromCategory = fromCategory;
MessageManager msg = plugin.getMessageManager();
String title = msg.get("gui.titles.item-detail");
this.inventory = Bukkit.createInventory(this, 54, TextUtil.colorize(title));
updateGui();
}
private void updateGui() {
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
EconomyManager economy = plugin.getEconomyManager();
ItemPrice price = plugin.getPricingService().getPrice(material);
// Fill with filler
ItemStack filler = new ItemBuilder(config.getFillerMaterial())
.name(config.getFillerName()).hideFlags().build();
for (int i = 0; i < 54; i++) {
inventory.setItem(i, filler);
}
if (price == null) return;
String buyPriceStr = price.isBuyEnabled() ? economy.format(price.getBuyPrice()) : "N/A";
String sellPriceStr = price.isSellEnabled() ? economy.format(price.getSellPrice()) : "N/A";
String spreadStr = String.format("%.0f", price.getSpread());
String balanceStr = economy.format(economy.getBalance(player));
String buyTotalStr = price.isBuyEnabled() ?
economy.format(price.getBuyPrice() * quantity) : "N/A";
String sellTotalStr = price.isSellEnabled() ?
economy.format(price.getSellPrice() * quantity) : "N/A";
Map<String, String> placeholders = new HashMap<>();
placeholders.put("buy_price", buyPriceStr);
placeholders.put("sell_price", sellPriceStr);
placeholders.put("spread", spreadStr);
placeholders.put("balance", balanceStr);
placeholders.put("amount", String.valueOf(quantity));
placeholders.put("buy_total", buyTotalStr);
placeholders.put("sell_total", sellTotalStr);
// Item info display
List<String> infoLore = msg.getList("gui.lore.item-detail-info", placeholders);
String itemName = "&f" + TextUtil.formatMaterialName(material.name());
ItemStack infoItem = new ItemBuilder(material)
.name(itemName)
.loreStr(infoLore)
.amount(Math.min(quantity, 64))
.hideFlags()
.build();
inventory.setItem(ITEM_INFO_SLOT, infoItem);
// Quantity adjustment buttons
inventory.setItem(DEC_32_SLOT, createQuantityButton(Material.RED_STAINED_GLASS_PANE,
msg.get("gui.buttons.decrease-32")));
inventory.setItem(DEC_16_SLOT, createQuantityButton(Material.RED_STAINED_GLASS_PANE,
msg.get("gui.buttons.decrease-16")));
inventory.setItem(DEC_8_SLOT, createQuantityButton(Material.RED_STAINED_GLASS_PANE,
msg.get("gui.buttons.decrease-8")));
inventory.setItem(DEC_1_SLOT, createQuantityButton(Material.RED_STAINED_GLASS_PANE,
msg.get("gui.buttons.decrease-1")));
inventory.setItem(INC_1_SLOT, createQuantityButton(Material.LIME_STAINED_GLASS_PANE,
msg.get("gui.buttons.increase-1")));
inventory.setItem(INC_8_SLOT, createQuantityButton(Material.LIME_STAINED_GLASS_PANE,
msg.get("gui.buttons.increase-8")));
inventory.setItem(INC_16_SLOT, createQuantityButton(Material.LIME_STAINED_GLASS_PANE,
msg.get("gui.buttons.increase-16")));
inventory.setItem(INC_32_SLOT, createQuantityButton(Material.LIME_STAINED_GLASS_PANE,
msg.get("gui.buttons.increase-32")));
// MIN / MAX buttons
inventory.setItem(MIN_SLOT, createQuantityButton(Material.YELLOW_STAINED_GLASS_PANE,
msg.get("gui.buttons.min-quantity")));
inventory.setItem(MAX_SLOT, createQuantityButton(Material.YELLOW_STAINED_GLASS_PANE,
msg.get("gui.buttons.max-quantity")));
// Buy button
if (price.isBuyEnabled() && price.getBuyPrice() > 0) {
Map<String, String> buyPlaceholders = Map.of(
"amount", String.valueOf(quantity),
"price", buyTotalStr
);
ItemStack buyButton = ItemBuilder.button(Material.EMERALD,
msg.get("gui.buttons.buy"),
msg.getList("gui.buttons.buy-lore", buyPlaceholders));
inventory.setItem(BUY_SLOT, buyButton);
}
// Sell button
if (price.isSellEnabled() && price.getSellPrice() > 0) {
Map<String, String> sellPlaceholders = Map.of(
"amount", String.valueOf(quantity),
"price", sellTotalStr
);
ItemStack sellButton = ItemBuilder.button(Material.GOLD_INGOT,
msg.get("gui.buttons.sell"),
msg.getList("gui.buttons.sell-lore", sellPlaceholders));
inventory.setItem(SELL_SLOT, sellButton);
}
// Back button
ItemStack backButton = ItemBuilder.button(Material.ARROW,
msg.get("gui.buttons.back"),
msg.getList("gui.buttons.back-lore"));
inventory.setItem(BACK_SLOT, backButton);
// Close button
ItemStack closeButton = ItemBuilder.button(Material.BARRIER,
msg.get("gui.buttons.close"),
msg.getList("gui.buttons.close-lore"));
inventory.setItem(CLOSE_SLOT, closeButton);
}
private ItemStack createQuantityButton(Material mat, String name) {
return new ItemBuilder(mat).name(name).hideFlags().build();
}
@Override
public void handleClick(InventoryClickEvent event, Player player) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 0 || slot >= 54) return;
ConfigManager config = plugin.getConfigManager();
int maxQty = config.getMaxTransactionQuantity();
switch (slot) {
case DEC_32_SLOT -> adjustQuantity(-32, maxQty);
case DEC_16_SLOT -> adjustQuantity(-16, maxQty);
case DEC_8_SLOT -> adjustQuantity(-8, maxQty);
case DEC_1_SLOT -> adjustQuantity(-1, maxQty);
case INC_1_SLOT -> adjustQuantity(1, maxQty);
case INC_8_SLOT -> adjustQuantity(8, maxQty);
case INC_16_SLOT -> adjustQuantity(16, maxQty);
case INC_32_SLOT -> adjustQuantity(32, maxQty);
case MIN_SLOT -> { quantity = 1; updateGui(); }
case MAX_SLOT -> { quantity = maxQty; updateGui(); }
case BUY_SLOT -> handleBuy(player);
case SELL_SLOT -> handleSell(player);
case BACK_SLOT -> {
playSound(player, config.getClickSound());
if (fromCategory != null) {
var cat = plugin.getCategoryRegistry().getCategory(fromCategory);
if (cat != null) {
plugin.getGuiManager().openCategoryGui(player, cat, 0);
return;
}
}
plugin.getGuiManager().openMainGui(player);
}
case CLOSE_SLOT -> player.closeInventory();
default -> {
// Ignore other slots
}
}
}
private void adjustQuantity(int delta, int max) {
quantity = Math.max(1, Math.min(quantity + delta, max));
updateGui();
}
private void handleBuy(Player player) {
ItemPrice price = plugin.getPricingService().getPrice(material);
if (price == null || !price.isBuyEnabled()) {
playSound(player, plugin.getConfigManager().getErrorSound());
return;
}
ShopService.ShopResult result = plugin.getShopService().buy(player, material, quantity);
MessageManager msg = plugin.getMessageManager();
player.sendMessage(msg.getPrefixed(result.messageKey(), result.placeholders()));
if (result.success()) {
playSound(player, plugin.getConfigManager().getBuySound());
} else {
playSound(player, plugin.getConfigManager().getErrorSound());
}
// Refresh the GUI to show updated balance
updateGui();
}
private void handleSell(Player player) {
ItemPrice price = plugin.getPricingService().getPrice(material);
if (price == null || !price.isSellEnabled()) {
playSound(player, plugin.getConfigManager().getErrorSound());
return;
}
ShopService.ShopResult result = plugin.getShopService().sell(player, material, quantity);
MessageManager msg = plugin.getMessageManager();
player.sendMessage(msg.getPrefixed(result.messageKey(), result.placeholders()));
if (result.success()) {
playSound(player, plugin.getConfigManager().getSellSound());
} else {
playSound(player, plugin.getConfigManager().getErrorSound());
}
// Refresh the GUI to show updated balance/inventory
updateGui();
}
private void playSound(Player player, Sound sound) {
if (plugin.getConfigManager().isSoundsEnabled() && sound != null) {
player.playSound(player.getLocation(), sound, 0.5f, 1.0f);
}
}
@Override
public Inventory getInventory() {
return inventory;
}
}
@@ -1,169 +0,0 @@
package pt.henrique.servershop.gui;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.category.ShopCategory;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.util.ItemBuilder;
import pt.henrique.servershop.util.TextUtil;
import java.util.*;
/**
* The main shop GUI showing category buttons, search, and sell options.
*/
public class MainShopGui implements ShopGui {
private final ServerShop plugin;
private final Player player;
private final Inventory inventory;
// Slot assignments
private static final int SEARCH_SLOT = 49;
private static final int SELL_HAND_SLOT = 46;
private static final int SELL_INVENTORY_SLOT = 47;
private static final int CLOSE_SLOT = 53;
public MainShopGui(ServerShop plugin, Player player) {
this.plugin = plugin;
this.player = player;
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
String title = msg.get("gui.titles.main-menu");
this.inventory = Bukkit.createInventory(this, 54, TextUtil.colorize(title));
buildGui();
}
private void buildGui() {
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
// Fill border with filler
ItemStack filler = new ItemBuilder(config.getFillerMaterial())
.name(config.getFillerName()).hideFlags().build();
for (int i = 0; i < 54; i++) {
inventory.setItem(i, filler);
}
// Place category buttons in the center area (slots 10-16, 19-25, 28-34)
int[] categorySlots = {10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34};
Collection<ShopCategory> categories = plugin.getCategoryRegistry().getCategories();
int index = 0;
for (ShopCategory category : categories) {
if (index >= categorySlots.length) break;
Map<String, String> placeholders = Map.of("count", String.valueOf(category.getItemCount()));
List<String> lore = msg.getList("gui.category.lore", placeholders);
ItemStack icon = new ItemBuilder(category.getIcon())
.name("&a" + category.getName())
.loreStr(lore)
.hideFlags()
.build();
inventory.setItem(categorySlots[index], icon);
index++;
}
// Search button
ItemStack searchButton = ItemBuilder.button(Material.COMPASS,
msg.get("gui.buttons.search"),
msg.getList("gui.buttons.search-lore"));
inventory.setItem(SEARCH_SLOT, searchButton);
// Sell hand button
if (config.isEnableSellHand()) {
ItemStack sellHand = ItemBuilder.button(Material.GOLDEN_SWORD,
msg.get("gui.buttons.sell-hand"),
msg.getList("gui.buttons.sell-hand-lore"));
inventory.setItem(SELL_HAND_SLOT, sellHand);
}
// Sell inventory button
if (config.isEnableSellInventory()) {
ItemStack sellInv = ItemBuilder.button(Material.CHEST,
msg.get("gui.buttons.sell-inventory"),
msg.getList("gui.buttons.sell-inventory-lore"));
inventory.setItem(SELL_INVENTORY_SLOT, sellInv);
}
// Close button
ItemStack closeButton = ItemBuilder.button(Material.BARRIER,
msg.get("gui.buttons.close"),
msg.getList("gui.buttons.close-lore"));
inventory.setItem(CLOSE_SLOT, closeButton);
}
@Override
public void handleClick(InventoryClickEvent event, Player player) {
event.setCancelled(true);
int slot = event.getRawSlot();
// Only handle clicks in the top inventory
if (slot < 0 || slot >= 54) return;
ConfigManager config = plugin.getConfigManager();
GuiManager guiManager = plugin.getGuiManager();
// Category slots
int[] categorySlots = {10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34};
List<ShopCategory> categories = new ArrayList<>(plugin.getCategoryRegistry().getCategories());
for (int i = 0; i < categorySlots.length && i < categories.size(); i++) {
if (slot == categorySlots[i]) {
playSound(player, config.getClickSound());
guiManager.openCategoryGui(player, categories.get(i), 0);
return;
}
}
// Search button
if (slot == SEARCH_SLOT) {
playSound(player, config.getClickSound());
guiManager.openSearchInput(player);
return;
}
// Sell hand
if (slot == SELL_HAND_SLOT && config.isEnableSellHand()) {
playSound(player, config.getClickSound());
guiManager.handleSellHand(player);
return;
}
// Sell inventory
if (slot == SELL_INVENTORY_SLOT && config.isEnableSellInventory()) {
playSound(player, config.getClickSound());
guiManager.handleSellInventory(player);
return;
}
// Close
if (slot == CLOSE_SLOT) {
player.closeInventory();
return;
}
}
private void playSound(Player player, Sound sound) {
if (plugin.getConfigManager().isSoundsEnabled() && sound != null) {
player.playSound(player.getLocation(), sound, 0.5f, 1.0f);
}
}
@Override
public Inventory getInventory() {
return inventory;
}
}
@@ -1,193 +0,0 @@
package pt.henrique.servershop.gui;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.config.MessageManager;
import pt.henrique.servershop.pricing.ItemPrice;
import pt.henrique.servershop.util.ItemBuilder;
import pt.henrique.servershop.util.TextUtil;
import java.util.*;
/**
* GUI showing search results with pagination.
*/
public class SearchResultsGui implements ShopGui {
private final ServerShop plugin;
private final Player player;
private final String query;
private final int page;
private final Inventory inventory;
private final List<ItemPrice> pagedItems;
private final List<ItemPrice> allResults;
private static final int[] ITEM_SLOTS = {
10, 11, 12, 13, 14, 15, 16,
19, 20, 21, 22, 23, 24, 25,
28, 29, 30, 31, 32, 33, 34,
37, 38, 39, 40, 41, 42, 43
};
private static final int BACK_SLOT = 45;
private static final int PREV_SLOT = 48;
private static final int INFO_SLOT = 49;
private static final int NEXT_SLOT = 50;
private static final int CLOSE_SLOT = 53;
public SearchResultsGui(ServerShop plugin, Player player, String query, int page) {
this.plugin = plugin;
this.player = player;
this.query = query;
this.page = page;
this.allResults = plugin.getPricingService().search(query);
int perPage = ITEM_SLOTS.length;
int start = page * perPage;
int end = Math.min(start + perPage, allResults.size());
this.pagedItems = (start < allResults.size()) ? allResults.subList(start, end) : List.of();
MessageManager msg = plugin.getMessageManager();
String title = msg.get("gui.titles.search-results", Map.of("query", query));
this.inventory = Bukkit.createInventory(this, 54, TextUtil.colorize(title));
buildGui();
}
private void buildGui() {
ConfigManager config = plugin.getConfigManager();
MessageManager msg = plugin.getMessageManager();
// Fill with filler
ItemStack filler = new ItemBuilder(config.getFillerMaterial())
.name(config.getFillerName()).hideFlags().build();
for (int i = 0; i < 54; i++) {
inventory.setItem(i, filler);
}
// Place items
for (int i = 0; i < pagedItems.size() && i < ITEM_SLOTS.length; i++) {
ItemPrice price = pagedItems.get(i);
String buyPriceStr = price.isBuyEnabled() ?
plugin.getEconomyManager().format(price.getBuyPrice()) : "N/A";
String sellPriceStr = price.isSellEnabled() ?
plugin.getEconomyManager().format(price.getSellPrice()) : "N/A";
String spreadStr = String.format("%.0f", price.getSpread());
Map<String, String> placeholders = Map.of(
"buy_price", buyPriceStr,
"sell_price", sellPriceStr,
"spread", spreadStr
);
List<String> lore = msg.getList("gui.lore.item-entry", placeholders);
String displayName = "&f" + TextUtil.formatMaterialName(price.getMaterial().name());
ItemStack item = new ItemBuilder(price.getMaterial())
.name(displayName)
.loreStr(lore)
.hideFlags()
.build();
inventory.setItem(ITEM_SLOTS[i], item);
}
// Navigation buttons
ItemStack backButton = ItemBuilder.button(Material.ARROW,
msg.get("gui.buttons.back"),
msg.getList("gui.buttons.back-lore"));
inventory.setItem(BACK_SLOT, backButton);
int totalPages = getTotalPages();
if (page > 0) {
ItemStack prevButton = ItemBuilder.button(Material.PAPER,
msg.get("gui.buttons.previous-page"),
msg.getList("gui.buttons.previous-page-lore",
Map.of("page", String.valueOf(page))));
inventory.setItem(PREV_SLOT, prevButton);
}
ItemStack infoItem = new ItemBuilder(Material.BOOK)
.name("&bPage " + (page + 1) + " / " + Math.max(1, totalPages))
.loreStr("&7" + allResults.size() + " results for '" + query + "'")
.build();
inventory.setItem(INFO_SLOT, infoItem);
if (page < totalPages - 1) {
ItemStack nextButton = ItemBuilder.button(Material.PAPER,
msg.get("gui.buttons.next-page"),
msg.getList("gui.buttons.next-page-lore",
Map.of("page", String.valueOf(page + 2))));
inventory.setItem(NEXT_SLOT, nextButton);
}
ItemStack closeButton = ItemBuilder.button(Material.BARRIER,
msg.get("gui.buttons.close"),
msg.getList("gui.buttons.close-lore"));
inventory.setItem(CLOSE_SLOT, closeButton);
}
@Override
public void handleClick(InventoryClickEvent event, Player player) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot < 0 || slot >= 54) return;
ConfigManager config = plugin.getConfigManager();
GuiManager guiManager = plugin.getGuiManager();
// Check item slots
for (int i = 0; i < ITEM_SLOTS.length && i < pagedItems.size(); i++) {
if (slot == ITEM_SLOTS[i]) {
ItemPrice price = pagedItems.get(i);
playSound(player, config.getClickSound());
guiManager.openItemDetailGui(player, price.getMaterial(), price.getCategory());
return;
}
}
if (slot == BACK_SLOT) {
playSound(player, config.getClickSound());
guiManager.openMainGui(player);
return;
}
if (slot == PREV_SLOT && page > 0) {
playSound(player, config.getClickSound());
guiManager.openSearchResults(player, query, page - 1);
return;
}
if (slot == NEXT_SLOT && page < getTotalPages() - 1) {
playSound(player, config.getClickSound());
guiManager.openSearchResults(player, query, page + 1);
return;
}
if (slot == CLOSE_SLOT) {
player.closeInventory();
}
}
private int getTotalPages() {
return Math.max(1, (int) Math.ceil((double) allResults.size() / ITEM_SLOTS.length));
}
private void playSound(Player player, Sound sound) {
if (plugin.getConfigManager().isSoundsEnabled() && sound != null) {
player.playSound(player.getLocation(), sound, 0.5f, 1.0f);
}
}
@Override
public Inventory getInventory() {
return inventory;
}
}
@@ -1,39 +0,0 @@
package pt.henrique.servershop.gui;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
/**
* Interface for all shop GUI screens.
* Implementing classes serve as InventoryHolder for click event delegation.
*/
public interface ShopGui extends InventoryHolder {
/**
* Handles a click event in this GUI.
*
* @param event the click event
* @param player the player who clicked
*/
void handleClick(InventoryClickEvent event, Player player);
/**
* Called when the GUI is closed.
*
* @param player the player who closed the GUI
*/
default void handleClose(Player player) {
// Default: no action
}
/**
* Whether this GUI allows item movement (shift-click from player inventory, etc.).
*
* @return true if item movement is allowed
*/
default boolean allowsItemMovement() {
return false;
}
}
@@ -1,124 +0,0 @@
package pt.henrique.servershop.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.gui.ShopGui;
/**
* Listens for inventory events and delegates to ShopGui implementations.
* Provides comprehensive anti-exploit protections against item duplication.
*/
public class GuiListener implements Listener {
private final ServerShop plugin;
public GuiListener(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Handles all click events within shop GUIs.
* Cancels illegal interactions and delegates valid clicks to the GUI handler.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player player)) return;
Inventory topInventory = event.getView().getTopInventory();
if (!(topInventory.getHolder() instanceof ShopGui gui)) return;
// Block all item movement in our GUIs unless explicitly allowed
if (!gui.allowsItemMovement()) {
// Block shift-click from bottom inventory
if (event.getClick().isShiftClick() && event.getRawSlot() >= topInventory.getSize()) {
event.setCancelled(true);
return;
}
// Block number key swaps
if (event.getClick() == ClickType.NUMBER_KEY) {
event.setCancelled(true);
return;
}
// Block swap/offhand
if (event.getClick() == ClickType.SWAP_OFFHAND) {
event.setCancelled(true);
return;
}
// Block double-click (collects items from all inventories)
if (event.getClick() == ClickType.DOUBLE_CLICK) {
event.setCancelled(true);
return;
}
}
// Delegate to the GUI handler for clicks in the top inventory
if (event.getRawSlot() < topInventory.getSize()) {
gui.handleClick(event, player);
} else {
// Clicks in the player's own inventory are cancelled for safety
event.setCancelled(true);
}
}
/**
* Blocks all drag events in shop GUIs.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onInventoryDrag(InventoryDragEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Inventory topInventory = event.getView().getTopInventory();
if (!(topInventory.getHolder() instanceof ShopGui gui)) return;
if (!gui.allowsItemMovement()) {
// Cancel if any dragged slot is in the top inventory
for (int slot : event.getRawSlots()) {
if (slot < topInventory.getSize()) {
event.setCancelled(true);
return;
}
}
}
}
/**
* Blocks item movement between inventories via hoppers etc.
*/
@EventHandler(priority = EventPriority.HIGH)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
if (event.getDestination().getHolder() instanceof ShopGui ||
event.getSource().getHolder() instanceof ShopGui) {
event.setCancelled(true);
}
}
/**
* Handles GUI close events.
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player player)) return;
Inventory topInventory = event.getView().getTopInventory();
if (topInventory.getHolder() instanceof ShopGui gui) {
gui.handleClose(player);
}
}
/**
* Cleans up when a player disconnects.
*/
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
plugin.getGuiManager().cancelSearch(event.getPlayer().getUniqueId());
}
}
@@ -1,64 +0,0 @@
package pt.henrique.servershop.pricing;
import org.bukkit.Material;
/**
* Represents the price configuration for a single item.
* Contains buy price, sell price, and enable/disable flags.
*/
public class ItemPrice {
private final Material material;
private final double buyPrice;
private final double sellPrice;
private final boolean buyEnabled;
private final boolean sellEnabled;
private final String category;
/**
* Constructs an ItemPrice.
*
* @param material the material
* @param buyPrice the price to buy from the server
* @param sellPrice the price to sell to the server
* @param buyEnabled whether buying is enabled
* @param sellEnabled whether selling is enabled
* @param category the category this item belongs to
*/
public ItemPrice(Material material, double buyPrice, double sellPrice,
boolean buyEnabled, boolean sellEnabled, String category) {
this.material = material;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.buyEnabled = buyEnabled;
this.sellEnabled = sellEnabled;
this.category = category;
}
public Material getMaterial() { return material; }
public double getBuyPrice() { return buyPrice; }
public double getSellPrice() { return sellPrice; }
public boolean isBuyEnabled() { return buyEnabled; }
public boolean isSellEnabled() { return sellEnabled; }
public String getCategory() { return category; }
/**
* Calculates the spread percentage between buy and sell prices.
* Spread = ((buyPrice - sellPrice) / buyPrice) * 100
*
* @return the spread percentage, or 0 if buy price is 0
*/
public double getSpread() {
if (buyPrice <= 0) return 0;
return ((buyPrice - sellPrice) / buyPrice) * 100.0;
}
/**
* Whether this item has any valid transaction available (buy or sell).
*
* @return true if at least one transaction type is enabled with a positive price
*/
public boolean isAvailable() {
return (buyEnabled && buyPrice > 0) || (sellEnabled && sellPrice > 0);
}
}
@@ -1,195 +0,0 @@
package pt.henrique.servershop.pricing;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.category.CategoryRegistry;
import pt.henrique.servershop.category.ShopCategory;
import java.io.File;
import java.util.*;
import java.util.logging.Level;
/**
* Service responsible for calculating and providing item prices.
* Loads base prices from prices.yml and applies category multipliers and per-item overrides.
*/
public class PricingService {
private final ServerShop plugin;
private final Map<Material, ItemPrice> prices = new HashMap<>();
public PricingService(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Loads all prices from prices.yml, applying multipliers and overrides.
*/
public void reload() {
prices.clear();
File pricesFile = new File(plugin.getDataFolder(), "prices.yml");
if (!pricesFile.exists()) {
plugin.saveResource("prices.yml", false);
}
FileConfiguration pricesConfig = YamlConfiguration.loadConfiguration(pricesFile);
double globalMultiplier = plugin.getConfigManager().getDefaultSellMultiplier();
// Load overrides section
ConfigurationSection overridesSection = pricesConfig.getConfigurationSection("overrides");
Map<Material, OverrideData> overrides = loadOverrides(overridesSection);
// Load prices from categories
CategoryRegistry registry = plugin.getCategoryRegistry();
ConfigurationSection categoriesSection = pricesConfig.getConfigurationSection("categories");
if (categoriesSection == null) return;
for (String categoryName : categoriesSection.getKeys(false)) {
ConfigurationSection catSection = categoriesSection.getConfigurationSection(categoryName);
if (catSection == null) continue;
ShopCategory category = registry.getCategory(categoryName);
if (category == null) continue;
double catMultiplier = catSection.getDouble("sell-multiplier", globalMultiplier);
boolean catBuyEnabled = catSection.getBoolean("buy-enabled", true);
boolean catSellEnabled = catSection.getBoolean("sell-enabled", true);
ConfigurationSection itemsSection = catSection.getConfigurationSection("items");
if (itemsSection == null) continue;
for (String materialName : itemsSection.getKeys(false)) {
try {
Material material = Material.valueOf(materialName);
if (material.isAir()) continue;
double buyPrice = itemsSection.getDouble(materialName);
double sellPrice = buyPrice * catMultiplier;
boolean buyEnabled = catBuyEnabled;
boolean sellEnabled = catSellEnabled;
// Apply per-item overrides
OverrideData override = overrides.get(material);
if (override != null) {
if (override.buyPrice >= 0) buyPrice = override.buyPrice;
if (override.sellPrice >= 0) sellPrice = override.sellPrice;
if (override.buyEnabled != null) buyEnabled = override.buyEnabled;
if (override.sellEnabled != null) sellEnabled = override.sellEnabled;
}
// Round prices to configured decimal places
int dp = plugin.getConfigManager().getDecimalPlaces();
double factor = Math.pow(10, dp);
buyPrice = Math.round(buyPrice * factor) / factor;
sellPrice = Math.round(sellPrice * factor) / factor;
prices.put(material, new ItemPrice(material, buyPrice, sellPrice,
buyEnabled, sellEnabled, categoryName));
} catch (IllegalArgumentException e) {
plugin.getLogger().log(Level.WARNING,
"Invalid material in pricing: " + materialName);
}
}
}
plugin.getLogger().info("Loaded pricing for " + prices.size() + " items.");
}
/**
* Gets the price data for a material.
*
* @param material the material
* @return the item price, or null if not priced
*/
public ItemPrice getPrice(Material material) {
return prices.get(material);
}
/**
* Gets all priced items.
*
* @return unmodifiable map of all prices
*/
public Map<Material, ItemPrice> getAllPrices() {
return Collections.unmodifiableMap(prices);
}
/**
* Checks if a material has pricing configured.
*
* @param material the material
* @return true if pricing exists
*/
public boolean hasPrice(Material material) {
return prices.containsKey(material);
}
/**
* Searches for items matching a query string.
*
* @param query the search query
* @return list of matching item prices
*/
public List<ItemPrice> search(String query) {
String lower = query.toLowerCase();
List<ItemPrice> results = new ArrayList<>();
for (ItemPrice price : prices.values()) {
String name = price.getMaterial().name().toLowerCase().replace("_", " ");
if (name.contains(lower)) {
results.add(price);
}
}
// Sort by relevance (exact match first, then alphabetical)
results.sort((a, b) -> {
String nameA = a.getMaterial().name().toLowerCase();
String nameB = b.getMaterial().name().toLowerCase();
boolean exactA = nameA.replace("_", " ").equals(lower);
boolean exactB = nameB.replace("_", " ").equals(lower);
if (exactA && !exactB) return -1;
if (!exactA && exactB) return 1;
return nameA.compareTo(nameB);
});
return results;
}
// ================================================================
// Override loading helper
// ================================================================
private Map<Material, OverrideData> loadOverrides(ConfigurationSection section) {
Map<Material, OverrideData> overrides = new HashMap<>();
if (section == null) return overrides;
for (String materialName : section.getKeys(false)) {
try {
Material material = Material.valueOf(materialName);
ConfigurationSection itemSection = section.getConfigurationSection(materialName);
if (itemSection == null) continue;
double buyPrice = itemSection.contains("buy") ? itemSection.getDouble("buy") : -1;
double sellPrice = itemSection.contains("sell") ? itemSection.getDouble("sell") : -1;
Boolean buyEnabled = itemSection.contains("buy-enabled") ?
itemSection.getBoolean("buy-enabled") : null;
Boolean sellEnabled = itemSection.contains("sell-enabled") ?
itemSection.getBoolean("sell-enabled") : null;
overrides.put(material, new OverrideData(buyPrice, sellPrice, buyEnabled, sellEnabled));
} catch (IllegalArgumentException e) {
plugin.getLogger().log(Level.WARNING, "Invalid material in overrides: " + materialName);
}
}
return overrides;
}
/**
* Internal data class for per-item overrides.
*/
private record OverrideData(double buyPrice, double sellPrice,
Boolean buyEnabled, Boolean sellEnabled) {}
}
@@ -1,277 +0,0 @@
package pt.henrique.servershop.service;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import pt.henrique.servershop.ServerShop;
import pt.henrique.servershop.config.ConfigManager;
import pt.henrique.servershop.economy.EconomyManager;
import pt.henrique.servershop.pricing.ItemPrice;
import pt.henrique.servershop.pricing.PricingService;
import pt.henrique.servershop.transaction.TransactionLogger;
import pt.henrique.servershop.util.TextUtil;
import java.util.HashMap;
import java.util.Map;
/**
* Core service handling buy and sell operations.
* All validation and economy interactions go through this service.
*/
public class ShopService {
private final ServerShop plugin;
public ShopService(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Result of a shop operation (buy/sell).
*/
public record ShopResult(boolean success, String messageKey, Map<String, String> placeholders) {
public static ShopResult success(String messageKey, Map<String, String> placeholders) {
return new ShopResult(true, messageKey, placeholders);
}
public static ShopResult failure(String messageKey, Map<String, String> placeholders) {
return new ShopResult(false, messageKey, placeholders);
}
public static ShopResult failure(String messageKey) {
return new ShopResult(false, messageKey, Map.of());
}
}
/**
* Attempts to process a buy transaction for a player.
*
* @param player the buyer
* @param material the material to buy
* @param amount the quantity to buy
* @return the result of the operation
*/
public ShopResult buy(Player player, Material material, int amount) {
PricingService pricing = plugin.getPricingService();
EconomyManager economy = plugin.getEconomyManager();
ConfigManager config = plugin.getConfigManager();
// Validate economy
if (!economy.isAvailable()) {
return ShopResult.failure("economy-unavailable");
}
// Validate item price
ItemPrice itemPrice = pricing.getPrice(material);
if (itemPrice == null || !itemPrice.isBuyEnabled()) {
return ShopResult.failure("buy-disabled");
}
if (itemPrice.getBuyPrice() <= 0) {
return ShopResult.failure("buy-zero-price");
}
// Validate amount
amount = Math.max(1, Math.min(amount, config.getMaxTransactionQuantity()));
double totalCost = itemPrice.getBuyPrice() * amount;
String itemName = TextUtil.formatMaterialName(material.name());
// Re-check balance at transaction time (anti-exploit)
if (!economy.has(player, totalCost)) {
Map<String, String> placeholders = Map.of(
"price", economy.format(totalCost),
"balance", economy.format(economy.getBalance(player))
);
return ShopResult.failure("buy-insufficient-funds", placeholders);
}
// Check inventory space
int freeSpace = calculateFreeSpace(player, material);
if (freeSpace <= 0 && !config.isDropOnFullInventory()) {
return ShopResult.failure("buy-inventory-full-cancel");
}
// Withdraw money
if (!economy.withdraw(player, totalCost)) {
Map<String, String> placeholders = Map.of(
"price", economy.format(totalCost),
"balance", economy.format(economy.getBalance(player))
);
return ShopResult.failure("buy-insufficient-funds", placeholders);
}
// Give items
boolean dropped = giveItems(player, material, amount);
// Log transaction
plugin.getTransactionLogger().log(
player.getUniqueId(), player.getName(), material, amount, totalCost,
TransactionLogger.TransactionType.BUY
);
Map<String, String> placeholders = new HashMap<>();
placeholders.put("amount", String.valueOf(amount));
placeholders.put("item", itemName);
placeholders.put("price", economy.format(totalCost));
if (dropped) {
// Send additional message about dropped items
player.sendMessage(plugin.getMessageManager().getPrefixed("buy-inventory-full-drop"));
}
return ShopResult.success("buy-success", placeholders);
}
/**
* Attempts to process a sell transaction for a player.
*
* @param player the seller
* @param material the material to sell
* @param amount the quantity to sell
* @return the result of the operation
*/
public ShopResult sell(Player player, Material material, int amount) {
PricingService pricing = plugin.getPricingService();
EconomyManager economy = plugin.getEconomyManager();
ConfigManager config = plugin.getConfigManager();
// Validate economy
if (!economy.isAvailable()) {
return ShopResult.failure("economy-unavailable");
}
// Validate item price
ItemPrice itemPrice = pricing.getPrice(material);
if (itemPrice == null || !itemPrice.isSellEnabled()) {
return ShopResult.failure("sell-disabled");
}
if (itemPrice.getSellPrice() <= 0) {
return ShopResult.failure("sell-zero-price");
}
// Validate amount
amount = Math.max(1, Math.min(amount, config.getMaxTransactionQuantity()));
// Re-check inventory at transaction time (anti-exploit)
int playerHas = countMaterial(player, material);
if (playerHas < amount) {
String itemName = TextUtil.formatMaterialName(material.name());
Map<String, String> placeholders = Map.of(
"amount", String.valueOf(amount),
"item", itemName
);
return ShopResult.failure("sell-insufficient-items", placeholders);
}
double totalEarnings = itemPrice.getSellPrice() * amount;
double tax = totalEarnings * config.getSellTax();
double netEarnings = totalEarnings - tax;
String itemName = TextUtil.formatMaterialName(material.name());
// Remove items from inventory
removeItems(player, material, amount);
// Deposit money
if (!economy.deposit(player, netEarnings)) {
// If deposit fails, give items back
giveItems(player, material, amount);
return ShopResult.failure("economy-unavailable");
}
// Log transaction
plugin.getTransactionLogger().log(
player.getUniqueId(), player.getName(), material, amount, netEarnings,
TransactionLogger.TransactionType.SELL
);
Map<String, String> placeholders = new HashMap<>();
placeholders.put("amount", String.valueOf(amount));
placeholders.put("item", itemName);
placeholders.put("price", economy.format(netEarnings));
placeholders.put("tax", economy.format(tax));
String messageKey = tax > 0 ? "sell-success-tax" : "sell-success";
return ShopResult.success(messageKey, placeholders);
}
/**
* Counts how many of a specific material a player has in their inventory.
*
* @param player the player
* @param material the material to count
* @return the total count
*/
public int countMaterial(Player player, Material material) {
int count = 0;
for (ItemStack item : player.getInventory().getContents()) {
if (item != null && item.getType() == material) {
count += item.getAmount();
}
}
return count;
}
/**
* Calculates how many of a material can fit in a player's inventory.
*/
private int calculateFreeSpace(Player player, Material material) {
int maxStack = material.getMaxStackSize();
int free = 0;
for (ItemStack item : player.getInventory().getStorageContents()) {
if (item == null || item.getType().isAir()) {
free += maxStack;
} else if (item.getType() == material) {
free += maxStack - item.getAmount();
}
}
return free;
}
/**
* Gives items to a player, dropping overflow at their feet.
*
* @return true if some items had to be dropped
*/
private boolean giveItems(Player player, Material material, int amount) {
boolean dropped = false;
int maxStack = material.getMaxStackSize();
while (amount > 0) {
int stackSize = Math.min(amount, maxStack);
ItemStack stack = new ItemStack(material, stackSize);
HashMap<Integer, ItemStack> overflow = player.getInventory().addItem(stack);
if (!overflow.isEmpty()) {
if (plugin.getConfigManager().isDropOnFullInventory()) {
for (ItemStack leftover : overflow.values()) {
player.getWorld().dropItemNaturally(player.getLocation(), leftover);
}
dropped = true;
}
}
amount -= stackSize;
}
return dropped;
}
/**
* Removes a specific amount of a material from a player's inventory.
*/
private void removeItems(Player player, Material material, int amount) {
ItemStack[] contents = player.getInventory().getContents();
for (int i = 0; i < contents.length && amount > 0; i++) {
ItemStack item = contents[i];
if (item != null && item.getType() == material) {
int take = Math.min(item.getAmount(), amount);
if (take >= item.getAmount()) {
player.getInventory().setItem(i, null);
} else {
item.setAmount(item.getAmount() - take);
}
amount -= take;
}
}
}
}
@@ -1,117 +0,0 @@
package pt.henrique.servershop.transaction;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import pt.henrique.servershop.ServerShop;
import java.io.File;
import java.sql.*;
import java.util.UUID;
import java.util.logging.Level;
/**
* Logs buy/sell transactions to a SQLite database.
* All database operations run asynchronously to avoid blocking the main thread.
*/
public class TransactionLogger {
private final ServerShop plugin;
private Connection connection;
private boolean enabled;
public TransactionLogger(ServerShop plugin) {
this.plugin = plugin;
}
/**
* Initializes the database connection and creates tables if needed.
*/
public void initialize() {
enabled = plugin.getConfigManager().isLoggingEnabled();
if (!enabled) {
plugin.getLogger().info("Transaction logging is disabled.");
return;
}
try {
String dbFile = plugin.getConfigManager().getDatabaseFile();
File dbPath = new File(plugin.getDataFolder(), dbFile);
dbPath.getParentFile().mkdirs();
String url = "jdbc:sqlite:" + dbPath.getAbsolutePath();
connection = DriverManager.getConnection(url);
// Create transactions table
try (Statement stmt = connection.createStatement()) {
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS transactions (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"uuid TEXT NOT NULL, " +
"player_name TEXT NOT NULL, " +
"material TEXT NOT NULL, " +
"amount INTEGER NOT NULL, " +
"total REAL NOT NULL, " +
"type TEXT NOT NULL, " +
"timestamp DATETIME DEFAULT CURRENT_TIMESTAMP" +
")"
);
}
plugin.getLogger().info("Transaction logging initialized (SQLite).");
} catch (SQLException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to initialize transaction database!", e);
enabled = false;
}
}
/**
* Logs a transaction asynchronously.
*
* @param playerUuid the player's UUID
* @param playerName the player's name
* @param material the material traded
* @param amount the quantity traded
* @param total the total price
* @param type the transaction type (BUY or SELL)
*/
public void log(UUID playerUuid, String playerName, Material material,
int amount, double total, TransactionType type) {
if (!enabled || connection == null) return;
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try (PreparedStatement ps = connection.prepareStatement(
"INSERT INTO transactions (uuid, player_name, material, amount, total, type) " +
"VALUES (?, ?, ?, ?, ?, ?)")) {
ps.setString(1, playerUuid.toString());
ps.setString(2, playerName);
ps.setString(3, material.name());
ps.setInt(4, amount);
ps.setDouble(5, total);
ps.setString(6, type.name());
ps.executeUpdate();
} catch (SQLException e) {
plugin.getLogger().log(Level.WARNING, "Failed to log transaction", e);
}
});
}
/**
* Closes the database connection.
*/
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
plugin.getLogger().log(Level.WARNING, "Error closing transaction database", e);
}
}
}
/**
* Transaction type enum.
*/
public enum TransactionType {
BUY, SELL
}
}
@@ -1,220 +0,0 @@
package pt.henrique.servershop.util;
import net.kyori.adventure.text.Component;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Fluent builder for creating ItemStacks with custom display properties.
*/
public class ItemBuilder {
private final ItemStack item;
private final ItemMeta meta;
/**
* Creates a new ItemBuilder for the given material.
*
* @param material the material type
*/
public ItemBuilder(Material material) {
this(material, 1);
}
/**
* Creates a new ItemBuilder for the given material and amount.
*
* @param material the material type
* @param amount the stack amount
*/
public ItemBuilder(Material material, int amount) {
this.item = new ItemStack(material, amount);
this.meta = item.getItemMeta();
}
/**
* Creates a new ItemBuilder from an existing ItemStack (cloned).
*
* @param item the item to clone
*/
public ItemBuilder(ItemStack item) {
this.item = item.clone();
this.meta = this.item.getItemMeta();
}
/**
* Sets the display name using Adventure Component.
*
* @param name the display name component
* @return this builder
*/
public ItemBuilder name(Component name) {
if (meta != null) {
meta.displayName(name);
}
return this;
}
/**
* Sets the display name from a string with color codes.
*
* @param name the display name with &amp; color codes
* @return this builder
*/
public ItemBuilder name(String name) {
return name(TextUtil.colorize(name));
}
/**
* Sets the lore from a list of Adventure Components.
*
* @param lore the lore lines
* @return this builder
*/
public ItemBuilder lore(List<Component> lore) {
if (meta != null) {
meta.lore(lore);
}
return this;
}
/**
* Sets the lore from string lines with color codes.
*
* @param lines the lore lines with &amp; color codes
* @return this builder
*/
public ItemBuilder loreStr(List<String> lines) {
if (meta != null && lines != null) {
List<Component> components = new ArrayList<>();
for (String line : lines) {
components.add(TextUtil.colorize(line));
}
meta.lore(components);
}
return this;
}
/**
* Sets the lore from string lines with color codes.
*
* @param lines the lore lines with &amp; color codes
* @return this builder
*/
public ItemBuilder loreStr(String... lines) {
return loreStr(Arrays.asList(lines));
}
/**
* Adds a glowing enchantment effect (hidden).
*
* @return this builder
*/
public ItemBuilder glow() {
if (meta != null) {
meta.addEnchant(Enchantment.UNBREAKING, 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
return this;
}
/**
* Sets the item amount.
*
* @param amount the stack size
* @return this builder
*/
public ItemBuilder amount(int amount) {
item.setAmount(Math.max(1, Math.min(amount, 64)));
return this;
}
/**
* Hides all item flags.
*
* @return this builder
*/
public ItemBuilder hideFlags() {
if (meta != null) {
meta.addItemFlags(ItemFlag.values());
}
return this;
}
/**
* Sets a custom model data value.
*
* @param data the custom model data
* @return this builder
*/
public ItemBuilder customModelData(int data) {
if (meta != null) {
meta.setCustomModelData(data);
}
return this;
}
/**
* Builds and returns the final ItemStack.
*
* @return the constructed ItemStack
*/
public ItemStack build() {
if (meta != null) {
item.setItemMeta(meta);
}
return item;
}
/**
* Creates a simple named item with lore, useful for GUI buttons.
*
* @param material the material
* @param name the display name
* @param lore the lore lines
* @return the constructed ItemStack
*/
public static ItemStack button(Material material, String name, String... lore) {
return new ItemBuilder(material).name(name).loreStr(lore).hideFlags().build();
}
/**
* Creates a simple named item with lore from a list.
*
* @param material the material
* @param name the display name
* @param lore the lore lines
* @return the constructed ItemStack
*/
public static ItemStack button(Material material, String name, List<String> lore) {
return new ItemBuilder(material).name(name).loreStr(lore).hideFlags().build();
}
/**
* Applies placeholder replacements to a list of lore strings.
*
* @param template the lore template lines
* @param replacements the placeholder key-value pairs
* @return the processed lore lines
*/
public static List<String> applyPlaceholders(List<String> template, Map<String, String> replacements) {
if (template == null) return new ArrayList<>();
List<String> result = new ArrayList<>();
for (String line : template) {
String processed = line;
for (Map.Entry<String, String> entry : replacements.entrySet()) {
processed = processed.replace("{" + entry.getKey() + "}", entry.getValue());
}
result.add(processed);
}
return result;
}
}
@@ -1,85 +0,0 @@
package pt.henrique.servershop.util;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
/**
* Utility class for text formatting and color code processing.
*/
public final class TextUtil {
private static final LegacyComponentSerializer LEGACY_SERIALIZER =
LegacyComponentSerializer.legacyAmpersand();
private TextUtil() {
// Utility class
}
/**
* Converts a string with ampersand color codes into an Adventure Component.
*
* @param text the raw text with &amp; color codes
* @return the formatted Component
*/
public static Component colorize(String text) {
if (text == null || text.isEmpty()) {
return Component.empty();
}
return LEGACY_SERIALIZER.deserialize(text);
}
/**
* Converts a string with ampersand color codes into a legacy string with section sign codes.
*
* @param text the raw text with &amp; color codes
* @return the formatted string with § color codes
*/
public static String color(String text) {
if (text == null) return "";
return text.replace('&', '\u00A7');
}
/**
* Strips all color codes from a string.
*
* @param text the text to strip
* @return the text without color codes
*/
public static String stripColor(String text) {
if (text == null) return "";
return text.replaceAll("[&§][0-9a-fk-orA-FK-OR]", "");
}
/**
* Formats a material name for display.
* Converts DIAMOND_SWORD to Diamond Sword.
*
* @param materialName the raw material name
* @return the formatted display name
*/
public static String formatMaterialName(String materialName) {
if (materialName == null || materialName.isEmpty()) return "";
String[] parts = materialName.toLowerCase().split("_");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
if (!part.isEmpty()) {
if (!sb.isEmpty()) sb.append(' ');
sb.append(Character.toUpperCase(part.charAt(0)));
sb.append(part.substring(1));
}
}
return sb.toString();
}
/**
* Formats a currency value.
*
* @param amount the amount
* @param symbol the currency symbol
* @param decimalPlaces the number of decimal places
* @return the formatted currency string
*/
public static String formatCurrency(double amount, String symbol, int decimalPlaces) {
return symbol + String.format("%,." + decimalPlaces + "f", amount);
}
}
-97
View File
@@ -1,97 +0,0 @@
# ============================================================
# ServerShop - Configuration
# A server-run global market for Paper/Purpur 1.21.1
# ============================================================
# Language: en_US or pt_PT
language: en_US
# ============================================================
# Economy Settings
# ============================================================
economy:
# Currency symbol for display
symbol: "$"
# Decimal places for price display
decimal-places: 2
# Tax rate on sell transactions (0.0 = no tax, 0.05 = 5%)
sell-tax: 0.0
# ============================================================
# Pricing Settings
# ============================================================
pricing:
# Global sell multiplier: sellPrice = buyPrice * sell-multiplier
# Low value (0.25) creates a large spread to keep CommunityMarket valuable
default-sell-multiplier: 0.25
# Whether to include items with special meta (enchanted books, potions, etc.)
# If false, only base items are shown in the shop
include-special-items: false
# ============================================================
# Shop Behavior
# ============================================================
shop:
# What to do when inventory is full during purchase:
# DROP - drop items at player feet
# CANCEL - cancel the purchase
full-inventory-action: DROP
# Enable "sell hand" button in main menu
enable-sell-hand: true
# Enable "sell inventory" button in main menu
enable-sell-inventory: true
# Maximum quantity for a single transaction
max-transaction-quantity: 2304
# ============================================================
# GUI Settings
# ============================================================
gui:
# Main menu title (supports color codes with &)
main-title: "&8Server Shop"
# Category page title
category-title: "&8{category}"
# Item detail title
detail-title: "&8Buy/Sell"
# Search results title
search-title: "&8Search: {query}"
# Filler item for empty slots (Material name)
filler-material: GRAY_STAINED_GLASS_PANE
# Filler item display name (empty = invisible name)
filler-name: " "
# Items per page in category view
items-per-page: 28
# Play sounds on actions
sounds:
enabled: true
open: BLOCK_CHEST_OPEN
click: UI_BUTTON_CLICK
buy: ENTITY_EXPERIENCE_ORB_PICKUP
sell: ENTITY_EXPERIENCE_ORB_PICKUP
error: ENTITY_VILLAGER_NO
# ============================================================
# Transaction Logging (SQLite)
# ============================================================
logging:
# Enable transaction logging to SQLite
enabled: true
# Database file (relative to plugin data folder)
database-file: transactions.db
# ============================================================
# Permissions (reference only - actual nodes in plugin.yml)
# ============================================================
# servershop.use - Access the shop
# servershop.buy - Buy items
# servershop.sell - Sell items
# servershop.sell.hand - Use sell-hand feature
# servershop.sell.inventory - Use sell-inventory feature
# servershop.admin - Admin commands
# servershop.admin.reload - Reload configuration
@@ -1,138 +0,0 @@
# ============================================================
# ServerShop - English (en_US) Language File
# ============================================================
prefix: "&7[&6ServerShop&7] "
messages:
# General
no-permission: "&cYou don't have permission to do that."
player-only: "&cThis command can only be used by players."
reload-success: "&aConfiguration reloaded successfully."
economy-unavailable: "&cEconomy system is not available. Please contact an admin."
# Buying
buy-success: "&aYou purchased &f{amount}x {item} &afor &6{price}&a."
buy-insufficient-funds: "&cYou don't have enough money. You need &6{price}&c but only have &6{balance}&c."
buy-inventory-full-drop: "&eYour inventory was full. Items were dropped at your feet."
buy-inventory-full-cancel: "&cYour inventory is full. Purchase cancelled."
buy-disabled: "&cThis item is not available for purchase."
buy-zero-price: "&cThis item cannot be purchased from the server."
# Selling
sell-success: "&aYou sold &f{amount}x {item} &afor &6{price}&a."
sell-success-tax: "&aYou sold &f{amount}x {item} &afor &6{price} &7(tax: &6{tax}&7)&a."
sell-insufficient-items: "&cYou don't have enough items. You need &f{amount}x {item}&c."
sell-disabled: "&cThis item cannot be sold to the server."
sell-zero-price: "&cThis item has no sell value."
sell-hand-empty: "&cYou're not holding any items."
sell-hand-not-sellable: "&cThe item you're holding cannot be sold."
sell-inventory-nothing: "&cYou don't have any sellable items in your inventory."
sell-inventory-success: "&aSold all sellable items for &6{price}&a."
# Confirmation
confirm-sell-hand: "&eClick to confirm selling &f{amount}x {item} &efor &6{price}&e."
confirm-sell-inventory: "&eClick to confirm selling all inventory items for &6{price}&e."
# Search
search-prompt: "&eType the item name to search for:"
search-no-results: "&cNo items found matching '&f{query}&c'."
# Admin
admin-usage: "&eUsage: /shop reload"
gui:
titles:
main-menu: "&8Server Shop"
category: "&8{category}"
item-detail: "&8Buy/Sell"
search-results: "&8Search: {query}"
confirm-sell-hand: "&8Confirm Sale"
confirm-sell-inventory: "&8Confirm Sale"
buttons:
search: "&eSearch"
search-lore:
- "&7Click to search for items"
sell-hand: "&6Sell Hand"
sell-hand-lore:
- "&7Click to sell the item"
- "&7you're holding"
sell-inventory: "&6Sell Inventory"
sell-inventory-lore:
- "&7Click to sell all sellable"
- "&7items in your inventory"
back: "&cBack"
back-lore:
- "&7Return to previous menu"
previous-page: "&ePrevious Page"
previous-page-lore:
- "&7Page {page}"
next-page: "&eNext Page"
next-page-lore:
- "&7Page {page}"
close: "&cClose"
close-lore:
- "&7Close the shop"
buy: "&a&lBUY"
buy-lore:
- "&7Click to buy &f{amount}x"
- "&7Cost: &6{price}"
sell: "&c&lSELL"
sell-lore:
- "&7Click to sell &f{amount}x"
- "&7Earn: &6{price}"
confirm: "&a&lCONFIRM"
confirm-lore:
- "&7Click to confirm"
cancel: "&c&lCANCEL"
cancel-lore:
- "&7Click to cancel"
decrease-1: "&c-1"
decrease-8: "&c-8"
decrease-16: "&c-16"
decrease-32: "&c-32"
increase-1: "&a+1"
increase-8: "&a+8"
increase-16: "&a+16"
increase-32: "&a+32"
min-quantity: "&eMin"
max-quantity: "&eMax"
info: "&bInfo"
lore:
item-entry:
- "&7Buy: &a{buy_price}"
- "&7Sell: &c{sell_price}"
- "&7Spread: &e{spread}%"
- ""
- "&eClick to view details"
item-detail-info:
- ""
- "&7Buy Price: &a{buy_price}"
- "&7Sell Price: &c{sell_price}"
- "&7Server Spread: &e{spread}%"
- ""
- "&7Your Balance: &6{balance}"
- "&7Quantity: &f{amount}"
- ""
- "&7Buy Total: &a{buy_total}"
- "&7Sell Total: &c{sell_total}"
buy-disabled-lore:
- "&7Buy: &8Not available"
- "&7Sell: &c{sell_price}"
- ""
- "&eClick to view details"
sell-disabled-lore:
- "&7Buy: &a{buy_price}"
- "&7Sell: &8Not available"
- ""
- "&eClick to view details"
both-disabled-lore:
- "&7Buy: &8Not available"
- "&7Sell: &8Not available"
category:
lore:
- "&7Click to browse"
- "&7{count} items available"
@@ -1,138 +0,0 @@
# ============================================================
# ServerShop - Português (pt_PT) Ficheiro de Idioma
# ============================================================
prefix: "&7[&6LojaServidor&7] "
messages:
# Geral
no-permission: "&cNão tens permissão para fazer isso."
player-only: "&cEste comando só pode ser usado por jogadores."
reload-success: "&aConfiguração recarregada com sucesso."
economy-unavailable: "&cO sistema de economia não está disponível. Contacta um admin."
# Compras
buy-success: "&aCompraste &f{amount}x {item} &apor &6{price}&a."
buy-insufficient-funds: "&cNão tens dinheiro suficiente. Precisas de &6{price}&c mas só tens &6{balance}&c."
buy-inventory-full-drop: "&eO teu inventário estava cheio. Os itens foram largados aos teus pés."
buy-inventory-full-cancel: "&cO teu inventário está cheio. Compra cancelada."
buy-disabled: "&cEste item não está disponível para compra."
buy-zero-price: "&cEste item não pode ser comprado ao servidor."
# Vendas
sell-success: "&aVendeste &f{amount}x {item} &apor &6{price}&a."
sell-success-tax: "&aVendeste &f{amount}x {item} &apor &6{price} &7(taxa: &6{tax}&7)&a."
sell-insufficient-items: "&cNão tens itens suficientes. Precisas de &f{amount}x {item}&c."
sell-disabled: "&cEste item não pode ser vendido ao servidor."
sell-zero-price: "&cEste item não tem valor de venda."
sell-hand-empty: "&cNão estás a segurar nenhum item."
sell-hand-not-sellable: "&cO item que estás a segurar não pode ser vendido."
sell-inventory-nothing: "&cNão tens itens vendáveis no teu inventário."
sell-inventory-success: "&aVendeste todos os itens vendáveis por &6{price}&a."
# Confirmação
confirm-sell-hand: "&eClica para confirmar a venda de &f{amount}x {item} &epor &6{price}&e."
confirm-sell-inventory: "&eClica para confirmar a venda de todos os itens do inventário por &6{price}&e."
# Pesquisa
search-prompt: "&eEscreve o nome do item para pesquisar:"
search-no-results: "&cNenhum item encontrado com '&f{query}&c'."
# Admin
admin-usage: "&eUso: /shop reload"
gui:
titles:
main-menu: "&8Loja do Servidor"
category: "&8{category}"
item-detail: "&8Comprar/Vender"
search-results: "&8Pesquisa: {query}"
confirm-sell-hand: "&8Confirmar Venda"
confirm-sell-inventory: "&8Confirmar Venda"
buttons:
search: "&ePesquisar"
search-lore:
- "&7Clica para pesquisar itens"
sell-hand: "&6Vender Mão"
sell-hand-lore:
- "&7Clica para vender o item"
- "&7que estás a segurar"
sell-inventory: "&6Vender Inventário"
sell-inventory-lore:
- "&7Clica para vender todos"
- "&7os itens vendáveis"
back: "&cVoltar"
back-lore:
- "&7Voltar ao menu anterior"
previous-page: "&ePágina Anterior"
previous-page-lore:
- "&7Página {page}"
next-page: "&ePróxima Página"
next-page-lore:
- "&7Página {page}"
close: "&cFechar"
close-lore:
- "&7Fechar a loja"
buy: "&a&lCOMPRAR"
buy-lore:
- "&7Clica para comprar &f{amount}x"
- "&7Custo: &6{price}"
sell: "&c&lVENDER"
sell-lore:
- "&7Clica para vender &f{amount}x"
- "&7Ganho: &6{price}"
confirm: "&a&lCONFIRMAR"
confirm-lore:
- "&7Clica para confirmar"
cancel: "&c&lCANCELAR"
cancel-lore:
- "&7Clica para cancelar"
decrease-1: "&c-1"
decrease-8: "&c-8"
decrease-16: "&c-16"
decrease-32: "&c-32"
increase-1: "&a+1"
increase-8: "&a+8"
increase-16: "&a+16"
increase-32: "&a+32"
min-quantity: "&eMín"
max-quantity: "&eMáx"
info: "&bInfo"
lore:
item-entry:
- "&7Compra: &a{buy_price}"
- "&7Venda: &c{sell_price}"
- "&7Margem: &e{spread}%"
- ""
- "&eClica para ver detalhes"
item-detail-info:
- ""
- "&7Preço de Compra: &a{buy_price}"
- "&7Preço de Venda: &c{sell_price}"
- "&7Margem do Servidor: &e{spread}%"
- ""
- "&7O Teu Saldo: &6{balance}"
- "&7Quantidade: &f{amount}"
- ""
- "&7Total Compra: &a{buy_total}"
- "&7Total Venda: &c{sell_total}"
buy-disabled-lore:
- "&7Compra: &8Não disponível"
- "&7Venda: &c{sell_price}"
- ""
- "&eClica para ver detalhes"
sell-disabled-lore:
- "&7Compra: &a{buy_price}"
- "&7Venda: &8Não disponível"
- ""
- "&eClica para ver detalhes"
both-disabled-lore:
- "&7Compra: &8Não disponível"
- "&7Venda: &8Não disponível"
category:
lore:
- "&7Clica para explorar"
- "&7{count} itens disponíveis"
-39
View File
@@ -1,39 +0,0 @@
name: ServerShop
version: ${project.version}
main: pt.henrique.servershop.ServerShop
api-version: '1.21'
description: Server-run global market with configurable pricing, GUI-driven interface, and Vault economy integration
author: henrique
website: https://github.com/henriquescrrrr/CommunityMarket
depend: [Vault]
load: POSTWORLD
commands:
shop:
description: Opens the server shop GUI
usage: /shop
aliases: [servershop]
permission: servershop.use
permissions:
servershop.use:
description: Allows access to the server shop
default: true
servershop.buy:
description: Allows buying items from the server shop
default: true
servershop.sell:
description: Allows selling items to the server shop
default: true
servershop.sell.hand:
description: Allows selling items held in hand
default: true
servershop.sell.inventory:
description: Allows selling all items from inventory
default: true
servershop.admin:
description: Admin permission for server shop management
default: op
servershop.admin.reload:
description: Allows reloading the server shop configuration
default: op
-645
View File
@@ -1,645 +0,0 @@
# ============================================================
# ServerShop - Prices Configuration
# All prices are BUY prices (server sells to player).
# SELL prices are auto-calculated: buyPrice * sell-multiplier
# Override sell prices per-item with explicit 'sell' key.
# ============================================================
# ============================================================
# Category Definitions
# Each category has:
# icon - Material for the category icon
# sell-multiplier - Override global multiplier (optional)
# buy-enabled - Allow buying from this category (default: true)
# sell-enabled - Allow selling in this category (default: true)
# items - Map of Material -> price config
# ============================================================
categories:
Blocks:
icon: GRASS_BLOCK
sell-multiplier: 0.25
buy-enabled: true
sell-enabled: true
items:
STONE: 2.0
GRANITE: 2.0
POLISHED_GRANITE: 3.0
DIORITE: 2.0
POLISHED_DIORITE: 3.0
ANDESITE: 2.0
POLISHED_ANDESITE: 3.0
DEEPSLATE: 3.0
COBBLED_DEEPSLATE: 2.5
POLISHED_DEEPSLATE: 4.0
CALCITE: 4.0
TUFF: 2.5
DRIPSTONE_BLOCK: 4.0
GRASS_BLOCK: 3.0
DIRT: 1.0
COARSE_DIRT: 1.5
PODZOL: 4.0
ROOTED_DIRT: 2.0
MUD: 2.0
COBBLESTONE: 1.5
OAK_PLANKS: 2.0
SPRUCE_PLANKS: 2.0
BIRCH_PLANKS: 2.0
JUNGLE_PLANKS: 2.5
ACACIA_PLANKS: 2.5
DARK_OAK_PLANKS: 2.5
MANGROVE_PLANKS: 3.0
CHERRY_PLANKS: 3.0
BAMBOO_PLANKS: 3.0
CRIMSON_PLANKS: 5.0
WARPED_PLANKS: 5.0
SAND: 1.5
RED_SAND: 2.0
GRAVEL: 1.5
CLAY: 3.0
BRICKS: 5.0
STONE_BRICKS: 4.0
MOSSY_STONE_BRICKS: 5.0
CRACKED_STONE_BRICKS: 5.0
CHISELED_STONE_BRICKS: 6.0
PACKED_MUD: 3.0
MUD_BRICKS: 4.0
SANDSTONE: 4.0
RED_SANDSTONE: 5.0
SMOOTH_STONE: 3.5
PRISMARINE: 8.0
PRISMARINE_BRICKS: 10.0
DARK_PRISMARINE: 12.0
NETHERRACK: 1.0
BASALT: 3.0
POLISHED_BASALT: 4.0
SMOOTH_BASALT: 4.0
BLACKSTONE: 3.0
POLISHED_BLACKSTONE: 4.0
POLISHED_BLACKSTONE_BRICKS: 5.0
END_STONE: 5.0
END_STONE_BRICKS: 6.0
PURPUR_BLOCK: 8.0
PURPUR_PILLAR: 10.0
OBSIDIAN: 15.0
CRYING_OBSIDIAN: 20.0
TERRACOTTA: 3.0
WHITE_TERRACOTTA: 4.0
ORANGE_TERRACOTTA: 4.0
MAGENTA_TERRACOTTA: 4.0
LIGHT_BLUE_TERRACOTTA: 4.0
YELLOW_TERRACOTTA: 4.0
LIME_TERRACOTTA: 4.0
PINK_TERRACOTTA: 4.0
GRAY_TERRACOTTA: 4.0
LIGHT_GRAY_TERRACOTTA: 4.0
CYAN_TERRACOTTA: 4.0
PURPLE_TERRACOTTA: 4.0
BLUE_TERRACOTTA: 4.0
BROWN_TERRACOTTA: 4.0
GREEN_TERRACOTTA: 4.0
RED_TERRACOTTA: 4.0
BLACK_TERRACOTTA: 4.0
WHITE_GLAZED_TERRACOTTA: 6.0
ORANGE_GLAZED_TERRACOTTA: 6.0
MAGENTA_GLAZED_TERRACOTTA: 6.0
LIGHT_BLUE_GLAZED_TERRACOTTA: 6.0
YELLOW_GLAZED_TERRACOTTA: 6.0
LIME_GLAZED_TERRACOTTA: 6.0
PINK_GLAZED_TERRACOTTA: 6.0
GRAY_GLAZED_TERRACOTTA: 6.0
LIGHT_GRAY_GLAZED_TERRACOTTA: 6.0
CYAN_GLAZED_TERRACOTTA: 6.0
PURPLE_GLAZED_TERRACOTTA: 6.0
BLUE_GLAZED_TERRACOTTA: 6.0
BROWN_GLAZED_TERRACOTTA: 6.0
GREEN_GLAZED_TERRACOTTA: 6.0
RED_GLAZED_TERRACOTTA: 6.0
BLACK_GLAZED_TERRACOTTA: 6.0
WHITE_CONCRETE: 4.0
ORANGE_CONCRETE: 4.0
MAGENTA_CONCRETE: 4.0
LIGHT_BLUE_CONCRETE: 4.0
YELLOW_CONCRETE: 4.0
LIME_CONCRETE: 4.0
PINK_CONCRETE: 4.0
GRAY_CONCRETE: 4.0
LIGHT_GRAY_CONCRETE: 4.0
CYAN_CONCRETE: 4.0
PURPLE_CONCRETE: 4.0
BLUE_CONCRETE: 4.0
BROWN_CONCRETE: 4.0
GREEN_CONCRETE: 4.0
RED_CONCRETE: 4.0
BLACK_CONCRETE: 4.0
AMETHYST_BLOCK: 12.0
COPPER_BLOCK: 40.0
EXPOSED_COPPER: 35.0
WEATHERED_COPPER: 30.0
OXIDIZED_COPPER: 25.0
CUT_COPPER: 45.0
ICE: 3.0
PACKED_ICE: 6.0
BLUE_ICE: 12.0
SNOW_BLOCK: 2.0
MOSS_BLOCK: 4.0
SCULK: 8.0
Ores:
icon: DIAMOND_ORE
sell-multiplier: 0.30
items:
COAL: 3.0
CHARCOAL: 2.5
RAW_IRON: 8.0
RAW_COPPER: 5.0
RAW_GOLD: 15.0
IRON_INGOT: 12.0
COPPER_INGOT: 8.0
GOLD_INGOT: 25.0
DIAMOND: 100.0
EMERALD: 50.0
LAPIS_LAZULI: 10.0
REDSTONE: 6.0
QUARTZ: 8.0
AMETHYST_SHARD: 8.0
NETHERITE_SCRAP: 250.0
NETHERITE_INGOT: 1000.0
COAL_ORE: 5.0
IRON_ORE: 10.0
COPPER_ORE: 7.0
GOLD_ORE: 20.0
DIAMOND_ORE: 120.0
EMERALD_ORE: 60.0
LAPIS_ORE: 15.0
REDSTONE_ORE: 10.0
NETHER_QUARTZ_ORE: 12.0
NETHER_GOLD_ORE: 18.0
ANCIENT_DEBRIS: 300.0
DEEPSLATE_COAL_ORE: 6.0
DEEPSLATE_IRON_ORE: 12.0
DEEPSLATE_COPPER_ORE: 9.0
DEEPSLATE_GOLD_ORE: 25.0
DEEPSLATE_DIAMOND_ORE: 140.0
DEEPSLATE_EMERALD_ORE: 70.0
DEEPSLATE_LAPIS_ORE: 18.0
DEEPSLATE_REDSTONE_ORE: 12.0
IRON_BLOCK: 108.0
GOLD_BLOCK: 225.0
DIAMOND_BLOCK: 900.0
EMERALD_BLOCK: 450.0
LAPIS_BLOCK: 90.0
REDSTONE_BLOCK: 54.0
COAL_BLOCK: 27.0
COPPER_BLOCK: 72.0
NETHERITE_BLOCK: 9000.0
Farming:
icon: WHEAT
sell-multiplier: 0.20
items:
WHEAT_SEEDS: 0.5
WHEAT: 2.0
HAY_BLOCK: 18.0
BEETROOT_SEEDS: 0.5
BEETROOT: 2.0
CARROT: 2.0
POTATO: 2.0
POISONOUS_POTATO: 1.0
MELON_SLICE: 1.5
MELON: 12.0
PUMPKIN: 5.0
SUGAR_CANE: 2.0
SUGAR: 2.5
COCOA_BEANS: 3.0
BAMBOO: 1.0
CACTUS: 2.0
CHORUS_FRUIT: 5.0
CHORUS_FLOWER: 8.0
SWEET_BERRIES: 2.0
GLOW_BERRIES: 4.0
KELP: 1.5
DRIED_KELP: 2.0
DRIED_KELP_BLOCK: 18.0
NETHER_WART: 4.0
NETHER_WART_BLOCK: 36.0
BONE_MEAL: 2.0
EGG: 2.0
HONEYCOMB: 5.0
HONEY_BOTTLE: 8.0
HONEYCOMB_BLOCK: 20.0
OAK_SAPLING: 3.0
SPRUCE_SAPLING: 3.0
BIRCH_SAPLING: 3.0
JUNGLE_SAPLING: 4.0
ACACIA_SAPLING: 4.0
DARK_OAK_SAPLING: 4.0
CHERRY_SAPLING: 5.0
MANGROVE_PROPAGULE: 4.0
OAK_LOG: 3.0
SPRUCE_LOG: 3.0
BIRCH_LOG: 3.0
JUNGLE_LOG: 3.5
ACACIA_LOG: 3.5
DARK_OAK_LOG: 3.5
MANGROVE_LOG: 4.0
CHERRY_LOG: 4.0
CRIMSON_STEM: 5.0
WARPED_STEM: 5.0
VINE: 3.0
LILY_PAD: 3.0
SEA_PICKLE: 4.0
Food:
icon: COOKED_BEEF
sell-multiplier: 0.20
items:
APPLE: 3.0
GOLDEN_APPLE: 100.0
ENCHANTED_GOLDEN_APPLE: 500.0
BREAD: 4.0
COOKED_BEEF: 8.0
COOKED_PORKCHOP: 8.0
COOKED_CHICKEN: 6.0
COOKED_MUTTON: 7.0
COOKED_RABBIT: 6.0
COOKED_COD: 5.0
COOKED_SALMON: 6.0
BEEF: 5.0
PORKCHOP: 5.0
CHICKEN: 3.0
MUTTON: 4.0
RABBIT: 4.0
COD: 3.0
SALMON: 4.0
TROPICAL_FISH: 6.0
PUFFERFISH: 5.0
BAKED_POTATO: 5.0
COOKIE: 3.0
CAKE: 20.0
PUMPKIN_PIE: 10.0
MUSHROOM_STEW: 8.0
RABBIT_STEW: 15.0
BEETROOT_SOUP: 6.0
SUSPICIOUS_STEW: 10.0
DRIED_KELP: 2.0
MELON_SLICE: 1.5
GLOW_BERRIES: 4.0
SWEET_BERRIES: 2.0
Mob_Drops:
icon: ROTTEN_FLESH
sell-multiplier: 0.25
items:
ROTTEN_FLESH: 1.0
BONE: 2.0
STRING: 2.5
SPIDER_EYE: 3.0
GUNPOWDER: 5.0
ENDER_PEARL: 15.0
BLAZE_ROD: 20.0
GHAST_TEAR: 25.0
MAGMA_CREAM: 12.0
SLIME_BALL: 8.0
PRISMARINE_SHARD: 5.0
PRISMARINE_CRYSTALS: 6.0
PHANTOM_MEMBRANE: 15.0
RABBIT_HIDE: 3.0
RABBIT_FOOT: 10.0
LEATHER: 5.0
FEATHER: 2.0
INK_SAC: 3.0
GLOW_INK_SAC: 8.0
ARROW: 2.0
WITHER_SKELETON_SKULL: 100.0
NETHER_STAR: 500.0
SHULKER_SHELL: 50.0
DRAGON_BREATH: 40.0
EXPERIENCE_BOTTLE: 20.0
TOTEM_OF_UNDYING: 200.0
TRIDENT: 300.0
NAUTILUS_SHELL: 25.0
HEART_OF_THE_SEA: 100.0
ECHO_SHARD: 30.0
DISC_FRAGMENT_5: 20.0
GOAT_HORN: 15.0
ARMADILLO_SCUTE: 10.0
BREEZE_ROD: 25.0
Redstone:
icon: REDSTONE
sell-multiplier: 0.25
items:
REDSTONE: 6.0
REDSTONE_BLOCK: 54.0
REDSTONE_TORCH: 4.0
REPEATER: 10.0
COMPARATOR: 15.0
PISTON: 15.0
STICKY_PISTON: 20.0
SLIME_BLOCK: 72.0
HONEY_BLOCK: 32.0
OBSERVER: 18.0
HOPPER: 30.0
DROPPER: 10.0
DISPENSER: 12.0
LEVER: 2.0
STONE_BUTTON: 2.0
OAK_BUTTON: 2.0
STONE_PRESSURE_PLATE: 3.0
OAK_PRESSURE_PLATE: 3.0
TRIPWIRE_HOOK: 5.0
TRAPPED_CHEST: 12.0
DAYLIGHT_DETECTOR: 15.0
NOTE_BLOCK: 10.0
TARGET: 12.0
TNT: 25.0
RAIL: 5.0
POWERED_RAIL: 20.0
DETECTOR_RAIL: 15.0
ACTIVATOR_RAIL: 15.0
MINECART: 25.0
CHEST_MINECART: 30.0
HOPPER_MINECART: 45.0
TNT_MINECART: 40.0
FURNACE_MINECART: 30.0
SCULK_SENSOR: 15.0
CALIBRATED_SCULK_SENSOR: 25.0
LIGHTNING_ROD: 15.0
CRAFTER: 20.0
Decoration:
icon: PAINTING
sell-multiplier: 0.20
items:
TORCH: 1.5
SOUL_TORCH: 2.5
LANTERN: 8.0
SOUL_LANTERN: 10.0
CANDLE: 4.0
SEA_LANTERN: 15.0
GLOWSTONE: 12.0
SHROOMLIGHT: 10.0
PAINTING: 5.0
ITEM_FRAME: 5.0
GLOW_ITEM_FRAME: 12.0
ARMOR_STAND: 10.0
FLOWER_POT: 4.0
GLASS: 3.0
GLASS_PANE: 2.0
WHITE_STAINED_GLASS: 4.0
WHITE_STAINED_GLASS_PANE: 3.0
CHAIN: 6.0
IRON_BARS: 5.0
BELL: 50.0
BOOKSHELF: 15.0
CHISELED_BOOKSHELF: 18.0
DECORATED_POT: 8.0
FLOWER_BANNER_PATTERN: 15.0
WHITE_BANNER: 12.0
WHITE_BED: 15.0
WHITE_CARPET: 2.0
WHITE_WOOL: 4.0
ORANGE_WOOL: 4.0
MAGENTA_WOOL: 4.0
LIGHT_BLUE_WOOL: 4.0
YELLOW_WOOL: 4.0
LIME_WOOL: 4.0
PINK_WOOL: 4.0
GRAY_WOOL: 4.0
LIGHT_GRAY_WOOL: 4.0
CYAN_WOOL: 4.0
PURPLE_WOOL: 4.0
BLUE_WOOL: 4.0
BROWN_WOOL: 4.0
GREEN_WOOL: 4.0
RED_WOOL: 4.0
BLACK_WOOL: 4.0
DANDELION: 2.0
POPPY: 2.0
BLUE_ORCHID: 3.0
ALLIUM: 3.0
AZURE_BLUET: 3.0
RED_TULIP: 3.0
ORANGE_TULIP: 3.0
WHITE_TULIP: 3.0
PINK_TULIP: 3.0
OXEYE_DAISY: 3.0
CORNFLOWER: 3.0
LILY_OF_THE_VALLEY: 3.0
SUNFLOWER: 4.0
LILAC: 4.0
ROSE_BUSH: 4.0
PEONY: 4.0
WITHER_ROSE: 25.0
TORCHFLOWER: 8.0
PITCHER_PLANT: 10.0
SPORE_BLOSSOM: 15.0
MOSS_CARPET: 3.0
PINK_PETALS: 3.0
BIG_DRIPLEAF: 5.0
SMALL_DRIPLEAF: 3.0
HANGING_ROOTS: 2.0
PLAYER_HEAD: 20.0
Tools:
icon: DIAMOND_PICKAXE
sell-multiplier: 0.20
items:
WOODEN_PICKAXE: 3.0
STONE_PICKAXE: 5.0
IRON_PICKAXE: 30.0
GOLDEN_PICKAXE: 55.0
DIAMOND_PICKAXE: 210.0
NETHERITE_PICKAXE: 1210.0
WOODEN_AXE: 3.0
STONE_AXE: 5.0
IRON_AXE: 30.0
GOLDEN_AXE: 55.0
DIAMOND_AXE: 210.0
NETHERITE_AXE: 1210.0
WOODEN_SHOVEL: 2.0
STONE_SHOVEL: 4.0
IRON_SHOVEL: 15.0
GOLDEN_SHOVEL: 30.0
DIAMOND_SHOVEL: 110.0
NETHERITE_SHOVEL: 1110.0
WOODEN_HOE: 2.0
STONE_HOE: 4.0
IRON_HOE: 15.0
GOLDEN_HOE: 30.0
DIAMOND_HOE: 110.0
NETHERITE_HOE: 1110.0
SHEARS: 10.0
FISHING_ROD: 10.0
FLINT_AND_STEEL: 10.0
COMPASS: 20.0
RECOVERY_COMPASS: 50.0
CLOCK: 20.0
SPYGLASS: 15.0
BRUSH: 15.0
LEAD: 8.0
NAME_TAG: 25.0
BUCKET: 15.0
WATER_BUCKET: 18.0
LAVA_BUCKET: 25.0
MILK_BUCKET: 20.0
SADDLE: 30.0
ELYTRA: 2000.0
MACE: 1500.0
Combat:
icon: DIAMOND_SWORD
sell-multiplier: 0.20
items:
WOODEN_SWORD: 2.0
STONE_SWORD: 4.0
IRON_SWORD: 18.0
GOLDEN_SWORD: 30.0
DIAMOND_SWORD: 210.0
NETHERITE_SWORD: 1210.0
BOW: 10.0
CROSSBOW: 25.0
ARROW: 2.0
SPECTRAL_ARROW: 5.0
TIPPED_ARROW: 8.0
SHIELD: 15.0
LEATHER_HELMET: 10.0
LEATHER_CHESTPLATE: 16.0
LEATHER_LEGGINGS: 14.0
LEATHER_BOOTS: 8.0
IRON_HELMET: 30.0
IRON_CHESTPLATE: 48.0
IRON_LEGGINGS: 42.0
IRON_BOOTS: 24.0
GOLDEN_HELMET: 60.0
GOLDEN_CHESTPLATE: 96.0
GOLDEN_LEGGINGS: 84.0
GOLDEN_BOOTS: 48.0
DIAMOND_HELMET: 260.0
DIAMOND_CHESTPLATE: 416.0
DIAMOND_LEGGINGS: 364.0
DIAMOND_BOOTS: 208.0
NETHERITE_HELMET: 1260.0
NETHERITE_CHESTPLATE: 1416.0
NETHERITE_LEGGINGS: 1364.0
NETHERITE_BOOTS: 1208.0
CHAINMAIL_HELMET: 25.0
CHAINMAIL_CHESTPLATE: 40.0
CHAINMAIL_LEGGINGS: 35.0
CHAINMAIL_BOOTS: 20.0
TURTLE_HELMET: 50.0
WOLF_ARMOR: 60.0
LEATHER_HORSE_ARMOR: 30.0
IRON_HORSE_ARMOR: 40.0
GOLDEN_HORSE_ARMOR: 60.0
DIAMOND_HORSE_ARMOR: 100.0
Brewing:
icon: BREWING_STAND
sell-multiplier: 0.25
items:
BREWING_STAND: 25.0
BLAZE_POWDER: 12.0
GLASS_BOTTLE: 2.0
GLASS_BOTTLE: 2.0
NETHER_WART: 4.0
SPIDER_EYE: 3.0
FERMENTED_SPIDER_EYE: 8.0
GLISTERING_MELON_SLICE: 15.0
GOLDEN_CARROT: 15.0
RABBIT_FOOT: 10.0
MAGMA_CREAM: 12.0
GHAST_TEAR: 25.0
PHANTOM_MEMBRANE: 15.0
DRAGON_BREATH: 40.0
SUGAR: 2.5
REDSTONE: 6.0
GLOWSTONE_DUST: 8.0
GUNPOWDER: 5.0
CAULDRON: 20.0
Misc:
icon: CHEST
sell-multiplier: 0.20
items:
CHEST: 10.0
ENDER_CHEST: 100.0
BARREL: 12.0
FURNACE: 10.0
BLAST_FURNACE: 30.0
SMOKER: 15.0
CRAFTING_TABLE: 5.0
ENCHANTING_TABLE: 200.0
ANVIL: 90.0
GRINDSTONE: 15.0
SMITHING_TABLE: 20.0
STONECUTTER: 12.0
LOOM: 8.0
CARTOGRAPHY_TABLE: 12.0
FLETCHING_TABLE: 12.0
COMPOSTER: 10.0
LECTERN: 20.0
BEACON: 2000.0
CONDUIT: 300.0
LODESTONE: 150.0
RESPAWN_ANCHOR: 200.0
JUKEBOX: 100.0
END_CRYSTAL: 100.0
FIRE_CHARGE: 5.0
FIREWORK_ROCKET: 8.0
FIREWORK_STAR: 10.0
MAP: 5.0
PAPER: 2.0
BOOK: 5.0
WRITABLE_BOOK: 8.0
ENDER_EYE: 25.0
SPONGE: 30.0
WET_SPONGE: 28.0
SCAFFOLDING: 3.0
LADDER: 3.0
OAK_SIGN: 3.0
TRIAL_KEY: 30.0
OMINOUS_TRIAL_KEY: 80.0
WIND_CHARGE: 15.0
# ============================================================
# Per-Item Overrides
# Override specific items with explicit buy/sell prices,
# or disable buying/selling for specific items.
# Format:
# MATERIAL_NAME:
# buy: <price> (override buy price)
# sell: <price> (override sell price)
# buy-enabled: false (disable buying)
# sell-enabled: false (disable selling)
# ============================================================
overrides:
BEDROCK:
buy: 10000.0
sell-enabled: false
COMMAND_BLOCK:
buy-enabled: false
sell-enabled: false
BARRIER:
buy-enabled: false
sell-enabled: false
SPAWNER:
buy: 5000.0
sell-enabled: false
DRAGON_EGG:
buy-enabled: false
sell: 5000.0
ENCHANTED_GOLDEN_APPLE:
sell: 200.0
NETHER_STAR:
sell: 200.0
ELYTRA:
sell: 500.0
BEACON:
sell: 600.0
NETHERITE_INGOT:
sell: 350.0
NETHERITE_BLOCK:
sell: 3000.0
MACE:
sell: 400.0
+16 -8
View File
@@ -4,7 +4,7 @@
<groupId>pt.henrique</groupId>
<artifactId>communitymarket</artifactId>
<name>CommunityMarket</name>
<version>1.0.0</version>
<version>2.1.0</version>
<description>A comprehensive player-to-player marketplace plugin with sales, auctions, and negotiations</description>
<build>
<resources>
@@ -18,13 +18,13 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration>
<source>21</source>
<target>21</target>
<source>25</source>
<target>25</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
@@ -39,6 +39,14 @@
</relocation>
</relocations>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>org.xerial:sqlite-jdbc</artifact>
<includes>
<include>**</include>
</includes>
</filter>
</filters>
</configuration>
</execution>
</executions>
@@ -64,7 +72,7 @@
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.21.1-R0.1-SNAPSHOT</version>
<version>26.3.build.140-beta</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -75,9 +83,9 @@
</dependency>
</dependencies>
<properties>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>21</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<paper.version>1.21.1-R0.1-SNAPSHOT</paper.version>
<paper.version>26.3.build.140-beta</paper.version>
<maven.compiler.target>25</maven.compiler.target>
<maven.compiler.source>25</maven.compiler.source>
</properties>
</project>
+22 -8
View File
@@ -6,17 +6,17 @@
<groupId>pt.henrique</groupId>
<artifactId>communitymarket</artifactId>
<version>1.0.0</version>
<version>2.1.0</version>
<packaging>jar</packaging>
<name>CommunityMarket</name>
<description>A comprehensive player-to-player marketplace plugin with sales, auctions, and negotiations</description>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<maven.compiler.source>25</maven.compiler.source>
<maven.compiler.target>25</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<paper.version>1.21.1-R0.1-SNAPSHOT</paper.version>
<paper.version>26.3.build.140-beta</paper.version>
</properties>
<repositories>
@@ -37,7 +37,7 @@
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>${paper.version}</version>
<version>26.3.build.140-beta</version>
<scope>provided</scope>
</dependency>
@@ -72,15 +72,15 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration>
<source>21</source>
<target>21</target>
<source>25</source>
<target>25</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
@@ -95,6 +95,20 @@
</relocation>
</relocations>
<minimizeJar>true</minimizeJar>
<!--
The SQLite driver is loaded by class name at runtime
(setDriverClassName("org.sqlite.JDBC")), so minimizeJar's static
reachability analysis cannot see it and would strip it, breaking the
default SQLite backend. Force its classes (and native libs) to be kept.
-->
<filters>
<filter>
<artifact>org.xerial:sqlite-jdbc</artifact>
<includes>
<include>**</include>
</includes>
</filter>
</filters>
</configuration>
</execution>
</executions>
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
@@ -124,8 +124,11 @@ public class ConfigManager {
// Economy settings
currencyFormat = config.getString("economy.currency-format", "$#,##0.00");
currencySymbol = config.getString("economy.currency-symbol", "$");
marketTax = config.getDouble("economy.taxes.market-tax", 5.0);
auctionTax = config.getDouble("economy.taxes.auction-tax", 7.5);
// Clamp taxes to [0, 100]. A tax > 100 would make seller earnings negative
// (price * (1 - tax/100)) which the deposit path would then mint/refuse - a config
// mistake must never be able to create or destroy money.
marketTax = clampPercent(config.getDouble("economy.taxes.market-tax", 5.0));
auctionTax = clampPercent(config.getDouble("economy.taxes.auction-tax", 7.5));
// Market settings
maxListingsPerPlayer = config.getInt("market.max-listings-per-player", 20);
@@ -272,6 +275,23 @@ public class ConfigManager {
return blacklistedMaterials.contains(material);
}
/**
* Clamps a percentage value to the valid [0, 100] range.
* Non-finite values (NaN/Infinity from a malformed config) fall back to 0.
*/
private double clampPercent(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
plugin.getLogger().warning("Invalid tax percentage in config; defaulting to 0.");
return 0.0;
}
if (value < 0.0) return 0.0;
if (value > 100.0) {
plugin.getLogger().warning("Tax percentage " + value + " exceeds 100; clamping to 100.");
return 100.0;
}
return value;
}
/**
* Checks if text contains blacklisted keywords
*/
@@ -36,8 +36,8 @@ public class MessageManager {
public void reload() {
messageCache.clear();
// Get language from config
currentLanguage = plugin.getConfig().getString("language", "en_US");
// Get language from config (default pt_PT; en_US remains bundled as a fallback)
currentLanguage = plugin.getConfig().getString("language", "pt_PT");
// Save default language files
saveDefaultLanguageFiles();
@@ -394,6 +394,30 @@ public class DatabaseManager {
});
}
/**
* Atomically transitions a listing to a new status ONLY if it is still ACTIVE.
* Returns true only for the caller that actually changed the row, so it can be
* used as a compare-and-swap guard to prevent double-processing races such as
* cancel-vs-purchase or expire-vs-purchase (which would otherwise duplicate the item).
*/
public CompletableFuture<Boolean> updateListingStatusIfActive(int listingId, Listing.ListingStatus status) {
return CompletableFuture.supplyAsync(() -> {
String sql = "UPDATE listings SET status = ? WHERE id = ? AND status = 'ACTIVE'";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, status.name());
stmt.setInt(2, listingId);
return stmt.executeUpdate() > 0;
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Failed to update listing status (conditional)", e);
}
return false;
});
}
/**
* Gets expired active listings.
*/
@@ -666,6 +690,31 @@ public class DatabaseManager {
});
}
/**
* Atomically transitions an auction to a new status ONLY if it is still ACTIVE.
* Returns true only for the caller that actually changed the row. Used as a
* compare-and-swap guard so that ending, buying-out or cancelling an auction can
* never be processed twice (which would otherwise duplicate seller earnings and
* the item delivered to the winner/seller).
*/
public CompletableFuture<Boolean> updateAuctionStatusIfActive(int auctionId, Auction.AuctionStatus status) {
return CompletableFuture.supplyAsync(() -> {
String sql = "UPDATE auctions SET status = ? WHERE id = ? AND status = 'ACTIVE'";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, status.name());
stmt.setInt(2, auctionId);
return stmt.executeUpdate() > 0;
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Failed to update auction status (conditional)", e);
}
return false;
});
}
/**
* Gets auctions that have ended but are still active.
*/
@@ -120,7 +120,10 @@ public class BrowseMarketGui implements MarketGui {
var msgManager = plugin.getMessageManager();
ItemStack display = listing.getItem().clone();
display.setAmount(listing.getAmount());
// Display only: a count above the max stack size makes the stack resolve to
// empty since 26.1, so the icon would render as nothing. The real amount is
// in the lore.
display.setAmount(Math.min(listing.getAmount(), Math.max(1, display.getMaxStackSize())));
// Calculate time remaining
String expires;
@@ -45,6 +45,10 @@ public class CreateAuctionGui implements MarketGui {
private Double buyoutPrice = null;
private int durationHours;
// Prevents double-submission (e.g. rapid double-click on confirm) which would
// otherwise create two auctions while only one set of items is removed = item/money dupe.
private boolean processing = false;
// ==================== LAYOUT CONSTANTS ====================
private static final int INFO_SLOT = 4; // Top center
private static final int ITEM_DISPLAY_SLOT = 13; // Center
@@ -314,6 +318,11 @@ public class CreateAuctionGui implements MarketGui {
}
private void confirmAuction(Player player) {
// Guard against double-submission: a confirm is already being processed.
if (processing) {
return;
}
var msgManager = plugin.getMessageManager();
// Verify item still exists in player's inventory with sufficient quantity
@@ -340,21 +349,44 @@ public class CreateAuctionGui implements MarketGui {
// Create the auction
ItemStack auctionItem = selectedItem.clone();
int amount = auctionItem.getAmount();
// From here an async creation is in flight; block further confirms until it finishes.
processing = true;
// Reserve the items NOW, atomically on the main thread, BEFORE the async DB write.
// Removing after the async round-trip is a dupe window: during the round-trip the
// player could drop/stash/hand off the items (the auction is built from a clone and
// does not need the live items), leaving them with both the items AND an auction that
// delivers the item to the winner. Remove-first + refund-on-failure closes that window.
if (!InventoryUtil.removeItem(player, auctionItem, amount)) {
processing = false;
player.sendMessage(msgManager.getPrefixed("messages.item-no-longer-available"));
SoundUtil.playSound(player, plugin.getConfigManager().getErrorSound());
new ItemSelectionGui(plugin, guiManager, ItemSelectionGui.SelectionMode.AUCTION).open(player);
return;
}
plugin.getTransactionService().createAuctionTransaction(
player, auctionItem, startPrice, buyoutPrice, durationHours
).thenAccept(result -> {
Bukkit.getScheduler().runTask(plugin, () -> {
processing = false;
if (result.isSuccess()) {
// Remove items from inventory AFTER successful creation
InventoryUtil.removeItem(player, auctionItem, auctionItem.getAmount());
player.sendMessage(msgManager.getPrefixed("messages.auction-created",
"id", String.valueOf(result.getId())));
SoundUtil.playSound(player, plugin.getConfigManager().getSuccessSound());
player.closeInventory();
guiManager.openMainMenu(player);
} else {
// Creation failed AFTER we removed the items - give them back so nothing is lost.
ItemStack refund = auctionItem.clone();
refund.setAmount(amount);
for (ItemStack leftover : InventoryUtil.giveItemSplit(player, refund)) {
plugin.getClaimService().addClaimItem(player.getUniqueId(), leftover,
pt.henrique.communityMarket.model.ClaimItem.ClaimReason.ADMIN_RETURN,
"Auction creation failed");
}
player.sendMessage(msgManager.getPrefixed("messages." + result.getErrorKey()));
SoundUtil.playSound(player, plugin.getConfigManager().getErrorSound());
}
@@ -44,6 +44,10 @@ public class CreateListingGui implements MarketGui {
private double price;
private int durationHours;
// Prevents double-submission (e.g. rapid double-click on confirm) which would
// otherwise create two listings while only one set of items is removed = item/money dupe.
private boolean processing = false;
// ==================== LAYOUT CONSTANTS ====================
private static final int INFO_SLOT = 4; // Top center
private static final int ITEM_DISPLAY_SLOT = 13; // Center row 1
@@ -258,6 +262,11 @@ public class CreateListingGui implements MarketGui {
}
private void confirmListing(Player player) {
// Guard against double-submission: a confirm is already being processed.
if (processing) {
return;
}
var msgManager = plugin.getMessageManager();
// Verify item still exists in player's inventory with sufficient quantity
@@ -286,20 +295,43 @@ public class CreateListingGui implements MarketGui {
int amount = selectedItem.getAmount();
ItemStack listItem = selectedItem.clone();
// From here an async creation is in flight; block further confirms until it finishes.
processing = true;
// Reserve the items NOW, atomically on the main thread, BEFORE the async DB write.
// Removing after the async round-trip is a dupe window: during the round-trip the
// player could drop/stash/hand off the items (the listing is built from a clone and
// does not need the live items), leaving them with both the items AND a listing that
// pays out. Remove-first + refund-on-failure closes that window.
if (!InventoryUtil.removeItem(player, listItem, amount)) {
// Couldn't take the full amount (item moved between the check and here) - abort.
processing = false;
player.sendMessage(msgManager.getPrefixed("messages.item-no-longer-available"));
SoundUtil.playSound(player, plugin.getConfigManager().getErrorSound());
new ItemSelectionGui(plugin, guiManager, ItemSelectionGui.SelectionMode.LISTING).open(player);
return;
}
plugin.getTransactionService().createListingTransaction(
player, listItem, amount, price, durationHours
).thenAccept(result -> {
Bukkit.getScheduler().runTask(plugin, () -> {
processing = false;
if (result.isSuccess()) {
// Remove items from inventory AFTER successful creation
InventoryUtil.removeItem(player, listItem, amount);
player.sendMessage(msgManager.getPrefixed("messages.listing-created",
"id", String.valueOf(result.getId())));
SoundUtil.playSound(player, plugin.getConfigManager().getSuccessSound());
player.closeInventory();
guiManager.openMainMenu(player);
} else {
// Creation failed AFTER we removed the items - give them back so nothing is lost.
ItemStack refund = listItem.clone();
refund.setAmount(amount);
for (ItemStack leftover : InventoryUtil.giveItemSplit(player, refund)) {
plugin.getClaimService().addClaimItem(player.getUniqueId(), leftover,
pt.henrique.communityMarket.model.ClaimItem.ClaimReason.ADMIN_RETURN,
"Listing creation failed");
}
player.sendMessage(msgManager.getPrefixed("messages." + result.getErrorKey()));
SoundUtil.playSound(player, plugin.getConfigManager().getErrorSound());
}
@@ -48,111 +48,24 @@ public class HelpGui implements MarketGui {
inventory.setItem(i, filler);
}
// Help content
// Help content (localized). Rendered as the book's lore so the Help screen
// respects the configured language instead of showing hardcoded English.
List<String> helpContent = msgManager.getList("help.content");
// Main help book
inventory.setItem(4, new ItemBuilder(Material.WRITTEN_BOOK)
// Main help book with the localized explanation of every feature
inventory.setItem(22, new ItemBuilder(Material.WRITTEN_BOOK)
.name(msgManager.getRaw("help.title"))
.lore(helpContent)
.build());
// Feature explanations
inventory.setItem(19, new ItemBuilder(Material.CHEST)
.name("&aBrowse Market")
.lore(
"&7View all fixed-price listings",
"&7from other players.",
"",
"&7Click on items to purchase them."
)
.build());
inventory.setItem(20, new ItemBuilder(Material.GOLD_INGOT)
.name("&6Browse Auctions")
.lore(
"&7View all active auctions.",
"",
"&eLeft-click &7to place a bid",
"&eRight-click &7to buyout (if available)"
)
.build());
inventory.setItem(21, new ItemBuilder(Material.WRITABLE_BOOK)
.name("&eCreate Listing")
.lore(
"&7Sell items at a fixed price.",
"",
"&71. Place your item in the slot",
"&72. Set the price",
"&73. Choose duration",
"&74. Click confirm"
)
.build());
inventory.setItem(22, new ItemBuilder(Material.GOLDEN_HELMET)
.name("&eCreate Auction")
.lore(
"&7Auction items to the highest bidder.",
"",
"&71. Place your item in the slot",
"&72. Set starting price",
"&73. Optionally set buyout",
"&74. Choose duration",
"&75. Click confirm"
)
.build());
inventory.setItem(23, new ItemBuilder(Material.BOOK)
.name("&bMy Listings")
.lore(
"&7View your active listings.",
"",
"&7Click on a listing to cancel it.",
"&7Cancelled items go to claim storage."
)
.build());
inventory.setItem(24, new ItemBuilder(Material.CLOCK)
.name("&bMy Auctions")
.lore(
"&7View your active auctions.",
"",
"&7You can only cancel auctions",
"&7that have no bids yet."
)
.build());
inventory.setItem(25, new ItemBuilder(Material.ENDER_CHEST)
.name("&dClaim Items")
.lore(
"&7Collect items waiting for you:",
"",
"&7- Expired listings",
"&7- Cancelled listings",
"&7- Won auctions",
"&7- Auction refunds"
)
.build());
inventory.setItem(31, new ItemBuilder(Material.EMERALD)
.name("&aEarnings")
.lore(
"&7Withdraw money from sales.",
"",
"&7When you sell something, the money",
"&7goes to pending earnings first.",
"&7Withdraw it here."
)
.build());
// Tax info
// Tax info (values are dynamic; labels come from the language file)
inventory.setItem(40, new ItemBuilder(Material.GOLD_NUGGET)
.name("&6Tax Information")
.name(msgManager.getRaw("help.tax-title"))
.lore(
"&7Market Tax: &f" + plugin.getConfigManager().getMarketTax() + "%",
"&7Auction Tax: &f" + plugin.getConfigManager().getAuctionTax() + "%",
msgManager.getRaw("help.tax-market").replace("{tax}", String.valueOf(plugin.getConfigManager().getMarketTax())),
msgManager.getRaw("help.tax-auction").replace("{tax}", String.valueOf(plugin.getConfigManager().getAuctionTax())),
"",
"&7Taxes are deducted from seller earnings."
msgManager.getRaw("help.tax-note")
)
.build());
@@ -229,9 +229,9 @@ public class ItemSelectionGui implements MarketGui {
itemWithQuantity.setAmount(quantity);
if (mode == SelectionMode.LISTING) {
guiManager.getCreateListingGui().openWithItem(player, playerInvSlot, itemWithQuantity);
new CreateListingGui(plugin, guiManager).openWithItem(player, playerInvSlot, itemWithQuantity);
} else {
guiManager.getCreateAuctionGui().openWithItem(player, playerInvSlot, itemWithQuantity);
new CreateAuctionGui(plugin, guiManager).openWithItem(player, playerInvSlot, itemWithQuantity);
}
} else {
// User cancelled - go back to item selection
@@ -244,9 +244,9 @@ public class ItemSelectionGui implements MarketGui {
singleItem.setAmount(1);
if (mode == SelectionMode.LISTING) {
guiManager.getCreateListingGui().openWithItem(player, playerInvSlot, singleItem);
new CreateListingGui(plugin, guiManager).openWithItem(player, playerInvSlot, singleItem);
} else {
guiManager.getCreateAuctionGui().openWithItem(player, playerInvSlot, singleItem);
new CreateAuctionGui(plugin, guiManager).openWithItem(player, playerInvSlot, singleItem);
}
}
}
@@ -80,7 +80,10 @@ public class MyListingsGui implements MarketGui {
var msgManager = plugin.getMessageManager();
ItemStack display = listing.getItem().clone();
display.setAmount(listing.getAmount());
// Display only: a count above the max stack size makes the stack resolve to
// empty since 26.1, so the icon would render as nothing. The real amount is
// in the lore.
display.setAmount(Math.min(listing.getAmount(), Math.max(1, display.getMaxStackSize())));
String expires;
if (listing.getExpiresAt() != null) {
@@ -112,9 +112,10 @@ public class QuantitySelectGui implements MarketGui {
)
.build());
// Item preview
// Item preview. Clamped: a count above the max stack size renders as an
// empty slot since 26.1. The chosen quantity is shown in the lore.
ItemStack displayItem = selectedItem.clone();
displayItem.setAmount(currentQuantity);
displayItem.setAmount(Math.min(currentQuantity, Math.max(1, displayItem.getMaxStackSize())));
inventory.setItem(ITEM_DISPLAY_SLOT, new ItemBuilder(displayItem)
.addLore(java.util.List.of(
"",
@@ -211,7 +212,7 @@ public class QuantitySelectGui implements MarketGui {
// Update item display amount
ItemStack displayItem = selectedItem.clone();
displayItem.setAmount(Math.min(currentQuantity, 64));
displayItem.setAmount(Math.min(currentQuantity, Math.max(1, displayItem.getMaxStackSize())));
inventory.setItem(ITEM_DISPLAY_SLOT, new ItemBuilder(displayItem)
.addLore(java.util.List.of(
"",
@@ -53,7 +53,9 @@ public class AuctionService {
return CompletableFuture.completedFuture(-1);
}
if (plugin.getConfigManager().isMaterialBlacklisted(item.getType())) {
// Last gate before persistence: applies the blacklist to the payload too,
// so a banned material cannot enter the market inside a container.
if (!plugin.getTransactionService().validateItem(item).isValid()) {
return CompletableFuture.completedFuture(-1);
}
@@ -305,27 +307,31 @@ public class AuctionService {
return CompletableFuture.completedFuture(CancelResult.HAS_BIDS);
}
// If admin cancelling with bids, refund highest bidder
if (isAdmin && auction.getBidCount() > 0 && auction.getHighestBidderUuid() != null) {
plugin.getEconomyManager().deposit(auction.getHighestBidderUuid(), auction.getCurrentBid());
}
// Update status
return plugin.getDatabaseManager().updateAuctionStatus(auctionId, Auction.AuctionStatus.CANCELLED)
// Atomically flip to CANCELLED only if still ACTIVE. This guarantees the
// refund + item return below run exactly once and never race with the
// periodic end-processing task (which would otherwise duplicate the item
// or hand the highest bidder both the item and a refund).
return plugin.getDatabaseManager().updateAuctionStatusIfActive(auctionId, Auction.AuctionStatus.CANCELLED)
.thenApply(success -> {
if (success) {
// Return item to claim storage
ClaimItem claimItem = new ClaimItem(
auction.getSellerUuid(),
auction.getItem().clone(),
ClaimItem.ClaimReason.CANCELLED_AUCTION,
"Auction #" + auctionId
);
plugin.getDatabaseManager().addClaimItem(claimItem);
invalidateCache();
return CancelResult.SUCCESS;
if (!success) {
return CancelResult.FAILED;
}
return CancelResult.FAILED;
// If admin cancelling with bids, refund highest bidder
if (isAdmin && auction.getBidCount() > 0 && auction.getHighestBidderUuid() != null) {
plugin.getEconomyManager().deposit(auction.getHighestBidderUuid(), auction.getCurrentBid());
}
// Return item to claim storage
ClaimItem claimItem = new ClaimItem(
auction.getSellerUuid(),
auction.getItem().clone(),
ClaimItem.ClaimReason.CANCELLED_AUCTION,
"Auction #" + auctionId
);
plugin.getDatabaseManager().addClaimItem(claimItem);
invalidateCache();
return CancelResult.SUCCESS;
});
});
}
@@ -350,17 +356,23 @@ public class AuctionService {
*/
private CompletableFuture<Void> processAuctionEnd(int auctionId) {
return getAuction(auctionId)
.thenAccept(optAuction -> {
if (optAuction.isEmpty()) return;
.thenCompose(optAuction -> {
if (optAuction.isEmpty()) return CompletableFuture.<Void>completedFuture(null);
Auction auction = optAuction.get();
// Update status first
// Determine terminal status
Auction.AuctionStatus newStatus = auction.getBidCount() > 0
? Auction.AuctionStatus.SOLD
: Auction.AuctionStatus.EXPIRED;
plugin.getDatabaseManager().updateAuctionStatus(auctionId, newStatus);
// Atomically claim the auction end: only the caller that flips the row
// away from ACTIVE proceeds to credit earnings / deliver the item. This
// makes end-processing idempotent and prevents duplication when the
// periodic task and a buyout (or two task runs) race on the same auction.
return plugin.getDatabaseManager().updateAuctionStatusIfActive(auctionId, newStatus)
.thenAccept(claimed -> {
if (!claimed) return;
if (auction.getBidCount() > 0 && auction.getHighestBidderUuid() != null) {
// Auction has a winner
@@ -432,6 +444,7 @@ public class AuctionService {
}
}
}
});
});
}
@@ -77,9 +77,10 @@ public class ClaimService {
// Give item to player on main thread
Bukkit.getScheduler().runTask(plugin, () -> {
ItemStack leftover = InventoryUtil.giveItem(player, claimItem.getItem());
if (leftover != null) {
// This shouldn't happen since we checked space, but just in case
// Every leftover stack is re-stored, not just the first:
// an item stored before the split fix can be several
// stacks wide and must not lose the tail.
for (ItemStack leftover : InventoryUtil.giveItemSplit(player, claimItem.getItem())) {
plugin.getDatabaseManager().addClaimItem(new ClaimItem(
player.getUniqueId(),
leftover,
@@ -116,8 +117,18 @@ public class ClaimService {
if (removed) {
// Give item on main thread
ItemStack itemToGive = item.getItem();
ClaimItem source = item;
Bukkit.getScheduler().runTask(plugin, () -> {
InventoryUtil.giveItem(player, itemToGive);
for (ItemStack leftover : InventoryUtil.giveItemSplit(player, itemToGive)) {
// Inventory filled up mid-claim: put the remainder back into
// claim storage instead of silently destroying the items.
plugin.getDatabaseManager().addClaimItem(new ClaimItem(
player.getUniqueId(),
leftover,
source.getReason(),
source.getSourceInfo()
));
}
});
claimed++;
}
@@ -52,7 +52,9 @@ public class ListingService {
return CompletableFuture.completedFuture(-1);
}
if (plugin.getConfigManager().isMaterialBlacklisted(item.getType())) {
// Last gate before persistence: applies the blacklist to the payload too,
// so a banned material cannot enter the market inside a container.
if (!plugin.getTransactionService().validateItem(item).isValid()) {
return CompletableFuture.completedFuture(-1);
}
@@ -229,17 +231,19 @@ public class ListingService {
Bukkit.getScheduler().runTask(plugin, () -> {
ItemStack item = listing.getItem().clone();
item.setAmount(listing.getAmount());
ItemStack leftover = InventoryUtil.giveItem(buyer, item);
java.util.List<ItemStack> leftovers = InventoryUtil.giveItemSplit(buyer, item);
if (leftover != null) {
// Couldn't fit in inventory, add to claim storage
ClaimItem claimItem = new ClaimItem(
buyer.getUniqueId(),
leftover,
ClaimItem.ClaimReason.PURCHASE_FULL_INVENTORY,
"Listing #" + listingId
);
plugin.getDatabaseManager().addClaimItem(claimItem);
if (!leftovers.isEmpty()) {
// Couldn't fit in inventory, add to claim storage.
// Every leftover stack is stored, not just the first.
for (ItemStack leftover : leftovers) {
plugin.getDatabaseManager().addClaimItem(new ClaimItem(
buyer.getUniqueId(),
leftover,
ClaimItem.ClaimReason.PURCHASE_FULL_INVENTORY,
"Listing #" + listingId
));
}
buyer.sendMessage(plugin.getMessageManager().getPrefixed("messages.claim-inventory-full"));
}
});
@@ -291,8 +295,9 @@ public class ListingService {
return CompletableFuture.completedFuture(false);
}
// Update status
return plugin.getDatabaseManager().updateListingStatus(listingId, Listing.ListingStatus.CANCELLED)
// Update status atomically (only if still ACTIVE) so a concurrent
// purchase/expiry can never both deliver the item AND return it here.
return plugin.getDatabaseManager().updateListingStatusIfActive(listingId, Listing.ListingStatus.CANCELLED)
.thenApply(success -> {
if (success) {
// Return item to claim storage
@@ -319,8 +324,9 @@ public class ListingService {
return plugin.getDatabaseManager().getExpiredListings()
.thenAccept(listings -> {
for (Listing listing : listings) {
// Update status to expired
plugin.getDatabaseManager().updateListingStatus(listing.getId(), Listing.ListingStatus.EXPIRED)
// Update status to expired atomically (only if still ACTIVE) so a
// concurrent purchase can't both sell the item and return it to claim.
plugin.getDatabaseManager().updateListingStatusIfActive(listing.getId(), Listing.ListingStatus.EXPIRED)
.thenAccept(success -> {
if (success) {
// Return item to claim storage
@@ -3,6 +3,7 @@ package pt.henrique.communityMarket.service;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import pt.henrique.communityMarket.CommunityMarket;
import pt.henrique.communityMarket.util.ContainerItemUtil;
import java.util.concurrent.CompletableFuture;
@@ -22,6 +23,11 @@ public class TransactionService {
/**
* Validates an item before it can be listed or auctioned.
* Checks material blacklist, keywords in name/lore, and other restrictions.
* <p>
* Prices here are set by the seller and the item is transferred intact, so a
* loaded container is not refused. What is refused is a banned material or a
* banned lore keyword hidden inside a shulker box, a bundle, a sulfur cube
* bucket or a crossbow, so every rule is applied to the payload as well.
*
* @param item The item to validate
* @return ValidationResult with success status and error message if applicable
@@ -31,6 +37,23 @@ public class TransactionService {
return new ValidationResult(false, "invalid-item");
}
ValidationResult own = validateSingleStack(item);
if (!own.isValid()) return own;
for (ItemStack nested : ContainerItemUtil.flattenPayload(item)) {
ValidationResult inner = validateSingleStack(nested);
if (!inner.isValid()) return inner;
}
return new ValidationResult(true, null);
}
/** Applies the blacklist rules to one stack, ignoring anything it contains. */
private ValidationResult validateSingleStack(ItemStack item) {
if (item == null || item.getType().isAir()) {
return new ValidationResult(true, null);
}
// Check material blacklist
if (plugin.getConfigManager().isMaterialBlacklisted(item.getType())) {
return new ValidationResult(false, "blacklisted-item");
@@ -0,0 +1,227 @@
package pt.henrique.communityMarket.util;
import io.papermc.paper.datacomponent.DataComponentTypes;
import io.papermc.paper.datacomponent.item.BundleContents;
import io.papermc.paper.datacomponent.item.ChargedProjectiles;
import io.papermc.paper.datacomponent.item.ItemContainerContents;
import io.papermc.paper.datacomponent.item.SulfurCubeContent;
import org.bukkit.block.ShulkerBox;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BlockStateMeta;
import org.bukkit.inventory.meta.BundleMeta;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* Single answer to "does this stack contain other stacks, and if so which ones".
* <p>
* As of 26.2 an {@link ItemStack} can carry other stacks in four distinct ways,
* none of which share an API:
* <ol>
* <li>Shulker boxes and other block-entity items: {@link BlockStateMeta} whose
* block state is a container, or the {@code minecraft:container} component.</li>
* <li>Bundles: {@link BundleMeta#getItems()} / {@code minecraft:bundle_contents}.</li>
* <li>{@code SULFUR_CUBE_BUCKET}: {@code minecraft:sulfur_cube_content}, reached
* through {@link SulfurCubeContent#absorbedItem()}. Neither a
* {@link BlockStateMeta} nor a {@link BundleMeta}.</li>
* <li>Crossbows: {@code minecraft:charged_projectiles}.</li>
* </ol>
* The server's own {@code ItemStack.validateComponents} recurses into
* {@code CONTAINER}, {@code BUNDLE_CONTENTS} and {@code CHARGED_PROJECTILES} but
* <b>not</b> {@code SULFUR_CUBE_CONTENT}, so a sulfur cube bucket payload is never
* sanitised by the server. Every pricing, selling, listing and anti-dupe check must
* go through {@link #payloadOf(ItemStack)} rather than testing for a shulker box.
* <p>
* The shulker-box read/rewrite helpers below stay shulker-specific: they back the
* three-option shulker sell flow, which needs the 27-slot inventory shape. Buckets,
* bundles and crossbows have no such shape and are never opened, only refused.
*/
public final class ContainerItemUtil {
/** Number of slots inside a shulker box. */
public static final int SHULKER_SIZE = 27;
/**
* Levels of nesting inspected by {@link #flattenPayload(ItemStack)}.
* Vanilla forbids shulker-in-shulker, so one level is enough today; the cap
* exists so a datapack or plugin that deepens the nesting cannot walk past
* the guard, and so a malformed cyclic payload cannot loop forever.
*/
public static final int MAX_NESTING_DEPTH = 3;
private ContainerItemUtil() {}
// ══════════════════════════════════════════════════════════════
// General nesting
// ══════════════════════════════════════════════════════════════
/**
* Returns the stacks held directly inside this one, across all four nesting
* classes. Empty when the stack holds nothing or is not a container.
* The returned stacks are the live snapshots handed back by the API; callers
* that keep them should clone.
*/
public static List<ItemStack> payloadOf(ItemStack stack) {
if (stack == null || stack.getType().isAir()) return List.of();
List<ItemStack> out = new ArrayList<>();
// getItemMeta() clones, and this runs once per inventory slot in the sell
// scans, so the meta routes are gated on the type name first. The component
// checks below are cheap map lookups and cover everything the gate misses,
// including block-entity items that are not shulker boxes.
String typeName = stack.getType().name();
if (typeName.endsWith("SHULKER_BOX")) {
if (stack.getItemMeta() instanceof BlockStateMeta bsm
&& bsm.getBlockState() instanceof ShulkerBox box) {
addNonEmpty(out, box.getInventory().getContents());
}
} else if (typeName.endsWith("BUNDLE")) {
if (stack.getItemMeta() instanceof BundleMeta bundle) {
addNonEmpty(out, bundle.getItems());
}
}
if (out.isEmpty() && stack.hasData(DataComponentTypes.CONTAINER)) {
ItemContainerContents container = stack.getData(DataComponentTypes.CONTAINER);
if (container != null) addNonEmpty(out, container.contents());
}
if (out.isEmpty() && stack.hasData(DataComponentTypes.BUNDLE_CONTENTS)) {
BundleContents bundle = stack.getData(DataComponentTypes.BUNDLE_CONTENTS);
if (bundle != null) addNonEmpty(out, bundle.contents());
}
if (stack.hasData(DataComponentTypes.SULFUR_CUBE_CONTENT)) {
SulfurCubeContent cube = stack.getData(DataComponentTypes.SULFUR_CUBE_CONTENT);
if (cube != null) addNonEmpty(out, List.of(cube.absorbedItem()));
}
if (stack.hasData(DataComponentTypes.CHARGED_PROJECTILES)) {
ChargedProjectiles charged = stack.getData(DataComponentTypes.CHARGED_PROJECTILES);
if (charged != null) addNonEmpty(out, charged.projectiles());
}
return out;
}
/**
* True when this stack carries other stacks. Such items are refused by every
* server-shop path: their payload has no price and would be destroyed with the
* container, and a container priced as empty is a value-laundering route.
*/
public static boolean isNestingItemWithContents(ItemStack stack) {
return !payloadOf(stack).isEmpty();
}
/**
* Every stack reachable from this one, breadth-first, down to
* {@link #MAX_NESTING_DEPTH} levels. The stack itself is not included.
* Used by the blacklist checks, which must see a banned material or a banned
* lore keyword wherever it is hidden.
*/
public static List<ItemStack> flattenPayload(ItemStack stack) {
List<ItemStack> out = new ArrayList<>();
Deque<ItemStack> frontier = new ArrayDeque<>(payloadOf(stack));
int depth = 0;
while (!frontier.isEmpty() && depth < MAX_NESTING_DEPTH) {
int levelSize = frontier.size();
for (int i = 0; i < levelSize; i++) {
ItemStack current = frontier.poll();
if (current == null) continue;
out.add(current);
if (depth + 1 < MAX_NESTING_DEPTH) frontier.addAll(payloadOf(current));
}
depth++;
}
return out;
}
/** Total number of items (summed amounts) held inside this stack, one level deep. */
public static int countTotalItems(ItemStack stack) {
int total = 0;
for (ItemStack c : payloadOf(stack)) total += c.getAmount();
return total;
}
/** Number of occupied slots inside this stack, one level deep. */
public static int countNonEmptySlots(ItemStack stack) {
return payloadOf(stack).size();
}
// ══════════════════════════════════════════════════════════════
// Shulker boxes: read and rewrite
// ══════════════════════════════════════════════════════════════
/** @return true if the stack is any shulker box (all 16 colors + uncolored). */
public static boolean isShulkerBox(ItemStack stack) {
return stack != null && !stack.getType().isAir()
&& stack.getType().name().endsWith("SHULKER_BOX");
}
/**
* Returns the shulker's internal contents as a detached snapshot array.
* {@code getBlockState()} returns a copy, so reading never mutates the original
* item. Returns an empty array if the stack is not a shulker box.
*/
public static ItemStack[] getContents(ItemStack shulker) {
if (!isShulkerBox(shulker)) return new ItemStack[0];
if (!(shulker.getItemMeta() instanceof BlockStateMeta bsm)) return new ItemStack[0];
if (!(bsm.getBlockState() instanceof ShulkerBox box)) return new ItemStack[0];
return box.getInventory().getContents();
}
/** @return true if the shulker box contains at least one item. */
public static boolean hasContents(ItemStack shulker) {
for (ItemStack c : getContents(shulker)) {
if (c != null && !c.getType().isAir()) return true;
}
return false;
}
/** Returns a clone of the shulker with its internal inventory emptied. */
public static ItemStack emptiedClone(ItemStack shulker) {
ItemStack clone = shulker.clone();
if (clone.getItemMeta() instanceof BlockStateMeta bsm
&& bsm.getBlockState() instanceof ShulkerBox box) {
box.getInventory().clear();
bsm.setBlockState(box);
clone.setItemMeta(bsm);
}
return clone;
}
/**
* Returns a clone of the shulker whose internal contents are replaced by the
* given array (length must be at most {@link #SHULKER_SIZE}; shorter arrays
* clear the remaining slots).
*/
public static ItemStack withContents(ItemStack shulker, ItemStack[] newContents) {
ItemStack clone = shulker.clone();
if (clone.getItemMeta() instanceof BlockStateMeta bsm
&& bsm.getBlockState() instanceof ShulkerBox box) {
box.getInventory().setContents(newContents);
bsm.setBlockState(box);
clone.setItemMeta(bsm);
}
return clone;
}
// ══════════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════════
private static void addNonEmpty(List<ItemStack> out, ItemStack[] items) {
if (items == null) return;
for (ItemStack i : items) {
if (i != null && !i.getType().isAir()) out.add(i);
}
}
private static void addNonEmpty(List<ItemStack> out, List<ItemStack> items) {
if (items == null) return;
for (ItemStack i : items) {
if (i != null && !i.getType().isAir()) out.add(i);
}
}
}
@@ -6,6 +6,7 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import pt.henrique.communityMarket.CommunityMarket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -51,24 +52,73 @@ public class InventoryUtil {
}
/**
* Gives an item to a player, returning any items that couldn't fit
* Splits a stack into legally-sized stacks.
* <p>
* Since 26.1 an {@link ItemStack} whose count exceeds its max stack size is
* treated as empty by the server, so a "give 320 dirt" shortcut built as one
* stack hands the player nothing. Anything that multiplies a quantity into a
* single stack must route through this first. The input amount is used as the
* total; the returned stacks are clones.
*
* @return one or more stacks, each within its max stack size; empty for air
*/
public static List<ItemStack> splitIntoLegalStacks(ItemStack item) {
if (item == null || item.getType().isAir() || item.getAmount() <= 0) {
return List.of();
}
int maxStack = Math.max(1, item.getMaxStackSize());
if (item.getAmount() <= maxStack) {
return List.of(item.clone());
}
List<ItemStack> out = new ArrayList<>();
for (int left = item.getAmount(); left > 0; left -= maxStack) {
ItemStack part = item.clone();
part.setAmount(Math.min(left, maxStack));
out.add(part);
}
return out;
}
/** @return true when the stack's count is within its max stack size. */
public static boolean isLegalStack(ItemStack item) {
return item == null || item.getType().isAir()
|| item.getAmount() <= Math.max(1, item.getMaxStackSize());
}
/**
* Gives an item to a player, returning any items that couldn't fit.
* The item is split into legal stacks first, so an oversized input is handed
* over in full instead of resolving to nothing.
*
* @param player The player
* @param item The item to give
* @return Items that couldn't fit, or null if all items were added
*/
public static ItemStack giveItem(Player player, ItemStack item) {
if (item == null || item.getType().isAir()) {
return null;
List<ItemStack> leftovers = giveItemSplit(player, item);
return leftovers.isEmpty() ? null : leftovers.get(0);
}
/**
* Gives an item to a player as legal stacks.
*
* @return every stack that did not fit, each within its max stack size
*/
public static List<ItemStack> giveItemSplit(Player player, ItemStack item) {
List<ItemStack> parts = splitIntoLegalStacks(item);
if (parts.isEmpty()) {
return List.of();
}
HashMap<Integer, ItemStack> leftover = player.getInventory().addItem(item.clone());
HashMap<Integer, ItemStack> leftover =
player.getInventory().addItem(parts.toArray(new ItemStack[0]));
if (leftover.isEmpty()) {
return null;
return List.of();
}
return leftover.values().iterator().next();
return new ArrayList<>(leftover.values());
}
/**
@@ -87,7 +137,12 @@ public class InventoryUtil {
ItemStack toRemove = item.clone();
toRemove.setAmount(amount);
HashMap<Integer, ItemStack> notRemoved = player.getInventory().removeItem(toRemove);
// Split first: an over-full stack is treated as empty since 26.1, so a
// single oversized removal request could take nothing while reporting
// success.
List<ItemStack> parts = splitIntoLegalStacks(toRemove);
HashMap<Integer, ItemStack> notRemoved =
player.getInventory().removeItem(parts.toArray(new ItemStack[0]));
return notRemoved.isEmpty();
}
@@ -38,8 +38,20 @@ public class ItemBuilder {
/**
* Creates a new ItemBuilder from an existing ItemStack
*/
/**
* Wraps an existing stack as a GUI icon.
* <p>
* The count is clamped to the item's max stack size. Builder output only ever
* goes into plugin GUI inventories, never to a player, and since 26.1 an
* over-full stack resolves to empty, which would render the icon as a blank
* slot. Real quantities are shown in the lore.
*/
public ItemBuilder(ItemStack item) {
this.item = item.clone();
int maxStack = Math.max(1, this.item.getMaxStackSize());
if (this.item.getAmount() > maxStack) {
this.item.setAmount(maxStack);
}
this.meta = this.item.getItemMeta();
}
@@ -115,7 +127,7 @@ public class ItemBuilder {
* Sets the item amount
*/
public ItemBuilder amount(int amount) {
item.setAmount(Math.min(64, Math.max(1, amount)));
item.setAmount(Math.min(Math.max(1, item.getMaxStackSize()), Math.max(1, amount)));
return this;
}
+1 -1
View File
@@ -4,7 +4,7 @@
# ============================================
# Language setting (available: en_US, pt_PT)
language: en_US
language: pt_PT
# Database Configuration
database:
+8
View File
@@ -45,12 +45,16 @@ messages:
claim-empty: "&eYou have no items to claim."
claim-inventory-full: "&cYour inventory is full! Please make space."
claim-all-success: "&aClaimed {count} items!"
claim-items: "&eYou have &6{count}&e item(s) waiting to be claimed. Use /market to claim them."
# Earnings Messages
earnings-withdrawn: "&aWithdrew {amount}! New balance: {balance}"
earnings-empty: "&eYou have no pending earnings."
earnings-balance: "&aYour pending earnings: {amount}"
# Generic
failed: "&cSomething went wrong. Please try again."
# Item Validation
invalid-item: "&cPlease select a valid item."
item-no-longer-available: "&cThe selected item is no longer in your inventory."
@@ -445,4 +449,8 @@ help:
- ""
- "&7&oTip: All actions are done through GUIs!"
- "&7&oJust click on buttons to navigate."
tax-title: "&6Tax Information"
tax-market: "&7Market Tax: &f{tax}%"
tax-auction: "&7Auction Tax: &f{tax}%"
tax-note: "&7Taxes are deducted from seller earnings."
+8
View File
@@ -45,12 +45,16 @@ messages:
claim-empty: "&eNão tens itens para reclamar."
claim-inventory-full: "&cO teu inventário está cheio! Por favor liberta espaço."
claim-all-success: "&aReclamaste {count} itens!"
claim-items: "&eTens &6{count}&e item(ns) por reclamar. Usa /market para os reclamar."
# Mensagens de Ganhos
earnings-withdrawn: "&aLevantaste {amount}! Novo saldo: {balance}"
earnings-empty: "&eNão tens ganhos pendentes."
earnings-balance: "&aOs teus ganhos pendentes: {amount}"
# Genérico
failed: "&cAlgo correu mal. Tenta novamente."
# Validação de Itens
invalid-item: "&cPor favor seleciona um item válido."
item-no-longer-available: "&cO item selecionado já não está no teu inventário."
@@ -445,4 +449,8 @@ help:
- ""
- "&7&oDica: Todas as ações são feitas através de GUIs!"
- "&7&oBasta clicar nos botões para navegar."
tax-title: "&6Informação de Taxas"
tax-market: "&7Taxa do Mercado: &f{tax}%"
tax-auction: "&7Taxa dos Leilões: &f{tax}%"
tax-note: "&7As taxas são deduzidas dos ganhos do vendedor."
+3 -19
View File
@@ -1,10 +1,10 @@
name: CommunityMarket
version: '${project.version}'
main: pt.henrique.communityMarket.CommunityMarket
api-version: '1.21'
api-version: "26.3"
description: A GUI-only marketplace plugin for fixed-price listings and auctions
author: Henrique
website: https://github.com/henrique/CommunityMarket
website: https://github.com/henriquescrrrr/carrageis-communitymarket
# Soft dependencies - plugin will detect and use these if available
softdepend:
@@ -63,21 +63,5 @@ permissions:
default: true
communitymarket.admin:
description: Allows access to admin functions
default: op
children:
communitymarket.admin.viewall: true
communitymarket.admin.remove: true
communitymarket.admin.reload: true
communitymarket.admin.viewall:
description: Allows viewing all listings/auctions
default: op
communitymarket.admin.remove:
description: Allows removing any listing or auction
default: op
communitymarket.admin.reload:
description: Allows reloading configuration
description: Allows access to admin functions (view all, remove listings, reload)
default: op
-152
View File
@@ -1,152 +0,0 @@
# ============================================
# CommunityMarket Configuration
# A GUI-only marketplace plugin
# ============================================
# Language setting (available: en_US, pt_PT)
language: en_US
# Database Configuration
database:
# Type: sqlite or mysql
type: sqlite
sqlite:
file: database.db
mysql:
host: localhost
port: 3306
database: communitymarket
username: root
password: ""
pool:
maximum-pool-size: 10
minimum-idle: 2
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# Economy Settings
economy:
# Currency display format (uses Java DecimalFormat)
currency-format: "$#,##0.00"
currency-symbol: "$"
taxes:
# Tax percentage for fixed-price market sales (seller pays)
market-tax: 5.0
# Tax percentage for auction sales (seller pays)
auction-tax: 7.5
# Fixed-Price Market Settings
market:
# Maximum active listings per player
max-listings-per-player: 20
# Cooldown between creating listings (seconds, 0 = disabled)
listing-cooldown: 0
# Default listing duration in hours
default-duration-hours: 168
# Available durations for players to choose (in hours)
available-durations:
- 24
- 72
- 168
- 336
# Price limits
min-price: 1.0
max-price: 1000000000.0
# Auction Settings
auction:
# Maximum active auctions per player
max-auctions-per-player: 10
# Duration limits (hours)
min-duration-hours: 1
max-duration-hours: 168
default-duration-hours: 24
# Available durations for players to choose (in hours)
available-durations:
- 1
- 6
- 12
- 24
- 48
- 72
- 168
# Price limits for starting bid
min-start-price: 1.0
max-start-price: 1000000000.0
# Minimum bid increment (percentage of current bid)
min-bid-increment-percent: 5.0
# Minimum absolute bid increment
min-bid-increment-absolute: 1.0
# Anti-snipe protection
anti-snipe:
enabled: true
# If bid placed within this many seconds of end, extend auction
trigger-seconds: 30
# How many seconds to extend
extension-seconds: 30
# Maximum number of extensions (0 = unlimited)
max-extensions: 10
# Item Blacklist
blacklist:
# Materials that cannot be listed/auctioned
materials:
- BARRIER
- COMMAND_BLOCK
- CHAIN_COMMAND_BLOCK
- REPEATING_COMMAND_BLOCK
- COMMAND_BLOCK_MINECART
- STRUCTURE_BLOCK
- STRUCTURE_VOID
- JIGSAW
- DEBUG_STICK
- KNOWLEDGE_BOOK
- SPAWNER
- BEDROCK
# Items with these keywords in their name/lore are blocked
keywords:
- "admin"
- "illegal"
- "exploit"
# GUI Settings
gui:
# Items displayed per page in browse views
items-per-page: 45
# Whether to show the Help button in the main menu
# Set to false to hide it (slot will be filled with glass)
show-help-button: true
# Sound effects (use Bukkit Sound enum names)
sounds:
click: UI_BUTTON_CLICK
success: ENTITY_PLAYER_LEVELUP
error: ENTITY_VILLAGER_NO
purchase: ENTITY_EXPERIENCE_ORB_PICKUP
# Notification Settings
notifications:
# Notify seller when their item sells
notify-on-sale: true
# Notify bidder when they are outbid
notify-on-outbid: true
# Notify winner when they win an auction
notify-on-win: true
# Notify seller when their listing expires
notify-on-expire: true
# Performance Settings
performance:
# How often to cache listings/auctions (seconds)
cache-duration: 30
# How often to check for ended auctions (seconds)
auction-check-interval: 5
# How often to check for expired listings (minutes)
expired-check-interval: 5
-448
View File
@@ -1,448 +0,0 @@
# ============================================
# CommunityMarket Language File - English (US)
# ============================================
# General
prefix: "&8[&6Market&8] &r"
# General Messages
messages:
no-permission: "&cYou don't have permission to do that."
player-only: "&cThis command can only be used by players."
reload-success: "&aConfiguration reloaded successfully!"
economy-not-found: "&cNo economy plugin found! Market disabled."
# Listing Messages
listing-created: "&aListing created successfully! ID: #{id}"
listing-cancelled: "&aListing cancelled. Item returned to claim storage."
listing-expired: "&eYour listing #{id} has expired. Item moved to claim storage."
listing-purchased: "&aYou purchased {item} x{amount} for {price}!"
listing-sold: "&aYour {item} x{amount} was sold to {buyer} for {price}!"
listing-limit-reached: "&cYou've reached the maximum number of listings ({max})."
listing-cooldown: "&cPlease wait {time} before creating another listing."
listing-not-found: "&cListing not found or no longer available."
listing-own-item: "&cYou cannot buy your own listing."
listing-insufficient-funds: "&cYou don't have enough money. Required: {price}"
# Auction Messages
auction-created: "&aAuction created successfully! ID: #{id}"
auction-cancelled: "&aAuction cancelled. Item returned to claim storage."
auction-ended-winner: "&aCongratulations! You won the auction for {item}! Paid: {price}"
auction-ended-seller: "&aYour auction for {item} ended! Winner: {winner}, Earned: {price}"
auction-ended-no-bids: "&eYour auction for {item} ended with no bids. Item moved to claim storage."
auction-limit-reached: "&cYou've reached the maximum number of auctions ({max})."
auction-not-found: "&cAuction not found or no longer available."
auction-own-item: "&cYou cannot bid on your own auction."
auction-bid-placed: "&aYou placed a bid of {amount} on {item}!"
auction-outbid: "&eYou've been outbid on {item}! New bid: {amount} by {bidder}"
auction-bid-too-low: "&cBid too low! Minimum bid: {min}"
auction-insufficient-funds: "&cYou don't have enough money. Required: {price}"
auction-buyout: "&aYou bought out the auction for {item} for {price}!"
auction-extended: "&eAuction extended by {seconds}s due to anti-snipe protection."
# Claim Messages
claim-success: "&aItem claimed successfully!"
claim-empty: "&eYou have no items to claim."
claim-inventory-full: "&cYour inventory is full! Please make space."
claim-all-success: "&aClaimed {count} items!"
# Earnings Messages
earnings-withdrawn: "&aWithdrew {amount}! New balance: {balance}"
earnings-empty: "&eYou have no pending earnings."
earnings-balance: "&aYour pending earnings: {amount}"
# Item Validation
invalid-item: "&cPlease select a valid item."
item-no-longer-available: "&cThe selected item is no longer in your inventory."
item-changed: "&cThe selected item has changed. Please select again."
quantity-changed: "&cThe available quantity has changed. Please verify and try again."
blacklisted-item: "&cThis item type is not allowed on the market."
blacklisted-content: "&cThis item contains blacklisted content."
invalid-price: "&cInvalid price. Range: {min} - {max}"
invalid-amount: "&cInvalid amount."
invalid-duration: "&cInvalid duration."
# Admin Messages
admin-listing-removed: "&aListing #{id} removed by admin."
admin-auction-cancelled: "&aAuction #{id} cancelled by admin."
admin-reload: "&aConfiguration reloaded."
# GUI Titles (support color codes)
gui-titles:
main-menu: "&8&lCommunity Market"
browse-market: "&8&lBrowse Market &7(Page {page})"
browse-auctions: "&8&lBrowse Auctions &7(Page {page})"
create-listing: "&8&lCreate Listing"
create-auction: "&8&lCreate Auction"
select-item-listing: "&8&lSelect Item to Sell"
select-item-auction: "&8&lSelect Item to Auction"
quantity-select: "&8&lSelect Quantity"
my-listings: "&8&lMy Listings"
my-auctions: "&8&lMy Auctions"
claim-items: "&8&lClaim Items"
earnings: "&8&lEarnings"
confirm-purchase: "&8&lConfirm Purchase"
confirm-bid: "&8&lConfirm Bid"
confirm-cancel: "&8&lConfirm Cancellation"
number-input: "&8&lEnter Amount"
admin-panel: "&8&lAdmin Panel"
admin-listings: "&8&lAll Listings"
admin-auctions: "&8&lAll Auctions"
listing-details: "&8&lListing Details"
auction-details: "&8&lAuction Details"
filter-menu: "&8&lFilter Options"
sort-menu: "&8&lSort Options"
duration-select: "&8&lSelect Duration"
help: "&8&lHelp"
# Button Names
buttons:
# Main Menu
browse-market: "&aBrowse Market"
browse-auctions: "&6Browse Auctions"
create-listing: "&eCreate Listing"
create-auction: "&eCreate Auction"
my-listings: "&bMy Listings"
my-auctions: "&bMy Auctions"
claim-items: "&dClaim Items"
earnings: "&aEarnings"
help: "&fHelp"
admin: "&cAdmin Panel"
# Navigation
next-page: "&aNext Page →"
previous-page: "&a← Previous Page"
back: "&cBack"
close: "&cClose"
# Actions
confirm: "&aConfirm"
cancel: "&cCancel"
buy: "&aBuy Now"
bid: "&6Place Bid"
buyout: "&eBuyout"
claim: "&aClaim"
claim-all: "&aClaim All"
withdraw: "&aWithdraw All"
remove: "&cRemove Listing"
cancel-auction: "&cCancel Auction"
# Number Input
add-1: "&a+1"
add-10: "&a+10"
add-100: "&a+100"
add-1000: "&a+1,000"
subtract-1: "&c-1"
subtract-10: "&c-10"
subtract-100: "&c-100"
subtract-1000: "&c-1,000"
set-min: "&eSet Min"
set-max: "&eSet Max"
custom-amount: "&bCustom Amount"
# Filters & Sort
filter: "&eFilter"
sort: "&eSort"
search: "&eSearch"
clear-filter: "&cClear Filters"
# Duration
duration-1h: "&e1 Hour"
duration-6h: "&e6 Hours"
duration-12h: "&e12 Hours"
duration-24h: "&e24 Hours"
duration-48h: "&e48 Hours"
duration-72h: "&e3 Days"
duration-168h: "&e7 Days"
duration-336h: "&e14 Days"
# Admin
admin-view-listings: "&aView All Listings"
admin-view-auctions: "&6View All Auctions"
admin-reload: "&eReload Config"
# Button Lore (descriptions)
lore:
browse-market:
- "&7Browse all fixed-price"
- "&7listings from players."
- ""
- "&eClick to browse!"
browse-auctions:
- "&7Browse all active auctions"
- "&7and place bids."
- ""
- "&eClick to browse!"
create-listing:
- "&7Sell items at a fixed price."
- "&7Tax: &f{tax}%"
- ""
- "&eClick to create!"
create-auction:
- "&7Auction items to the"
- "&7highest bidder."
- "&7Tax: &f{tax}%"
- ""
- "&eClick to create!"
my-listings:
- "&7View and manage your"
- "&7active listings."
- ""
- "&7Active: &f{count}/{max}"
- ""
- "&eClick to view!"
my-auctions:
- "&7View and manage your"
- "&7active auctions."
- ""
- "&7Active: &f{count}/{max}"
- ""
- "&eClick to view!"
claim-items:
- "&7Claim items from expired"
- "&7listings or won auctions."
- ""
- "&7Pending: &f{count}"
- ""
- "&eClick to claim!"
earnings:
- "&7View and withdraw your"
- "&7pending earnings from sales."
- ""
- "&7Pending: &a{amount}"
- ""
- "&eClick to view!"
help:
- "&7Learn how to use the"
- "&7Community Market."
- ""
- "&eClick for help!"
admin:
- "&cAdmin Panel"
- "&7Manage listings and auctions."
- ""
- "&eClick to open!"
# Listing Info
listing-info:
- "&7Seller: &f{seller}"
- "&7Price: &a{price}"
- "&7Amount: &f{amount}"
- "&7Expires: &f{expires}"
- ""
- "&eLeft-click to buy!"
# Auction Info
auction-info:
- "&7Seller: &f{seller}"
- "&7Starting bid: &a{start_price}"
- "&7Current bid: &a{current_bid}"
- "&7Bidder: &f{bidder}"
- "&7Bids: &f{bid_count}"
- "&7Ends: &f{ends}"
- ""
- "&eLeft-click to bid!"
- "&eRight-click to buyout!"
# My Listing Info
my-listing-info:
- "&7Price: &a{price}"
- "&7Amount: &f{amount}"
- "&7Created: &f{created}"
- "&7Expires: &f{expires}"
- ""
- "&cClick to cancel"
# My Auction Info
my-auction-info:
- "&7Starting bid: &a{start_price}"
- "&7Current bid: &a{current_bid}"
- "&7Bidder: &f{bidder}"
- "&7Bids: &f{bid_count}"
- "&7Ends: &f{ends}"
- ""
- "&cClick to cancel (if no bids)"
# Confirm Purchase
confirm-purchase-info:
- "&7You are purchasing:"
- "&f{item} x{amount}"
- ""
- "&7Price: &a{price}"
- "&7Tax: &e{tax}"
- "&7Total: &a{total}"
- ""
- "&aClick to confirm!"
# Confirm Bid
confirm-bid-info:
- "&7You are bidding on:"
- "&f{item}"
- ""
- "&7Your bid: &a{bid}"
- "&7Current high: &e{current}"
- ""
- "&aClick to confirm!"
# Claim Item
claim-item-info:
- "&7Reason: &f{reason}"
- "&7From: &f{source}"
- "&7Date: &f{date}"
- ""
- "&eClick to claim!"
# Earnings Info
earnings-info:
- "&7Your pending earnings"
- "&7from market sales."
- ""
- "&7Total: &a{amount}"
- ""
- "&aClick to withdraw!"
# Number Input Info
current-value:
- "&7Current: &a{value}"
# Filter Options
filters:
all: "&fAll Items"
weapons: "&cWeapons"
armor: "&bArmor"
tools: "&eTools"
blocks: "&7Blocks"
food: "&6Food"
potions: "&dPotions"
materials: "&aMaterials"
enchanted: "&5Enchanted Items"
misc: "&8Miscellaneous"
# Sort Options
sort:
newest: "&aNewest First"
oldest: "&eOldest First"
price-low: "&aPrice: Low to High"
price-high: "&cPrice: High to Low"
ending-soon: "&6Ending Soon"
most-bids: "&bMost Bids"
# Time Formats
time:
expired: "&cExpired"
days: "{d}d"
hours: "{h}h"
minutes: "{m}m"
seconds: "{s}s"
# Quantity Selector GUI
quantity-select:
title: "&6&lSelect Quantity"
info-line-1: "&7Choose how many items"
info-line-2: "&7you want to sell."
available: "&7Available: &f{amount}"
selected: "&7Selected: &f{amount}"
quantity-label: "Quantity"
minimum: "&7Minimum: &f{amount}"
maximum: "&7Maximum: &f{amount}"
use-buttons: "&eUse buttons to adjust"
click-adjust: "&7Click: &e{amount}"
set-minimum: "&6Set Minimum"
set-maximum: "&6Set Maximum"
set-to: "&7Set to: &f{amount}"
back-lore: "&7Return to item selection"
confirm-lore: "&7Quantity: &a{amount}"
# Item Selection GUI
item-selection:
info-title: "&fSelect an Item"
info-lore-listing: "&7Click on an item from your|&7inventory to create a &eListing&7."
info-lore-auction: "&7Click on an item from your|&7inventory to create a &6Auction&7."
blacklisted-note: "&7Blacklisted items are shown in red."
click-to-select: "&a► Click to select"
blocked-title: "&c{material}"
blocked-lore-1: "&7This item cannot be listed."
blocked-lore-2: "&cBlacklisted or invalid."
back-lore: "&7Return to main menu"
# Create Listing GUI
create-listing:
info-title: "&6&lCreate Listing"
info-lore-1: "&7Set a price and duration"
info-lore-2: "&7for your listing."
tax-info: "&7Tax: &f{tax}%"
item-lore: "&7Quantity: &f{amount}|&eThis item will be listed"
price-title: "&6Price: {price}"
price-tax: "&7Tax ({percent}%): &c{amount}"
price-earnings: "&7You receive: &a{amount}"
price-click: "&eClick to change price"
duration-title: "&eDuration: {duration}"
duration-lore: "&7Listing expires after this time"
duration-click: "&eClick to change duration"
back-lore: "&7Return to item selection"
confirm-item: "&7Item: &f{item} x{amount}"
confirm-price: "&7Price: &a{price}"
confirm-earnings: "&7You receive: &a{amount}"
confirm-duration: "&7Duration: &e{duration}"
confirm-click: "&aClick to create listing!"
# Create Auction GUI
create-auction:
info-title: "&6&lCreate Auction"
info-lore-1: "&7Set starting price, optional buyout,"
info-lore-2: "&7and duration for your auction."
tax-info: "&7Tax on sale: &f{tax}%"
item-lore: "&7Quantity: &f{amount}|&eThis item will be auctioned"
start-price-title: "&6Starting Price: {price}"
start-price-lore-1: "&7Minimum bid to start"
start-price-lore-2: "&7the auction."
start-price-click: "&eClick to change"
buyout-title-set: "&bBuyout: {price}"
buyout-title-unset: "&bBuyout: &7Not set"
buyout-lore-set-1: "&7Instant purchase price."
buyout-lore-set-2: "&eLeft-click to change"
buyout-lore-set-3: "&cRight-click to remove"
buyout-lore-unset-1: "&7Optional instant purchase"
buyout-lore-unset-2: "&7price for your auction."
buyout-lore-unset-click: "&eClick to set buyout price"
duration-title: "&eDuration: {duration}"
duration-lore: "&7Auction ends after this time."
duration-click: "&eClick to change duration"
back-lore: "&7Return to item selection"
confirm-item: "&7Item: &f{item} x{amount}"
confirm-start: "&7Start: &a{price}"
confirm-buyout: "&7Buyout: &b{price}"
confirm-buyout-none: "&7Buyout: &7None"
confirm-duration: "&7Duration: &e{duration}"
confirm-click: "&aClick to create auction!"
# Number Input GUI
number-input:
display-title: "&6&l{value}"
minimum: "&7Minimum: &f{value}"
maximum: "&7Maximum: &f{value}"
use-buttons: "&eUse buttons to adjust"
click-adjust: "&7Click: &e{amount}"
shift-click: "&7Shift-click: &e{amount}"
set-minimum: "&6Set Minimum"
set-maximum: "&6Set Maximum"
set-to: "&7Set to: &f{value}"
cancel-lore: "&7Cancel and go back"
confirm-lore: "&7Confirm: &a{value}"
# Help Content
help:
title: "&6&lCommunity Market Help"
content:
- "&eBrowse Market &7- View and buy fixed-price listings"
- "&eBrowse Auctions &7- View and bid on auctions"
- "&eCreate Listing &7- Sell items at a fixed price"
- "&eCreate Auction &7- Auction items to highest bidder"
- "&eMy Listings &7- Manage your active listings"
- "&eMy Auctions &7- Manage your active auctions"
- "&eClaim Items &7- Collect unsold/won items"
- "&eEarnings &7- Withdraw money from sales"
- ""
- "&7&oTip: All actions are done through GUIs!"
- "&7&oJust click on buttons to navigate."
-448
View File
@@ -1,448 +0,0 @@
# ============================================
# CommunityMarket Ficheiro de Idioma - Português (Portugal)
# ============================================
# Geral
prefix: "&8[&6Mercado&8] &r"
# Mensagens Gerais
messages:
no-permission: "&cNão tens permissão para fazer isso."
player-only: "&cEste comando só pode ser usado por jogadores."
reload-success: "&aConfiguração recarregada com sucesso!"
economy-not-found: "&cNenhum plugin de economia encontrado! Mercado desativado."
# Mensagens de Anúncios
listing-created: "&aAnúncio criado com sucesso! ID: #{id}"
listing-cancelled: "&aAnúncio cancelado. Item devolvido ao armazém."
listing-expired: "&eO teu anúncio #{id} expirou. Item movido para o armazém."
listing-purchased: "&aCompraste {item} x{amount} por {price}!"
listing-sold: "&aO teu {item} x{amount} foi vendido a {buyer} por {price}!"
listing-limit-reached: "&cAtingiste o número máximo de anúncios ({max})."
listing-cooldown: "&cPor favor aguarda {time} antes de criar outro anúncio."
listing-not-found: "&cAnúncio não encontrado ou já não está disponível."
listing-own-item: "&cNão podes comprar o teu próprio anúncio."
listing-insufficient-funds: "&cNão tens dinheiro suficiente. Necessário: {price}"
# Mensagens de Leilões
auction-created: "&aLeilão criado com sucesso! ID: #{id}"
auction-cancelled: "&aLeilão cancelado. Item devolvido ao armazém."
auction-ended-winner: "&aParabéns! Ganhaste o leilão por {item}! Pagaste: {price}"
auction-ended-seller: "&aO teu leilão por {item} terminou! Vencedor: {winner}, Ganhaste: {price}"
auction-ended-no-bids: "&eO teu leilão por {item} terminou sem licitações. Item movido para o armazém."
auction-limit-reached: "&cAtingiste o número máximo de leilões ({max})."
auction-not-found: "&cLeilão não encontrado ou já não está disponível."
auction-own-item: "&cNão podes licitar no teu próprio leilão."
auction-bid-placed: "&aFizeste uma licitação de {amount} em {item}!"
auction-outbid: "&eForam feitas licitações superiores à tua em {item}! Nova licitação: {amount} por {bidder}"
auction-bid-too-low: "&cLicitação muito baixa! Mínimo: {min}"
auction-insufficient-funds: "&cNão tens dinheiro suficiente. Necessário: {price}"
auction-buyout: "&aCompraste o leilão de {item} por {price}!"
auction-extended: "&eLeilão prolongado por {seconds}s devido à proteção anti-snipe."
# Mensagens de Reclamação
claim-success: "&aItem reclamado com sucesso!"
claim-empty: "&eNão tens itens para reclamar."
claim-inventory-full: "&cO teu inventário está cheio! Por favor liberta espaço."
claim-all-success: "&aReclamaste {count} itens!"
# Mensagens de Ganhos
earnings-withdrawn: "&aLevantaste {amount}! Novo saldo: {balance}"
earnings-empty: "&eNão tens ganhos pendentes."
earnings-balance: "&aOs teus ganhos pendentes: {amount}"
# Validação de Itens
invalid-item: "&cPor favor seleciona um item válido."
item-no-longer-available: "&cO item selecionado já não está no teu inventário."
item-changed: "&cO item selecionado foi alterado. Por favor seleciona novamente."
quantity-changed: "&cA quantidade disponível foi alterada. Por favor verifica e tenta novamente."
blacklisted-item: "&cEste tipo de item não é permitido no mercado."
blacklisted-content: "&cEste item contém conteúdo bloqueado."
invalid-price: "&cPreço inválido. Intervalo: {min} - {max}"
invalid-amount: "&cQuantidade inválida."
invalid-duration: "&cDuração inválida."
# Mensagens de Admin
admin-listing-removed: "&aAnúncio #{id} removido pelo admin."
admin-auction-cancelled: "&aLeilão #{id} cancelado pelo admin."
admin-reload: "&aConfiguração recarregada."
# Títulos GUI (suportam códigos de cor)
gui-titles:
main-menu: "&8&lMercado Comunitário"
browse-market: "&8&lExplorar Mercado &7(Página {page})"
browse-auctions: "&8&lExplorar Leilões &7(Página {page})"
create-listing: "&8&lCriar Anúncio"
create-auction: "&8&lCriar Leilão"
select-item-listing: "&8&lSelecionar Item para Vender"
select-item-auction: "&8&lSelecionar Item para Leilão"
quantity-select: "&8&lSelecionar Quantidade"
my-listings: "&8&lOs Meus Anúncios"
my-auctions: "&8&lOs Meus Leilões"
claim-items: "&8&lReclamar Itens"
earnings: "&8&lGanhos"
confirm-purchase: "&8&lConfirmar Compra"
confirm-bid: "&8&lConfirmar Licitação"
confirm-cancel: "&8&lConfirmar Cancelamento"
number-input: "&8&lIntroduzir Valor"
admin-panel: "&8&lPainel de Admin"
admin-listings: "&8&lTodos os Anúncios"
admin-auctions: "&8&lTodos os Leilões"
listing-details: "&8&lDetalhes do Anúncio"
auction-details: "&8&lDetalhes do Leilão"
filter-menu: "&8&lOpções de Filtro"
sort-menu: "&8&lOpções de Ordenação"
duration-select: "&8&lSelecionar Duração"
help: "&8&lAjuda"
# Nomes dos Botões
buttons:
# Menu Principal
browse-market: "&aExplorar Mercado"
browse-auctions: "&6Explorar Leilões"
create-listing: "&eCriar Anúncio"
create-auction: "&eCriar Leilão"
my-listings: "&bOs Meus Anúncios"
my-auctions: "&bOs Meus Leilões"
claim-items: "&dReclamar Itens"
earnings: "&aGanhos"
help: "&fAjuda"
admin: "&cPainel de Admin"
# Navegação
next-page: "&aPágina Seguinte →"
previous-page: "&a← Página Anterior"
back: "&cVoltar"
close: "&cFechar"
# Ações
confirm: "&aConfirmar"
cancel: "&cCancelar"
buy: "&aComprar Agora"
bid: "&6Fazer Licitação"
buyout: "&eCompra Imediata"
claim: "&aReclamar"
claim-all: "&aReclamar Tudo"
withdraw: "&aLevantar Tudo"
remove: "&cRemover Anúncio"
cancel-auction: "&cCancelar Leilão"
# Entrada Numérica
add-1: "&a+1"
add-10: "&a+10"
add-100: "&a+100"
add-1000: "&a+1.000"
subtract-1: "&c-1"
subtract-10: "&c-10"
subtract-100: "&c-100"
subtract-1000: "&c-1.000"
set-min: "&eDefinir Mín"
set-max: "&eDefinir Máx"
custom-amount: "&bValor Personalizado"
# Filtros e Ordenação
filter: "&eFiltro"
sort: "&eOrdenar"
search: "&ePesquisar"
clear-filter: "&cLimpar Filtros"
# Duração
duration-1h: "&e1 Hora"
duration-6h: "&e6 Horas"
duration-12h: "&e12 Horas"
duration-24h: "&e24 Horas"
duration-48h: "&e48 Horas"
duration-72h: "&e3 Dias"
duration-168h: "&e7 Dias"
duration-336h: "&e14 Dias"
# Admin
admin-view-listings: "&aVer Todos os Anúncios"
admin-view-auctions: "&6Ver Todos os Leilões"
admin-reload: "&eRecarregar Config"
# Lore dos Botões (descrições)
lore:
browse-market:
- "&7Explora todos os anúncios"
- "&7de preço fixo dos jogadores."
- ""
- "&eClica para explorar!"
browse-auctions:
- "&7Explora todos os leilões ativos"
- "&7e faz licitações."
- ""
- "&eClica para explorar!"
create-listing:
- "&7Vende itens a um preço fixo."
- "&7Taxa: &f{tax}%"
- ""
- "&eClica para criar!"
create-auction:
- "&7Leiloa itens ao"
- "&7maior licitador."
- "&7Taxa: &f{tax}%"
- ""
- "&eClica para criar!"
my-listings:
- "&7Vê e gere os teus"
- "&7anúncios ativos."
- ""
- "&7Ativos: &f{count}/{max}"
- ""
- "&eClica para ver!"
my-auctions:
- "&7Vê e gere os teus"
- "&7leilões ativos."
- ""
- "&7Ativos: &f{count}/{max}"
- ""
- "&eClica para ver!"
claim-items:
- "&7Reclama itens de anúncios"
- "&7expirados ou leilões ganhos."
- ""
- "&7Pendentes: &f{count}"
- ""
- "&eClica para reclamar!"
earnings:
- "&7Vê e levanta os teus"
- "&7ganhos pendentes das vendas."
- ""
- "&7Pendente: &a{amount}"
- ""
- "&eClica para ver!"
help:
- "&7Aprende a usar o"
- "&7Mercado Comunitário."
- ""
- "&eClica para ajuda!"
admin:
- "&cPainel de Admin"
- "&7Gere anúncios e leilões."
- ""
- "&eClica para abrir!"
# Info do Anúncio
listing-info:
- "&7Vendedor: &f{seller}"
- "&7Preço: &a{price}"
- "&7Quantidade: &f{amount}"
- "&7Expira: &f{expires}"
- ""
- "&eClique esquerdo para comprar!"
# Info do Leilão
auction-info:
- "&7Vendedor: &f{seller}"
- "&7Licitação inicial: &a{start_price}"
- "&7Licitação atual: &a{current_bid}"
- "&7Licitador: &f{bidder}"
- "&7Licitações: &f{bid_count}"
- "&7Termina: &f{ends}"
- ""
- "&eClique esquerdo para licitar!"
- "&eClique direito para compra imediata!"
# Info do Meu Anúncio
my-listing-info:
- "&7Preço: &a{price}"
- "&7Quantidade: &f{amount}"
- "&7Criado: &f{created}"
- "&7Expira: &f{expires}"
- ""
- "&cClica para cancelar"
# Info do Meu Leilão
my-auction-info:
- "&7Licitação inicial: &a{start_price}"
- "&7Licitação atual: &a{current_bid}"
- "&7Licitador: &f{bidder}"
- "&7Licitações: &f{bid_count}"
- "&7Termina: &f{ends}"
- ""
- "&cClica para cancelar (sem licitações)"
# Confirmar Compra
confirm-purchase-info:
- "&7Estás a comprar:"
- "&f{item} x{amount}"
- ""
- "&7Preço: &a{price}"
- "&7Taxa: &e{tax}"
- "&7Total: &a{total}"
- ""
- "&aClica para confirmar!"
# Confirmar Licitação
confirm-bid-info:
- "&7Estás a licitar em:"
- "&f{item}"
- ""
- "&7A tua licitação: &a{bid}"
- "&7Atual mais alta: &e{current}"
- ""
- "&aClica para confirmar!"
# Reclamar Item
claim-item-info:
- "&7Razão: &f{reason}"
- "&7De: &f{source}"
- "&7Data: &f{date}"
- ""
- "&eClica para reclamar!"
# Info de Ganhos
earnings-info:
- "&7Os teus ganhos pendentes"
- "&7das vendas no mercado."
- ""
- "&7Total: &a{amount}"
- ""
- "&aClica para levantar!"
# Info de Entrada Numérica
current-value:
- "&7Atual: &a{value}"
# Opções de Filtro
filters:
all: "&fTodos os Itens"
weapons: "&cArmas"
armor: "&bArmadura"
tools: "&eFerramentas"
blocks: "&7Blocos"
food: "&6Comida"
potions: "&dPoções"
materials: "&aMateriais"
enchanted: "&5Itens Encantados"
misc: "&8Diversos"
# Opções de Ordenação
sort:
newest: "&aMais Recente"
oldest: "&eMais Antigo"
price-low: "&aPreço: Menor para Maior"
price-high: "&cPreço: Maior para Menor"
ending-soon: "&6A Terminar Em Breve"
most-bids: "&bMais Licitações"
# Formatos de Tempo
time:
expired: "&cExpirado"
days: "{d}d"
hours: "{h}h"
minutes: "{m}m"
seconds: "{s}s"
# GUI de Seleção de Quantidade
quantity-select:
title: "&6&lSelecionar Quantidade"
info-line-1: "&7Escolhe quantos itens"
info-line-2: "&7queres vender."
available: "&7Disponível: &f{amount}"
selected: "&7Selecionado: &f{amount}"
quantity-label: "Quantidade"
minimum: "&7Mínimo: &f{amount}"
maximum: "&7Máximo: &f{amount}"
use-buttons: "&eUsa os botões para ajustar"
click-adjust: "&7Clica: &e{amount}"
set-minimum: "&6Definir Mínimo"
set-maximum: "&6Definir Máximo"
set-to: "&7Definir para: &f{amount}"
back-lore: "&7Voltar à seleção de item"
confirm-lore: "&7Quantidade: &a{amount}"
# GUI de Seleção de Item
item-selection:
info-title: "&fSelecionar um Item"
info-lore-listing: "&7Clica num item do teu|&7inventário para criar um &eAnúncio&7."
info-lore-auction: "&7Clica num item do teu|&7inventário para criar um &6Leilão&7."
blacklisted-note: "&7Itens bloqueados aparecem a vermelho."
click-to-select: "&a► Clica para selecionar"
blocked-title: "&c{material}"
blocked-lore-1: "&7Este item não pode ser listado."
blocked-lore-2: "&cBloqueado ou inválido."
back-lore: "&7Voltar ao menu principal"
# GUI de Criar Anúncio
create-listing:
info-title: "&6&lCriar Anúncio"
info-lore-1: "&7Define um preço e duração"
info-lore-2: "&7para o teu anúncio."
tax-info: "&7Taxa: &f{tax}%"
item-lore: "&7Quantidade: &f{amount}|&eEste item será listado"
price-title: "&6Preço: {price}"
price-tax: "&7Taxa ({percent}%): &c{amount}"
price-earnings: "&7Recebes: &a{amount}"
price-click: "&eClica para alterar preço"
duration-title: "&eDuração: {duration}"
duration-lore: "&7O anúncio expira após este tempo"
duration-click: "&eClica para alterar duração"
back-lore: "&7Voltar à seleção de item"
confirm-item: "&7Item: &f{item} x{amount}"
confirm-price: "&7Preço: &a{price}"
confirm-earnings: "&7Recebes: &a{amount}"
confirm-duration: "&7Duração: &e{duration}"
confirm-click: "&aClica para criar anúncio!"
# GUI de Criar Leilão
create-auction:
info-title: "&6&lCriar Leilão"
info-lore-1: "&7Define preço inicial, compra imediata opcional,"
info-lore-2: "&7e duração para o teu leilão."
tax-info: "&7Taxa na venda: &f{tax}%"
item-lore: "&7Quantidade: &f{amount}|&eEste item será leiloado"
start-price-title: "&6Preço Inicial: {price}"
start-price-lore-1: "&7Licitação mínima para iniciar"
start-price-lore-2: "&7o leilão."
start-price-click: "&eClica para alterar"
buyout-title-set: "&bCompra Imediata: {price}"
buyout-title-unset: "&bCompra Imediata: &7Não definido"
buyout-lore-set-1: "&7Preço de compra instantânea."
buyout-lore-set-2: "&eClique esquerdo para alterar"
buyout-lore-set-3: "&cClique direito para remover"
buyout-lore-unset-1: "&7Preço opcional de compra"
buyout-lore-unset-2: "&7instantânea para o teu leilão."
buyout-lore-unset-click: "&eClica para definir preço de compra imediata"
duration-title: "&eDuração: {duration}"
duration-lore: "&7O leilão termina após este tempo."
duration-click: "&eClica para alterar duração"
back-lore: "&7Voltar à seleção de item"
confirm-item: "&7Item: &f{item} x{amount}"
confirm-start: "&7Início: &a{price}"
confirm-buyout: "&7Compra Imediata: &b{price}"
confirm-buyout-none: "&7Compra Imediata: &7Nenhum"
confirm-duration: "&7Duração: &e{duration}"
confirm-click: "&aClica para criar leilão!"
# GUI de Entrada Numérica
number-input:
display-title: "&6&l{value}"
minimum: "&7Mínimo: &f{value}"
maximum: "&7Máximo: &f{value}"
use-buttons: "&eUsa os botões para ajustar"
click-adjust: "&7Clica: &e{amount}"
shift-click: "&7Shift-clica: &e{amount}"
set-minimum: "&6Definir Mínimo"
set-maximum: "&6Definir Máximo"
set-to: "&7Definir para: &f{value}"
cancel-lore: "&7Cancelar e voltar"
confirm-lore: "&7Confirmar: &a{value}"
# Conteúdo de Ajuda
help:
title: "&6&lAjuda do Mercado Comunitário"
content:
- "&eExplorar Mercado &7- Ver e comprar anúncios de preço fixo"
- "&eExplorar Leilões &7- Ver e licitar em leilões"
- "&eCriar Anúncio &7- Vender itens a um preço fixo"
- "&eCriar Leilão &7- Leiloar itens ao maior licitador"
- "&eOs Meus Anúncios &7- Gerir os teus anúncios ativos"
- "&eOs Meus Leilões &7- Gerir os teus leilões ativos"
- "&eReclamar Itens &7- Recolher itens não vendidos/ganhos"
- "&eGanhos &7- Levantar dinheiro das vendas"
- ""
- "&7&oDica: Todas as ações são feitas através de GUIs!"
- "&7&oBasta clicar nos botões para navegar."
-83
View File
@@ -1,83 +0,0 @@
name: CommunityMarket
version: '1.0.0'
main: pt.henrique.communityMarket.CommunityMarket
api-version: '1.21'
description: A GUI-only marketplace plugin for fixed-price listings and auctions
author: Henrique
website: https://github.com/henrique/CommunityMarket
# Soft dependencies - plugin will detect and use these if available
softdepend:
- Vault
- Essentials
load: POSTWORLD
commands:
market:
description: Opens the Community Market main menu
usage: /<command>
aliases: [cmarket]
permission: communitymarket.use
permissions:
communitymarket.*:
description: Grants all CommunityMarket permissions
default: op
children:
communitymarket.use: true
communitymarket.sell: true
communitymarket.auction: true
communitymarket.buy: true
communitymarket.bid: true
communitymarket.claim: true
communitymarket.withdraw: true
communitymarket.admin: true
communitymarket.use:
description: Allows access to the market GUI
default: true
communitymarket.sell:
description: Allows creating fixed-price listings
default: true
communitymarket.auction:
description: Allows creating auctions
default: true
communitymarket.buy:
description: Allows purchasing from the market
default: true
communitymarket.bid:
description: Allows bidding on auctions
default: true
communitymarket.claim:
description: Allows claiming items from storage
default: true
communitymarket.withdraw:
description: Allows withdrawing earnings
default: true
communitymarket.admin:
description: Allows access to admin functions
default: op
children:
communitymarket.admin.viewall: true
communitymarket.admin.remove: true
communitymarket.admin.reload: true
communitymarket.admin.viewall:
description: Allows viewing all listings/auctions
default: op
communitymarket.admin.remove:
description: Allows removing any listing or auction
default: op
communitymarket.admin.reload:
description: Allows reloading configuration
default: op

Some files were not shown because too many files have changed in this diff Show More