mirror of
https://github.com/R0m1k3/Priceflow.git
synced 2026-10-11 17:29:14 +02:00
Add files via upload
This commit is contained in:
72 files changed
+12339
No files matched your search
+48
@@ -0,0 +1,48 @@
|
||||
# Stage 1: Build Frontend
|
||||
FROM node:22-alpine as frontend-build
|
||||
|
||||
WORKDIR /app/frontend
|
||||
|
||||
COPY frontend/package.json frontend/package-lock.json* ./
|
||||
RUN npm install
|
||||
|
||||
COPY frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Build Backend and Serve
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install uv
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
|
||||
|
||||
# Copy build files
|
||||
COPY pyproject.toml .
|
||||
COPY README.md .
|
||||
|
||||
# Use uv for faster installation (fixed syntax)
|
||||
RUN uv pip install --system --no-cache .
|
||||
|
||||
# Copy backend code
|
||||
COPY app/ ./app
|
||||
COPY alembic.ini ./
|
||||
COPY docker-entrypoint.sh ./
|
||||
|
||||
# Make entrypoint executable
|
||||
RUN chmod +x docker-entrypoint.sh
|
||||
|
||||
# Copy built frontend static files
|
||||
COPY --from=frontend-build /app/frontend/dist /app/static
|
||||
|
||||
# Create screenshots directory
|
||||
RUN mkdir -p screenshots
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8000
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/')" || exit 1
|
||||
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
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.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means to 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 (1) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (2) 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>.
|
||||
@@ -0,0 +1,142 @@
|
||||
<p align="center">
|
||||
<img src="frontend/public/logo.png" alt="Pricecious logo" width="80">
|
||||
</p>
|
||||
|
||||
<h1 align="center">(My) Pricecious</h1>
|
||||
|
||||
<p align="center">
|
||||
Price tracking using A-Eyes 🤦
|
||||
</p>
|
||||
|
||||
> [!WARNING]
|
||||
> This is 100% vibe-coded.
|
||||
|
||||
**Pricecious** is a self-hosted, AI-powered price tracking application. It uses **GenAI Vision Models** (OpenAI, Anthropic, Ollama, etc.) to visually analyze product pages, detect prices, and monitor stock status.
|
||||
|
||||
<img width="1186" height="482" alt="SCR-20251120-sdky" src="https://github.com/user-attachments/assets/b9c09142-496e-458e-9a86-9e3d7b1fb7c0" />
|
||||
|
||||
## Features
|
||||
|
||||
* **AI-Powered Analysis**: Uses GenAI Vision Models to "see" the price and stock status on any webpage, bypassing complex HTML structures.
|
||||
* **Confidence Scoring**: AI provides confidence scores (0-1) for each extraction, enabling smart business rules and quality monitoring.
|
||||
* **Robust JSON Parsing**: Hardened parsing pipeline with automatic JSON repair fallback when primary extraction fails.
|
||||
* **Provider-Specific Optimization**: Leverages native JSON modes and structured output features for OpenAI, Ollama, and other providers.
|
||||
* **Visual History**: Keeps a screenshot history of every check with full AI metadata (model, provider, confidence, etc.).
|
||||
* **Smart Scrolling**: Automatically scrolls pages to load lazy-loaded content before capturing.
|
||||
* **Text Context**: Optionally extracts page text to improve AI accuracy.
|
||||
* **Notifications**: Supports multi-channel notifications (Discord, Telegram, Email, etc.) via [Apprise](https://github.com/caronc/apprise).
|
||||
* **Dark Mode**: Beautiful UI with full dark/light mode support.
|
||||
* **Dockerized**: Easy to deploy with Docker Compose.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* **Docker** and **Docker Compose**
|
||||
* **AI Provider**: An API key for OpenAI, Anthropic, Gemini, OR a local Ollama instance.
|
||||
* **PostgreSQL**: A database for storing items and history (handled via Docker Compose).
|
||||
* **Browserless**: A headless browser service for scraping (handled via Docker Compose).
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. **Create a `docker-compose.yml` file:**
|
||||
Save the following content to a file named `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: ghcr.io/ds-sebastian/pricecious:latest
|
||||
container_name: pricecious-app
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://user:password@db:5432/pricewatch
|
||||
- BROWSERLESS_URL=ws://browserless:3000
|
||||
depends_on:
|
||||
- db
|
||||
- browserless
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
- screenshots_data:/app/screenshots
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: pricewatch
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
browserless:
|
||||
image: browserless/chrome:latest
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- MAX_CONCURRENT_SESSIONS=10
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
screenshots_data:
|
||||
```
|
||||
|
||||
2. **Start the Application:**
|
||||
Run the following command in the same directory:
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
3. **Access the Dashboard:**
|
||||
Open your browser and navigate to `http://localhost:8000`.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
The following environment variables can be configured in your `docker-compose.yml`:
|
||||
|
||||
| Variable | Description | Default | Example |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `DATABASE_URL` | PostgreSQL connection string | `postgresql://user:password@db:5432/pricewatch` | `postgresql://u:p@localhost:5432/db` |
|
||||
| `BROWSERLESS_URL` | WebSocket URL for Browserless | `ws://browserless:3000` | `ws://browserless:3000` |
|
||||
| `LOG_LEVEL` | Application logging level | `INFO` | `DEBUG` |
|
||||
| `SQL_ECHO` | Log all SQL queries to console | `false` | `true` |
|
||||
| `CORS_ORIGINS` | Allowed CORS origins (comma-separated) | `*` | `http://localhost:3000,https://myapp.com` |
|
||||
|
||||
> [!TIP]
|
||||
> LiteLLM environment variables should work too to prepopulate AI model default settings
|
||||
|
||||
### Scraper Settings
|
||||
All scraper settings are configured via the **Settings** page in the UI:
|
||||
* **Smart Scroll**: Enable to handle infinite scroll pages.
|
||||
* **Text Context**: Enable to send page text to the AI for better accuracy.
|
||||
* **Scraper Timeout**: Maximum time to wait for page load.
|
||||
|
||||
### AI Configuration
|
||||
All AI settings are configured via the **Settings** page in the UI. No environment variables are required.
|
||||
|
||||
**Provider Settings**:
|
||||
* **Provider**: Choose between OpenAI, Anthropic, Gemini, Ollama, or Custom.
|
||||
* **Model**: Specify the model name (e.g., `gpt-4o`, `claude-3-5-sonnet`, `gemma3:4b`).
|
||||
* **API Key**: Enter your API key (not required for Ollama).
|
||||
* **Base URL**: Required for Ollama or custom OpenAI-compatible endpoints.
|
||||
|
||||
**Advanced AI Settings**:
|
||||
* **Temperature**: Controls output randomness (0.0-1.0).
|
||||
* **Max Tokens**: Maximum tokens for AI responses.
|
||||
* **Price/Stock Confidence Thresholds**: Minimum confidence required to update values.
|
||||
* **Enable JSON Repair**: Automatically attempt to repair malformed JSON responses.
|
||||
|
||||
**How Confidence Works**:
|
||||
- The AI provides a confidence score (0.0 to 1.0) for each extracted value
|
||||
- Scores represent the AI's subjective probability that the extraction is correct
|
||||
- If confidence is below the threshold, the value is logged but doesn't overwrite the current value
|
||||
- Large price changes (>20%) with low confidence (<0.7) are flagged for manual review
|
||||
- All extractions are saved in history with their confidence scores for analysis
|
||||
|
||||
### Notifications
|
||||
Create **Notification Profiles** in the Settings page using Apprise URLs.
|
||||
* Example Discord: `discord://webhook_id/webhook_token`
|
||||
* Example Telegram: `tgram://bot_token/chat_id`
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the GNU General Public License v3.0 - see the [LICENSE](LICENSE) file for details.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = app/alembic
|
||||
|
||||
# template used to generate migration file
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If consistent_date_and_time is True, the timezone is set to UTC.
|
||||
# timezone =
|
||||
|
||||
# max_length = 20
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:app/alembic/versions
|
||||
|
||||
# version_path_separator = :
|
||||
|
||||
# set to 'true' to search for and load revisions in the
|
||||
# order of their 'depends_on' configuration
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or RFE hooks that run
|
||||
# after a new revision script is written.
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
[tool:pytest]
|
||||
# A list of file name patterns to identify test files.
|
||||
# testpaths = tests
|
||||
|
||||
[mypy]
|
||||
# mypy configuration
|
||||
# ignore_missing_imports = True
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
Whitespace-only changes.
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
Unified JSON schema for AI extraction responses.
|
||||
|
||||
This module defines the canonical schema for all AI model responses,
|
||||
including confidence scores and metadata tracking.
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from app.utils.text import filter_relevant_text
|
||||
|
||||
# Schema version for tracking prompt/schema changes
|
||||
PROMPT_VERSION = "v2.0"
|
||||
|
||||
# Default confidence thresholds
|
||||
DEFAULT_PRICE_CONFIDENCE_THRESHOLD = 0.5
|
||||
DEFAULT_STOCK_CONFIDENCE_THRESHOLD = 0.5
|
||||
DEFAULT_MULTI_SAMPLE_THRESHOLD = 0.6
|
||||
|
||||
# Text filtering constants
|
||||
MIN_SNIPPET_LENGTH = 10
|
||||
SNIPPET_MERGE_DISTANCE = 50
|
||||
SNIPPET_CONTEXT_WINDOW = 100
|
||||
|
||||
|
||||
class AIExtractionResponse(BaseModel):
|
||||
"""
|
||||
Canonical schema for AI extraction responses.
|
||||
|
||||
All AI models must return data matching this schema.
|
||||
"""
|
||||
|
||||
price: float | None = Field(
|
||||
None,
|
||||
description="Extracted price as a number, or null if no price found",
|
||||
)
|
||||
currency: str = Field(
|
||||
"USD",
|
||||
description="Currency code (ISO 4217)",
|
||||
)
|
||||
in_stock: bool | None = Field(
|
||||
None,
|
||||
description="Stock status: true if in stock, false if out of stock, null if unclear",
|
||||
)
|
||||
price_confidence: float = Field(
|
||||
0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Confidence in price extraction (0.0 to 1.0)",
|
||||
)
|
||||
in_stock_confidence: float = Field(
|
||||
0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Confidence in stock status extraction (0.0 to 1.0)",
|
||||
)
|
||||
source_type: Literal["image", "text", "both"] = Field(
|
||||
"image",
|
||||
description="Source of extraction: image, text, or both",
|
||||
)
|
||||
|
||||
@field_validator("price_confidence", "in_stock_confidence", mode="before")
|
||||
@classmethod
|
||||
def clamp_confidence(cls, v):
|
||||
"""Clamp confidence values to [0.0, 1.0] range."""
|
||||
if v is None:
|
||||
return 0.0
|
||||
return max(0.0, min(1.0, float(v)))
|
||||
|
||||
@field_validator("price", mode="before")
|
||||
@classmethod
|
||||
def normalize_price(cls, v):
|
||||
"""Normalize price to float or None."""
|
||||
if v is None or v in ("null", ""):
|
||||
return None
|
||||
if isinstance(v, str):
|
||||
# Remove currency symbols and commas
|
||||
cleaned = re.sub(r"[^\d.]", "", v)
|
||||
if cleaned:
|
||||
return float(cleaned)
|
||||
return None
|
||||
return float(v)
|
||||
|
||||
@field_validator("in_stock", mode="before")
|
||||
@classmethod
|
||||
def normalize_stock(cls, v):
|
||||
"""Normalize stock status to boolean or None."""
|
||||
if v is None or v == "null":
|
||||
return None
|
||||
if isinstance(v, str):
|
||||
v_lower = v.lower().strip()
|
||||
if v_lower in ("true", "yes", "in stock", "available", "1"):
|
||||
return True
|
||||
if v_lower in ("false", "no", "out of stock", "unavailable", "0"):
|
||||
return False
|
||||
return None
|
||||
return bool(v)
|
||||
|
||||
|
||||
class AIExtractionMetadata(BaseModel):
|
||||
"""
|
||||
Metadata about an AI extraction operation.
|
||||
|
||||
Tracks which model was used, whether repair was needed, etc.
|
||||
"""
|
||||
|
||||
model_name: str = Field(..., description="AI model identifier (e.g., 'gpt-4o')")
|
||||
provider: str = Field(..., description="AI provider (e.g., 'openai', 'ollama')")
|
||||
prompt_version: str = Field(PROMPT_VERSION, description="Version of the extraction prompt used")
|
||||
repair_used: bool = Field(False, description="Whether JSON repair fallback was used")
|
||||
multi_sample: bool = Field(False, description="Whether multi-sample validation was used")
|
||||
sample_count: int = Field(1, description="Number of samples generated (for multi-sample)")
|
||||
|
||||
|
||||
# Prompt template for schema-first extraction
|
||||
EXTRACTION_PROMPT_TEMPLATE = """Extract product price and stock status from the image.
|
||||
|
||||
**PRICE:**
|
||||
- Find the main current price
|
||||
- Ignore crossed-out prices
|
||||
- Extract number only (no symbols)
|
||||
- If unclear: set null and confidence < 0.5
|
||||
|
||||
**STOCK:**
|
||||
- TRUE if: "Add to Cart", "Buy Now", "In Stock", "Available"
|
||||
- FALSE if: "Out of Stock", "Sold Out", "Unavailable", "Notify Me"
|
||||
- NULL if unclear or not shown
|
||||
|
||||
**CONFIDENCE (0.0 to 1.0):**
|
||||
- 0.9-1.0: Very certain
|
||||
- 0.5-0.8: Moderately certain
|
||||
- Below 0.5: Unsure
|
||||
|
||||
Respond ONLY with valid JSON:
|
||||
{{
|
||||
"price": <number or null>,
|
||||
"currency": "USD",
|
||||
"in_stock": <true, false, or null>,
|
||||
"price_confidence": <0.0 to 1.0>,
|
||||
"in_stock_confidence": <0.0 to 1.0>,
|
||||
"source_type": "both"
|
||||
}}
|
||||
|
||||
{context_section}"""
|
||||
|
||||
# Repair prompt template
|
||||
REPAIR_PROMPT_TEMPLATE = """Convert the following text into valid JSON matching this schema:
|
||||
|
||||
{{
|
||||
"price": <number or null>,
|
||||
"currency": "<ISO currency code, default USD>",
|
||||
"in_stock": <true, false, or null>,
|
||||
"price_confidence": <number from 0.0 to 1.0>,
|
||||
"in_stock_confidence": <number from 0.0 to 1.0>,
|
||||
"source_type": "<image, text, or both>"
|
||||
}}
|
||||
|
||||
Rules:
|
||||
- Extract numeric price value only (no symbols)
|
||||
- Boolean values must be true, false, or null (not strings)
|
||||
- Confidence values must be numbers between 0.0 and 1.0
|
||||
- Respond with ONLY the JSON object, no other text
|
||||
|
||||
Text to convert:
|
||||
{raw_output}"""
|
||||
|
||||
|
||||
def get_extraction_prompt(page_text: str | None = None) -> str:
|
||||
"""
|
||||
Generate the extraction prompt with optional text context.
|
||||
|
||||
Args:
|
||||
page_text: Optional webpage text to include as context
|
||||
|
||||
Returns:
|
||||
Formatted prompt string
|
||||
"""
|
||||
if page_text:
|
||||
# Apply smart filtering to extract only relevant snippets
|
||||
filtered_text = filter_relevant_text(page_text, max_length=1500)
|
||||
context_section = f"""**Relevant text from page:**
|
||||
{filtered_text}"""
|
||||
else:
|
||||
context_section = ""
|
||||
|
||||
return EXTRACTION_PROMPT_TEMPLATE.format(context_section=context_section)
|
||||
|
||||
|
||||
def get_repair_prompt(raw_output: str) -> str:
|
||||
"""
|
||||
Generate the repair prompt for fixing invalid JSON.
|
||||
|
||||
Args:
|
||||
raw_output: Raw AI output that failed parsing
|
||||
|
||||
Returns:
|
||||
Formatted repair prompt
|
||||
"""
|
||||
return REPAIR_PROMPT_TEMPLATE.format(raw_output=raw_output[:1000])
|
||||
@@ -0,0 +1,82 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from alembic import context
|
||||
from app.database import DATABASE_URL
|
||||
from app.models import Base
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = DATABASE_URL
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
configuration = config.get_section(config.config_ini_section)
|
||||
configuration["sqlalchemy.url"] = DATABASE_URL
|
||||
|
||||
connectable = engine_from_config(
|
||||
configuration,
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Add refresh fields
|
||||
|
||||
Revision ID: 6ecb6f39fd8c
|
||||
Revises: initial_migration
|
||||
Create Date: 2025-11-19 12:53:09.412700
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
from app.models import Base
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "6ecb6f39fd8c"
|
||||
down_revision: str | None = "initial_migration"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.add_column("items", sa.Column("is_refreshing", sa.Boolean(), nullable=True))
|
||||
op.add_column("items", sa.Column("last_error", sa.String(), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column("items", "last_error")
|
||||
op.drop_column("items", "is_refreshing")
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,39 @@
|
||||
"""add_performance_indexes
|
||||
|
||||
Revision ID: 7f8e9d2a1b3c
|
||||
Revises: a1b2c3d4e5f6
|
||||
Create Date: 2025-11-19 19:14:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "7f8e9d2a1b3c"
|
||||
down_revision = "a1b2c3d4e5f6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Add indexes for performance optimization
|
||||
# Items table indexes
|
||||
op.create_index("ix_items_last_checked", "items", ["last_checked"])
|
||||
op.create_index("ix_items_is_active", "items", ["is_active"])
|
||||
# Note: url already has an index from the model definition
|
||||
|
||||
# Composite index for common query pattern (active items due for refresh)
|
||||
op.create_index("ix_items_active_last_checked", "items", ["is_active", "last_checked"])
|
||||
|
||||
# Price history indexes for time-series queries
|
||||
op.create_index("ix_price_history_timestamp", "price_history", ["timestamp"])
|
||||
op.create_index("ix_price_history_item_timestamp", "price_history", ["item_id", "timestamp"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Remove indexes in reverse order
|
||||
op.drop_index("ix_price_history_item_timestamp", table_name="price_history")
|
||||
op.drop_index("ix_price_history_timestamp", table_name="price_history")
|
||||
op.drop_index("ix_items_active_last_checked", table_name="items")
|
||||
op.drop_index("ix_items_is_active", table_name="items")
|
||||
op.drop_index("ix_items_last_checked", table_name="items")
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Add confidence and AI metadata
|
||||
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises: 6ecb6f39fd8c
|
||||
Create Date: 2025-11-19 13:55:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
from app.models import Base
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "a1b2c3d4e5f6"
|
||||
down_revision: str | None = "6ecb6f39fd8c"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Add confidence scores and AI metadata to price_history and items tables."""
|
||||
|
||||
# Add columns to price_history table
|
||||
op.add_column("price_history", sa.Column("price_confidence", sa.Float(), nullable=True))
|
||||
op.add_column("price_history", sa.Column("in_stock_confidence", sa.Float(), nullable=True))
|
||||
op.add_column("price_history", sa.Column("ai_model", sa.String(), nullable=True))
|
||||
op.add_column("price_history", sa.Column("ai_provider", sa.String(), nullable=True))
|
||||
op.add_column("price_history", sa.Column("prompt_version", sa.String(), nullable=True))
|
||||
op.add_column("price_history", sa.Column("repair_used", sa.Boolean(), nullable=True, server_default="false"))
|
||||
|
||||
# Add columns to items table for quick access to latest confidence
|
||||
op.add_column("items", sa.Column("current_price_confidence", sa.Float(), nullable=True))
|
||||
op.add_column("items", sa.Column("in_stock_confidence", sa.Float(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Remove confidence scores and AI metadata columns."""
|
||||
|
||||
# Remove columns from items table
|
||||
op.drop_column("items", "in_stock_confidence")
|
||||
op.drop_column("items", "current_price_confidence")
|
||||
|
||||
# Remove columns from price_history table
|
||||
op.drop_column("price_history", "repair_used")
|
||||
op.drop_column("price_history", "prompt_version")
|
||||
op.drop_column("price_history", "ai_provider")
|
||||
op.drop_column("price_history", "ai_model")
|
||||
op.drop_column("price_history", "in_stock_confidence")
|
||||
op.drop_column("price_history", "price_confidence")
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: initial_migration
|
||||
Revises:
|
||||
Create Date: 2023-11-19 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "initial_migration"
|
||||
down_revision: str | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# We are assuming the database is already created by the previous code
|
||||
# But for a fresh install, we need to create tables.
|
||||
# However, since we are retrofitting, we should use --autogenerate usually.
|
||||
# But I cannot run that easily.
|
||||
# So I will define the tables here to be safe.
|
||||
|
||||
# Check if tables exist before creating to avoid errors on existing DBs
|
||||
# Actually, standard alembic practice is to define them.
|
||||
# But since we had `Base.metadata.create_all`, tables might exist.
|
||||
# Ideally we would use `alembic stamp head` on existing deployments.
|
||||
|
||||
# For now, I will leave this empty and assume the user will run
|
||||
# `alembic revision --autogenerate` if they want to capture the state,
|
||||
# or I should try to capture it.
|
||||
# Given I can't run the DB, I'll leave it as a placeholder or try to define it.
|
||||
# Let's define it properly so new installs work.
|
||||
|
||||
# ... actually, writing all create_table calls manually is error prone without running it.
|
||||
# I will rely on the fact that I removed `create_all` from main.py, so this MUST do it.
|
||||
|
||||
op.create_table(
|
||||
"notification_profiles",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=True),
|
||||
sa.Column("apprise_url", sa.String(), nullable=True),
|
||||
sa.Column("notify_on_price_drop", sa.Boolean(), nullable=True),
|
||||
sa.Column("notify_on_target_price", sa.Boolean(), nullable=True),
|
||||
sa.Column("price_drop_threshold_percent", sa.Float(), nullable=True),
|
||||
sa.Column("notify_on_stock_change", sa.Boolean(), nullable=True),
|
||||
sa.Column("check_interval_minutes", sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_notification_profiles_id"), "notification_profiles", ["id"], unique=False)
|
||||
op.create_index(op.f("ix_notification_profiles_name"), "notification_profiles", ["name"], unique=True)
|
||||
|
||||
op.create_table(
|
||||
"items",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("url", sa.String(), nullable=True),
|
||||
sa.Column("name", sa.String(), nullable=True),
|
||||
sa.Column("selector", sa.String(), nullable=True),
|
||||
sa.Column("target_price", sa.Float(), nullable=True),
|
||||
sa.Column("check_interval_minutes", sa.Integer(), nullable=True),
|
||||
sa.Column("current_price", sa.Float(), nullable=True),
|
||||
sa.Column("in_stock", sa.Boolean(), nullable=True),
|
||||
sa.Column("tags", sa.String(), nullable=True),
|
||||
sa.Column("description", sa.String(), nullable=True),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=True),
|
||||
sa.Column("last_checked", sa.DateTime(), nullable=True),
|
||||
sa.Column("notification_profile_id", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["notification_profile_id"],
|
||||
["notification_profiles.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_items_id"), "items", ["id"], unique=False)
|
||||
op.create_index(op.f("ix_items_url"), "items", ["url"], unique=False)
|
||||
|
||||
op.create_table(
|
||||
"price_history",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("item_id", sa.Integer(), nullable=True),
|
||||
sa.Column("price", sa.Float(), nullable=True),
|
||||
sa.Column("timestamp", sa.DateTime(), nullable=True),
|
||||
sa.Column("screenshot_path", sa.String(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["item_id"],
|
||||
["items.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(op.f("ix_price_history_id"), "price_history", ["id"], unique=False)
|
||||
|
||||
op.create_table(
|
||||
"settings",
|
||||
sa.Column("key", sa.String(), nullable=False),
|
||||
sa.Column("value", sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("key"),
|
||||
)
|
||||
op.create_index(op.f("ix_settings_key"), "settings", ["key"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f("ix_settings_key"), table_name="settings")
|
||||
op.drop_table("settings")
|
||||
op.drop_index(op.f("ix_price_history_id"), table_name="price_history")
|
||||
op.drop_table("price_history")
|
||||
op.drop_index(op.f("ix_items_url"), table_name="items")
|
||||
op.drop_index(op.f("ix_items_id"), table_name="items")
|
||||
op.drop_table("items")
|
||||
op.drop_index(op.f("ix_notification_profiles_name"), table_name="notification_profiles")
|
||||
op.drop_index(op.f("ix_notification_profiles_id"), table_name="notification_profiles")
|
||||
op.drop_table("notification_profiles")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Add performance indexes
|
||||
|
||||
Revision ID: performance_indexes_v2
|
||||
Revises: 7f8e9d2a1b3c
|
||||
Create Date: 2025-11-19
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "performance_indexes_v2"
|
||||
down_revision = "7f8e9d2a1b3c"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Add indexes only if they don't exist
|
||||
# Using raw SQL with IF NOT EXISTS for safety
|
||||
op.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS ix_price_history_timestamp
|
||||
ON price_history (timestamp)
|
||||
"""
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS ix_price_history_item_timestamp
|
||||
ON price_history (item_id, timestamp)
|
||||
"""
|
||||
)
|
||||
|
||||
op.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS ix_items_is_active
|
||||
ON items (is_active)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_items_is_active", table_name="items", if_exists=True)
|
||||
op.drop_index("ix_price_history_item_timestamp", table_name="price_history", if_exists=True)
|
||||
op.drop_index("ix_price_history_timestamp", table_name="price_history", if_exists=True)
|
||||
@@ -0,0 +1,58 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import QueuePool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Remove hardcoded credentials - require environment variable
|
||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
||||
|
||||
if not DATABASE_URL:
|
||||
raise ValueError(
|
||||
"DATABASE_URL environment variable is required. Example: postgresql://user:password@localhost:5432/pricewatch"
|
||||
)
|
||||
|
||||
# Connection pool configuration
|
||||
# pool_size: number of connections to maintain
|
||||
# max_overflow: max number of connections above pool_size
|
||||
# pool_pre_ping: verify connections before using (prevents stale connections)
|
||||
# pool_recycle: recycle connections after N seconds (prevents timeout issues)
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
poolclass=QueuePool,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=3600, # 1 hour
|
||||
echo=os.getenv("SQL_ECHO", "false").lower() == "true",
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# Log database connection events for debugging
|
||||
@event.listens_for(engine, "connect")
|
||||
def receive_connect(dbapi_conn, connection_record):
|
||||
logger.debug("Database connection established")
|
||||
|
||||
|
||||
@event.listens_for(engine, "close")
|
||||
def receive_close(dbapi_conn, connection_record):
|
||||
logger.debug("Database connection closed")
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,4 @@
|
||||
from slowapi import Limiter
|
||||
from slowapi.util import get_remote_address
|
||||
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from slowapi import _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
|
||||
from app.limiter import limiter
|
||||
from app.routers import items, jobs, notifications, settings
|
||||
from app.services.scheduler_service import scheduled_refresh, scheduler
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=os.getenv("LOG_LEVEL", "INFO").upper(),
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Starting smart scheduler (Heartbeat: 1 minute)")
|
||||
scheduler.add_job(scheduled_refresh, IntervalTrigger(minutes=1), id="refresh_job", replace_existing=True)
|
||||
scheduler.start()
|
||||
logger.info("Application started")
|
||||
yield
|
||||
logger.info("Shutting down scheduler...")
|
||||
scheduler.shutdown(wait=True)
|
||||
logger.info("Application shutdown complete")
|
||||
|
||||
|
||||
app = FastAPI(title="Pricecious API", version="0.1.0", lifespan=lifespan)
|
||||
|
||||
# Rate Limiting & CORS
|
||||
app.state.limiter = limiter
|
||||
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) # type: ignore
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=os.getenv("CORS_ORIGINS", "*").split(","),
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def log_requests(request: Request, call_next):
|
||||
logger.debug(f"Request: {request.method} {request.url}")
|
||||
response = await call_next(request)
|
||||
logger.debug(f"Response: {response.status_code}")
|
||||
return response
|
||||
|
||||
|
||||
# Static Files
|
||||
if os.path.exists("static"):
|
||||
app.mount("/assets", StaticFiles(directory="static/assets"), name="assets")
|
||||
os.makedirs("screenshots", exist_ok=True)
|
||||
app.mount("/screenshots", StaticFiles(directory="screenshots"), name="screenshots")
|
||||
|
||||
# Routers
|
||||
for router in [notifications.router, items.router, settings.router, jobs.router]:
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/api/")
|
||||
def read_root():
|
||||
return {"message": "Welcome to Pricecious API"}
|
||||
|
||||
|
||||
# Frontend Serving
|
||||
@app.get("/{full_path:path}")
|
||||
async def serve_spa(full_path: str):
|
||||
if full_path.startswith(("api", "screenshots", "assets")):
|
||||
return {"message": "Not found"}
|
||||
|
||||
# Serve static files from root (favicon, logo, etc.)
|
||||
static_file_path = f"static/{full_path}"
|
||||
if os.path.isfile(static_file_path):
|
||||
return FileResponse(static_file_path)
|
||||
|
||||
# Default to SPA index.html
|
||||
if os.path.exists("static/index.html"):
|
||||
return FileResponse("static/index.html")
|
||||
return {"message": "Frontend not built or not found"}
|
||||
@@ -0,0 +1,79 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .database import Base
|
||||
|
||||
|
||||
class NotificationProfile(Base):
|
||||
__tablename__ = "notification_profiles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, unique=True, index=True)
|
||||
apprise_url = Column(String)
|
||||
notify_on_price_drop = Column(Boolean, default=True)
|
||||
notify_on_target_price = Column(Boolean, default=True)
|
||||
price_drop_threshold_percent = Column(Float, default=10.0)
|
||||
notify_on_stock_change = Column(Boolean, default=True)
|
||||
check_interval_minutes = Column(Integer, default=60)
|
||||
|
||||
items = relationship("Item", back_populates="notification_profile")
|
||||
|
||||
|
||||
class Item(Base):
|
||||
__tablename__ = "items"
|
||||
|
||||
id: int = Column(Integer, primary_key=True, index=True) # type: ignore
|
||||
url: str = Column(String, index=True) # type: ignore
|
||||
name: str = Column(String) # type: ignore
|
||||
selector: str | None = Column(String, nullable=True) # type: ignore
|
||||
target_price: float | None = Column(Float, nullable=True) # type: ignore
|
||||
check_interval_minutes: int = Column(Integer, default=60) # type: ignore
|
||||
|
||||
# New fields
|
||||
current_price: float | None = Column(Float, nullable=True) # type: ignore
|
||||
in_stock: bool | None = Column(Boolean, nullable=True) # type: ignore
|
||||
tags: str | None = Column(String, nullable=True) # type: ignore
|
||||
description: str | None = Column(String, nullable=True) # type: ignore
|
||||
|
||||
# Confidence scores for latest extraction
|
||||
current_price_confidence: float | None = Column(Float, nullable=True) # type: ignore
|
||||
in_stock_confidence: float | None = Column(Float, nullable=True) # type: ignore
|
||||
|
||||
is_active: bool = Column(Boolean, default=True) # type: ignore
|
||||
last_checked: datetime | None = Column(DateTime, nullable=True) # type: ignore
|
||||
is_refreshing: bool = Column(Boolean, default=False) # type: ignore
|
||||
last_error: str | None = Column(String, nullable=True) # type: ignore
|
||||
|
||||
notification_profile_id: int | None = Column(Integer, ForeignKey("notification_profiles.id"), nullable=True) # type: ignore
|
||||
notification_profile = relationship("NotificationProfile", back_populates="items")
|
||||
|
||||
price_history = relationship("PriceHistory", back_populates="item", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PriceHistory(Base):
|
||||
__tablename__ = "price_history"
|
||||
|
||||
id: int = Column(Integer, primary_key=True, index=True) # type: ignore
|
||||
item_id: int = Column(Integer, ForeignKey("items.id")) # type: ignore
|
||||
price: float = Column(Float) # type: ignore
|
||||
timestamp: datetime = Column(DateTime, default=lambda: datetime.now(UTC)) # type: ignore
|
||||
screenshot_path: str | None = Column(String, nullable=True) # type: ignore
|
||||
|
||||
# Confidence scores and AI metadata
|
||||
price_confidence: float | None = Column(Float, nullable=True) # type: ignore
|
||||
in_stock_confidence: float | None = Column(Float, nullable=True) # type: ignore
|
||||
ai_model: str | None = Column(String, nullable=True) # type: ignore
|
||||
ai_provider: str | None = Column(String, nullable=True) # type: ignore
|
||||
prompt_version: str | None = Column(String, nullable=True) # type: ignore
|
||||
repair_used: bool | None = Column(Boolean, nullable=True, default=False) # type: ignore
|
||||
|
||||
item = relationship("Item", back_populates="price_history")
|
||||
|
||||
|
||||
class Settings(Base):
|
||||
__tablename__ = "settings"
|
||||
|
||||
key = Column(String, primary_key=True, index=True)
|
||||
value = Column(Text)
|
||||
@@ -0,0 +1,36 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import apprise
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _send_sync(urls: list, title: str, body: str):
|
||||
"""
|
||||
Synchronous notification sending.
|
||||
"""
|
||||
if not urls:
|
||||
return
|
||||
|
||||
apobj = apprise.Apprise()
|
||||
|
||||
for url in urls:
|
||||
apobj.add(url)
|
||||
|
||||
try:
|
||||
apobj.notify(
|
||||
body=body,
|
||||
title=title,
|
||||
)
|
||||
logger.info(f"Notification sent: {title}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending notification: {e}")
|
||||
|
||||
|
||||
async def send_notification(urls: list, title: str, body: str):
|
||||
"""
|
||||
Async wrapper for sending notifications.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
await loop.run_in_executor(None, _send_sync, urls, title, body)
|
||||
@@ -0,0 +1,46 @@
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import database, schemas
|
||||
from app.limiter import limiter
|
||||
from app.services.item_service import ItemService
|
||||
from app.services.scheduler_service import process_item_check
|
||||
|
||||
router = APIRouter(prefix="/items", tags=["items"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[schemas.ItemResponse])
|
||||
def get_items(db: Session = Depends(database.get_db)):
|
||||
return ItemService.get_items(db)
|
||||
|
||||
|
||||
@router.post("", response_model=schemas.ItemResponse)
|
||||
def create_item(item: schemas.ItemCreate, db: Session = Depends(database.get_db)):
|
||||
return ItemService.create_item(db, item)
|
||||
|
||||
|
||||
@router.put("/{item_id}", response_model=schemas.ItemResponse)
|
||||
def update_item(item_id: int, item_update: schemas.ItemCreate, db: Session = Depends(database.get_db)):
|
||||
return ItemService.update_item(db, item_id, item_update)
|
||||
|
||||
|
||||
@router.delete("/{item_id}")
|
||||
def delete_item(item_id: int, db: Session = Depends(database.get_db)):
|
||||
return ItemService.delete_item(db, item_id)
|
||||
|
||||
|
||||
@router.post("/{item_id}/check")
|
||||
@limiter.limit("10/minute")
|
||||
def check_item(
|
||||
request: Request, item_id: int, background_tasks: BackgroundTasks, db: Session = Depends(database.get_db)
|
||||
):
|
||||
item = ItemService.get_item(db, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
item.is_refreshing = True
|
||||
item.last_error = None
|
||||
db.commit()
|
||||
|
||||
background_tasks.add_task(process_item_check, item_id)
|
||||
return {"message": "Check triggered"}
|
||||
@@ -0,0 +1,61 @@
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import database, models, schemas
|
||||
from app.limiter import limiter
|
||||
from app.services.scheduler_service import process_item_check, scheduled_refresh, scheduler
|
||||
from app.services.settings_service import SettingsService
|
||||
|
||||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
def get_job_config(db: Session = Depends(database.get_db)):
|
||||
interval = int(SettingsService.get_setting_value(db, "refresh_interval_minutes", "60"))
|
||||
|
||||
next_run = None
|
||||
job = scheduler.get_job("refresh_job")
|
||||
if job:
|
||||
next_run = job.next_run_time
|
||||
|
||||
return {"refresh_interval_minutes": interval, "next_run": next_run, "running": scheduler.running}
|
||||
|
||||
|
||||
@router.post("/config")
|
||||
def update_job_config(config: schemas.SettingsUpdate, db: Session = Depends(database.get_db)):
|
||||
if config.key != "refresh_interval_minutes":
|
||||
raise HTTPException(status_code=400, detail="Invalid setting key for job config")
|
||||
|
||||
try:
|
||||
interval = int(config.value)
|
||||
if interval < 1:
|
||||
raise ValueError("Interval must be at least 1 minute")
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail="Invalid interval value") from e
|
||||
|
||||
SettingsService.update_setting(db, config)
|
||||
|
||||
try:
|
||||
scheduler.reschedule_job("refresh_job", trigger=IntervalTrigger(minutes=interval))
|
||||
except Exception:
|
||||
scheduler.add_job(scheduled_refresh, IntervalTrigger(minutes=interval), id="refresh_job", replace_existing=True)
|
||||
|
||||
return {"message": "Job configuration updated", "refresh_interval_minutes": interval}
|
||||
|
||||
|
||||
@router.post("/refresh-all")
|
||||
@limiter.limit("5/minute")
|
||||
def refresh_all_items(request: Request, background_tasks: BackgroundTasks, db: Session = Depends(database.get_db)):
|
||||
items = db.query(models.Item).filter(models.Item.is_active).all()
|
||||
|
||||
# Mark all items as refreshing immediately so UI updates persist
|
||||
for item in items:
|
||||
item.is_refreshing = True
|
||||
db.commit()
|
||||
|
||||
for item in items:
|
||||
if item.id is not None:
|
||||
background_tasks.add_task(process_item_check, int(item.id))
|
||||
|
||||
return {"message": f"Triggered refresh for {len(items)} items"}
|
||||
@@ -0,0 +1,29 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import database, schemas
|
||||
from app.services.notification_service import NotificationService
|
||||
|
||||
router = APIRouter(prefix="/notification-profiles", tags=["notifications"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[schemas.NotificationProfileResponse])
|
||||
def get_notification_profiles(db: Session = Depends(database.get_db)):
|
||||
return NotificationService.get_notification_profiles(db)
|
||||
|
||||
|
||||
@router.post("", response_model=schemas.NotificationProfileResponse)
|
||||
def create_notification_profile(profile: schemas.NotificationProfileCreate, db: Session = Depends(database.get_db)):
|
||||
return NotificationService.create_notification_profile(db, profile)
|
||||
|
||||
|
||||
@router.delete("/{profile_id}")
|
||||
def delete_notification_profile(profile_id: int, db: Session = Depends(database.get_db)):
|
||||
return NotificationService.delete_notification_profile(db, profile_id)
|
||||
|
||||
|
||||
@router.put("/{profile_id}", response_model=schemas.NotificationProfileResponse)
|
||||
def update_notification_profile(
|
||||
profile_id: int, profile: schemas.NotificationProfileUpdate, db: Session = Depends(database.get_db)
|
||||
):
|
||||
return NotificationService.update_notification_profile(db, profile_id, profile)
|
||||
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import database, schemas
|
||||
from app.services.settings_service import SettingsService
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_settings(db: Session = Depends(database.get_db)):
|
||||
return SettingsService.get_settings(db)
|
||||
|
||||
|
||||
@router.post("", response_model=schemas.SettingsUpdate)
|
||||
def update_setting(setting: schemas.SettingsUpdate, db: Session = Depends(database.get_db)):
|
||||
return SettingsService.update_setting(db, setting)
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class NotificationProfileCreate(BaseModel):
|
||||
name: str
|
||||
apprise_url: str
|
||||
notify_on_price_drop: bool = True
|
||||
notify_on_target_price: bool = True
|
||||
price_drop_threshold_percent: float = 10.0
|
||||
notify_on_stock_change: bool = True
|
||||
check_interval_minutes: int = 60
|
||||
|
||||
|
||||
class NotificationProfileUpdate(NotificationProfileCreate):
|
||||
pass
|
||||
|
||||
|
||||
class NotificationProfileResponse(NotificationProfileCreate):
|
||||
id: int
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class ItemCreate(BaseModel):
|
||||
url: str
|
||||
name: str
|
||||
selector: str | None = None
|
||||
target_price: float | None = None
|
||||
check_interval_minutes: int = 60
|
||||
tags: str | None = None
|
||||
description: str | None = None
|
||||
notification_profile_id: int | None = None
|
||||
|
||||
|
||||
class ItemResponse(ItemCreate):
|
||||
id: int
|
||||
current_price: float | None
|
||||
in_stock: bool | None
|
||||
current_price_confidence: float | None = None
|
||||
in_stock_confidence: float | None = None
|
||||
is_active: bool
|
||||
last_checked: datetime | None
|
||||
is_refreshing: bool = False
|
||||
last_error: str | None = None
|
||||
screenshot_url: str | None = None
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class SettingsUpdate(BaseModel):
|
||||
key: str
|
||||
value: str
|
||||
@@ -0,0 +1,352 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any, TypedDict
|
||||
|
||||
from litellm import acompletion
|
||||
from pydantic import ValidationError
|
||||
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
|
||||
|
||||
from app import models
|
||||
from app.ai_schema import (
|
||||
PROMPT_VERSION,
|
||||
AIExtractionMetadata,
|
||||
AIExtractionResponse,
|
||||
get_extraction_prompt,
|
||||
get_repair_prompt,
|
||||
)
|
||||
from app.database import SessionLocal
|
||||
from app.utils.image import encode_image
|
||||
from app.utils.text import clean_text
|
||||
|
||||
# Default configuration (can be overridden by DB settings)
|
||||
DEFAULT_PROVIDER = "ollama"
|
||||
DEFAULT_MODEL = "gemma3:4b"
|
||||
DEFAULT_API_BASE = "http://ollama:11434"
|
||||
DEFAULT_TEMPERATURE = 0.1
|
||||
DEFAULT_MAX_TOKENS = 300
|
||||
DEFAULT_TIMEOUT = 30 # seconds
|
||||
MAX_TEXT_LENGTH = 5000 # Will be filtered to ~1500-2000 relevant chars
|
||||
|
||||
# Config caching
|
||||
_config_cache: dict[str, Any] = {"data": None, "timestamp": 0.0}
|
||||
CONFIG_CACHE_TTL = 60 # seconds
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AIConfig(TypedDict):
|
||||
provider: str
|
||||
model: str
|
||||
api_key: str
|
||||
api_base: str
|
||||
temperature: float
|
||||
max_tokens: int
|
||||
timeout: int
|
||||
enable_json_repair: bool
|
||||
enable_multi_sample: bool
|
||||
multi_sample_threshold: float
|
||||
|
||||
|
||||
MIN_API_KEY_LENGTH = 12
|
||||
|
||||
|
||||
def _sanitize_api_key(key: str) -> str:
|
||||
"""Redact API key for logging (show first/last 4 chars only)."""
|
||||
if not key or len(key) < MIN_API_KEY_LENGTH:
|
||||
return "***"
|
||||
return f"{key[:4]}...{key[-4:]}"
|
||||
|
||||
|
||||
class AIService:
|
||||
@staticmethod
|
||||
def get_ai_config() -> AIConfig:
|
||||
"""
|
||||
Fetches AI configuration from the database with caching.
|
||||
Returns a dict with: provider, model, api_key, api_base, temperature, max_tokens, timeout
|
||||
"""
|
||||
# Check cache
|
||||
now = time.time()
|
||||
if _config_cache["data"] and (now - _config_cache["timestamp"]) < CONFIG_CACHE_TTL:
|
||||
return _config_cache["data"] # type: ignore
|
||||
|
||||
# Fetch from DB
|
||||
session = SessionLocal()
|
||||
try:
|
||||
settings = session.query(models.Settings).all()
|
||||
settings_map = {s.key: s.value for s in settings}
|
||||
|
||||
config: AIConfig = {
|
||||
"provider": settings_map.get("ai_provider", DEFAULT_PROVIDER),
|
||||
"model": settings_map.get("ai_model", DEFAULT_MODEL),
|
||||
"api_key": settings_map.get("ai_api_key", ""),
|
||||
"api_base": settings_map.get("ai_api_base", DEFAULT_API_BASE),
|
||||
"temperature": float(settings_map.get("ai_temperature", str(DEFAULT_TEMPERATURE))),
|
||||
"max_tokens": int(settings_map.get("ai_max_tokens", str(DEFAULT_MAX_TOKENS))),
|
||||
"timeout": int(settings_map.get("ai_timeout", str(DEFAULT_TIMEOUT))),
|
||||
"enable_json_repair": settings_map.get("enable_json_repair", "true").lower() == "true",
|
||||
"enable_multi_sample": settings_map.get("enable_multi_sample", "false").lower() == "true",
|
||||
"multi_sample_threshold": float(settings_map.get("multi_sample_confidence_threshold", "0.6")),
|
||||
}
|
||||
|
||||
# Update cache
|
||||
_config_cache["data"] = config # type: ignore
|
||||
_config_cache["timestamp"] = now
|
||||
|
||||
return config
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching AI config: {e}")
|
||||
return {
|
||||
"provider": DEFAULT_PROVIDER,
|
||||
"model": DEFAULT_MODEL,
|
||||
"api_key": "",
|
||||
"api_base": DEFAULT_API_BASE,
|
||||
"temperature": DEFAULT_TEMPERATURE,
|
||||
"max_tokens": DEFAULT_MAX_TOKENS,
|
||||
"timeout": DEFAULT_TIMEOUT,
|
||||
"enable_json_repair": True,
|
||||
"enable_multi_sample": False,
|
||||
"multi_sample_threshold": 0.6,
|
||||
}
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
@staticmethod
|
||||
def parse_and_validate_response(response_text: str) -> AIExtractionResponse:
|
||||
"""
|
||||
Parse and validate AI response against schema.
|
||||
|
||||
Pipeline:
|
||||
1. Extract JSON from response (handle markdown code blocks)
|
||||
2. Parse JSON
|
||||
3. Validate against Pydantic schema (includes normalization and clamping)
|
||||
|
||||
Raises:
|
||||
ValidationError: If response doesn't match schema
|
||||
json.JSONDecodeError: If JSON is invalid
|
||||
"""
|
||||
# Try to extract JSON from markdown code blocks
|
||||
json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", response_text, re.DOTALL)
|
||||
if json_match:
|
||||
json_str = json_match.group(1)
|
||||
else:
|
||||
# Try to find raw JSON object
|
||||
json_match = re.search(r"\{.*\}", response_text, re.DOTALL)
|
||||
if json_match:
|
||||
json_str = json_match.group(0)
|
||||
else:
|
||||
json_str = response_text
|
||||
|
||||
# Parse JSON
|
||||
data = json.loads(json_str)
|
||||
|
||||
# Validate and normalize through Pydantic
|
||||
return AIExtractionResponse(**data)
|
||||
|
||||
@classmethod
|
||||
async def repair_json_response(
|
||||
cls,
|
||||
raw_output: str,
|
||||
config: AIConfig,
|
||||
) -> AIExtractionResponse:
|
||||
"""
|
||||
Attempt to repair invalid JSON using a second LLM call.
|
||||
|
||||
Args:
|
||||
raw_output: The raw AI output that failed parsing
|
||||
config: AI configuration dict
|
||||
|
||||
Returns:
|
||||
Validated AIExtractionResponse
|
||||
|
||||
Raises:
|
||||
Exception: If repair also fails
|
||||
"""
|
||||
logger.warning("Attempting JSON repair with second LLM call")
|
||||
|
||||
repair_prompt = get_repair_prompt(raw_output)
|
||||
|
||||
# Use a simpler, cheaper model for repair if possible
|
||||
# For now, use the same model
|
||||
kwargs = {
|
||||
"model": config["model"] if config["provider"] != "ollama" else f"ollama/{config['model']}",
|
||||
"messages": [{"role": "user", "content": repair_prompt}],
|
||||
"max_tokens": 300,
|
||||
"temperature": 0.0, # Very deterministic for repair
|
||||
"timeout": config["timeout"],
|
||||
}
|
||||
|
||||
if config["api_key"]:
|
||||
kwargs["api_key"] = config["api_key"]
|
||||
|
||||
if config["provider"] == "ollama":
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
kwargs["format"] = "json"
|
||||
elif config["provider"] == "openai" and config["api_base"]:
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
|
||||
response = await acompletion(**kwargs)
|
||||
repaired_text = response.choices[0].message.content
|
||||
|
||||
# Validate repaired response
|
||||
return cls.parse_and_validate_response(repaired_text)
|
||||
|
||||
@staticmethod
|
||||
@retry(
|
||||
retry=retry_if_exception_type((TimeoutError, ConnectionError)),
|
||||
stop=stop_after_attempt(3),
|
||||
wait=wait_exponential(multiplier=1, min=2, max=10),
|
||||
reraise=True,
|
||||
)
|
||||
async def call_llm(
|
||||
prompt: str,
|
||||
image_data_url: str,
|
||||
config: AIConfig,
|
||||
) -> str:
|
||||
"""
|
||||
Call LLM with structured output settings and retry logic.
|
||||
|
||||
Returns:
|
||||
Raw response text from the model
|
||||
|
||||
Raises:
|
||||
TimeoutError: If request times out after retries
|
||||
ConnectionError: If connection fails after retries
|
||||
"""
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": prompt},
|
||||
{"type": "image_url", "image_url": {"url": image_data_url}},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
# Prepare kwargs for litellm
|
||||
kwargs: dict[str, Any] = {
|
||||
"model": config["model"] if config["provider"] != "ollama" else f"ollama/{config['model']}",
|
||||
"messages": messages,
|
||||
"max_tokens": config["max_tokens"],
|
||||
"temperature": config["temperature"],
|
||||
"timeout": config["timeout"],
|
||||
}
|
||||
|
||||
if config["api_key"]:
|
||||
kwargs["api_key"] = config["api_key"]
|
||||
|
||||
# Provider-specific structured output features
|
||||
if config["provider"] == "ollama":
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
kwargs["format"] = "json" # Force JSON mode for Ollama
|
||||
elif config["provider"] == "openai":
|
||||
# Use OpenAI's JSON mode
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
if config["api_base"]:
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
elif config["provider"] == "anthropic":
|
||||
# Anthropic doesn't have native JSON mode yet, rely on prompt
|
||||
if config["api_base"]:
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
# Other providers - rely on prompt engineering
|
||||
elif config["api_base"]:
|
||||
kwargs["api_base"] = config["api_base"]
|
||||
|
||||
# Call litellm asynchronously
|
||||
sanitized_key = _sanitize_api_key(config["api_key"]) if config["api_key"] else "(none)"
|
||||
logger.info(
|
||||
f"Calling {config['provider']}/{config['model']} "
|
||||
f"(temp={config['temperature']}, max_tokens={config['max_tokens']}, "
|
||||
f"timeout={config['timeout']}s, key={sanitized_key})"
|
||||
)
|
||||
response = await acompletion(**kwargs)
|
||||
|
||||
content = response.choices[0].message.content
|
||||
return content or ""
|
||||
|
||||
@classmethod
|
||||
async def analyze_image(
|
||||
cls,
|
||||
image_path: str,
|
||||
page_text: str = "",
|
||||
) -> tuple[AIExtractionResponse, AIExtractionMetadata] | None:
|
||||
"""
|
||||
Analyze image and extract price/stock information.
|
||||
|
||||
Args:
|
||||
image_path: Path to screenshot
|
||||
page_text: Optional webpage text context
|
||||
|
||||
Returns:
|
||||
Tuple of (AIExtractionResponse, AIExtractionMetadata) or None on failure
|
||||
"""
|
||||
try:
|
||||
# Get AI config
|
||||
loop = asyncio.get_running_loop()
|
||||
config = await loop.run_in_executor(None, cls.get_ai_config)
|
||||
|
||||
logger.info(
|
||||
f"Analyzing image with Provider: {config['provider']}, "
|
||||
f"Model: {config['model']}, Timeout: {config['timeout']}s"
|
||||
)
|
||||
|
||||
# Encode image
|
||||
base64_image = await encode_image(image_path)
|
||||
data_url = f"data:image/jpeg;base64,{base64_image}"
|
||||
|
||||
# Prepare prompt with optional text context
|
||||
cleaned_text = ""
|
||||
if page_text:
|
||||
cleaned_text = clean_text(page_text)
|
||||
if len(cleaned_text) > MAX_TEXT_LENGTH:
|
||||
cleaned_text = cleaned_text[:MAX_TEXT_LENGTH] + "...(truncated)"
|
||||
logger.info(f"Added text context (original: {len(page_text)}, cleaned: {len(cleaned_text)})")
|
||||
|
||||
prompt = get_extraction_prompt(cleaned_text if cleaned_text else None)
|
||||
|
||||
# Call LLM
|
||||
response_text = await cls.call_llm(prompt, data_url, config)
|
||||
|
||||
logger.info(f"AI Response: {response_text[:200]}...")
|
||||
|
||||
# Parse and validate response
|
||||
repair_used = False
|
||||
try:
|
||||
extraction_result = cls.parse_and_validate_response(response_text)
|
||||
except (ValidationError, json.JSONDecodeError) as e:
|
||||
logger.warning(f"Primary parsing failed: {e}")
|
||||
|
||||
if config["enable_json_repair"]:
|
||||
try:
|
||||
extraction_result = await cls.repair_json_response(response_text, config)
|
||||
repair_used = True
|
||||
logger.info("JSON repair successful")
|
||||
except Exception as repair_error:
|
||||
logger.error(f"JSON repair also failed: {repair_error}")
|
||||
raise
|
||||
else:
|
||||
raise
|
||||
|
||||
# Create metadata
|
||||
metadata = AIExtractionMetadata(
|
||||
model_name=config["model"],
|
||||
provider=config["provider"],
|
||||
prompt_version=PROMPT_VERSION,
|
||||
repair_used=repair_used,
|
||||
multi_sample=False,
|
||||
sample_count=1,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Extraction successful: price={extraction_result.price} "
|
||||
f"(conf={extraction_result.price_confidence:.2f}), "
|
||||
f"stock={extraction_result.in_stock} (conf={extraction_result.in_stock_confidence:.2f})"
|
||||
)
|
||||
|
||||
return extraction_result, metadata
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in analyze_image: {e}", exc_info=True)
|
||||
return None
|
||||
@@ -0,0 +1,135 @@
|
||||
import logging
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import models, schemas
|
||||
from app.services.settings_service import SettingsService
|
||||
from app.url_validation import URLValidationError, validate_url
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ItemService:
|
||||
@staticmethod
|
||||
def get_items(db: Session):
|
||||
items = db.query(models.Item).all()
|
||||
return [
|
||||
{
|
||||
**item.__dict__,
|
||||
"screenshot_url": f"/screenshots/item_{item.id}.png"
|
||||
if os.path.exists(f"screenshots/item_{item.id}.png")
|
||||
else None,
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def create_item(db: Session, item: schemas.ItemCreate):
|
||||
logger.info(f"Creating item: {item.name} - {item.url}")
|
||||
try:
|
||||
validate_url(item.url)
|
||||
except URLValidationError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid URL: {e}") from e
|
||||
|
||||
db_item = models.Item(**item.model_dump())
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@staticmethod
|
||||
def update_item(db: Session, item_id: int, item_update: schemas.ItemCreate):
|
||||
db_item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
for key, value in item_update.model_dump().items():
|
||||
setattr(db_item, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
|
||||
@staticmethod
|
||||
def delete_item(db: Session, item_id: int):
|
||||
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
if os.path.exists(f"screenshots/item_{item_id}.png"):
|
||||
try:
|
||||
os.remove(f"screenshots/item_{item_id}.png")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
db.delete(item)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@staticmethod
|
||||
def get_item(db: Session, item_id: int):
|
||||
return db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
|
||||
@staticmethod
|
||||
def get_item_data_for_checking(db: Session, item_id: int):
|
||||
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not item:
|
||||
return None, None
|
||||
|
||||
settings = {s.key: s.value for s in db.query(models.Settings).all()}
|
||||
profile = item.notification_profile
|
||||
|
||||
item_data = {
|
||||
"id": item.id,
|
||||
"url": item.url,
|
||||
"selector": item.selector,
|
||||
"name": item.name,
|
||||
"current_price": item.current_price,
|
||||
"in_stock": item.in_stock,
|
||||
"target_price": item.target_price,
|
||||
"notification_profile": profile.__dict__ if profile else None,
|
||||
}
|
||||
|
||||
config = {
|
||||
"smart_scroll": settings.get("smart_scroll_enabled", "false").lower() == "true",
|
||||
"smart_scroll_pixels": int(settings.get("smart_scroll_pixels", "350")),
|
||||
"text_context_enabled": settings.get("text_context_enabled", "false").lower() == "true",
|
||||
"text_length": int(settings.get("text_context_length", "5000"))
|
||||
if settings.get("text_context_enabled", "false").lower() == "true"
|
||||
else 0,
|
||||
"scraper_timeout": int(settings.get("scraper_timeout", "90000")),
|
||||
}
|
||||
return item_data, config
|
||||
|
||||
@staticmethod
|
||||
def get_due_items(db: Session):
|
||||
items = db.query(models.Item).filter(models.Item.is_active).all()
|
||||
global_interval = int(SettingsService.get_setting_value(db, "refresh_interval_minutes", "60"))
|
||||
due_items = []
|
||||
now = datetime.now(UTC)
|
||||
|
||||
for item in items:
|
||||
if item.is_refreshing:
|
||||
continue
|
||||
|
||||
interval = (
|
||||
item.notification_profile.check_interval_minutes
|
||||
if item.notification_profile and item.notification_profile.check_interval_minutes
|
||||
else global_interval
|
||||
)
|
||||
|
||||
if not item.last_checked:
|
||||
due_items.append((item.id, interval, -1))
|
||||
continue
|
||||
|
||||
last_checked = (
|
||||
item.last_checked.replace(tzinfo=UTC) if item.last_checked.tzinfo is None else item.last_checked
|
||||
)
|
||||
time_since = (now - last_checked).total_seconds() / 60
|
||||
if time_since >= interval:
|
||||
due_items.append((item.id, interval, int(time_since)))
|
||||
|
||||
return due_items
|
||||
@@ -0,0 +1,89 @@
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import models, notification_sender, schemas
|
||||
|
||||
|
||||
class NotificationService:
|
||||
@staticmethod
|
||||
def get_notification_profiles(db: Session):
|
||||
return db.query(models.NotificationProfile).all()
|
||||
|
||||
@staticmethod
|
||||
def create_notification_profile(db: Session, profile: schemas.NotificationProfileCreate):
|
||||
db_profile = models.NotificationProfile(**profile.model_dump())
|
||||
db.add(db_profile)
|
||||
db.commit()
|
||||
db.refresh(db_profile)
|
||||
return db_profile
|
||||
|
||||
@staticmethod
|
||||
def delete_notification_profile(db: Session, profile_id: int):
|
||||
profile = db.query(models.NotificationProfile).filter(models.NotificationProfile.id == profile_id).first()
|
||||
if not profile:
|
||||
raise HTTPException(status_code=404, detail="Profile not found")
|
||||
db.delete(profile)
|
||||
db.commit()
|
||||
db.delete(profile)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@staticmethod
|
||||
def update_notification_profile(db: Session, profile_id: int, profile_data: schemas.NotificationProfileUpdate):
|
||||
profile = db.query(models.NotificationProfile).filter(models.NotificationProfile.id == profile_id).first()
|
||||
if not profile:
|
||||
raise HTTPException(status_code=404, detail="Profile not found")
|
||||
|
||||
for key, value in profile_data.model_dump().items():
|
||||
setattr(profile, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(profile)
|
||||
return profile
|
||||
|
||||
@staticmethod
|
||||
async def send_item_notifications(
|
||||
item_data: dict,
|
||||
price: float | None,
|
||||
old_price: float | None,
|
||||
in_stock: bool | None,
|
||||
old_stock: bool | None,
|
||||
):
|
||||
profile = item_data["notification_profile"]
|
||||
if not profile:
|
||||
return
|
||||
|
||||
if profile["notify_on_price_drop"] and price is not None and old_price is not None:
|
||||
if price < old_price:
|
||||
drop_percent = ((old_price - price) / old_price) * 100
|
||||
if drop_percent >= profile["price_drop_threshold_percent"]:
|
||||
await notification_sender.send_notification(
|
||||
[profile["apprise_url"]],
|
||||
f"Price Drop Alert: {item_data['name']}",
|
||||
f"Price dropped by {drop_percent:.1f}%! Now ${price} (was ${old_price})",
|
||||
)
|
||||
|
||||
if (
|
||||
profile["notify_on_target_price"]
|
||||
and price is not None
|
||||
and item_data["target_price"]
|
||||
and price <= item_data["target_price"]
|
||||
):
|
||||
await notification_sender.send_notification(
|
||||
[profile["apprise_url"]],
|
||||
f"Target Price Alert: {item_data['name']}",
|
||||
f"Price is ${price} (Target: ${item_data['target_price']})",
|
||||
)
|
||||
|
||||
if (
|
||||
profile["notify_on_stock_change"]
|
||||
and in_stock is not None
|
||||
and old_stock is not None
|
||||
and in_stock != old_stock
|
||||
):
|
||||
status = "In Stock" if in_stock else "Out of Stock"
|
||||
await notification_sender.send_notification(
|
||||
[profile["apprise_url"]],
|
||||
f"Stock Alert: {item_data['name']}",
|
||||
f"Item is now {status}",
|
||||
)
|
||||
@@ -0,0 +1,147 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
|
||||
from app import database, models
|
||||
from app.ai_schema import AIExtractionMetadata, AIExtractionResponse
|
||||
from app.services.ai_service import AIService
|
||||
from app.services.item_service import ItemService
|
||||
from app.services.notification_service import NotificationService
|
||||
from app.services.scraper_service import ScraperService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
scheduler = AsyncIOScheduler()
|
||||
|
||||
PRICE_CHANGE_THRESHOLD_PERCENT = 20.0
|
||||
LOW_CONFIDENCE_THRESHOLD = 0.7
|
||||
|
||||
|
||||
def _get_thresholds():
|
||||
with database.SessionLocal() as session:
|
||||
settings = {s.key: s.value for s in session.query(models.Settings).all()}
|
||||
return {
|
||||
"price": float(settings.get("confidence_threshold_price", "0.5")),
|
||||
"stock": float(settings.get("confidence_threshold_stock", "0.5")),
|
||||
}
|
||||
|
||||
|
||||
def _update_db_result(
|
||||
item_id: int,
|
||||
extraction: AIExtractionResponse,
|
||||
metadata: AIExtractionMetadata,
|
||||
thresholds: dict,
|
||||
screenshot_path: str,
|
||||
):
|
||||
with database.SessionLocal() as session:
|
||||
item = session.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not item:
|
||||
return None, None
|
||||
|
||||
old_price, old_stock = item.current_price, item.in_stock
|
||||
price, in_stock = extraction.price, extraction.in_stock
|
||||
p_conf, s_conf = extraction.price_confidence, extraction.in_stock_confidence
|
||||
|
||||
if price is not None:
|
||||
if p_conf >= thresholds["price"]:
|
||||
if (
|
||||
old_price
|
||||
and (abs(price - old_price) / old_price * 100 > PRICE_CHANGE_THRESHOLD_PERCENT)
|
||||
and p_conf < LOW_CONFIDENCE_THRESHOLD
|
||||
):
|
||||
item.last_error = f"Uncertain: Large price change with low confidence ({p_conf:.2f})"
|
||||
else:
|
||||
item.last_error = None
|
||||
item.current_price = price
|
||||
item.current_price_confidence = p_conf
|
||||
|
||||
session.add(
|
||||
models.PriceHistory(
|
||||
item_id=item.id,
|
||||
price=price,
|
||||
screenshot_path=screenshot_path,
|
||||
price_confidence=p_conf,
|
||||
in_stock_confidence=s_conf,
|
||||
ai_model=metadata.model_name,
|
||||
ai_provider=metadata.provider,
|
||||
prompt_version=metadata.prompt_version,
|
||||
repair_used=metadata.repair_used,
|
||||
)
|
||||
)
|
||||
|
||||
if in_stock is not None and s_conf >= thresholds["stock"]:
|
||||
item.in_stock = in_stock
|
||||
item.in_stock_confidence = s_conf
|
||||
|
||||
item.last_checked = datetime.now(UTC)
|
||||
item.is_refreshing = False
|
||||
if item.last_error and not item.last_error.startswith("Uncertain:"):
|
||||
item.last_error = None
|
||||
|
||||
session.commit()
|
||||
return old_price, old_stock
|
||||
|
||||
|
||||
def _update_db_error(item_id, error_msg):
|
||||
with database.SessionLocal() as session:
|
||||
if item := session.query(models.Item).filter(models.Item.id == item_id).first():
|
||||
item.is_refreshing = False
|
||||
item.last_error = error_msg
|
||||
item.last_checked = datetime.now(UTC)
|
||||
session.commit()
|
||||
|
||||
|
||||
async def process_item_check(item_id: int):
|
||||
loop = asyncio.get_running_loop()
|
||||
with database.SessionLocal() as session:
|
||||
item_data, config = await loop.run_in_executor(None, ItemService.get_item_data_for_checking, session, item_id)
|
||||
|
||||
if not item_data:
|
||||
logger.error(f"process_item_check: Item ID {item_id} not found")
|
||||
return
|
||||
|
||||
try:
|
||||
logger.info(f"Checking item: {item_data['name']} ({item_data['url']})")
|
||||
screenshot_path, page_text = await ScraperService.scrape_item(
|
||||
item_data["url"],
|
||||
item_data["selector"],
|
||||
item_id,
|
||||
smart_scroll=config["smart_scroll"],
|
||||
scroll_pixels=config["smart_scroll_pixels"],
|
||||
text_length=config["text_length"],
|
||||
timeout=config["scraper_timeout"],
|
||||
)
|
||||
|
||||
if not screenshot_path:
|
||||
raise Exception("Failed to capture screenshot")
|
||||
|
||||
if not (ai_result := await AIService.analyze_image(screenshot_path, page_text=page_text)):
|
||||
raise Exception("AI analysis failed")
|
||||
|
||||
extraction, metadata = ai_result
|
||||
thresholds = await loop.run_in_executor(None, _get_thresholds)
|
||||
old_price, old_stock = await loop.run_in_executor(
|
||||
None, _update_db_result, item_id, extraction, metadata, thresholds, screenshot_path
|
||||
)
|
||||
|
||||
await NotificationService.send_item_notifications(
|
||||
item_data, extraction.price, old_price, extraction.in_stock, old_stock
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in process_item_check: {e}")
|
||||
await loop.run_in_executor(None, _update_db_error, item_id, str(e))
|
||||
|
||||
|
||||
async def scheduled_refresh():
|
||||
logger.info("Heartbeat: Checking for items due for refresh")
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
with database.SessionLocal() as session:
|
||||
due_items = await loop.run_in_executor(None, ItemService.get_due_items, session)
|
||||
|
||||
for item_id, _, _ in due_items:
|
||||
await process_item_check(item_id)
|
||||
except Exception as e:
|
||||
logger.error(f"Error in scheduled refresh: {e}", exc_info=True)
|
||||
@@ -0,0 +1,185 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
|
||||
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BROWSERLESS_URL = os.getenv("BROWSERLESS_URL", "ws://browserless:3000")
|
||||
|
||||
|
||||
class ScraperService:
|
||||
@staticmethod
|
||||
async def scrape_item( # noqa: PLR0913, PLR0912, PLR0915
|
||||
url: str,
|
||||
selector: str | None = None,
|
||||
item_id: int | None = None,
|
||||
smart_scroll: bool = False,
|
||||
scroll_pixels: int = 350,
|
||||
text_length: int = 0,
|
||||
timeout: int = 90000,
|
||||
) -> tuple[str | None, str]:
|
||||
"""
|
||||
Scrapes the given URL using Browserless and Playwright.
|
||||
Returns a tuple: (screenshot_path, page_text)
|
||||
|
||||
Args:
|
||||
url: Target URL to scrape
|
||||
selector: Optional CSS selector to focus on
|
||||
item_id: Optional item ID for screenshot naming
|
||||
smart_scroll: Enable scrolling to load lazy content
|
||||
scroll_pixels: Number of pixels to scroll (must be positive)
|
||||
text_length: Number of characters to extract (0 = disabled)
|
||||
timeout: Page load timeout in milliseconds
|
||||
"""
|
||||
# Input validation
|
||||
if scroll_pixels <= 0:
|
||||
logger.warning(f"Invalid scroll_pixels value: {scroll_pixels}, using default 350")
|
||||
scroll_pixels = 350
|
||||
|
||||
if timeout <= 0:
|
||||
logger.warning(f"Invalid timeout value: {timeout}, using default 90000")
|
||||
timeout = 90000
|
||||
async with async_playwright() as p:
|
||||
browser = None
|
||||
try:
|
||||
logger.info(f"Connecting to Browserless at {BROWSERLESS_URL}")
|
||||
browser = await p.chromium.connect_over_cdp(BROWSERLESS_URL)
|
||||
context = await browser.new_context(
|
||||
viewport={"width": 1920, "height": 1080},
|
||||
user_agent=(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/120.0.0.0 Safari/537.36"
|
||||
),
|
||||
)
|
||||
|
||||
# Stealth mode / Ad blocking attempts
|
||||
await context.route("**/*", lambda route: route.continue_())
|
||||
|
||||
page = await context.new_page()
|
||||
|
||||
logger.info(f"Navigating to {url} (Timeout: {timeout}ms)")
|
||||
try:
|
||||
# First wait for domcontentloaded - this is the minimum we need
|
||||
await page.goto(url, wait_until="domcontentloaded", timeout=timeout)
|
||||
logger.info(f"Page loaded (domcontentloaded): {url}")
|
||||
|
||||
# Then try to wait for networkidle, but don't fail if it times out
|
||||
# This helps with heavy pages that never fully settle
|
||||
try:
|
||||
await page.wait_for_load_state("networkidle", timeout=5000)
|
||||
logger.info("Network idle reached")
|
||||
except PlaywrightTimeoutError:
|
||||
logger.info("Network idle timed out (non-critical), proceeding...")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error navigating to {url}: {e}")
|
||||
# Try to take screenshot anyway if page partially loaded
|
||||
pass
|
||||
|
||||
# Wait a bit for dynamic content if needed
|
||||
await page.wait_for_timeout(2000)
|
||||
|
||||
# Try to close common popups
|
||||
logger.info("Attempting to close popups...")
|
||||
popup_selectors = [
|
||||
"button[aria-label='Close']",
|
||||
"button[aria-label='close']",
|
||||
".close-button",
|
||||
".modal-close",
|
||||
"svg[data-name='Close']",
|
||||
"[class*='popup'] button",
|
||||
"[class*='modal'] button",
|
||||
"button:has-text('No, thanks')",
|
||||
"button:has-text('No thanks')",
|
||||
"a:has-text('No, thanks')",
|
||||
"div[role='dialog'] button[aria-label='Close']",
|
||||
]
|
||||
|
||||
for popup_selector in popup_selectors:
|
||||
try:
|
||||
if await page.locator(popup_selector).count() > 0:
|
||||
logger.info(f"Found popup close button: {popup_selector}")
|
||||
# Try to click it. If it fails, catch and continue
|
||||
await page.locator(popup_selector).first.click(timeout=2000)
|
||||
await page.wait_for_timeout(1000) # Wait for animation
|
||||
except Exception as e:
|
||||
logger.debug(f"Could not close popup with selector {popup_selector}: {e}")
|
||||
|
||||
# Also try pressing Escape
|
||||
try:
|
||||
await page.keyboard.press("Escape")
|
||||
except Exception as e:
|
||||
logger.debug(f"Could not press Escape key: {e}")
|
||||
|
||||
if selector:
|
||||
try:
|
||||
logger.info(f"Waiting for selector: {selector}")
|
||||
await page.wait_for_selector(selector, timeout=5000)
|
||||
# Scroll to element
|
||||
element = page.locator(selector).first
|
||||
await element.scroll_into_view_if_needed()
|
||||
logger.info(f"Scrolled to selector: {selector}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Selector {selector} not found or timed out: {e}")
|
||||
else:
|
||||
# Auto-detect price if no selector
|
||||
logger.info("No selector provided. Attempting to find price element...")
|
||||
try:
|
||||
# Look for common price patterns
|
||||
price_locator = page.locator("text=/$[0-9,]+(\\.[0-9]{2})?/")
|
||||
if await price_locator.count() > 0:
|
||||
# Pick the first one that looks visible and reasonable size
|
||||
# This is heuristic
|
||||
await price_locator.first.scroll_into_view_if_needed()
|
||||
logger.info("Scrolled to potential price element")
|
||||
except Exception as e:
|
||||
logger.warning(f"Auto-price detection failed: {e}")
|
||||
|
||||
# Smart Scroll
|
||||
if smart_scroll:
|
||||
logger.info(f"Performing smart scroll ({scroll_pixels}px)...")
|
||||
try:
|
||||
await page.evaluate(f"window.scrollBy(0, {scroll_pixels})")
|
||||
await page.wait_for_timeout(1000)
|
||||
except Exception as e:
|
||||
logger.warning(f"Smart scroll failed: {e}")
|
||||
|
||||
# Text Extraction
|
||||
page_text = ""
|
||||
if text_length > 0:
|
||||
try:
|
||||
logger.info(f"Extracting text (limit: {text_length} chars)...")
|
||||
# Get text from body
|
||||
raw_text = await page.inner_text("body")
|
||||
# Simple truncation
|
||||
page_text = raw_text[:text_length]
|
||||
logger.info(f"Extracted {len(page_text)} characters")
|
||||
except Exception as e:
|
||||
logger.error(f"Text extraction failed: {e}")
|
||||
|
||||
# Take screenshot
|
||||
screenshot_dir = "screenshots"
|
||||
os.makedirs(screenshot_dir, exist_ok=True)
|
||||
if item_id:
|
||||
filename = f"{screenshot_dir}/item_{item_id}.png"
|
||||
else:
|
||||
url_part = url.split("//")[-1].replace("/", "_")
|
||||
timestamp = asyncio.get_event_loop().time()
|
||||
filename = f"{screenshot_dir}/{url_part}_{timestamp}.png"
|
||||
|
||||
await page.screenshot(path=filename, full_page=False)
|
||||
logger.info(f"Screenshot saved to {filename}")
|
||||
|
||||
return filename, page_text
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error scraping {url}: {e}")
|
||||
return None, ""
|
||||
|
||||
finally:
|
||||
if browser:
|
||||
await browser.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import models, schemas
|
||||
|
||||
|
||||
class SettingsService:
|
||||
@staticmethod
|
||||
def get_settings(db: Session):
|
||||
return db.query(models.Settings).all()
|
||||
|
||||
@staticmethod
|
||||
def update_setting(db: Session, setting: schemas.SettingsUpdate):
|
||||
db_setting = db.query(models.Settings).filter(models.Settings.key == setting.key).first()
|
||||
if db_setting:
|
||||
db_setting.value = setting.value
|
||||
else:
|
||||
db_setting = models.Settings(key=setting.key, value=setting.value)
|
||||
db.add(db_setting)
|
||||
db.commit()
|
||||
return db_setting
|
||||
|
||||
@staticmethod
|
||||
def get_setting_value(db: Session, key: str, default: str | None = None):
|
||||
setting = db.query(models.Settings).filter(models.Settings.key == key).first()
|
||||
return setting.value if setting else default
|
||||
@@ -0,0 +1,69 @@
|
||||
"""URL validation utilities for security."""
|
||||
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class URLValidationError(Exception):
|
||||
"""Raised when URL validation fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# Blocked schemes that could be used for SSRF
|
||||
BLOCKED_SCHEMES = {"file", "javascript", "data", "ftp"}
|
||||
|
||||
# Private IP ranges (RFC 1918, RFC 4193, loopback)
|
||||
PRIVATE_IP_PATTERNS = [
|
||||
re.compile(r"^127\."), # Loopback
|
||||
re.compile(r"^10\."), # Private Class A
|
||||
re.compile(r"^172\.(1[6-9]|2[0-9]|3[0-1])\."), # Private Class B
|
||||
re.compile(r"^192\.168\."), # Private Class C
|
||||
re.compile(r"^169\.254\."), # Link-local
|
||||
re.compile(r"^::1$"), # IPv6 loopback
|
||||
re.compile(r"^fc00:"), # IPv6 private
|
||||
re.compile(r"^fe80:"), # IPv6 link-local
|
||||
re.compile(r"^localhost$", re.IGNORECASE),
|
||||
re.compile(r"^0\.0\.0\.0$"), # Any address
|
||||
]
|
||||
|
||||
|
||||
def validate_url(url: str, allow_private: bool = False) -> None:
|
||||
"""
|
||||
Validate URL for security (SSRF prevention).
|
||||
|
||||
Args:
|
||||
url: URL to validate
|
||||
allow_private: Allow private/internal IPs (default: False)
|
||||
|
||||
Raises:
|
||||
URLValidationError: If URL is invalid or blocked
|
||||
"""
|
||||
if not url or not isinstance(url, str):
|
||||
raise URLValidationError("URL must be a non-empty string")
|
||||
|
||||
try:
|
||||
parsed = urlparse(url.strip())
|
||||
except Exception as e:
|
||||
raise URLValidationError(f"Invalid URL format: {e}") from e
|
||||
|
||||
# Check scheme
|
||||
if not parsed.scheme:
|
||||
raise URLValidationError("URL must include a scheme (http:// or https://)")
|
||||
|
||||
if parsed.scheme.lower() in BLOCKED_SCHEMES:
|
||||
raise URLValidationError(f"Blocked URL scheme: {parsed.scheme}")
|
||||
|
||||
if parsed.scheme.lower() not in {"http", "https"}:
|
||||
raise URLValidationError(f"Only HTTP/HTTPS schemes allowed, got: {parsed.scheme}")
|
||||
|
||||
# Check hostname
|
||||
if not parsed.hostname:
|
||||
raise URLValidationError("URL must include a hostname")
|
||||
|
||||
# Check for private IPs unless explicitly allowed
|
||||
if not allow_private:
|
||||
hostname = parsed.hostname.lower()
|
||||
for pattern in PRIVATE_IP_PATTERNS:
|
||||
if pattern.match(hostname):
|
||||
raise URLValidationError(f"Private/internal IPs not allowed: {hostname}")
|
||||
@@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
|
||||
from PIL import Image
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Image processing constants
|
||||
MAX_IMAGE_SIZE = 1024
|
||||
JPEG_QUALITY = 85
|
||||
|
||||
|
||||
def _process_image(image_path: str) -> str:
|
||||
"""
|
||||
Synchronous image processing function to be run in an executor.
|
||||
"""
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
# Resize if too large (e.g., max dimension 1024)
|
||||
if max(img.size) > MAX_IMAGE_SIZE:
|
||||
img.thumbnail((MAX_IMAGE_SIZE, MAX_IMAGE_SIZE))
|
||||
logger.info(f"Resized image to {img.size}")
|
||||
|
||||
# Convert to RGB if necessary (e.g. for PNGs with alpha)
|
||||
if img.mode in ("RGBA", "P"):
|
||||
img_to_process = img.convert("RGB")
|
||||
else:
|
||||
img_to_process = img
|
||||
|
||||
buffered = io.BytesIO()
|
||||
img_to_process.save(buffered, format="JPEG", quality=JPEG_QUALITY)
|
||||
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.error(f"Error encoding image: {e}")
|
||||
raise
|
||||
|
||||
|
||||
async def encode_image(image_path: str) -> str:
|
||||
"""
|
||||
Asynchronously encode image by running blocking code in a thread.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
return await loop.run_in_executor(None, _process_image, image_path)
|
||||
@@ -0,0 +1,144 @@
|
||||
import re
|
||||
|
||||
# Text filtering constants
|
||||
MIN_SNIPPET_LENGTH = 10
|
||||
SNIPPET_MERGE_DISTANCE = 50
|
||||
SNIPPET_CONTEXT_WINDOW = 100
|
||||
|
||||
|
||||
def clean_text(text: str) -> str:
|
||||
"""
|
||||
Cleans the text by removing code blocks, HTML tags, and excessive whitespace.
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
# Remove code blocks (```...```)
|
||||
text = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
|
||||
|
||||
# Remove HTML tags (basic)
|
||||
text = re.sub(r"<[^>]+>", "", text)
|
||||
|
||||
# Remove non-printable characters (keep newlines and tabs)
|
||||
text = re.sub(r"[^\x20-\x7E\n\t]", "", text)
|
||||
|
||||
# Collapse excessive whitespace
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def _find_matches(text: str, text_lower: str, keyword: str) -> list[tuple[int, str]]:
|
||||
snippets = []
|
||||
if keyword.startswith("r\\"):
|
||||
pattern = keyword[1:] # Remove 'r' prefix
|
||||
for match in re.finditer(pattern, text_lower, re.IGNORECASE):
|
||||
start = max(0, match.start() - SNIPPET_CONTEXT_WINDOW)
|
||||
end = min(len(text), match.end() + SNIPPET_CONTEXT_WINDOW)
|
||||
snippet = text[start:end].strip()
|
||||
if snippet and len(snippet) > MIN_SNIPPET_LENGTH:
|
||||
snippets.append((start, snippet))
|
||||
else:
|
||||
pos = 0
|
||||
while True:
|
||||
pos = text_lower.find(keyword.lower(), pos)
|
||||
if pos == -1:
|
||||
break
|
||||
start = max(0, pos - SNIPPET_CONTEXT_WINDOW)
|
||||
end = min(len(text), pos + len(keyword) + SNIPPET_CONTEXT_WINDOW)
|
||||
snippet = text[start:end].strip()
|
||||
if snippet and len(snippet) > MIN_SNIPPET_LENGTH:
|
||||
snippets.append((start, snippet))
|
||||
pos += 1
|
||||
return snippets
|
||||
|
||||
|
||||
def filter_relevant_text(text: str, max_length: int = 2000) -> str:
|
||||
"""
|
||||
Filter text to extract only relevant snippets around price and stock indicators.
|
||||
|
||||
Args:
|
||||
text: Full cleaned webpage text
|
||||
max_length: Maximum total length of filtered output
|
||||
|
||||
Returns:
|
||||
Filtered text containing only relevant snippets
|
||||
"""
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
# Keywords to search for (case-insensitive)
|
||||
price_keywords = [
|
||||
r"\$\d+\.?\d*", # $XX.XX pattern
|
||||
r"\d+\.\d{2}\s*(usd|eur|gbp|cad)", # XX.XX USD pattern
|
||||
"price:",
|
||||
"cost:",
|
||||
"sale:",
|
||||
"msrp:",
|
||||
"save:",
|
||||
"discount:",
|
||||
r"\$", # Any dollar sign
|
||||
]
|
||||
|
||||
stock_keywords = [
|
||||
"add to cart",
|
||||
"buy now",
|
||||
"purchase",
|
||||
"order now",
|
||||
"in stock",
|
||||
"out of stock",
|
||||
"available",
|
||||
"unavailable",
|
||||
"sold out",
|
||||
"notify me",
|
||||
"back in stock",
|
||||
"pre-order",
|
||||
"ships",
|
||||
"delivery",
|
||||
"get it by",
|
||||
]
|
||||
|
||||
all_keywords = price_keywords + stock_keywords
|
||||
snippets = []
|
||||
|
||||
text_lower = text.lower()
|
||||
|
||||
# Find all matches and extract context
|
||||
for keyword in all_keywords:
|
||||
snippets.extend(_find_matches(text, text_lower, keyword))
|
||||
|
||||
if not snippets:
|
||||
# No matches found, return beginning of text
|
||||
if len(text) > max_length:
|
||||
return text[:max_length] + "...(truncated)"
|
||||
return text
|
||||
|
||||
# Sort by position and deduplicate overlapping snippets
|
||||
snippets.sort(key=lambda x: x[0])
|
||||
merged_snippets = []
|
||||
current_start, current_text = snippets[0]
|
||||
current_end = current_start + len(current_text)
|
||||
|
||||
for start, snippet in snippets[1:]:
|
||||
end = start + len(snippet)
|
||||
# If overlapping or close together, merge
|
||||
if start <= current_end + SNIPPET_MERGE_DISTANCE:
|
||||
# Extend current snippet
|
||||
if end > current_end:
|
||||
# Merge overlapping text
|
||||
current_text = current_text + " " + snippet[max(0, current_end - start) :]
|
||||
current_end = end
|
||||
else:
|
||||
# Save current and start new
|
||||
merged_snippets.append(current_text)
|
||||
current_start, current_text = start, snippet
|
||||
current_end = end
|
||||
|
||||
merged_snippets.append(current_text)
|
||||
|
||||
# Join snippets with separator and limit total length
|
||||
result = " ... ".join(merged_snippets)
|
||||
if len(result) > max_length:
|
||||
result = result[:max_length] + "...(truncated)"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo "Setting up screenshots directory..."
|
||||
mkdir -p screenshots
|
||||
|
||||
echo "Running database migrations..."
|
||||
alembic upgrade head
|
||||
|
||||
echo "Starting application..."
|
||||
exec uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Pricecious</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Generated
+3577
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "pricecious-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"axios": "^1.6.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.292.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.30.2",
|
||||
"sonner": "^1.4.0",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss-animate": "^1.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.37",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@vitejs/plugin-react": "^4.2.0",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"postcss": "^8.4.31",
|
||||
"tailwindcss": "^3.3.5",
|
||||
"vite": "^7.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,23 @@
|
||||
import React from 'react'
|
||||
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
|
||||
import { Toaster } from 'sonner'
|
||||
import Layout from '@/components/layout/Layout'
|
||||
import Dashboard from '@/pages/Dashboard'
|
||||
import Settings from '@/pages/Settings'
|
||||
import { useTheme } from '@/hooks/use-theme'
|
||||
|
||||
export default function App() {
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<Toaster position="bottom-right" theme={theme} />
|
||||
<Layout theme={theme} toggleTheme={toggleTheme}>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import React from 'react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export function DeleteConfirmationModal({ item, onClose, onConfirm, open }) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onClose}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete Item</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete <span className="font-semibold text-foreground">{item?.name}</span>? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button variant="destructive" onClick={onConfirm}>Delete</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import React from 'react';
|
||||
import { ExternalLink, Edit2, RefreshCw, Trash2, AlertTriangle, Clock } from 'lucide-react';
|
||||
import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Marquee } from '@/components/ui/marquee';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function ItemCard({ item, onEdit, onDelete, onCheck, onZoom }) {
|
||||
const getStockStatus = (inStock) => {
|
||||
if (inStock === true) return { label: 'In Stock', color: 'bg-green-500/90 text-white border-green-400/50' };
|
||||
if (inStock === false) return { label: 'Out of Stock', color: 'bg-red-500/90 text-white border-red-400/50' };
|
||||
return { label: 'Unknown', color: 'bg-zinc-500/90 text-white border-zinc-400/50' };
|
||||
};
|
||||
|
||||
const stockStatus = getStockStatus(item.in_stock);
|
||||
|
||||
return (
|
||||
<Card className="group overflow-hidden transition-all duration-300 hover:shadow-md border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900">
|
||||
<div className="relative aspect-video overflow-hidden bg-zinc-100 dark:bg-zinc-950 cursor-zoom-in group/image" onClick={() => onZoom(item.screenshot_url)}>
|
||||
{item.screenshot_url ? (
|
||||
<>
|
||||
<img
|
||||
src={`${item.screenshot_url}?t=${new Date(item.last_checked).getTime()}`}
|
||||
alt={`Screenshot of ${item.name}`}
|
||||
className="h-full w-full object-cover transition-transform duration-500 group-hover/image:scale-105"
|
||||
onError={(e) => { e.target.style.display = 'none' }}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 transition-colors group-hover/image:bg-black/10" />
|
||||
</>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-sm text-zinc-400">
|
||||
No screenshot
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stock Confidence Bar */}
|
||||
{(item.in_stock_confidence !== null && item.in_stock_confidence !== undefined) && (
|
||||
<div className="absolute bottom-0 left-0 right-0 h-1.5 bg-black/20 backdrop-blur-sm">
|
||||
<div
|
||||
className={cn("h-full transition-all duration-500",
|
||||
item.in_stock_confidence > 0.8 ? 'bg-emerald-500' :
|
||||
item.in_stock_confidence > 0.5 ? 'bg-yellow-500' : 'bg-red-500'
|
||||
)}
|
||||
style={{ width: `${item.in_stock_confidence * 100}%` }}
|
||||
title={`Stock Confidence: ${Math.round(item.in_stock_confidence * 100)}%`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stock Badge */}
|
||||
<div className={cn("absolute right-3 top-3 rounded-full border px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide shadow-sm backdrop-blur-md", stockStatus.color)}>
|
||||
{stockStatus.label}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CardContent className="p-5 relative">
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div className="flex-1 overflow-hidden pr-2">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<a
|
||||
href={item.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex-shrink-0 rounded-md bg-zinc-100 p-1.5 text-zinc-500 transition-colors hover:bg-zinc-200 dark:bg-zinc-800 dark:hover:bg-zinc-700"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
<div className="w-full overflow-hidden">
|
||||
<Marquee text={item.name} className="font-semibold leading-tight" />
|
||||
</div>
|
||||
</div>
|
||||
<a href={item.url} target="_blank" rel="noopener noreferrer" className="block truncate text-xs text-zinc-400 transition-colors hover:text-primary">
|
||||
{new URL(item.url).hostname.replace('www.', '')}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="mb-1 flex items-baseline justify-between">
|
||||
<span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">Price</span>
|
||||
{item.target_price && (
|
||||
<span className={cn("rounded px-2 py-0.5 text-xs font-medium",
|
||||
item.current_price <= item.target_price
|
||||
? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
|
||||
: 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400'
|
||||
)}>
|
||||
Target: ${item.target_price}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<span className={cn("text-3xl font-bold tracking-tight leading-none",
|
||||
item.target_price && item.current_price <= item.target_price
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-foreground'
|
||||
)}>
|
||||
{item.current_price ? `$${item.current_price}` : '---'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Price Confidence Bar */}
|
||||
{(item.current_price_confidence !== null && item.current_price_confidence !== undefined) && (
|
||||
<div className="group/confidence relative mt-2">
|
||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800">
|
||||
<div
|
||||
className={cn("h-full rounded-full transition-all duration-500",
|
||||
item.current_price_confidence > 0.8 ? 'bg-primary' :
|
||||
item.current_price_confidence > 0.5 ? 'bg-primary/70' : 'bg-primary/40'
|
||||
)}
|
||||
style={{ width: `${item.current_price_confidence * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute -bottom-4 left-0 text-[10px] text-muted-foreground opacity-0 transition-opacity group-hover/confidence:opacity-100">
|
||||
Price Confidence: {Math.round(item.current_price_confidence * 100)}%
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tags */}
|
||||
{item.tags && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{item.tags.split(',').map(tag => (
|
||||
<span key={tag} className="rounded-md border bg-secondary px-2 py-0.5 text-[10px] font-medium text-secondary-foreground">
|
||||
{tag.trim()}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Description */}
|
||||
{item.description && (
|
||||
<p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="border-t bg-zinc-50/50 p-3 dark:bg-zinc-900/50">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="flex items-center gap-3 text-[10px] text-muted-foreground">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="h-3 w-3" />
|
||||
<span>{item.last_checked ? new Date(item.last_checked).toLocaleString() : 'Never'}</span>
|
||||
</div>
|
||||
{item.last_error && (
|
||||
<div className="flex items-center gap-1 text-destructive" title={item.last_error}>
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="max-w-[100px] truncate">Error</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1">
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => onEdit(item)}>
|
||||
<Edit2 className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => onCheck(item.id)} disabled={item.is_refreshing}>
|
||||
<RefreshCw className={cn("h-3 w-3", item.is_refreshing && "animate-spin text-primary")} />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6 text-destructive hover:text-destructive" onClick={() => onDelete(item)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { toast } from 'sonner';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
|
||||
const API_URL = '/api';
|
||||
|
||||
export function ItemModal({ item, onClose, onSaved, open }) {
|
||||
const [formData, setFormData] = useState({
|
||||
url: '',
|
||||
name: '',
|
||||
target_price: '',
|
||||
selector: '',
|
||||
tags: '',
|
||||
description: '',
|
||||
notification_profile_id: ''
|
||||
});
|
||||
const [profiles, setProfiles] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (item) {
|
||||
setFormData({
|
||||
url: item.url || '',
|
||||
name: item.name || '',
|
||||
target_price: item.target_price || '',
|
||||
selector: item.selector || '',
|
||||
tags: item.tags || '',
|
||||
description: item.description || '',
|
||||
notification_profile_id: item.notification_profile_id ? item.notification_profile_id.toString() : ''
|
||||
});
|
||||
} else {
|
||||
setFormData({
|
||||
url: '',
|
||||
name: '',
|
||||
target_price: '',
|
||||
selector: '',
|
||||
tags: '',
|
||||
description: '',
|
||||
notification_profile_id: ''
|
||||
});
|
||||
}
|
||||
}, [item, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
axios.get(`${API_URL}/notification-profiles`).then(res => setProfiles(res.data)).catch(console.error);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
target_price: formData.target_price ? parseFloat(formData.target_price) : null,
|
||||
notification_profile_id: formData.notification_profile_id ? parseInt(formData.notification_profile_id) : null
|
||||
};
|
||||
|
||||
if (item) {
|
||||
await axios.put(`${API_URL}/items/${item.id}`, payload);
|
||||
toast.success('Item updated');
|
||||
} else {
|
||||
await axios.post(`${API_URL}/items`, payload);
|
||||
toast.success('Item added');
|
||||
}
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error('Error saving item:', error);
|
||||
toast.error('Failed to save item');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{item ? 'Edit Item' : 'Add New Item'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="url">URL</Label>
|
||||
<Input
|
||||
id="url"
|
||||
type="url"
|
||||
required
|
||||
placeholder="https://example.com/product"
|
||||
value={formData.url}
|
||||
onChange={e => setFormData({ ...formData, url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
required
|
||||
placeholder="Product Name"
|
||||
value={formData.name}
|
||||
onChange={e => setFormData({ ...formData, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="target_price">Target Price ($)</Label>
|
||||
<Input
|
||||
id="target_price"
|
||||
type="number"
|
||||
step="0.01"
|
||||
placeholder="0.00"
|
||||
value={formData.target_price}
|
||||
onChange={e => setFormData({ ...formData, target_price: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="selector">Selector (Optional)</Label>
|
||||
<Input
|
||||
id="selector"
|
||||
placeholder=".price-class"
|
||||
value={formData.selector}
|
||||
onChange={e => setFormData({ ...formData, selector: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="profile">Notification Profile</Label>
|
||||
<Select
|
||||
value={formData.notification_profile_id}
|
||||
onValueChange={(value) => setFormData({ ...formData, notification_profile_id: value })}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a profile" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">None</SelectItem>
|
||||
{profiles.map(p => (
|
||||
<SelectItem key={p.id} value={p.id.toString()}>{p.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="tags">Tags</Label>
|
||||
<Input
|
||||
id="tags"
|
||||
placeholder="tech, home, gift (comma separated)"
|
||||
value={formData.tags}
|
||||
onChange={e => setFormData({ ...formData, tags: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<textarea
|
||||
id="description"
|
||||
className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
placeholder="Add notes about this item..."
|
||||
value={formData.description}
|
||||
onChange={e => setFormData({ ...formData, description: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit">Save Item</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { LayoutDashboard, Settings, Moon, Sun, Menu } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Layout = ({ children, theme, toggleTheme }) => {
|
||||
const location = useLocation();
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||
|
||||
const navItems = [
|
||||
{ icon: LayoutDashboard, label: 'Dashboard', path: '/' },
|
||||
{ icon: Settings, label: 'Settings', path: '/settings' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background font-sans antialiased">
|
||||
{/* Sidebar */}
|
||||
<aside className="fixed left-0 top-0 z-40 h-screen w-64 border-r bg-card hidden md:block">
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex h-14 items-center border-b px-6">
|
||||
<Link to="/" className="flex items-center gap-2 font-semibold">
|
||||
<img src="/logo.png" alt="Pricecious Logo" className="h-8 w-8" />
|
||||
<span className="text-xl font-bold bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
|
||||
Pricecious
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
<nav className="flex-1 space-y-1 p-4">
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = location.pathname === item.path;
|
||||
return (
|
||||
<Link key={item.path} to={item.path}>
|
||||
<Button
|
||||
variant={isActive ? "secondary" : "ghost"}
|
||||
className={cn("w-full justify-start gap-2", isActive && "bg-secondary")}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{item.label}
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<div className="border-t p-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleTheme}
|
||||
className="w-full justify-start gap-2 px-4"
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<>
|
||||
<Sun className="h-4 w-4" />
|
||||
<span>Light Mode</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Moon className="h-4 w-4" />
|
||||
<span>Dark Mode</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Mobile Header */}
|
||||
<header className="sticky top-0 z-30 flex h-14 items-center gap-4 border-b bg-background px-6 md:hidden">
|
||||
<Sheet open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Menu className="h-5 w-5" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-64 p-0">
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex h-14 items-center border-b px-6">
|
||||
<img src="/logo.png" alt="Pricecious Logo" className="h-8 w-8 mr-2" />
|
||||
<span className="text-xl font-bold bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
|
||||
Pricecious
|
||||
</span>
|
||||
</div>
|
||||
<nav className="flex-1 space-y-1 p-4">
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = location.pathname === item.path;
|
||||
return (
|
||||
<Link key={item.path} to={item.path} onClick={() => setMobileMenuOpen(false)}>
|
||||
<Button
|
||||
variant={isActive ? "secondary" : "ghost"}
|
||||
className={cn("w-full justify-start gap-2", isActive && "bg-secondary")}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
{item.label}
|
||||
</Button>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
<div className="border-t p-4">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={toggleTheme}
|
||||
className="w-full justify-start gap-2"
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<>
|
||||
<Sun className="h-4 w-4" />
|
||||
<span>Light Mode</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Moon className="h-4 w-4" />
|
||||
<span>Dark Mode</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<Link to="/" className="flex items-center gap-2 font-semibold">
|
||||
<img src="/logo.png" alt="Pricecious Logo" className="h-6 w-6" />
|
||||
Pricecious
|
||||
</Link>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<Button variant="ghost" size="icon" onClick={toggleTheme}>
|
||||
{theme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 md:pl-64">
|
||||
<div className="container py-6">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
|
||||
})
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,60 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Card = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Card.displayName = "Card"
|
||||
|
||||
const CardHeader = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardHeader.displayName = "CardHeader"
|
||||
|
||||
const CardTitle = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-2xl font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardTitle.displayName = "CardTitle"
|
||||
|
||||
const CardDescription = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<p
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardDescription.displayName = "CardDescription"
|
||||
|
||||
const CardContent = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
))
|
||||
CardContent.displayName = "CardContent"
|
||||
|
||||
const CardFooter = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("flex items-center p-6 pt-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CardFooter.displayName = "CardFooter"
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
||||
@@ -0,0 +1,107 @@
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { X } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal
|
||||
|
||||
const DialogClose = DialogPrimitive.Close
|
||||
|
||||
const DialogOverlay = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||
|
||||
const DialogContent = React.forwardRef(({ className, children, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
))
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogHeader.displayName = "DialogHeader"
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogFooter.displayName = "DialogFooter"
|
||||
|
||||
const DialogTitle = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||
|
||||
const DialogDescription = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef(({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const labelVariants = cva(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
)
|
||||
|
||||
const Label = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(labelVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Label.displayName = LabelPrimitive.Root.displayName
|
||||
|
||||
export { Label }
|
||||
@@ -0,0 +1,38 @@
|
||||
import React, { useState, useEffect, useRef } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function Marquee({ text, className }) {
|
||||
const [isOverflowing, setIsOverflowing] = useState(false);
|
||||
const containerRef = useRef(null);
|
||||
const textRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkOverflow = () => {
|
||||
if (containerRef.current && textRef.current) {
|
||||
const isOver = textRef.current.scrollWidth > containerRef.current.clientWidth;
|
||||
setIsOverflowing(isOver);
|
||||
if (isOver) {
|
||||
const distance = textRef.current.scrollWidth + 32; // 32px gap
|
||||
containerRef.current.style.setProperty('--marquee-duration', `${distance / 40}s`); // 40px/s speed
|
||||
containerRef.current.style.setProperty('--marquee-distance', `${distance}px`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkOverflow();
|
||||
window.addEventListener('resize', checkOverflow);
|
||||
return () => window.removeEventListener('resize', checkOverflow);
|
||||
}, [text]);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={cn("overflow-hidden w-full group", className)}>
|
||||
<div
|
||||
ref={textRef}
|
||||
className={cn("whitespace-nowrap flex gap-8", isOverflowing && "group-hover:animate-scroll")}
|
||||
>
|
||||
<span>{text}</span>
|
||||
{isOverflowing && <span aria-hidden="true">{text}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Select = SelectPrimitive.Root
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group
|
||||
|
||||
const SelectValue = SelectPrimitive.Value
|
||||
|
||||
const SelectTrigger = React.forwardRef(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
))
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
))
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
))
|
||||
SelectScrollDownButton.displayName =
|
||||
SelectPrimitive.ScrollDownButton.displayName
|
||||
|
||||
const SelectContent = React.forwardRef(({ className, children, position = "popper", ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
))
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName
|
||||
|
||||
const SelectLabel = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
||||
|
||||
const SelectItem = React.forwardRef(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
))
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName
|
||||
|
||||
const SelectSeparator = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
|
||||
const SheetTrigger = SheetPrimitive.Trigger
|
||||
|
||||
const SheetClose = SheetPrimitive.Close
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
|
||||
const SheetOverlay = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom:
|
||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
right:
|
||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const SheetContent = React.forwardRef(({ side = "right", className, children, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
))
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
|
||||
const SheetHeader = ({
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetHeader.displayName = "SheetHeader"
|
||||
|
||||
const SheetFooter = ({
|
||||
className,
|
||||
...props
|
||||
}) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetFooter.displayName = "SheetFooter"
|
||||
|
||||
const SheetTitle = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
|
||||
const SheetDescription = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Slider = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<input
|
||||
type="range"
|
||||
className={cn(
|
||||
"w-full h-2 bg-zinc-200 rounded-lg appearance-none cursor-pointer dark:bg-zinc-700 accent-primary",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Slider.displayName = "Slider";
|
||||
|
||||
export { Slider };
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Switch = React.forwardRef(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitive.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
))
|
||||
Switch.displayName = SwitchPrimitive.Root.displayName
|
||||
|
||||
export { Switch }
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export function useTheme() {
|
||||
const [theme, setTheme] = useState(localStorage.getItem('theme') || 'dark');
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove('light', 'dark');
|
||||
root.classList.add(theme);
|
||||
localStorage.setItem('theme', theme);
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = () => setTheme(prev => prev === 'dark' ? 'light' : 'dark');
|
||||
|
||||
return { theme, toggleTheme };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 240 10% 3.9%;
|
||||
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 240 10% 3.9%;
|
||||
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 240 10% 3.9%;
|
||||
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
|
||||
--secondary: 240 4.8% 95.9%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
|
||||
--muted: 240 4.8% 95.9%;
|
||||
--muted-foreground: 240 3.8% 46.1%;
|
||||
|
||||
--accent: 240 4.8% 95.9%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
|
||||
--border: 240 5.9% 90%;
|
||||
--input: 240 5.9% 90%;
|
||||
--ring: 240 10% 3.9%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 240 10% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
|
||||
--card: 240 10% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
|
||||
--popover: 240 10% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
|
||||
--secondary: 240 3.7% 15.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
|
||||
--muted: 240 3.7% 15.9%;
|
||||
--muted-foreground: 240 5% 64.9%;
|
||||
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
|
||||
--border: 240 3.7% 15.9%;
|
||||
--input: 240 3.7% 15.9%;
|
||||
--ring: 240 4.9% 83.9%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
import './index.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { toast } from 'sonner';
|
||||
import { Plus, RefreshCw, Search, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ItemCard } from '@/components/dashboard/ItemCard';
|
||||
import { ItemModal } from '@/components/dashboard/ItemModal';
|
||||
import { DeleteConfirmationModal } from '@/components/dashboard/DeleteConfirmationModal';
|
||||
|
||||
const API_URL = '/api';
|
||||
|
||||
export default function Dashboard() {
|
||||
const [items, setItems] = useState([]);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [showAddModal, setShowAddModal] = useState(false);
|
||||
const [editingItem, setEditingItem] = useState(null);
|
||||
const [itemToDelete, setItemToDelete] = useState(null);
|
||||
const [zoomedImage, setZoomedImage] = useState(null);
|
||||
|
||||
const refreshItems = async () => {
|
||||
try {
|
||||
const response = await axios.get(`${API_URL}/items`);
|
||||
const sortedItems = response.data.sort((a, b) => a.id - b.id);
|
||||
setItems(sortedItems);
|
||||
} catch (error) {
|
||||
console.error('Error fetching items:', error);
|
||||
toast.error('Failed to fetch items');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
refreshItems();
|
||||
const interval = setInterval(refreshItems, 10000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const handleCheck = async (id) => {
|
||||
try {
|
||||
toast.info('Check triggered...');
|
||||
await axios.post(`${API_URL}/items/${id}/check`);
|
||||
toast.success('Check started in background');
|
||||
refreshItems();
|
||||
} catch (error) {
|
||||
console.error('Error triggering check:', error);
|
||||
toast.error('Failed to trigger check');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefreshAll = async () => {
|
||||
try {
|
||||
toast.info('Triggering refresh for all items...');
|
||||
setItems(prevItems => prevItems.map(item => ({ ...item, is_refreshing: true })));
|
||||
await axios.post(`${API_URL}/jobs/refresh-all`);
|
||||
toast.success('Refresh all started');
|
||||
} catch (error) {
|
||||
console.error('Error triggering refresh all:', error);
|
||||
toast.error('Failed to trigger refresh all');
|
||||
refreshItems();
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!itemToDelete) return;
|
||||
try {
|
||||
await axios.delete(`${API_URL}/items/${itemToDelete.id}`);
|
||||
toast.success('Item deleted');
|
||||
refreshItems();
|
||||
setItemToDelete(null);
|
||||
} catch (error) {
|
||||
console.error('Error deleting item:', error);
|
||||
toast.error('Failed to delete item');
|
||||
}
|
||||
};
|
||||
|
||||
const filteredItems = items.filter(item => {
|
||||
const term = searchTerm.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(term) ||
|
||||
item.url.toLowerCase().includes(term) ||
|
||||
(item.tags && item.tags.toLowerCase().includes(term)) ||
|
||||
(item.description && item.description.toLowerCase().includes(term))
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in duration-500">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Dashboard</h2>
|
||||
<p className="text-muted-foreground">Manage and monitor your product watchlist.</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative w-full md:w-64">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search items..."
|
||||
className="pl-8"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" onClick={handleRefreshAll}>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Refresh All
|
||||
</Button>
|
||||
<Button onClick={() => setShowAddModal(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Item
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{filteredItems.map(item => (
|
||||
<ItemCard
|
||||
key={item.id}
|
||||
item={item}
|
||||
onEdit={setEditingItem}
|
||||
onDelete={setItemToDelete}
|
||||
onCheck={handleCheck}
|
||||
onZoom={setZoomedImage}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<ItemModal
|
||||
open={showAddModal}
|
||||
onClose={() => setShowAddModal(false)}
|
||||
onSaved={refreshItems}
|
||||
/>
|
||||
|
||||
<ItemModal
|
||||
open={!!editingItem}
|
||||
item={editingItem}
|
||||
onClose={() => setEditingItem(null)}
|
||||
onSaved={refreshItems}
|
||||
/>
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={!!itemToDelete}
|
||||
item={itemToDelete}
|
||||
onClose={() => setItemToDelete(null)}
|
||||
onConfirm={handleDelete}
|
||||
/>
|
||||
|
||||
{/* Image Zoom Modal */}
|
||||
{zoomedImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 animate-in fade-in duration-200"
|
||||
onClick={() => setZoomedImage(null)}
|
||||
>
|
||||
<div className="relative max-h-full max-w-full">
|
||||
<img
|
||||
src={zoomedImage}
|
||||
alt="Zoomed screenshot"
|
||||
className="max-h-[90vh] max-w-[90vw] rounded-lg shadow-2xl"
|
||||
/>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="secondary"
|
||||
className="absolute -right-4 -top-4 rounded-full shadow-lg"
|
||||
onClick={() => setZoomedImage(null)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
import { toast } from 'sonner';
|
||||
import { Sun, Clock, Cpu, Settings as SettingsIcon, Bell, Trash2, ChevronDown, ChevronUp, Edit2, CheckCircle2, AlertCircle, TrendingDown, DollarSign, Package } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const API_URL = '/api';
|
||||
|
||||
export default function Settings() {
|
||||
const [profiles, setProfiles] = useState([]);
|
||||
const [jobConfig, setJobConfig] = useState({ refresh_interval_minutes: 60, next_run: null, running: false });
|
||||
const [config, setConfig] = useState({
|
||||
ai_provider: 'ollama',
|
||||
ai_model: 'moondream',
|
||||
ai_api_key: '',
|
||||
ai_api_base: 'http://ollama:11434',
|
||||
ai_temperature: 0.1,
|
||||
ai_max_tokens: 300,
|
||||
confidence_threshold_price: 0.5,
|
||||
confidence_threshold_stock: 0.5,
|
||||
enable_json_repair: true,
|
||||
smart_scroll_enabled: false,
|
||||
smart_scroll_pixels: 350,
|
||||
text_context_enabled: false,
|
||||
text_context_length: 5000,
|
||||
scraper_timeout: 90000
|
||||
});
|
||||
const [newProfile, setNewProfile] = useState({
|
||||
name: '',
|
||||
apprise_url: '',
|
||||
check_interval_minutes: 60,
|
||||
notify_on_price_drop: true,
|
||||
notify_on_target_price: true,
|
||||
price_drop_threshold_percent: 10,
|
||||
notify_on_stock_change: true
|
||||
});
|
||||
|
||||
const [editingProfileId, setEditingProfileId] = useState(null);
|
||||
const [showAdvancedAI, setShowAdvancedAI] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAll();
|
||||
}, []);
|
||||
|
||||
const fetchAll = async () => {
|
||||
try {
|
||||
const [profilesRes, settingsRes, jobRes] = await Promise.all([
|
||||
axios.get(`${API_URL}/notification-profiles`),
|
||||
axios.get(`${API_URL}/settings`),
|
||||
axios.get(`${API_URL}/jobs/config`)
|
||||
]);
|
||||
|
||||
setProfiles(profilesRes.data);
|
||||
setJobConfig(jobRes.data);
|
||||
|
||||
const settingsMap = {};
|
||||
settingsRes.data.forEach(s => settingsMap[s.key] = s.value);
|
||||
|
||||
setConfig({
|
||||
ai_provider: settingsMap['ai_provider'] || 'ollama',
|
||||
ai_model: settingsMap['ai_model'] || 'moondream',
|
||||
ai_api_key: settingsMap['ai_api_key'] || '',
|
||||
ai_api_base: settingsMap['ai_api_base'] || 'http://ollama:11434',
|
||||
ai_temperature: parseFloat(settingsMap['ai_temperature'] || '0.1'),
|
||||
ai_max_tokens: parseInt(settingsMap['ai_max_tokens'] || '300'),
|
||||
confidence_threshold_price: parseFloat(settingsMap['confidence_threshold_price'] || '0.5'),
|
||||
confidence_threshold_stock: parseFloat(settingsMap['confidence_threshold_stock'] || '0.5'),
|
||||
enable_json_repair: settingsMap['enable_json_repair'] !== 'false',
|
||||
smart_scroll_enabled: settingsMap['smart_scroll_enabled'] === 'true',
|
||||
smart_scroll_pixels: parseInt(settingsMap['smart_scroll_pixels'] || '350'),
|
||||
text_context_enabled: settingsMap['text_context_enabled'] === 'true',
|
||||
text_context_length: parseInt(settingsMap['text_context_length'] || '5000'),
|
||||
scraper_timeout: parseInt(settingsMap['scraper_timeout'] || '90000')
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error('Failed to fetch settings');
|
||||
}
|
||||
};
|
||||
|
||||
const updateSetting = async (key, value) => {
|
||||
try {
|
||||
await axios.post(`${API_URL}/settings`, { key, value: value.toString() });
|
||||
setConfig(prev => ({ ...prev, [key]: value }));
|
||||
toast.success('Setting updated');
|
||||
} catch (error) {
|
||||
toast.error('Failed to update setting');
|
||||
}
|
||||
};
|
||||
|
||||
const updateJobConfig = async () => {
|
||||
try {
|
||||
await axios.post(`${API_URL}/jobs/config`, {
|
||||
key: 'refresh_interval_minutes',
|
||||
value: jobConfig.refresh_interval_minutes.toString()
|
||||
});
|
||||
toast.success('Job configuration updated');
|
||||
fetchAll();
|
||||
} catch (error) {
|
||||
toast.error('Failed to update job config');
|
||||
}
|
||||
};
|
||||
|
||||
const handleProfileSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
if (editingProfileId) {
|
||||
await axios.put(`${API_URL}/notification-profiles/${editingProfileId}`, newProfile);
|
||||
toast.success('Profile updated');
|
||||
} else {
|
||||
await axios.post(`${API_URL}/notification-profiles`, newProfile);
|
||||
toast.success('Profile created');
|
||||
}
|
||||
|
||||
setNewProfile({
|
||||
name: '',
|
||||
apprise_url: '',
|
||||
check_interval_minutes: 60,
|
||||
notify_on_price_drop: true,
|
||||
notify_on_target_price: true,
|
||||
price_drop_threshold_percent: 10,
|
||||
notify_on_stock_change: true
|
||||
});
|
||||
setEditingProfileId(null);
|
||||
fetchAll();
|
||||
} catch (error) {
|
||||
toast.error(editingProfileId ? 'Failed to update profile' : 'Failed to create profile');
|
||||
}
|
||||
};
|
||||
|
||||
const editProfile = (profile) => {
|
||||
setNewProfile({
|
||||
name: profile.name,
|
||||
apprise_url: profile.apprise_url,
|
||||
check_interval_minutes: profile.check_interval_minutes,
|
||||
notify_on_price_drop: profile.notify_on_price_drop,
|
||||
notify_on_target_price: profile.notify_on_target_price,
|
||||
price_drop_threshold_percent: profile.price_drop_threshold_percent,
|
||||
notify_on_stock_change: profile.notify_on_stock_change
|
||||
});
|
||||
setEditingProfileId(profile.id);
|
||||
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
setNewProfile({
|
||||
name: '',
|
||||
apprise_url: '',
|
||||
check_interval_minutes: 60,
|
||||
notify_on_price_drop: true,
|
||||
notify_on_target_price: true,
|
||||
price_drop_threshold_percent: 10,
|
||||
notify_on_stock_change: true
|
||||
});
|
||||
setEditingProfileId(null);
|
||||
};
|
||||
|
||||
const deleteProfile = async (id) => {
|
||||
if (confirm('Are you sure you want to delete this profile?')) {
|
||||
try {
|
||||
await axios.delete(`${API_URL}/notification-profiles/${id}`);
|
||||
toast.success('Profile deleted');
|
||||
if (editingProfileId === id) {
|
||||
cancelEdit();
|
||||
}
|
||||
fetchAll();
|
||||
} catch (error) {
|
||||
toast.error('Failed to delete profile');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-in fade-in duration-500 max-w-5xl mx-auto pb-10">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight">Settings</h2>
|
||||
<p className="text-muted-foreground">Configure application preferences and notifications.</p>
|
||||
</div>
|
||||
|
||||
{/* AI Configuration */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Cpu className="h-5 w-5" />AI Configuration</CardTitle>
|
||||
<CardDescription>Configure the AI model used for analyzing product pages.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Provider</Label>
|
||||
<Select value={config.ai_provider} onValueChange={(val) => updateSetting('ai_provider', val)}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ollama">Ollama</SelectItem>
|
||||
<SelectItem value="openai">OpenAI</SelectItem>
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Model</Label>
|
||||
<Input value={config.ai_model} onChange={(e) => updateSetting('ai_model', e.target.value)} placeholder="e.g., moondream" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>API Key</Label>
|
||||
<Input type="password" value={config.ai_api_key} onChange={(e) => updateSetting('ai_api_key', e.target.value)} placeholder="Optional for local models" />
|
||||
</div>
|
||||
|
||||
<div className="pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full flex items-center justify-between"
|
||||
onClick={() => setShowAdvancedAI(!showAdvancedAI)}
|
||||
>
|
||||
<span>Advanced Settings</span>
|
||||
{showAdvancedAI ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showAdvancedAI && (
|
||||
<div className="space-y-6 pt-4 animate-in slide-in-from-top-2 duration-200">
|
||||
<div className="space-y-2">
|
||||
<Label>API Base URL</Label>
|
||||
<Input value={config.ai_api_base} onChange={(e) => updateSetting('ai_api_base', e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<Label>Temperature</Label>
|
||||
<span className="text-xs text-muted-foreground">{config.ai_temperature}</span>
|
||||
</div>
|
||||
<Slider
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.1}
|
||||
value={config.ai_temperature}
|
||||
onChange={(e) => updateSetting('ai_temperature', parseFloat(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<Label>Price Confidence Threshold</Label>
|
||||
<span className="text-xs text-muted-foreground">{config.confidence_threshold_price}</span>
|
||||
</div>
|
||||
<Slider
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.1}
|
||||
value={config.confidence_threshold_price}
|
||||
onChange={(e) => updateSetting('confidence_threshold_price', parseFloat(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<Label>Stock Confidence Threshold</Label>
|
||||
<span className="text-xs text-muted-foreground">{config.confidence_threshold_stock}</span>
|
||||
</div>
|
||||
<Slider
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.1}
|
||||
value={config.confidence_threshold_stock}
|
||||
onChange={(e) => updateSetting('confidence_threshold_stock', parseFloat(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Max Tokens</Label>
|
||||
<Input type="number" value={config.ai_max_tokens} onChange={(e) => updateSetting('ai_max_tokens', parseInt(e.target.value))} />
|
||||
</div>
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<Label htmlFor="json_repair">Enable JSON Repair</Label>
|
||||
<Switch id="json_repair" checked={config.enable_json_repair} onCheckedChange={(checked) => updateSetting('enable_json_repair', checked)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Scraper Configuration */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><SettingsIcon className="h-5 w-5" />Scraper Configuration</CardTitle>
|
||||
<CardDescription>Configure how the scraper interacts with web pages.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Smart Scroll</Label>
|
||||
<p className="text-sm text-muted-foreground">Scroll down to trigger lazy loading.</p>
|
||||
</div>
|
||||
<Switch checked={config.smart_scroll_enabled} onCheckedChange={(checked) => updateSetting('smart_scroll_enabled', checked)} />
|
||||
</div>
|
||||
{config.smart_scroll_enabled && (
|
||||
<div className="space-y-2">
|
||||
<Label>Scroll Pixels</Label>
|
||||
<Input type="number" value={config.smart_scroll_pixels} onChange={(e) => updateSetting('smart_scroll_pixels', parseInt(e.target.value))} />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>Text Context</Label>
|
||||
<p className="text-sm text-muted-foreground">Send page text to AI along with screenshot.</p>
|
||||
</div>
|
||||
<Switch checked={config.text_context_enabled} onCheckedChange={(checked) => updateSetting('text_context_enabled', checked)} />
|
||||
</div>
|
||||
{config.text_context_enabled && (
|
||||
<div className="space-y-2">
|
||||
<Label>Max Text Length</Label>
|
||||
<Input type="number" value={config.text_context_length} onChange={(e) => updateSetting('text_context_length', parseInt(e.target.value))} />
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label>Timeout (ms)</Label>
|
||||
<Input type="number" value={config.scraper_timeout} onChange={(e) => updateSetting('scraper_timeout', parseInt(e.target.value))} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Job Configuration */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Clock className="h-5 w-5" />Automated Refresh Job</CardTitle>
|
||||
<CardDescription>Configure the background job that checks for price updates.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Refresh Interval (Minutes)</Label>
|
||||
<Input type="number" min="1" value={jobConfig.refresh_interval_minutes} onChange={(e) => setJobConfig({ ...jobConfig, refresh_interval_minutes: e.target.value })} />
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p>Next run: {jobConfig.next_run ? new Date(jobConfig.next_run).toLocaleString() : 'Not scheduled'}</p>
|
||||
<p>Status: {jobConfig.running ? 'Running' : 'Idle'}</p>
|
||||
</div>
|
||||
<Button onClick={updateJobConfig}>Save Job Config</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Notification Profiles */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Bell className="h-5 w-5" />Notification Profiles</CardTitle>
|
||||
<CardDescription>Manage notification settings for different groups of items.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-8">
|
||||
<form onSubmit={handleProfileSubmit} className="space-y-4 border-b pb-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="text-sm font-medium">{editingProfileId ? 'Edit Profile' : 'Create New Profile'}</h4>
|
||||
{editingProfileId && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={cancelEdit}>Cancel Edit</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input required value={newProfile.name} onChange={(e) => setNewProfile({ ...newProfile, name: e.target.value })} placeholder="e.g., Email Alerts" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Apprise URL</Label>
|
||||
<Input required value={newProfile.apprise_url} onChange={(e) => setNewProfile({ ...newProfile, apprise_url: e.target.value })} placeholder="mailto://user:pass@gmail.com" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Check Interval (Minutes)</Label>
|
||||
<Input type="number" min="1" value={newProfile.check_interval_minutes} onChange={(e) => setNewProfile({ ...newProfile, check_interval_minutes: parseInt(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Price Drop Threshold (%)</Label>
|
||||
<Input type="number" min="1" max="100" value={newProfile.price_drop_threshold_percent} onChange={(e) => setNewProfile({ ...newProfile, price_drop_threshold_percent: parseFloat(e.target.value) })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch checked={newProfile.notify_on_price_drop} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_price_drop: checked })} />
|
||||
<Label>Notify on Drop</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch checked={newProfile.notify_on_target_price} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_target_price: checked })} />
|
||||
<Label>Notify on Target</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch checked={newProfile.notify_on_stock_change} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_stock_change: checked })} />
|
||||
<Label>Notify on Stock Change</Label>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit">{editingProfileId ? 'Update Profile' : 'Create Profile'}</Button>
|
||||
</form>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-sm font-medium">Existing Profiles</h4>
|
||||
{profiles.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No profiles created yet.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{profiles.map(profile => (
|
||||
<div key={profile.id} className={cn(
|
||||
"relative group overflow-hidden rounded-xl border bg-card text-card-foreground shadow transition-all hover:shadow-md",
|
||||
editingProfileId === profile.id && "ring-2 ring-primary"
|
||||
)}>
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold leading-none tracking-tight">{profile.name}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 truncate max-w-[200px]" title={profile.apprise_url}>{profile.apprise_url}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => editProfile(profile)}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={() => deleteProfile(profile.id)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{profile.check_interval_minutes}m interval</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<TrendingDown className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{profile.price_drop_threshold_percent}% drop</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 pt-2">
|
||||
{profile.notify_on_price_drop && (
|
||||
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
|
||||
<DollarSign className="mr-1 h-3 w-3" /> Price Drop
|
||||
</span>
|
||||
)}
|
||||
{profile.notify_on_target_price && (
|
||||
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
|
||||
<CheckCircle2 className="mr-1 h-3 w-3" /> Target Hit
|
||||
</span>
|
||||
)}
|
||||
{profile.notify_on_stock_change && (
|
||||
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
|
||||
<Package className="mr-1 h-3 w-3" /> Stock Change
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute top-0 right-0 p-6 opacity-5 pointer-events-none">
|
||||
<Bell className="h-24 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
darkMode: ["class"],
|
||||
content: [
|
||||
'./pages/**/*.{js,jsx}',
|
||||
'./components/**/*.{js,jsx}',
|
||||
'./app/**/*.{js,jsx}',
|
||||
'./src/**/*.{js,jsx}',
|
||||
],
|
||||
theme: {
|
||||
container: {
|
||||
center: true,
|
||||
padding: "2rem",
|
||||
screens: {
|
||||
"2xl": "1400px",
|
||||
},
|
||||
},
|
||||
extend: {
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
keyframes: {
|
||||
"accordion-down": {
|
||||
from: { height: "0" },
|
||||
to: { height: "var(--radix-accordion-content-height)" },
|
||||
},
|
||||
"accordion-up": {
|
||||
from: { height: "var(--radix-accordion-content-height)" },
|
||||
to: { height: "0" },
|
||||
},
|
||||
"scroll": {
|
||||
"0%": { transform: "translateX(0)" },
|
||||
"100%": { transform: "translateX(-100%)" },
|
||||
}
|
||||
},
|
||||
animation: {
|
||||
"accordion-down": "accordion-down 0.2s ease-out",
|
||||
"accordion-up": "accordion-up 0.2s ease-out",
|
||||
"scroll": "scroll 20s linear infinite",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [require("tailwindcss-animate")],
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import path from "path"
|
||||
import react from "@vitejs/plugin-react"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
[project]
|
||||
name = "pricecious-backend"
|
||||
version = "0.1.0"
|
||||
description = "Backend for Pricecious Price Tracker"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi",
|
||||
"uvicorn",
|
||||
"sqlalchemy",
|
||||
"psycopg2-binary",
|
||||
"playwright",
|
||||
"requests",
|
||||
"pydantic",
|
||||
"apprise",
|
||||
"Pillow",
|
||||
"apscheduler",
|
||||
"python-multipart",
|
||||
"pydantic-settings",
|
||||
"aiofiles",
|
||||
"litellm",
|
||||
"alembic",
|
||||
"tenacity",
|
||||
"slowapi",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["app"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest",
|
||||
"pytest-asyncio",
|
||||
"pytest-cov",
|
||||
"ruff",
|
||||
"httpx",
|
||||
"mypy",
|
||||
"bandit",
|
||||
"pip-audit",
|
||||
"pre-commit",
|
||||
]
|
||||
|
||||
[tool.hatch.envs.default]
|
||||
dependencies = [
|
||||
"pytest",
|
||||
"ruff",
|
||||
"httpx",
|
||||
]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "W", "B", "UP", "PL", "RUF"]
|
||||
ignore = []
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"tests/*" = ["PLR2004"]
|
||||
"app/routers/*" = ["B008"]
|
||||
"app/main.py" = ["B008"]
|
||||
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
testpaths = ["tests"]
|
||||
addopts = "--cov=app --cov-report=html --cov-report=term-missing"
|
||||
asyncio_mode = "auto"
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["app"]
|
||||
omit = ["*/tests/*", "*/alembic/*"]
|
||||
|
||||
[tool.coverage.report]
|
||||
exclude_lines = [
|
||||
"pragma: no cover",
|
||||
"def __repr__",
|
||||
"raise AssertionError",
|
||||
"raise NotImplementedError",
|
||||
"if __name__ == .__main__.:",
|
||||
"if TYPE_CHECKING:",
|
||||
"@abstractmethod",
|
||||
]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = false # Enable gradually
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.bandit]
|
||||
exclude_dirs = ["tests", "app/alembic"]
|
||||
skips = ["B101"] # Skip assert_used (common in tests)
|
||||
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
# Set env var before importing app.database
|
||||
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
|
||||
|
||||
from app.database import Base, get_db
|
||||
from app.main import app
|
||||
|
||||
# Use in-memory SQLite for testing
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def db():
|
||||
# Create tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
session = TestingSessionLocal()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
# Drop tables
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def client(db):
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
# Mock scheduler to prevent event loop issues
|
||||
# Mock SessionLocal to return the test session
|
||||
# We need a factory that returns the session, but SessionLocal() creates a new session.
|
||||
# So we mock SessionLocal to return a mock that acts like a session but is actually our test session.
|
||||
# However, our test session is scoped to the function.
|
||||
# A better approach is to use a separate engine for the background task or share the connection.
|
||||
# Since we use SQLite in-memory, sharing connection is key.
|
||||
# But process_item_check creates a NEW session.
|
||||
|
||||
# Let's mock SessionLocal to return a session bound to the SAME engine.
|
||||
# But we are using StaticPool, so all sessions share the same connection.
|
||||
# So we just need SessionLocal to return a session from TestingSessionLocal.
|
||||
|
||||
with (
|
||||
patch("app.main.scheduler.start"),
|
||||
patch("app.main.scheduler.shutdown"),
|
||||
patch("app.database.SessionLocal", side_effect=TestingSessionLocal),
|
||||
):
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
Unit tests for AI schema validation and normalization.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.ai_schema import AIExtractionMetadata, AIExtractionResponse, get_extraction_prompt, get_repair_prompt
|
||||
|
||||
|
||||
class TestAIExtractionResponse:
|
||||
"""Test the AI extraction response schema."""
|
||||
|
||||
def test_valid_response(self):
|
||||
"""Test that valid data passes validation."""
|
||||
data = {
|
||||
"price": 99.99,
|
||||
"currency": "USD",
|
||||
"in_stock": True,
|
||||
"price_confidence": 0.95,
|
||||
"in_stock_confidence": 0.90,
|
||||
"source_type": "image",
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price == 99.99
|
||||
assert response.in_stock is True
|
||||
assert response.price_confidence == 0.95
|
||||
assert response.in_stock_confidence == 0.90
|
||||
|
||||
def test_null_price(self):
|
||||
"""Test that null price is handled correctly."""
|
||||
data = {
|
||||
"price": None,
|
||||
"in_stock": False,
|
||||
"price_confidence": 0.2,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price is None
|
||||
assert response.in_stock is False
|
||||
|
||||
def test_confidence_clamping_above(self):
|
||||
"""Test that confidence values above 1.0 are clamped."""
|
||||
data = {
|
||||
"price": 50.0,
|
||||
"in_stock": True,
|
||||
"price_confidence": 1.5, # Should clamp to 1.0
|
||||
"in_stock_confidence": 2.0, # Should clamp to 1.0
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price_confidence == 1.0
|
||||
assert response.in_stock_confidence == 1.0
|
||||
|
||||
def test_confidence_clamping_below(self):
|
||||
"""Test that confidence values below 0.0 are clamped."""
|
||||
data = {
|
||||
"price": 50.0,
|
||||
"in_stock": True,
|
||||
"price_confidence": -0.5, # Should clamp to 0.0
|
||||
"in_stock_confidence": -1.0, # Should clamp to 0.0
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price_confidence == 0.0
|
||||
assert response.in_stock_confidence == 0.0
|
||||
|
||||
def test_price_string_normalization(self):
|
||||
"""Test that price strings are normalized to floats."""
|
||||
data = {
|
||||
"price": "$99.99",
|
||||
"in_stock": True,
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price == 99.99
|
||||
|
||||
def test_price_string_with_commas(self):
|
||||
"""Test that prices with commas are handled."""
|
||||
data = {
|
||||
"price": "$1,234.56",
|
||||
"in_stock": True,
|
||||
"price_confidence": 0.9,
|
||||
"in_stock_confidence": 0.9,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.price == 1234.56
|
||||
|
||||
def test_stock_string_normalization_true(self):
|
||||
"""Test that stock status strings are normalized to booleans."""
|
||||
test_cases = ["true", "True", "yes", "in stock", "available", "1"]
|
||||
for value in test_cases:
|
||||
data = {
|
||||
"price": 10.0,
|
||||
"in_stock": value,
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.in_stock is True, f"Failed for value: {value}"
|
||||
|
||||
def test_stock_string_normalization_false(self):
|
||||
"""Test that out-of-stock strings are normalized to False."""
|
||||
test_cases = ["false", "False", "no", "out of stock", "unavailable", "0"]
|
||||
for value in test_cases:
|
||||
data = {
|
||||
"price": 10.0,
|
||||
"in_stock": value,
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.in_stock is False, f"Failed for value: {value}"
|
||||
|
||||
def test_stock_ambiguous_string(self):
|
||||
"""Test that ambiguous stock strings return None."""
|
||||
data = {
|
||||
"price": 10.0,
|
||||
"in_stock": "maybe",
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.3,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.in_stock is None
|
||||
|
||||
def test_default_currency(self):
|
||||
"""Test that default currency is USD."""
|
||||
data = {
|
||||
"price": 10.0,
|
||||
"in_stock": True,
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.currency == "USD"
|
||||
|
||||
def test_default_source_type(self):
|
||||
"""Test that default source type is 'image'."""
|
||||
data = {
|
||||
"price": 10.0,
|
||||
"in_stock": True,
|
||||
"price_confidence": 0.8,
|
||||
"in_stock_confidence": 0.8,
|
||||
}
|
||||
response = AIExtractionResponse(**data)
|
||||
assert response.source_type == "image"
|
||||
|
||||
def test_source_type_validation(self):
|
||||
"""Test that source_type must be one of: image, text, both."""
|
||||
with pytest.raises(ValidationError):
|
||||
AIExtractionResponse(
|
||||
price=10.0,
|
||||
in_stock=True,
|
||||
price_confidence=0.8,
|
||||
in_stock_confidence=0.8,
|
||||
source_type="invalid", # Should fail
|
||||
)
|
||||
|
||||
|
||||
class TestAIExtractionMetadata:
|
||||
"""Test the AI extraction metadata schema."""
|
||||
|
||||
def test_valid_metadata(self):
|
||||
"""Test that valid metadata passes validation."""
|
||||
data = {
|
||||
"model_name": "gpt-4o",
|
||||
"provider": "openai",
|
||||
"prompt_version": "v2.0",
|
||||
"repair_used": False,
|
||||
"multi_sample": False,
|
||||
"sample_count": 1,
|
||||
}
|
||||
metadata = AIExtractionMetadata(**data)
|
||||
assert metadata.model_name == "gpt-4o"
|
||||
assert metadata.provider == "openai"
|
||||
assert metadata.repair_used is False
|
||||
|
||||
def test_default_values(self):
|
||||
"""Test that default values are set correctly."""
|
||||
data = {
|
||||
"model_name": "gemma3:4b",
|
||||
"provider": "ollama",
|
||||
}
|
||||
metadata = AIExtractionMetadata(**data)
|
||||
assert metadata.repair_used is False
|
||||
assert metadata.multi_sample is False
|
||||
assert metadata.sample_count == 1
|
||||
|
||||
|
||||
class TestPromptGeneration:
|
||||
"""Test prompt generation functions."""
|
||||
|
||||
def test_extraction_prompt_without_text(self):
|
||||
"""Test extraction prompt without text context."""
|
||||
prompt = get_extraction_prompt(None)
|
||||
assert "Extract product price" in prompt
|
||||
assert "JSON" in prompt
|
||||
assert "price_confidence" in prompt
|
||||
assert "**Relevant text from page:**" not in prompt
|
||||
|
||||
def test_extraction_prompt_with_text(self):
|
||||
"""Test extraction prompt with text context."""
|
||||
page_text = "Product is in stock for $99.99"
|
||||
prompt = get_extraction_prompt(page_text)
|
||||
assert "Extract product price" in prompt
|
||||
assert "**Relevant text from page:**" in prompt
|
||||
assert "$99.99" in prompt
|
||||
|
||||
def test_extraction_prompt_with_long_text(self):
|
||||
"""Test that long text is truncated."""
|
||||
page_text = "A" * 5000
|
||||
prompt = get_extraction_prompt(page_text)
|
||||
assert "**Relevant text from page:**" in prompt
|
||||
assert "truncated" in prompt
|
||||
|
||||
def test_repair_prompt(self):
|
||||
"""Test repair prompt generation."""
|
||||
raw_output = "This is malformed JSON { price: 99.99 }"
|
||||
prompt = get_repair_prompt(raw_output)
|
||||
assert "Convert the following text" in prompt
|
||||
assert raw_output in prompt
|
||||
assert "JSON" in prompt
|
||||
@@ -0,0 +1,109 @@
|
||||
# Since we are using sync TestClient with async endpoints, FastAPI handles the loop.
|
||||
# However, if we want to test async functions directly, we need pytest-asyncio.
|
||||
# For API tests, TestClient is fine as it wraps the app.
|
||||
|
||||
|
||||
def test_read_main(client):
|
||||
response = client.get("/api/")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"message": "Welcome to Pricecious API"}
|
||||
|
||||
|
||||
def test_create_notification_profile(client):
|
||||
response = client.post(
|
||||
"/api/notification-profiles",
|
||||
json={
|
||||
"name": "Test Profile",
|
||||
"apprise_url": "mailto://test@example.com",
|
||||
"notify_on_price_drop": True,
|
||||
"notify_on_target_price": True,
|
||||
"price_drop_threshold_percent": 10.0,
|
||||
"notify_on_stock_change": True,
|
||||
"check_interval_minutes": 60,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["name"] == "Test Profile"
|
||||
assert "id" in data
|
||||
|
||||
|
||||
def test_update_notification_profile(client):
|
||||
# Create a profile first
|
||||
response = client.post(
|
||||
"/api/notification-profiles",
|
||||
json={
|
||||
"name": "Update Test Profile",
|
||||
"apprise_url": "mailto://test@example.com",
|
||||
},
|
||||
)
|
||||
profile_id = response.json()["id"]
|
||||
|
||||
# Update the profile
|
||||
response = client.put(
|
||||
f"/api/notification-profiles/{profile_id}",
|
||||
json={
|
||||
"name": "Updated Profile Name",
|
||||
"apprise_url": "mailto://updated@example.com",
|
||||
"notify_on_price_drop": False,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["name"] == "Updated Profile Name"
|
||||
assert data["apprise_url"] == "mailto://updated@example.com"
|
||||
assert data["notify_on_price_drop"] is False
|
||||
assert data["id"] == profile_id
|
||||
|
||||
|
||||
def test_create_item(client):
|
||||
# First create a profile
|
||||
profile_response = client.post(
|
||||
"/api/notification-profiles",
|
||||
json={"name": "Test Profile 2", "apprise_url": "mailto://test@example.com"},
|
||||
)
|
||||
profile_id = profile_response.json()["id"]
|
||||
|
||||
response = client.post(
|
||||
"/api/items",
|
||||
json={
|
||||
"url": "https://example.com/product",
|
||||
"name": "Test Product",
|
||||
"target_price": 100.0,
|
||||
"notification_profile_id": profile_id,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["name"] == "Test Product"
|
||||
assert data["url"] == "https://example.com/product"
|
||||
assert data["notification_profile_id"] == profile_id
|
||||
|
||||
|
||||
def test_get_settings(client):
|
||||
response = client.get("/api/settings")
|
||||
assert response.status_code == 200
|
||||
assert isinstance(response.json(), list)
|
||||
|
||||
|
||||
def test_update_setting(client):
|
||||
response = client.post("/api/settings", json={"key": "test_key", "value": "test_value"})
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["key"] == "test_key"
|
||||
assert data["value"] == "test_value"
|
||||
|
||||
|
||||
# Add test for check_item to ensure background task triggering works
|
||||
# Note: This doesn't verify the background task execution, just the endpoint
|
||||
def test_check_item_trigger(client):
|
||||
# Create item first
|
||||
response = client.post(
|
||||
"/api/items",
|
||||
json={"url": "https://example.com/check", "name": "Check Product", "target_price": 100.0},
|
||||
)
|
||||
item_id = response.json()["id"]
|
||||
|
||||
response = client.post(f"/api/items/{item_id}/check")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"message": "Check triggered"}
|
||||
@@ -0,0 +1,39 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import models
|
||||
|
||||
|
||||
def test_refresh_all_sets_status(client, db):
|
||||
# Create a profile
|
||||
profile = models.NotificationProfile(name="Test Profile", apprise_url="mailto://test@example.com")
|
||||
db.add(profile)
|
||||
db.commit()
|
||||
db.refresh(profile)
|
||||
|
||||
# Create items
|
||||
item1 = models.Item(
|
||||
url="https://example.com/1", name="Item 1", notification_profile_id=profile.id, is_refreshing=False
|
||||
)
|
||||
item2 = models.Item(
|
||||
url="https://example.com/2", name="Item 2", notification_profile_id=profile.id, is_refreshing=False
|
||||
)
|
||||
db.add(item1)
|
||||
db.add(item2)
|
||||
db.commit()
|
||||
|
||||
# Mock process_item_check to prevent actual execution
|
||||
with patch("app.routers.jobs.process_item_check") as mock_process:
|
||||
response = client.post("/api/jobs/refresh-all")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["message"] == "Triggered refresh for 2 items"
|
||||
|
||||
# Verify mock was called
|
||||
assert mock_process.call_count == 2
|
||||
|
||||
# Verify items are marked as refreshing in DB
|
||||
# We need to refresh the objects from the DB
|
||||
db.refresh(item1)
|
||||
db.refresh(item2)
|
||||
|
||||
assert item1.is_refreshing is True
|
||||
assert item2.is_refreshing is True
|
||||
@@ -0,0 +1,60 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import models
|
||||
from app.services.scheduler_service import process_item_check
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_item_check_updates_last_checked_on_error(db):
|
||||
# Create a profile
|
||||
profile = models.NotificationProfile(name="Test Profile", apprise_url="mailto://test@example.com")
|
||||
db.add(profile)
|
||||
db.commit()
|
||||
db.refresh(profile)
|
||||
|
||||
# Create item
|
||||
item = models.Item(
|
||||
url="https://example.com/error",
|
||||
name="Error Item",
|
||||
notification_profile_id=profile.id,
|
||||
is_refreshing=True,
|
||||
selector="body",
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
|
||||
item_id = item.id
|
||||
initial_last_checked = item.last_checked
|
||||
|
||||
# Create a session maker bound to the same engine as the test db
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
connection = db.get_bind()
|
||||
TestSession = sessionmaker(bind=connection)
|
||||
|
||||
# Mock ScraperService.scrape_item to raise an exception
|
||||
# And patch SessionLocal to return our test session
|
||||
with (
|
||||
patch("app.services.scraper_service.ScraperService.scrape_item", side_effect=Exception("Scraper failed")),
|
||||
patch("app.database.SessionLocal", side_effect=TestSession),
|
||||
):
|
||||
await process_item_check(item_id)
|
||||
|
||||
# Refresh item from DB
|
||||
# We need to expire the object to reload from DB because the other session updated it
|
||||
db.expire(item)
|
||||
db.refresh(item)
|
||||
|
||||
# Assertions
|
||||
assert item.is_refreshing is False
|
||||
assert item.last_error == "Scraper failed"
|
||||
assert item.last_checked is not None
|
||||
if initial_last_checked:
|
||||
assert item.last_checked > initial_last_checked
|
||||
|
||||
# Ensure last_checked is recent (within last minute)
|
||||
assert datetime.now(UTC) - item.last_checked.replace(tzinfo=UTC) < timedelta(minutes=1)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Unit tests for scraper module.
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.scraper_service import ScraperService
|
||||
|
||||
|
||||
class TestScraperInputValidation:
|
||||
"""Test input validation in scraper."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_scroll_pixels(self, caplog):
|
||||
"""Test that invalid scroll_pixels is corrected."""
|
||||
with patch("app.services.scraper_service.async_playwright") as mock_playwright:
|
||||
# Mock the playwright context
|
||||
mock_browser = AsyncMock()
|
||||
mock_context = AsyncMock()
|
||||
mock_page = AsyncMock()
|
||||
mock_page.goto = AsyncMock()
|
||||
mock_page.screenshot = AsyncMock()
|
||||
mock_context.new_page = AsyncMock(return_value=mock_page)
|
||||
mock_browser.new_context = AsyncMock(return_value=mock_context)
|
||||
mock_browser.close = AsyncMock()
|
||||
|
||||
mock_pw = AsyncMock()
|
||||
mock_pw.chromium.connect_over_cdp = AsyncMock(return_value=mock_browser)
|
||||
mock_playwright.return_value.__aenter__.return_value = mock_pw
|
||||
|
||||
# Test with negative scroll_pixels
|
||||
await ScraperService.scrape_item("https://example.com", scroll_pixels=-100)
|
||||
|
||||
# Check that warning was logged
|
||||
assert "Invalid scroll_pixels value" in caplog.text
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_timeout(self, caplog):
|
||||
"""Test that invalid timeout is corrected."""
|
||||
with patch("app.services.scraper_service.async_playwright") as mock_playwright:
|
||||
mock_browser = AsyncMock()
|
||||
mock_context = AsyncMock()
|
||||
mock_page = AsyncMock()
|
||||
mock_page.goto = AsyncMock()
|
||||
mock_page.screenshot = AsyncMock()
|
||||
mock_context.new_page = AsyncMock(return_value=mock_page)
|
||||
mock_browser.new_context = AsyncMock(return_value=mock_context)
|
||||
mock_browser.close = AsyncMock()
|
||||
|
||||
mock_pw = AsyncMock()
|
||||
mock_pw.chromium.connect_over_cdp = AsyncMock(return_value=mock_browser)
|
||||
mock_playwright.return_value.__aenter__.return_value = mock_pw
|
||||
|
||||
# Test with zero timeout
|
||||
await ScraperService.scrape_item("https://example.com", timeout=0)
|
||||
|
||||
# Check that warning was logged
|
||||
assert "Invalid timeout value" in caplog.text
|
||||
|
||||
|
||||
class TestScraperScreenshot:
|
||||
"""Test screenshot functionality."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_screenshot_path_generation(self):
|
||||
"""Test that screenshot paths are generated correctly."""
|
||||
with patch("app.services.scraper_service.async_playwright") as mock_playwright:
|
||||
mock_browser = AsyncMock()
|
||||
mock_context = AsyncMock()
|
||||
mock_page = AsyncMock()
|
||||
mock_page.goto = AsyncMock()
|
||||
mock_page.screenshot = AsyncMock()
|
||||
mock_page.inner_text = AsyncMock(return_value="test text")
|
||||
mock_context.new_page = AsyncMock(return_value=mock_page)
|
||||
mock_browser.new_context = AsyncMock(return_value=mock_context)
|
||||
mock_browser.close = AsyncMock()
|
||||
|
||||
mock_pw = AsyncMock()
|
||||
mock_pw.chromium.connect_over_cdp = AsyncMock(return_value=mock_browser)
|
||||
mock_playwright.return_value.__aenter__.return_value = mock_pw
|
||||
|
||||
# Test with item_id
|
||||
path, _ = await ScraperService.scrape_item("https://example.com", item_id=123)
|
||||
|
||||
assert path == "screenshots/item_123.png"
|
||||
mock_page.screenshot.assert_called_once_with(path="screenshots/item_123.png", full_page=False)
|
||||
|
||||
|
||||
class TestScraperErrorHandling:
|
||||
"""Test error handling in scraper."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connection_failure(self):
|
||||
"""Test handling of connection failures."""
|
||||
with patch("app.services.scraper_service.async_playwright") as mock_playwright:
|
||||
mock_pw = AsyncMock()
|
||||
mock_pw.chromium.connect_over_cdp = AsyncMock(side_effect=Exception("Connection failed"))
|
||||
mock_playwright.return_value.__aenter__.return_value = mock_pw
|
||||
|
||||
# Should return None on error
|
||||
result, text = await ScraperService.scrape_item("https://example.com")
|
||||
|
||||
assert result is None
|
||||
assert text == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_page_load_timeout(self):
|
||||
"""Test handling of page load timeout."""
|
||||
with patch("app.services.scraper_service.async_playwright") as mock_playwright:
|
||||
mock_browser = AsyncMock()
|
||||
mock_context = AsyncMock()
|
||||
mock_page = AsyncMock()
|
||||
mock_page.goto = AsyncMock(side_effect=Exception("Timeout"))
|
||||
mock_page.screenshot = AsyncMock() # Should still try to screenshot
|
||||
mock_context.new_page = AsyncMock(return_value=mock_page)
|
||||
mock_browser.new_context = AsyncMock(return_value=mock_context)
|
||||
mock_browser.close = AsyncMock()
|
||||
|
||||
mock_pw = AsyncMock()
|
||||
mock_pw.chromium.connect_over_cdp = AsyncMock(return_value=mock_browser)
|
||||
mock_playwright.return_value.__aenter__.return_value = mock_pw
|
||||
|
||||
# Should continue and try to screenshot
|
||||
await ScraperService.scrape_item("https://example.com", item_id=1)
|
||||
|
||||
# Even with timeout, should attempt screenshot
|
||||
mock_page.screenshot.assert_called_once()
|
||||
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
Tests for URL validation and security.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.url_validation import URLValidationError, validate_url
|
||||
|
||||
|
||||
class TestURLValidation:
|
||||
"""Test URL validation for security."""
|
||||
|
||||
def test_valid_https_url(self):
|
||||
"""Test that valid HTTPS URLs pass validation."""
|
||||
validate_url("https://example.com/product")
|
||||
# Should not raise
|
||||
|
||||
def test_valid_http_url(self):
|
||||
"""Test that valid HTTP URLs pass validation."""
|
||||
validate_url("http://example.com/product")
|
||||
# Should not raise
|
||||
|
||||
def test_empty_url(self):
|
||||
"""Test that empty URLs are rejected."""
|
||||
with pytest.raises(URLValidationError, match="non-empty string"):
|
||||
validate_url("")
|
||||
|
||||
def test_none_url(self):
|
||||
"""Test that None URLs are rejected."""
|
||||
with pytest.raises(URLValidationError, match="non-empty string"):
|
||||
validate_url(None)
|
||||
|
||||
def test_missing_scheme(self):
|
||||
"""Test that URLs without scheme are rejected."""
|
||||
with pytest.raises(URLValidationError, match="must include a scheme"):
|
||||
validate_url("example.com/product")
|
||||
|
||||
def test_blocked_scheme_file(self):
|
||||
"""Test that file:// URLs are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Blocked URL scheme"):
|
||||
validate_url("file:///etc/passwd")
|
||||
|
||||
def test_blocked_scheme_javascript(self):
|
||||
"""Test that javascript: URLs are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Blocked URL scheme"):
|
||||
validate_url("javascript:alert(1)")
|
||||
|
||||
def test_blocked_scheme_data(self):
|
||||
"""Test that data: URLs are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Blocked URL scheme"):
|
||||
validate_url("data:text/html,<script>alert(1)</script>")
|
||||
|
||||
def test_blocked_scheme_ftp(self):
|
||||
"""Test that FTP URLs are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Blocked URL scheme"):
|
||||
validate_url("ftp://example.com/file")
|
||||
|
||||
def test_localhost_blocked(self):
|
||||
"""Test that localhost is blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://localhost:8000/")
|
||||
|
||||
def test_127_0_0_1_blocked(self):
|
||||
"""Test that 127.0.0.1 is blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://127.0.0.1:8000/")
|
||||
|
||||
def test_private_ip_10_blocked(self):
|
||||
"""Test that 10.x.x.x addresses are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://10.0.0.1/")
|
||||
|
||||
def test_private_ip_192_blocked(self):
|
||||
"""Test that 192.168.x.x addresses are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://192.168.1.1/")
|
||||
|
||||
def test_private_ip_172_blocked(self):
|
||||
"""Test that 172.16-31.x.x addresses are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://172.16.0.1/")
|
||||
|
||||
def test_link_local_blocked(self):
|
||||
"""Test that link-local addresses (169.254.x.x) are blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://169.254.0.1/")
|
||||
|
||||
def test_ipv6_loopback_blocked(self):
|
||||
"""Test that IPv6 loopback (::1) is blocked."""
|
||||
with pytest.raises(URLValidationError, match="Private/internal IPs"):
|
||||
validate_url("http://[::1]:8000/")
|
||||
|
||||
def test_allow_private_param(self):
|
||||
"""Test that allow_private parameter works."""
|
||||
# Should not raise when allow_private=True
|
||||
validate_url("http://localhost:8000/", allow_private=True)
|
||||
validate_url("http://127.0.0.1:8000/", allow_private=True)
|
||||
validate_url("http://192.168.1.1/", allow_private=True)
|
||||
|
||||
def test_missing_hostname(self):
|
||||
"""Test that URLs without hostname are rejected."""
|
||||
with pytest.raises(URLValidationError, match="must include a hostname"):
|
||||
validate_url("http:///path")
|
||||
|
||||
def test_url_with_query_params(self):
|
||||
"""Test that URLs with query parameters work."""
|
||||
validate_url("https://example.com/product?id=123&ref=abc")
|
||||
# Should not raise
|
||||
|
||||
def test_url_with_fragment(self):
|
||||
"""Test that URLs with fragments work."""
|
||||
validate_url("https://example.com/product#section")
|
||||
# Should not raise
|
||||
|
||||
def test_url_with_port(self):
|
||||
"""Test that URLs with ports work."""
|
||||
validate_url("https://example.com:8443/product")
|
||||
# Should not raise
|
||||
|
||||
def test_international_domain(self):
|
||||
"""Test that international domains work."""
|
||||
validate_url("https://例え.jp/product")
|
||||
# Should not raise
|
||||
|
||||
|
||||
class TestSSRFPrevention:
|
||||
"""Test SSRF attack prevention."""
|
||||
|
||||
def test_ssrf_localhost_variants(self):
|
||||
"""Test various localhost representations."""
|
||||
localhost_variants = [
|
||||
"http://localhost/",
|
||||
"http://127.0.0.1/",
|
||||
"http://127.1/",
|
||||
"http://0.0.0.0/",
|
||||
]
|
||||
|
||||
for url in localhost_variants:
|
||||
with pytest.raises(URLValidationError):
|
||||
validate_url(url)
|
||||
|
||||
def test_ssrf_private_networks(self):
|
||||
"""Test private network ranges."""
|
||||
private_ranges = [
|
||||
"http://10.1.2.3/",
|
||||
"http://172.16.0.1/",
|
||||
"http://172.31.255.255/",
|
||||
"http://192.168.0.1/",
|
||||
"http://169.254.169.254/", # AWS metadata
|
||||
]
|
||||
|
||||
for url in private_ranges:
|
||||
with pytest.raises(URLValidationError):
|
||||
validate_url(url)
|
||||
|
||||
def test_public_ips_allowed(self):
|
||||
"""Test that public IPs are allowed."""
|
||||
public_ips = [
|
||||
"http://8.8.8.8/",
|
||||
"http://1.1.1.1/",
|
||||
"http://142.250.185.78/", # Google
|
||||
]
|
||||
|
||||
for url in public_ips:
|
||||
validate_url(url)
|
||||
# Should not raise
|
||||
Reference in new issue
Block a user