Merge pull request #1 from lindesvard/feature/app-dir

Feature/app dir
This commit is contained in:
Carl-Gerhard Lindesvärd
2024-03-11 13:45:49 +01:00
committed by GitHub
655 changed files with 49731 additions and 8875 deletions

3
.env.example Normal file
View File

@@ -0,0 +1,3 @@
# Ready for docker-compose
REDIS_URL="redis://127.0.0.1:6379"
DATABASE_URL="postgres://username:password@127.0.0.1:5435/postgres?sslmode=disable"

3
.gitignore vendored
View File

@@ -2,6 +2,9 @@
packages/sdk/profileId.txt
packages/sdk/test.ts
dump.sql
dump-*
.sql
clickhouse
# Logs

View File

@@ -15,5 +15,8 @@
"typescript.preferences.autoImportFileExcludePatterns": [
"next/router.d.ts",
"next/dist/client/router.d.ts"
]
],
"[sql]": {
"editor.defaultFormatter": "adpyke.vscode-sql-formatter"
}
}

661
LICENSE.md Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

113
README.md
View File

@@ -1,10 +1,6 @@
<p align="center">
<img src="images/mixan.svg">
</p>
# openpanel
# mixan
Mixan is a simple analytics tool for logging events on web and react-native. My goal is to make a minimal mixpanel copy with the most basic features (for now).
Openpanel is a simple analytics tool for logging events on web and react-native. My goal is to make a minimal mixpanel copy with the most basic features (for now).
- Easy to use
- Fully responsive UI
@@ -17,10 +13,23 @@ Mixan is a simple analytics tool for logging events on web and react-native. My
### Speed/Benchmark
As of today (2023-12-12) I have more then 1.2 million events in PSQL and performance is smooth as butter 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`.
As of today (~~2023-12-12~~ 2024-01-16) I have more then ~~1.2~~ 2.8 million events and 20 thousand profiles in postgres and performance is smooth as butter\* 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`.
\* Smooth as butter is somewhat exaggerated but I would say it still fast! It takes 1.4 sec to search through all events (3 million) with advanced where clause. I think this performance is absolutly good enough.
### GUI
- [x] Fix design for report editor
- [x] Fix profiles
- [x] Pagination
- [x] Filter by event name
- [x] Fix [profileId]
- [x] Add events
- [x] Improve design for properties and linked profiles
- [x] New design for events
- [ ] Map events to convertions
- [ ] Map ids
- [x] Fix menu links when projectId is undefined
- [x] Fix tables on settings
- [x] Rename event label
- [ ] Common web dashboard
@@ -36,14 +45,16 @@ As of today (2023-12-12) I have more then 1.2 million events in PSQL and perform
- [x] View events in a list
- [x] Simple filters
- [x] View profiles in a list
- [ ] Invite users
- [x] Invite users
- [ ] Drag n Drop reports on dashboard
- [x] Manage dashboards
- [ ] Support more chart types
- [x] Support more chart types
- [x] Bar
- [x] Histogram
- [ ] Pie
- [ ] Area
- [x] Pie
- [x] Area
- [x] Metric
- [x] Line
- [ ] Support funnels
- [ ] Support multiple breakdowns
- [x] Aggregations (sum, average...)
@@ -56,53 +67,49 @@ As of today (2023-12-12) I have more then 1.2 million events in PSQL and perform
- [x] Create web sdk
- [x] Screen view function should take in title, path and parse query string (especially utm tags)
## @mixan/sdk
## @openpanel/sdk
For pushing events
### Install
- npm: `npm install @mixan/sdk`
- pnpm: `pnpm add @mixan/sdk`
- yarn: `yarn add @mixan/sdk`
- npm: `npm install @openpanel/sdk`
- pnpm: `pnpm add @openpanel/sdk`
- yarn: `yarn add @openpanel/sdk`
### Usage
```ts
import { Mixan } from '@mixan/sdk';
import { OpenpanelWeb } from '@openpanel/web';
const mixan = new Mixan({
// import { OpenpanelNative } from '@openpanel/sdk-native';
const openpanel = new OpenpanelWeb({
clientId: 'uuid',
clientSecret: 'uuid',
url: 'http://localhost:8080/api/sdk',
batchInterval: 10000,
verbose: false,
saveProfileId(id) {
// Web
localStorage.setItem('@profileId', id);
// // react-native-mmkv
// mmkv.setItem('@profileId', id)
},
removeProfileId() {
// Web
localStorage.removeItem('@profileId');
// // react-native-mmkv
// mmkv.delete('@profileId')
},
getProfileId() {
// Web
return localStorage.getItem('@profileId');
// // react-native-mmkv
// return mmkv.getString('@profileId')
},
trackIp: true,
});
// const openpanel = new OpenpanelNative({
// clientId: 'uuid',
// clientSecret: 'uuid',
// url: 'http://localhost:8080/api/sdk',
// batchInterval: 10000,
// verbose: false,
// trackIp: true,
// });
// Call this before you send any events
// It will create a anonymous profile
// This profile will be merged if you call `setUser` in a later stage
mixan.init();
openpanel.init();
mixan.setUser({
// tracks all outgoing links as a `link_out` event
openpanel.trackOutgoingLinks();
openpanel.setUser({
id: 'id',
first_name: 'John',
last_name: 'Doe',
@@ -111,33 +118,36 @@ mixan.setUser({
});
// will upsert 'app_open' on user property and increment it
mixan.increment('app_open');
openpanel.increment('app_open');
// will upsert 'app_open' on user property and increment it by 10
mixan.increment('app_open', 10);
openpanel.increment('app_open', 10);
// will upsert 'app_open' on user property and decrement it by 2
mixan.decrement('app_open', 2);
openpanel.decrement('app_open', 2);
// send a sign_in event
mixan.event('sign_in');
openpanel.event('sign_in');
// send a sign_in event with properties
mixan.event('sign_in', {
openpanel.event('sign_in', {
provider: 'gmail',
});
// short hand for 'screen_view', can also take any properties
mixan.screenView('Profile', {
id: '123',
// any other properties, url, public
// Screen view for web
openpanel.screenView();
// Screen view for native
openpanel.screenView('Article', {
id: '3',
title: 'Nice article here',
});
// Call this when a user is logged out.
// This will just make sure you do not send
// the associated profile id for the next events
mixan.clear();
openpanel.clear();
```
## @mixan/web
## @openpanel/dashboard
A nextjs web app. Collects all events and your gui to analyze your data.
@@ -150,6 +160,11 @@ We use https://cron-job.org (free) to handle our cronjobs, you can use any provi
- **https://domain.com/api/cron/cache/update** Will update the memory cache
- **https://domain.com/api/cron/events/enrich** Enrich events (adds duration etc)
## Development
1. Run `docker-compose up -d` to get redis and postgres running
2. Then `pnpm dev` to boot the web and worker (queue)
## Screenshots
![Line chart](images/line.png)

15
ROADMAP.md Normal file
View File

@@ -0,0 +1,15 @@
# Roadmap
## Simple todos
- [ ] add session_id on events table, link this id on create
- [ ] add overview page containing
- [x] User histogram (last 30 minutes)
- [ ] Bounce rate
- [ ] Session duration
- [ ] Views per session
- [ ] Unique users
- [ ] Total users
- [ ] Total pageviews
- [ ] Total events
- [ ]

64
TRADEMARK.md Normal file
View File

@@ -0,0 +1,64 @@
# Openpanel Trademark Guidelines
## Overview
Welcome to Openpanel's Trademark Guidelines. These guidelines are designed to help you understand how to use and refer to the Openpanel brand and trademarks properly. By following these guidelines, you contribute to maintaining the integrity of the Openpanel brand.
## Trademark Usage
### Openpanel Logo
The Openpanel logo is a key element of our brand identity. To ensure consistency and visibility, please adhere to the following guidelines:
- **Do not modify or alter the Openpanel logo.**
- **Maintain proper spacing around the logo to ensure clarity and legibility.**
- **Use the official Openpanel logo assets provided on our official website.**
### Openpanel Name
When referring to Openpanel in text, please follow these guidelines:
- **Use the full, unaltered "Openpanel" name when mentioning our product.**
- **Capitalize the "O" in Openpanel.**
- **Avoid using Openpanel in a way that could be misleading or imply endorsement.**
## Domain Names
To avoid confusion and maintain the clarity of the Openpanel brand, please refrain from using domain names that may be misleading or suggest an official affiliation with Openpanel.
## Open Source Projects
If you are developing an open-source project related to Openpanel, feel free to use and reference our trademarks as long as it is clear that your project is not officially endorsed or affiliated with Openpanel.
## Contact Us
If you have any questions or need further clarification on the use of Openpanel trademarks, please contact us at [hey@openpanel.dev].
---
## Acceptable Uses
You are permitted to use the Openpanel name in the following situations, provided it is done truthfully and accurately:
- To refer to Openpanel and its products and services in news articles and other content without alteration.
- To discuss Openpanel and its products in a fair and honest manner that does not imply sponsorship, endorsement, or affiliation with Openpanel.
- To refer to and/or link to the products and services hosted on Openpanels servers and website.
- To indicate if your product, service, or solution integrates, is interoperable, or compatible with Openpanel, as long as it does not create confusion about the origin of your offering.
- You may use our word marks as part of a public subdomain solely for serving as the URL for your self-managed Openpanel instance (e.g., openpanel.companyname.com).
## Prohibited Uses
Unless you have explicit written permission from Openpanel or your use falls under the acceptable uses mentioned above, the use of Openpanel trademarks is strictly prohibited. Here are examples of prohibited uses that may be considered for permission upon request:
- Use of Openpanel trademarks in connection with a public website offering Openpanel software for installation and use on a server (instead of directing users to the official Openpanel site).
- Use of Openpanel trademarks in connection with versions of Openpanel products made publicly available or offered in the cloud by a managed service provider, resale, or other commercial basis.
- Use of Openpanel trademarks in connection with bundling Openpanel products with other software.
In these cases:
- Adherence to the terms of the open-source license for Openpanel software products and code is mandatory.
- Removal of all Openpanel logos is required, with the adoption of your own branding to clearly signify no affiliation with or endorsement by Openpanel.
- Avoidance of using any Openpanel trademark in connection with the user-facing name, branding, or marketing materials of your project.
- Usage of word marks, but not logos, in truthful statements describing the relationship between your software and Openpanel is allowed. For instance, "this software is derived from the source code of the Openpanel software," along with a disclaimer that your project is not officially associated with Openpanel or its products.
Openpanel reserves the right, at its sole discretion, to (i) terminate, revoke, modify, or change permission to use the trademarks at any time and; (ii) object to any use or misuse of the trademarks globally. Any changes to these guidelines are effective immediately upon posting, and your continued use of the trademarks following revised guidelines signifies your acceptance of such revisions.

104
apps/api/Dockerfile Normal file
View File

@@ -0,0 +1,104 @@
# Dockerfile that builds the web app only
FROM --platform=linux/amd64 node:20-slim AS base
ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL
ARG CLICKHOUSE_DB
ENV CLICKHOUSE_DB=$CLICKHOUSE_DB
ARG CLICKHOUSE_PASSWORD
ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD
ARG CLICKHOUSE_URL
ENV CLICKHOUSE_URL=$CLICKHOUSE_URL
ARG CLICKHOUSE_USER
ENV CLICKHOUSE_USER=$CLICKHOUSE_USER
ARG REDIS_URL
ENV REDIS_URL=$REDIS_URL
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
ARG NODE_VERSION=20
RUN apt update \
&& apt install -y curl python3 make g++ \
&& curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \
&& bash n $NODE_VERSION \
&& rm n \
&& npm install -g n \
&& rm -rf /var/cache/apk/*
WORKDIR /app
COPY package.json package.json
COPY pnpm-lock.yaml pnpm-lock.yaml
COPY pnpm-workspace.yaml pnpm-workspace.yaml
COPY apps/api/package.json apps/api/package.json
COPY packages/db/package.json packages/db/package.json
COPY packages/redis/package.json packages/redis/package.json
COPY packages/queue/package.json packages/queue/package.json
COPY packages/common/package.json packages/common/package.json
COPY packages/constants/package.json packages/constants/package.json
COPY packages/validation/package.json packages/validation/package.json
COPY packages/sdk/package.json packages/sdk/package.json
# BUILD
FROM base AS build
WORKDIR /app/apps/api
RUN pnpm install --frozen-lockfile
WORKDIR /app
COPY apps apps
COPY packages packages
COPY tooling tooling
RUN pnpm db:codegen
WORKDIR /app/apps/api
RUN pnpm run build
# PROD
FROM base AS prod
WORKDIR /app/apps/api
RUN pnpm install --frozen-lockfile --prod
# FINAL
FROM base AS runner
COPY --from=build /app/package.json /app/package.json
COPY --from=prod /app/node_modules /app/node_modules
# Apps
COPY --from=build /app/apps/api /app/apps/api
# Apps node_modules
COPY --from=prod /app/apps/api/node_modules /app/apps/api/node_modules
# Packages
COPY --from=build /app/packages/db /app/packages/db
COPY --from=build /app/packages/redis /app/packages/redis
COPY --from=build /app/packages/queue /app/packages/queue
COPY --from=build /app/packages/common /app/packages/common
# Packages node_modules
COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules
COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules
COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules
COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules
RUN pnpm db:codegen
WORKDIR /app/apps/api
EXPOSE 3000
CMD ["pnpm", "start"]

51
apps/api/package.json Normal file
View File

@@ -0,0 +1,51 @@
{
"name": "@openpanel/api",
"version": "0.0.1",
"scripts": {
"dev": "dotenv -e ../../.env -c -v WATCH=1 tsup",
"testing": "API_PORT=3333 pnpm dev",
"start": "node dist/index.js",
"build": "rm -rf dist && tsup",
"lint": "eslint .",
"format": "prettier --check \"**/*.{mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@fastify/cors": "^9.0.0",
"@fastify/websocket": "^8.3.1",
"@logtail/pino": "^0.4.19",
"@openpanel/common": "workspace:*",
"@openpanel/db": "workspace:*",
"@openpanel/queue": "workspace:*",
"@openpanel/redis": "workspace:*",
"fastify": "^4.25.2",
"ico-to-png": "^0.2.1",
"pino": "^8.17.2",
"pino-pretty": "^10.3.1",
"ramda": "^0.29.1",
"sharp": "^0.33.2",
"ua-parser-js": "^1.0.37",
"uuid": "^9.0.1"
},
"devDependencies": {
"@openpanel/eslint-config": "workspace:*",
"@openpanel/prettier-config": "workspace:*",
"@openpanel/sdk": "workspace:*",
"@openpanel/tsconfig": "workspace:*",
"@types/ramda": "^0.29.6",
"@types/ua-parser-js": "^0.7.39",
"@types/uuid": "^9.0.8",
"@types/ws": "^8.5.10",
"eslint": "^8.48.0",
"prettier": "^3.0.3",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
},
"eslintConfig": {
"root": true,
"extends": [
"@openpanel/eslint-config/base"
]
},
"prettier": "@openpanel/prettier-config"
}

View File

@@ -0,0 +1,48 @@
import fs from 'fs';
import path from 'path';
function transform(data: any) {
const obj: Record<string, unknown> = {};
for (const type in data) {
for (const name in data[type]) {
const domains = data[type][name].domains ?? [];
for (const domain of domains) {
obj[domain] = {
type,
name,
};
}
}
}
return obj;
}
async function main() {
// Get document, or throw exception on error
try {
const data = await fetch(
'https://s3-eu-west-1.amazonaws.com/snowplow-hosted-assets/third-party/referer-parser/referers-latest.json'
).then((res) => res.json());
fs.writeFileSync(
path.resolve(__dirname, '../src/referrers/index.ts'),
[
'// This file is generated by the script get-referrers.ts',
'',
'// The data is fetch from snowplow-referer-parser https://github.com/snowplow-referer-parser/referer-parser',
`// The orginal referers.yml is based on Piwik's SearchEngines.php and Socials.php, copyright 2012 Matthieu Aubry and available under the GNU General Public License v3.`,
'',
`const referrers: Record<string, { type: string, name: string }> = ${JSON.stringify(
transform(data)
)} as const;`,
'export default referrers;',
].join('\n'),
'utf-8'
);
} catch (e) {
console.log(e);
}
}
main();

View File

@@ -0,0 +1,224 @@
import { omit, prop, uniqBy } from "ramda";
import { generateProfileId, getTime, toISOString } from "@openpanel/common";
import type { Event, IServiceCreateEventPayload } from "@openpanel/db";
import {
createEvent as createClickhouseEvent,
db,
formatClickhouseDate,
getSalts,
} from "@openpanel/db";
import { parseIp } from "../src/utils/parseIp";
import { parseUserAgent } from "../src/utils/parseUserAgent";
const clean = omit([
"ip",
"os",
"ua",
"url",
"hash",
"host",
"path",
"device",
"screen",
"hostname",
"language",
"referrer",
"timezone",
]);
async function main() {
const events = await db.event.findMany({
where: {
project_id: "4e2798cb-e255-4e9d-960d-c9ad095aabd7",
name: "screen_view",
createdAt: {
gte: new Date("2024-01-01"),
lt: new Date("2024-02-04"),
},
},
orderBy: {
createdAt: "asc",
},
});
const grouped: Record<string, Event[]> = {};
let index = 0;
for (const event of events.slice()) {
// console.log(index, event.name, event.createdAt.toISOString());
index++;
const properties = event.properties as Record<string, any>;
if (properties.ua?.includes("bot")) {
// console.log('IGNORE', event.id);
continue;
}
if (!event.profile_id) {
// console.log('IGNORE', event.id);
continue;
}
const hej = grouped[event.profile_id];
if (hej) {
hej.push(event);
} else {
grouped[event.profile_id] = [event];
}
}
console.log("Total users", Object.keys(grouped).length);
let uidx = -1;
for (const profile_id of Object.keys(grouped)) {
uidx++;
console.log(`User index ${uidx}`);
const events = uniqBy(prop("createdAt"), grouped[profile_id] || []);
if (events) {
let lastSessionStart = null;
let screenViews = 0;
let totalDuration = 0;
console.log("new user...");
let eidx = -1;
for (const event of events) {
eidx++;
const prevEvent = events[eidx - 1];
const prevEventAt = prevEvent?.createdAt;
const nextEvent = events[eidx + 1];
const properties = event.properties as Record<string, any>;
const projectId = event.project_id;
const path = properties.path!;
const ip = properties.ip!;
const origin = "https://openpanel.kiddo.se";
const ua = properties.ua!;
const uaInfo = parseUserAgent(ua);
const salts = await getSalts();
const profileId = generateProfileId({
salt: salts.current,
origin,
ip,
ua,
});
const geo = parseIp(ip);
const isNextEventNewSession =
nextEvent &&
nextEvent.createdAt.getTime() - event.createdAt.getTime() >
1000 * 60 * 30;
const payload: IServiceCreateEventPayload = {
name: event.name,
profileId,
projectId,
properties: clean(properties),
createdAt: event.createdAt.toISOString(),
country: geo.country,
city: geo.city,
region: geo.region,
continent: geo.continent,
os: uaInfo.os,
osVersion: uaInfo.osVersion,
browser: uaInfo.browser,
browserVersion: uaInfo.browserVersion,
device: uaInfo.device,
brand: uaInfo.brand,
model: uaInfo.model,
duration:
nextEvent && !isNextEventNewSession
? nextEvent.createdAt.getTime() - event.createdAt.getTime()
: 0,
path,
referrer: properties?.referrer?.host ?? "", // TODO
referrerName: properties?.referrer?.host ?? "", // TODO
};
if (!prevEventAt) {
lastSessionStart = await createSessionStart(payload);
} else if (
event.createdAt.getTime() - prevEventAt.getTime() >
1000 * 60 * 30
) {
if (eidx > 0 && prevEventAt && lastSessionStart) {
await createSessionEnd(prevEventAt, lastSessionStart, {
screenViews,
totalDuration,
});
totalDuration = 0;
screenViews = 0;
lastSessionStart = await createSessionStart(payload);
}
}
screenViews++;
totalDuration += payload.duration;
await createEvent(payload);
} // for each user event
const prevEventAt = events[events.length - 1]?.createdAt;
if (prevEventAt && lastSessionStart) {
await createSessionEnd(prevEventAt, lastSessionStart, {
screenViews,
totalDuration,
});
}
}
}
}
async function createEvent(event: IServiceCreateEventPayload) {
console.log(
`Create ${event.name} - ${event.path} - ${formatClickhouseDate(
event.createdAt,
)} - ${event.duration / 1000} sec`,
);
await createClickhouseEvent(event);
}
async function createSessionStart(event: IServiceCreateEventPayload) {
const session: IServiceCreateEventPayload = {
...event,
duration: 0,
name: "session_start",
createdAt: toISOString(getTime(event.createdAt) - 100),
};
await createEvent(session);
return session;
}
async function createSessionEnd(
prevEventAt: Date,
sessionStart: IServiceCreateEventPayload,
options: {
screenViews: number;
totalDuration: number;
},
) {
const properties: Record<string, unknown> = {};
if (options.screenViews === 1) {
properties.__bounce = true;
} else {
properties.__bounce = false;
}
const session: IServiceCreateEventPayload = {
...sessionStart,
properties: {
...properties,
...sessionStart.properties,
},
duration: options.totalDuration,
name: "session_end",
createdAt: toISOString(prevEventAt.getTime() + 10),
};
await createEvent(session);
return session;
}
main();

View File

@@ -0,0 +1,18 @@
//@ts-nocheck
async function main() {
const crypto = require('crypto');
function createHash(data, len) {
return crypto
.createHash('shake256', { outputLength: len })
.update(data)
.digest('hex');
}
console.log(createHash('foo', 2));
// 1af9
console.log(createHash('foo', 32));
// 1af97f7818a28edf}
}
main();

View File

@@ -0,0 +1,6 @@
# Device Detector - The Universal Device Detection library for parsing User Agents
> @link https://matomo.org
> @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or lat
[bots.ts](./bots.ts) is based on matomo bots.yml file. You can see the original version here [here](https://raw.githubusercontent.com/matomo-org/device-detector/master/regexes/bots.yml).

4901
apps/api/src/bots/bots.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
import bots from './bots';
export function isBot(ua: string) {
const res = bots.find((bot) => {
if (new RegExp(bot.regex).test(ua)) {
return true;
}
return false;
});
if (!res) {
return null;
}
return {
name: res.name,
type: res.category || 'Unknown',
};
}

View File

@@ -0,0 +1,325 @@
import { logger, logInfo, noop } from "@/utils/logger";
import { getClientIp, parseIp } from "@/utils/parseIp";
import { getReferrerWithQuery, parseReferrer } from "@/utils/parseReferrer";
import { isUserAgentSet, parseUserAgent } from "@/utils/parseUserAgent";
import { isSameDomain, parsePath } from "@/utils/url";
import type { FastifyReply, FastifyRequest } from "fastify";
import { omit } from "ramda";
import { v4 as uuid } from "uuid";
import { generateDeviceId, getTime, toISOString } from "@openpanel/common";
import type { IServiceCreateEventPayload } from "@openpanel/db";
import { createEvent, getEvents, getSalts } from "@openpanel/db";
import type { JobsOptions } from "@openpanel/queue";
import { eventsQueue } from "@openpanel/queue";
import { findJobByPrefix } from "@openpanel/queue/src/utils";
import type { PostEventPayload } from "@openpanel/sdk";
const SESSION_TIMEOUT = 1000 * 60 * 30;
const SESSION_END_TIMEOUT = SESSION_TIMEOUT + 1000;
async function withTiming<T>(name: string, promise: T) {
try {
const start = Date.now();
const res = await promise;
const end = Date.now();
if (end - start > 1000) {
logInfo(`${name} took too long: ${end - start}ms`);
}
return res;
} catch (error) {
logger.error(error, `Failed to execute ${name}`);
throw error;
}
}
function createContextLogger(request: FastifyRequest) {
const _log = request.log.child({
requestId: request.id,
requestUrl: request.url,
headers: request.headers,
projectId: request.projectId,
});
let obj: Record<string, unknown> = {};
return {
add: (key: string, value: unknown) => (obj[key] = value),
addObject: (key: string, value: Record<string, unknown>) => {
obj = { ...obj, ...value };
},
send: (message: string, value: Record<string, unknown>) =>
_log.info({ ...obj, ...value }, message),
};
}
export async function postEvent(
request: FastifyRequest<{
Body: PostEventPayload;
}>,
reply: FastifyReply,
) {
const contextLogger = createContextLogger(request);
let deviceId: string | null = null;
const { projectId, body } = request;
const properties = body.properties ?? {};
const getProperty = (name: string): string | undefined => {
// replace thing is just for older sdks when we didn't have `__`
// remove when kiddokitchen app (24.09.02) is not used anymore
return (
((properties[name] || properties[name.replace("__", "")]) as
| string
| null
| undefined) ?? undefined
);
};
const profileId = body.profileId ?? "";
const createdAt = new Date(body.timestamp);
const url = getProperty("__path");
const { path, hash, query } = parsePath(url);
const referrer = isSameDomain(getProperty("__referrer"), url)
? null
: parseReferrer(getProperty("__referrer"));
const utmReferrer = getReferrerWithQuery(query);
const ip = getClientIp(request)!;
const origin = request.headers.origin!;
const ua = request.headers["user-agent"]!;
const uaInfo = parseUserAgent(ua);
const salts = await getSalts();
const currentDeviceId = generateDeviceId({
salt: salts.current,
origin,
ip,
ua,
});
const previousDeviceId = generateDeviceId({
salt: salts.previous,
origin,
ip,
ua,
});
const isServerEvent = !ip && !origin && !isUserAgentSet(ua);
if (isServerEvent) {
const [event] = await withTiming(
"Get last event (server-event)",
getEvents(
`SELECT * FROM events WHERE name = 'screen_view' AND profile_id = '${profileId}' AND project_id = '${projectId}' ORDER BY created_at DESC LIMIT 1`,
),
);
eventsQueue.add("event", {
type: "createEvent",
payload: {
name: body.name,
deviceId: event?.deviceId || "",
sessionId: event?.sessionId || "",
profileId,
projectId,
properties: Object.assign(
{},
omit(["__path", "__referrer"], properties),
{
hash,
query,
},
),
createdAt,
country: event?.country ?? "",
city: event?.city ?? "",
region: event?.region ?? "",
continent: event?.continent ?? "",
os: event?.os ?? "",
osVersion: event?.osVersion ?? "",
browser: event?.browser ?? "",
browserVersion: event?.browserVersion ?? "",
device: event?.device ?? "",
brand: event?.brand ?? "",
model: event?.model ?? "",
duration: 0,
path: event?.path ?? "",
referrer: event?.referrer ?? "",
referrerName: event?.referrerName ?? "",
referrerType: event?.referrerType ?? "",
profile: undefined,
meta: undefined,
},
});
return reply.status(200).send("");
}
const [geo, sessionEndJobCurrentDeviceId, sessionEndJobPreviousDeviceId] =
await withTiming(
"Get geo and jobs from queue",
Promise.all([
parseIp(ip),
findJobByPrefix(
eventsQueue,
`sessionEnd:${projectId}:${currentDeviceId}:`,
),
findJobByPrefix(
eventsQueue,
`sessionEnd:${projectId}:${previousDeviceId}:`,
),
]),
);
const createSessionStart =
!sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId;
if (sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId) {
deviceId = currentDeviceId;
const diff = Date.now() - sessionEndJobCurrentDeviceId.timestamp;
sessionEndJobCurrentDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
} else if (!sessionEndJobCurrentDeviceId && sessionEndJobPreviousDeviceId) {
deviceId = previousDeviceId;
const diff = Date.now() - sessionEndJobPreviousDeviceId.timestamp;
sessionEndJobPreviousDeviceId.changeDelay(diff + SESSION_END_TIMEOUT);
} else {
deviceId = currentDeviceId;
// Queue session end
eventsQueue.add(
"event",
{
type: "createSessionEnd",
payload: {
deviceId,
},
},
{
delay: SESSION_END_TIMEOUT,
jobId: `sessionEnd:${projectId}:${deviceId}:${Date.now()}`,
},
);
}
const [[sessionStartEvent], prevEventJob] = await withTiming(
"Get session start event",
Promise.all([
getEvents(
`SELECT * FROM events WHERE name = 'session_start' AND device_id = '${deviceId}' AND project_id = '${projectId}' ORDER BY created_at DESC LIMIT 1`,
),
findJobByPrefix(eventsQueue, `event:${projectId}:${deviceId}:`),
]),
);
const payload: Omit<IServiceCreateEventPayload, "id"> = {
name: body.name,
deviceId,
profileId,
projectId,
sessionId: createSessionStart ? uuid() : sessionStartEvent?.sessionId ?? "",
properties: Object.assign({}, omit(["__path", "__referrer"], properties), {
hash,
query,
}),
createdAt,
country: geo.country,
city: geo.city,
region: geo.region,
continent: geo.continent,
os: uaInfo.os,
osVersion: uaInfo.osVersion,
browser: uaInfo.browser,
browserVersion: uaInfo.browserVersion,
device: uaInfo.device,
brand: uaInfo.brand,
model: uaInfo.model,
duration: 0,
path: path,
referrer: referrer?.url,
referrerName: referrer?.name ?? utmReferrer?.name ?? "",
referrerType: referrer?.type ?? utmReferrer?.type ?? "",
profile: undefined,
meta: undefined,
};
const isDelayed = prevEventJob ? await prevEventJob?.isDelayed() : false;
if (isDelayed && prevEventJob && prevEventJob.data.type === "createEvent") {
const prevEvent = prevEventJob.data.payload;
const duration = getTime(payload.createdAt) - getTime(prevEvent.createdAt);
contextLogger.add("prevEvent", prevEvent);
// Set path from prev screen_view event if current event is not a screen_view
if (payload.name != "screen_view") {
payload.path = prevEvent.path;
}
if (payload.name === "screen_view") {
if (duration < 0) {
contextLogger.send("duration is wrong", {
payload,
duration,
});
} else {
// Skip update duration if it's wrong
// Seems like request is not in right order
await withTiming(
"Update previous job with duration",
prevEventJob.updateData({
type: "createEvent",
payload: {
...prevEvent,
duration,
},
}),
);
}
await withTiming("Promote previous job", prevEventJob.promote());
}
} else if (payload.name !== "screen_view") {
contextLogger.send("no previous job", {
prevEventJob,
payload,
});
}
if (createSessionStart) {
// We do not need to queue session_start
await withTiming(
"Create session start event",
createEvent({
...payload,
name: "session_start",
// @ts-expect-error
createdAt: toISOString(getTime(payload.createdAt) - 100),
}),
);
}
const options: JobsOptions = {};
if (payload.name === "screen_view") {
options.delay = SESSION_TIMEOUT;
options.jobId = `event:${projectId}:${deviceId}:${Date.now()}`;
}
contextLogger.send("event is queued", {
ip,
origin,
ua,
uaInfo,
referrer,
profileId,
projectId,
deviceId,
geo,
sessionStartEvent,
path,
payload,
});
// Queue current event
eventsQueue
.add(
"event",
{
type: "createEvent",
payload,
},
options,
)
.catch(noop("Failed to queue event"));
reply.status(202).send(deviceId);
}

View File

@@ -0,0 +1,109 @@
import type { FastifyReply, FastifyRequest } from "fastify";
import type * as WebSocket from "ws";
import { getSafeJson } from "@openpanel/common";
import type { IServiceCreateEventPayload } from "@openpanel/db";
import { getEvents, getLiveVisitors } from "@openpanel/db";
import { redis, redisPub, redisSub } from "@openpanel/redis";
export function getLiveEventInfo(key: string) {
return key.split(":").slice(2) as [string, string];
}
export async function test(
req: FastifyRequest<{
Params: {
projectId: string;
};
}>,
reply: FastifyReply,
) {
const [event] = await getEvents(
`SELECT * FROM events WHERE project_id = '${req.params.projectId}' AND name = 'screen_view' LIMIT 1`,
);
if (!event) {
return reply.status(404).send("No event found");
}
redisPub.publish("event", JSON.stringify(event));
redis.set(
`live:event:${event.projectId}:${Math.random() * 1000}`,
"",
"EX",
10,
);
reply.status(202).send(event);
}
export function wsVisitors(
connection: {
socket: WebSocket;
},
req: FastifyRequest<{
Params: {
projectId: string;
};
}>,
) {
const { params } = req;
redisSub.subscribe("event");
redisSub.psubscribe("__key*:expired");
const message = (channel: string, message: string) => {
if (channel === "event") {
const event = getSafeJson<IServiceCreateEventPayload>(message);
if (event?.projectId === params.projectId) {
getLiveVisitors(params.projectId).then((count) => {
connection.socket.send(String(count));
});
}
}
};
const pmessage = (pattern: string, channel: string, message: string) => {
const [projectId] = getLiveEventInfo(message);
if (projectId && projectId === params.projectId) {
getLiveVisitors(params.projectId).then((count) => {
connection.socket.send(String(count));
});
}
};
redisSub.on("message", message);
redisSub.on("pmessage", pmessage);
connection.socket.on("close", () => {
redisSub.unsubscribe("event");
redisSub.punsubscribe("__key*:expired");
redisSub.off("message", message);
redisSub.off("pmessage", pmessage);
});
}
export function wsEvents(
connection: {
socket: WebSocket;
},
req: FastifyRequest<{
Params: {
projectId: string;
};
}>,
) {
const { params } = req;
redisSub.subscribe("event");
const message = (channel: string, message: string) => {
const event = getSafeJson<IServiceCreateEventPayload>(message);
if (event?.projectId === params.projectId) {
connection.socket.send(JSON.stringify(event));
}
};
redisSub.on("message", message);
connection.socket.on("close", () => {
redisSub.unsubscribe("event");
redisSub.off("message", message);
});
}

View File

@@ -0,0 +1,127 @@
import type { FastifyReply, FastifyRequest } from "fastify";
import icoToPng from "ico-to-png";
import sharp from "sharp";
import { createHash } from "@openpanel/common";
import { redis } from "@openpanel/redis";
interface GetFaviconParams {
url: string;
}
async function getImageBuffer(url: string) {
try {
const res = await fetch(url);
const contentType = res.headers.get("content-type");
if (!contentType?.includes("image")) {
return null;
}
if (!res.ok) {
return null;
}
if (contentType === "image/x-icon" || url.endsWith(".ico")) {
const arrayBuffer = await res.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return await icoToPng(buffer, 30);
}
return await sharp(await res.arrayBuffer())
.resize(30, 30, {
fit: "cover",
})
.png()
.toBuffer();
} catch (e) {
console.log("Failed to get image from url", url);
console.log(e);
}
}
const imageExtensions = ["svg", "png", "jpg", "jpeg", "gif", "webp", "ico"];
export async function getFavicon(
request: FastifyRequest<{
Querystring: GetFaviconParams;
}>,
reply: FastifyReply,
) {
function sendBuffer(buffer: Buffer, cacheKey?: string) {
if (cacheKey) {
redis.set(`favicon:${cacheKey}`, buffer.toString("base64"));
}
reply.type("image/png");
console.log("buffer", buffer.byteLength);
return reply.send(buffer);
}
if (!request.query.url) {
return reply.status(404).send("Not found");
}
const url = decodeURIComponent(request.query.url);
// DIRECT IMAGE
if (imageExtensions.find((ext) => url.endsWith(ext))) {
const cacheKey = createHash(url, 32);
const cache = await redis.get(`favicon:${cacheKey}`);
if (cache) {
return sendBuffer(Buffer.from(cache, "base64"));
}
const buffer = await getImageBuffer(url);
if (buffer && buffer.byteLength > 0) {
return sendBuffer(buffer, cacheKey);
}
}
const { hostname, origin } = new URL(url);
const cache = await redis.get(`favicon:${hostname}`);
if (cache) {
return sendBuffer(Buffer.from(cache, "base64"));
}
// TRY FAVICON.ICO
const buffer = await getImageBuffer(`${origin}/favicon.ico`);
if (buffer && buffer.byteLength > 0) {
return sendBuffer(buffer, hostname);
}
// PARSE HTML
const res = await fetch(url).then((res) => res.text());
function findFavicon(res: string) {
const match = res.match(
/(\<link(.+?)image\/x-icon(.+?)\>|\<link(.+?)shortcut\sicon(.+?)\>)/,
);
if (!match) {
return null;
}
return match[0].match(/href="(.+?)"/)?.[1] ?? null;
}
const favicon = findFavicon(res);
if (favicon) {
const buffer = await getImageBuffer(favicon);
if (buffer && buffer.byteLength > 0) {
return sendBuffer(buffer, hostname);
}
}
return reply.status(404).send("Not found");
}
export async function clearFavicons(
request: FastifyRequest,
reply: FastifyReply,
) {
const keys = await redis.keys("favicon:*");
for (const key of keys) {
await redis.del(key);
}
return reply.status(404).send("OK");
}

View File

@@ -0,0 +1,113 @@
import { getClientIp, parseIp } from "@/utils/parseIp";
import { isUserAgentSet, parseUserAgent } from "@/utils/parseUserAgent";
import type { FastifyReply, FastifyRequest } from "fastify";
import { assocPath, pathOr } from "ramda";
import { getProfileById, upsertProfile } from "@openpanel/db";
import type {
IncrementProfilePayload,
UpdateProfilePayload,
} from "@openpanel/sdk";
export async function updateProfile(
request: FastifyRequest<{
Body: UpdateProfilePayload;
}>,
reply: FastifyReply,
) {
const { profileId, properties, ...rest } = request.body;
const projectId = request.projectId;
const ip = getClientIp(request)!;
const ua = request.headers["user-agent"]!;
const uaInfo = parseUserAgent(ua);
const geo = await parseIp(ip);
await upsertProfile({
id: profileId,
projectId,
properties: {
...(properties ?? {}),
...(ip ? geo : {}),
...(isUserAgentSet(ua) ? uaInfo : {}),
},
...rest,
});
reply.status(202).send(profileId);
}
export async function incrementProfileProperty(
request: FastifyRequest<{
Body: IncrementProfilePayload;
}>,
reply: FastifyReply,
) {
const { profileId, property, value } = request.body;
const projectId = request.projectId;
const profile = await getProfileById(profileId);
if (!profile) {
return reply.status(404).send("Not found");
}
const parsed = parseInt(
pathOr<string>("0", property.split("."), profile.properties),
10,
);
if (isNaN(parsed)) {
return reply.status(400).send("Not number");
}
profile.properties = assocPath(
property.split("."),
parsed + value,
profile.properties,
);
await upsertProfile({
id: profile.id,
projectId,
properties: profile.properties,
});
reply.status(202).send(profile.id);
}
export async function decrementProfileProperty(
request: FastifyRequest<{
Body: IncrementProfilePayload;
}>,
reply: FastifyReply,
) {
const { profileId, property, value } = request.body;
const projectId = request.projectId;
const profile = await getProfileById(profileId);
if (!profile) {
return reply.status(404).send("Not found");
}
const parsed = parseInt(
pathOr<string>("0", property.split("."), profile.properties),
10,
);
if (isNaN(parsed)) {
return reply.status(400).send("Not number");
}
profile.properties = assocPath(
property.split("."),
parsed - value,
profile.properties,
);
await upsertProfile({
id: profile.id,
projectId,
properties: profile.properties,
});
reply.status(202).send(profile.id);
}

73
apps/api/src/index.ts Normal file
View File

@@ -0,0 +1,73 @@
import cors from "@fastify/cors";
import Fastify from "fastify";
import { redisPub } from "@openpanel/redis";
import eventRouter from "./routes/event.router";
import liveRouter from "./routes/live.router";
import miscRouter from "./routes/misc.router";
import profileRouter from "./routes/profile.router";
import { logger, logInfo } from "./utils/logger";
declare module "fastify" {
interface FastifyRequest {
projectId: string;
}
}
const port = parseInt(process.env.API_PORT || "3000", 10);
const startServer = async () => {
logInfo("Starting server");
try {
const fastify = Fastify({
logger: logger,
});
fastify.register(cors, {
origin: "*",
});
fastify.decorateRequest("projectId", "");
fastify.register(eventRouter, { prefix: "/event" });
fastify.register(profileRouter, { prefix: "/profile" });
fastify.register(liveRouter, { prefix: "/live" });
fastify.register(miscRouter, { prefix: "/misc" });
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error(error);
});
fastify.get("/", (request, reply) => {
reply.send({ name: "openpanel sdk api" });
});
// fastify.get('/health-check', async (request, reply) => {
// try {
// await utils.healthCheck()
// reply.status(200).send()
// } catch (e) {
// reply.status(500).send()
// }
// })
if (process.env.NODE_ENV === "production") {
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, (err) => {
logger.fatal(err, `uncaught exception detected ${signal}`);
fastify.close().then((err) => {
process.exit(err ? 1 : 0);
});
});
}
}
await fastify.listen({
host: process.env.NODE_ENV === "production" ? "0.0.0.0" : "localhost",
port,
});
// Notify when keys expires
redisPub.config("SET", "notify-keyspace-events", "Ex");
} catch (e) {
console.error(e);
}
};
startServer();

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
# Snowplow Referer Parser
The file index.ts in this dir is generated from snowplows referer database [Snowplow Referer Parser](https://github.com/snowplow-referer-parser/referer-parser).
The orginal [referers.yml](https://github.com/snowplow-referer-parser/referer-parser/blob/master/resources/referers.yml) is based on Piwik's SearchEngines.php and Socials.php, copyright 2012 Matthieu Aubry and available under the GNU General Public License v3.

View File

@@ -0,0 +1,59 @@
import { isBot } from "@/bots";
import * as controller from "@/controllers/event.controller";
import { validateSdkRequest } from "@/utils/auth";
import type { FastifyPluginCallback, FastifyRequest } from "fastify";
import { createBotEvent } from "@openpanel/db";
import type { PostEventPayload } from "@openpanel/sdk";
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
fastify.addHook(
"preHandler",
async (
req: FastifyRequest<{
Body: PostEventPayload;
}>,
reply,
) => {
try {
const projectId = await validateSdkRequest(req.headers);
req.projectId = projectId;
const bot = req.headers["user-agent"]
? isBot(req.headers["user-agent"])
: null;
if (bot) {
const path = (req.body?.properties?.__path ||
req.body?.properties?.path) as string | undefined;
req.log.warn({ ...req.headers, bot }, "Bot detected (event)");
await createBotEvent({
...bot,
projectId,
path: path ?? "",
createdAt: new Date(req.body?.timestamp),
});
reply.status(202).send("OK");
}
} catch (e) {
req.log.error(e, "Failed to create bot event");
reply.status(401).send();
return;
}
},
);
fastify.route({
method: "POST",
url: "/",
handler: controller.postEvent,
});
fastify.route({
method: "GET",
url: "/",
handler: controller.postEvent,
});
done();
};
export default eventRouter;

View File

@@ -0,0 +1,27 @@
import * as controller from '@/controllers/live.controller';
import fastifyWS from '@fastify/websocket';
import type { FastifyPluginCallback } from 'fastify';
const liveRouter: FastifyPluginCallback = (fastify, opts, done) => {
fastify.route({
method: 'GET',
url: '/events/test/:projectId',
handler: controller.test,
});
fastify.register(fastifyWS);
fastify.register((fastify, _, done) => {
fastify.get(
'/visitors/:projectId',
{ websocket: true },
controller.wsVisitors
);
fastify.get('/events/:projectId', { websocket: true }, controller.wsEvents);
done();
});
done();
};
export default liveRouter;

View File

@@ -0,0 +1,20 @@
import * as controller from '@/controllers/misc.controller';
import type { FastifyPluginCallback } from 'fastify';
const miscRouter: FastifyPluginCallback = (fastify, opts, done) => {
fastify.route({
method: 'GET',
url: '/favicon',
handler: controller.getFavicon,
});
fastify.route({
method: 'GET',
url: '/favicon/clear',
handler: controller.clearFavicons,
});
done();
};
export default miscRouter;

View File

@@ -0,0 +1,46 @@
import { isBot } from '@/bots';
import * as controller from '@/controllers/profile.controller';
import { validateSdkRequest } from '@/utils/auth';
import type { FastifyPluginCallback } from 'fastify';
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
fastify.addHook('preHandler', async (req, reply) => {
try {
const projectId = await validateSdkRequest(req.headers);
req.projectId = projectId;
const bot = req.headers['user-agent']
? isBot(req.headers['user-agent'])
: null;
if (bot) {
reply.log.warn({ ...req.headers, bot }, 'Bot detected (profile)');
reply.status(202).send('OK');
}
} catch (e) {
reply.status(401).send();
return;
}
});
fastify.route({
method: 'POST',
url: '/',
handler: controller.updateProfile,
});
fastify.route({
method: 'POST',
url: '/increment',
handler: controller.incrementProfileProperty,
});
fastify.route({
method: 'POST',
url: '/decrement',
handler: controller.decrementProfileProperty,
});
done();
};
export default eventRouter;

View File

@@ -0,0 +1,43 @@
import type { RawRequestDefaultExpression } from 'fastify';
import { verifyPassword } from '@openpanel/common';
import { db } from '@openpanel/db';
export async function validateSdkRequest(
headers: RawRequestDefaultExpression['headers']
): Promise<string> {
const clientId = headers['openpanel-client-id'] as string;
const clientSecret = headers['openpanel-client-secret'] as string;
const origin = headers.origin;
if (!clientId) {
throw new Error('Misisng client id');
}
const client = await db.client.findUnique({
where: {
id: clientId,
},
});
if (!client) {
throw new Error('Invalid client id');
}
if (client.secret) {
if (!(await verifyPassword(clientSecret || '', client.secret))) {
throw new Error('Invalid client secret');
}
} else if (client.cors !== '*') {
const domainAllowed = client.cors.split(',').find((domain) => {
if (domain === origin) {
return true;
}
});
if (!domainAllowed) {
throw new Error('Invalid cors settings');
}
}
return client.project_id;
}

View File

@@ -0,0 +1,29 @@
import type { TransportTargetOptions } from 'pino';
import pino from 'pino';
const targets: TransportTargetOptions[] =
process.env.NODE_ENV === 'production'
? [
{
target: '@logtail/pino',
options: { sourceToken: process.env.BETTERSTACK_TOKEN },
},
]
: [
{
target: 'pino-pretty',
},
];
const transport = pino.transport({
targets,
});
export const logger = pino(transport);
export function logInfo(msg: string, obj?: unknown) {
logger.info(obj, msg);
}
export const noop = (message: string) => (error: unknown) =>
logger.error(error, message);

View File

@@ -0,0 +1,61 @@
import type { FastifyRequest } from 'fastify';
import { logger } from './logger';
interface RemoteIpLookupResponse {
country: string | undefined;
city: string | undefined;
stateprov: string | undefined;
continent: string | undefined;
}
interface GeoLocation {
country: string | undefined;
city: string | undefined;
region: string | undefined;
continent: string | undefined;
}
const geo: GeoLocation = {
country: undefined,
city: undefined,
region: undefined,
continent: undefined,
};
const ignore = ['127.0.0.1', '::1'];
export function getClientIp(req: FastifyRequest) {
if (req.headers['cf-connecting-ip']) {
return String(req.headers['cf-connecting-ip']);
}
if (req.headers['x-forwarded-for']) {
return String(req.headers['x-forwarded-for']);
}
return null;
}
export async function parseIp(ip?: string): Promise<GeoLocation> {
if (!ip || ignore.includes(ip)) {
return geo;
}
try {
const geo = await fetch(`${process.env.GEO_IP_HOST}/${ip}`, {
signal: AbortSignal.timeout(2000),
});
const res = (await geo.json()) as RemoteIpLookupResponse;
return {
country: res.country,
city: res.city,
region: res.stateprov,
continent: res.continent,
};
} catch (e) {
logger.error('Failed to fetch geo location for ip', e);
return geo;
}
}

View File

@@ -0,0 +1,50 @@
import { stripTrailingSlash } from "@openpanel/common";
import referrers from "../referrers";
function getHostname(url: string | undefined) {
if (!url) {
return "";
}
try {
return new URL(url).hostname;
} catch (e) {
return "";
}
}
export function parseReferrer(url: string | undefined) {
const hostname = getHostname(url);
const match = referrers[hostname] ?? referrers[hostname.replace("www.", "")];
return {
name: match?.name ?? "",
type: match?.type ?? "unknown",
url: stripTrailingSlash(url ?? ""),
};
}
export function getReferrerWithQuery(
query: Record<string, string> | undefined,
) {
if (!query) {
return null;
}
const source = query.utm_source ?? query.ref ?? query.utm_referrer ?? "";
const match = Object.values(referrers).find(
(referrer) => referrer.name.toLowerCase() === source?.toLowerCase(),
);
if (!match) {
return null;
}
return {
name: match.name,
type: match.type,
url: "",
};
}

View File

@@ -0,0 +1,33 @@
import { UAParser } from 'ua-parser-js';
export function isUserAgentSet(ua: string) {
return ua !== 'node' && ua !== 'undici' && !!ua;
}
export function parseUserAgent(ua: string) {
const res = new UAParser(ua).getResult();
return {
os: res.os.name,
osVersion: res.os.version,
browser: res.browser.name,
browserVersion: res.browser.version,
device: res.device.type ?? getDevice(ua),
brand: res.device.vendor,
model: res.device.model,
};
}
export function getDevice(ua: string) {
const t1 =
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
ua
);
const t2 =
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
ua.slice(0, 4)
);
if (t1 || t2) {
return 'mobile';
}
return 'desktop';
}

48
apps/api/src/utils/url.ts Normal file
View File

@@ -0,0 +1,48 @@
export function parseSearchParams(
params: URLSearchParams
): Record<string, string> | undefined {
const result: Record<string, string> = {};
for (const [key, value] of params.entries()) {
result[key] = value;
}
return Object.keys(result).length ? result : undefined;
}
export function parsePath(path?: string): {
query?: Record<string, string>;
path: string;
hash?: string;
} {
if (!path) {
return {
path: '',
};
}
try {
const url = new URL(path);
return {
query: parseSearchParams(url.searchParams),
path: url.pathname,
hash: url.hash || undefined,
};
} catch (error) {
return {
path,
};
}
}
export function isSameDomain(
url1: string | undefined,
url2: string | undefined
) {
if (!url1 || !url2) {
return false;
}
try {
return new URL(url1).hostname === new URL(url2).hostname;
} catch (e) {
return false;
}
}

12
apps/api/tsconfig.json Normal file
View File

@@ -0,0 +1,12 @@
{
"extends": "@openpanel/tsconfig/base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}

18
apps/api/tsup.config.ts Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig } from 'tsup';
import type { Options } from 'tsup';
const options: Options = {
clean: true,
entry: ['src/index.ts'],
noExternal: [/^@openpanel\/.*$/u, /^@\/.*$/u],
sourcemap: true,
splitting: false,
};
if (process.env.WATCH) {
options.watch = ['src/**/*', '../../packages/**/*'];
options.onSuccess = 'node dist/index.js';
options.minify = false;
}
export default defineConfig(options);

113
apps/dashboard/Dockerfile Normal file
View File

@@ -0,0 +1,113 @@
FROM --platform=linux/amd64 node:20-slim AS base
ARG NEXT_PUBLIC_DASHBOARD_URL
ENV NEXT_PUBLIC_DASHBOARD_URL=$NEXT_PUBLIC_DASHBOARD_URL
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL
ARG CLICKHOUSE_DB
ENV CLICKHOUSE_DB=$CLICKHOUSE_DB
ARG CLICKHOUSE_PASSWORD
ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD
ARG CLICKHOUSE_URL
ENV CLICKHOUSE_URL=$CLICKHOUSE_URL
ARG CLICKHOUSE_USER
ENV CLICKHOUSE_USER=$CLICKHOUSE_USER
ARG REDIS_URL
ENV REDIS_URL=$REDIS_URL
ARG NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
ENV NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
ARG CLERK_SECRET_KEY
ENV CLERK_SECRET_KEY=$CLERK_SECRET_KEY
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
ARG NODE_VERSION=20
RUN apt update \
&& apt install -y curl \
&& curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \
&& bash n $NODE_VERSION \
&& rm n \
&& npm install -g n
WORKDIR /app
COPY package.json package.json
COPY pnpm-lock.yaml pnpm-lock.yaml
COPY pnpm-workspace.yaml pnpm-workspace.yaml
COPY apps/dashboard/package.json apps/dashboard/package.json
COPY packages/db/package.json packages/db/package.json
COPY packages/redis/package.json packages/redis/package.json
COPY packages/queue/package.json packages/queue/package.json
COPY packages/common/package.json packages/common/package.json
COPY packages/constants/package.json packages/constants/package.json
COPY packages/validation/package.json packages/validation/package.json
COPY packages/sdk/package.json packages/sdk/package.json
# BUILD
FROM base AS build
WORKDIR /app/apps/dashboard
RUN pnpm install --frozen-lockfile --ignore-scripts
WORKDIR /app
COPY apps apps
COPY packages packages
COPY tooling tooling
RUN pnpm db:codegen
WORKDIR /app/apps/dashboard
RUN pnpm run build
# PROD
FROM base AS prod
WORKDIR /app/apps/dashboard
RUN pnpm install --frozen-lockfile --prod --ignore-scripts
# FINAL
FROM base AS runner
COPY --from=build /app/package.json /app/package.json
COPY --from=prod /app/node_modules /app/node_modules
# Apps
COPY --from=build /app/apps/dashboard /app/apps/dashboard
# Apps node_modules
COPY --from=prod /app/apps/dashboard/node_modules /app/apps/dashboard/node_modules
# Packages
COPY --from=build /app/packages/db /app/packages/db
COPY --from=build /app/packages/redis /app/packages/redis
COPY --from=build /app/packages/common /app/packages/common
COPY --from=build /app/packages/queue /app/packages/queue
COPY --from=build /app/packages/constants /app/packages/constants
COPY --from=build /app/packages/validation /app/packages/validation
COPY --from=build /app/packages/sdk /app/packages/sdk
# Packages node_modules
COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules
COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules
COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules
COPY --from=prod /app/packages/validation/node_modules /app/packages/validation/node_modules
COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules
RUN pnpm db:codegen
WORKDIR /app/apps/dashboard
EXPOSE 3000
CMD ["pnpm", "start"]

View File

@@ -0,0 +1,6 @@
- new org
- create project
- all trpc mutations seems to break in prod
- top event convertions
- create events_meta (name, color, icon)
- edit event convertion

View File

@@ -7,9 +7,13 @@ await import('./src/env.mjs');
/** @type {import("next").NextConfig} */
const config = {
reactStrictMode: true,
transpilePackages: [],
transpilePackages: ['@openpanel/queue'],
eslint: { ignoreDuringBuilds: true },
typescript: { ignoreBuildErrors: true },
experimental: {
// Avoid "Critical dependency: the request of a dependency is an expression"
serverComponentsExternalPackages: ['bullmq'],
},
/**
* If you are using `appDir` then you must comment the below `i18n` config out.
*

130
apps/dashboard/package.json Normal file
View File

@@ -0,0 +1,130 @@
{
"name": "@openpanel/dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "rm -rf .next && pnpm with-env next dev",
"testing": "pnpm dev",
"build": "next build",
"start": "next start",
"lint": "eslint .",
"format": "prettier --write \"**/*.{tsx,mjs,ts,md,json}\"",
"typecheck": "tsc --noEmit",
"with-env": "dotenv -e ../../.env -c --"
},
"dependencies": {
"@clerk/nextjs": "^4.29.7",
"@clickhouse/client": "^0.2.9",
"@hookform/resolvers": "^3.3.4",
"@openpanel/common": "workspace:^",
"@openpanel/constants": "workspace:^",
"@openpanel/db": "workspace:^",
"@openpanel/queue": "workspace:^",
"@openpanel/validation": "workspace:^",
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-aspect-ratio": "^1.0.3",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-progress": "^1.0.3",
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-toggle": "^1.0.3",
"@radix-ui/react-toggle-group": "^1.0.4",
"@radix-ui/react-tooltip": "^1.0.7",
"@reduxjs/toolkit": "^1.9.7",
"@t3-oss/env-nextjs": "^0.7.3",
"@tanstack/react-query": "^4.36.1",
"@tanstack/react-table": "^8.11.8",
"@trpc/client": "^10.45.1",
"@trpc/next": "^10.45.1",
"@trpc/react-query": "^10.45.1",
"@trpc/server": "^10.45.1",
"@types/d3": "^7.4.3",
"bcrypt": "^5.1.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"cmdk": "^0.2.1",
"d3": "^7.8.5",
"date-fns": "^3.3.1",
"embla-carousel-react": "8.0.0-rc22",
"flag-icons": "^7.1.0",
"hamburger-react": "^2.5.0",
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1",
"lottie-react": "^2.4.0",
"lucide-react": "^0.331.0",
"mathjs": "^12.3.2",
"mitt": "^3.0.1",
"next": "~14.0.4",
"next-auth": "^4.24.5",
"next-themes": "^0.2.1",
"nuqs": "^1.16.1",
"prisma-error-enum": "^0.1.3",
"ramda": "^0.29.1",
"random-animal-name": "^0.1.1",
"react": "18.2.0",
"react-animate-height": "^3.2.3",
"react-animated-numbers": "^0.18.0",
"react-day-picker": "^8.10.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.50.1",
"react-in-viewport": "1.0.0-alpha.30",
"react-redux": "^8.1.3",
"react-responsive": "^9.0.2",
"react-svg-worldmap": "2.0.0-alpha.16",
"react-syntax-highlighter": "^15.5.0",
"react-use-websocket": "^4.7.0",
"react-virtualized-auto-sizer": "^1.0.22",
"recharts": "^2.12.0",
"request-ip": "^3.3.0",
"short-unique-id": "^5.0.3",
"slugify": "^1.6.6",
"sonner": "^1.4.0",
"superjson": "^1.13.3",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7",
"usehooks-ts": "^2.14.0",
"zod": "^3.22.4"
},
"devDependencies": {
"@openpanel/eslint-config": "workspace:*",
"@openpanel/prettier-config": "workspace:*",
"@openpanel/tsconfig": "workspace:*",
"@types/bcrypt": "^5.0.2",
"@types/lodash.debounce": "^4.0.9",
"@types/lodash.throttle": "^4.1.9",
"@types/node": "^18.19.15",
"@types/ramda": "^0.29.10",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@types/react-syntax-highlighter": "^15.5.11",
"@types/request-ip": "^0.0.41",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"autoprefixer": "^10.4.17",
"eslint": "^8.56.0",
"postcss": "^8.4.35",
"prettier": "^3.2.5",
"prettier-plugin-tailwindcss": "^0.5.11",
"tailwindcss": "^3.4.1",
"typescript": "^5.3.3"
},
"ct3aMetadata": {
"initVersion": "7.21.0"
},
"eslintConfig": {
"root": true,
"extends": [
"@openpanel/eslint-config/base",
"@openpanel/eslint-config/react",
"@openpanel/eslint-config/nextjs"
]
},
"prettier": "@openpanel/prettier-config"
}

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

@@ -0,0 +1,15 @@
<svg width="824" height="824" viewBox="0 0 824 824" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="824" height="824" fill="#007BFF" fill-opacity="0.3"/>
<path d="M0 0L824 0V824H0L0 0Z" fill="url(#paint0_linear_0_131)"/>
<path d="M436 220H508C520.73 220 532.939 225.057 541.941 234.059C550.943 243.061 556 255.27 556 268V604" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M172 604H244" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M436 604H652" stroke="#BED2FF" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M364 412V412.24" stroke="white" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M436 233.488V621.256C435.999 624.902 435.168 628.499 433.569 631.775C431.97 635.052 429.646 637.92 426.772 640.164C423.899 642.408 420.553 643.968 416.987 644.726C413.421 645.483 409.729 645.418 406.192 644.536L244 604V257.488C244.002 246.784 247.581 236.388 254.169 227.952C260.757 219.516 269.976 213.524 280.36 210.928L376.36 186.928C383.434 185.16 390.818 185.026 397.951 186.538C405.084 188.05 411.779 191.167 417.528 195.652C423.277 200.138 427.928 205.874 431.129 212.426C434.329 218.978 435.995 226.196 436 233.488Z" stroke="white" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
<defs>
<linearGradient id="paint0_linear_0_131" x1="353" y1="93.0001" x2="528" y2="747.5" gradientUnits="userSpaceOnUse">
<stop stop-color="#2563EB"/>
<stop offset="1" stop-color="#1D54CD"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.0 KiB

View File

@@ -0,0 +1,5 @@
<svg width="278" height="278" viewBox="0 0 278 278" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="278" height="278" rx="20" fill="#2664EB"/>
<path d="M148.959 203H128.873C128.291 203 128 202.698 128 202.095L128.349 74.7242C128.349 74.2414 128.582 74 129.048 74H163.456C174.402 74 183.048 77.4702 189.394 84.4105C195.798 91.2905 199 100.675 199 112.564C199 121.255 197.341 128.829 194.022 135.286C190.645 141.684 186.279 146.632 180.923 150.133C175.566 153.633 169.744 155.383 163.456 155.383H149.833V202.095C149.833 202.698 149.542 203 148.959 203ZM163.456 95.9979L149.833 96.179V132.933H163.456C167.241 132.933 170.53 131.062 173.325 127.32C176.119 123.518 177.517 118.599 177.517 112.564C177.517 107.736 176.265 103.783 173.761 100.705C171.258 97.567 167.823 95.9979 163.456 95.9979Z" fill="white" fill-opacity="0.9"/>
<path d="M114.47 203C108.074 203 102.177 201.36 96.7791 198.079C91.4395 194.798 87.1267 190.434 83.8408 184.986C80.6136 179.479 79 173.445 79 166.884L79.176 109.853C79.176 103.174 80.7896 97.1696 84.0169 91.8386C87.1854 86.4489 91.4688 82.143 96.8671 78.921C102.265 75.6403 108.133 74 114.47 74C121.042 74 126.939 75.611 132.161 78.8331C137.442 82.0552 141.667 86.3903 144.835 91.8386C148.063 97.2282 149.676 103.233 149.676 109.853L149.852 166.884C149.852 173.445 148.268 179.45 145.099 184.898C141.872 190.405 137.589 194.798 132.249 198.079C126.91 201.36 120.983 203 114.47 203ZM114.47 181.295C118.108 181.295 121.277 179.83 123.976 176.901C126.675 173.913 128.025 170.574 128.025 166.884L127.848 109.853C127.848 105.869 126.587 102.501 124.064 99.7473C121.541 96.9939 118.343 95.6172 114.47 95.6172C110.774 95.6172 107.605 96.9646 104.965 99.6594C102.324 102.354 101.004 105.752 101.004 109.853V166.884C101.004 170.809 102.324 174.206 104.965 177.077C107.605 179.889 110.774 181.295 114.47 181.295Z" fill="white" fill-opacity="0.9"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -0,0 +1,252 @@
'use client';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { CheckboxInput } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAppParams } from '@/hooks/useAppParams';
import { clipboard } from '@/utils/clipboard';
import { zodResolver } from '@hookform/resolvers/zod';
import { Copy, SaveIcon } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import type { SubmitHandler } from 'react-hook-form';
import { Controller, useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { api, handleError } from '../../../_trpc/client';
const validation = z.object({
name: z.string().min(1),
domain: z.string().optional(),
withSecret: z.boolean().optional(),
});
type IForm = z.infer<typeof validation>;
export function CreateClient() {
const [open, setOpen] = useState(false);
const { organizationId, projectId } = useAppParams();
const clients = api.client.list.useQuery({
organizationId,
});
const clientsCount = clients.data?.length;
useEffect(() => {
if (clientsCount === 0) {
setOpen(true);
}
}, [clientsCount]);
const router = useRouter();
const form = useForm<IForm>({
resolver: zodResolver(validation),
defaultValues: {
withSecret: false,
name: '',
domain: '',
},
});
const mutation = api.client.create2.useMutation({
onError: handleError,
onSuccess() {
toast.success('Client created');
router.refresh();
},
});
const onSubmit: SubmitHandler<IForm> = (values) => {
mutation.mutate({
name: values.name,
domain: values.withSecret ? undefined : values.domain,
organizationId,
projectId,
});
};
const watch = useWatch({
control: form.control,
name: 'withSecret',
});
return (
<Dialog open={open}>
{mutation.isSuccess ? (
<>
<DialogContent
className="sm:max-w-[425px]"
onClose={() => setOpen(false)}
>
<DialogHeader>
<DialogTitle>Success</DialogTitle>
<DialogDescription>
{mutation.data.clientSecret
? 'Use your client id and secret with our SDK to send events to us. '
: 'Use your client id with our SDK to send events to us. '}
See our{' '}
<Link href="https//openpanel.dev/docs" className="underline">
documentation
</Link>
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<button
className="mt-4 text-left"
onClick={() => clipboard(mutation.data.clientId)}
>
<Label>Client ID</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.clientId}
<Copy size={16} />
</div>
</button>
{mutation.data.clientSecret ? (
<button
className="mt-4 text-left"
onClick={() => clipboard(mutation.data.clientId)}
>
<Label>Secret</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.clientSecret}
<Copy size={16} />
</div>
</button>
) : (
<div className="mt-4 text-left">
<Label>Cors settings</Label>
<div className="flex items-center justify-between rounded bg-gray-100 p-2 px-3">
{mutation.data.cors}
</div>
<div className="text-sm italic mt-1">
You can update cors settings{' '}
<Link className="underline" href="/qwe/qwe/">
here
</Link>
</div>
</div>
)}
</div>
<DialogFooter>
<Button
type="button"
variant={'secondary'}
onClick={() => setOpen(false)}
>
Close
</Button>
</DialogFooter>
</DialogContent>
</>
) : (
<>
<DialogContent
className="sm:max-w-[425px]"
onClose={() => setOpen(false)}
>
<DialogHeader>
<DialogTitle>Let's connect</DialogTitle>
<DialogDescription>
Create a client so you can start send events to us 🚀
</DialogDescription>
</DialogHeader>
<form
className="flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<div className="grid gap-4 py-4">
<div>
<Label>Client name</Label>
<Input
placeholder="Eg. My App Client"
error={form.formState.errors.name?.message}
{...form.register('name')}
/>
</div>
<Controller
name="withSecret"
control={form.control}
render={({ field }) => (
<CheckboxInput
defaultChecked={field.value}
onCheckedChange={(checked) => {
field.onChange(!checked);
}}
>
This is a website
</CheckboxInput>
)}
/>
<div>
<Label>Your domain name</Label>
<Input
placeholder="https://...."
error={form.formState.errors.domain?.message}
{...form.register('domain')}
disabled={watch}
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant={'secondary'}
onClick={() => setOpen(false)}
>
Cancel
</Button>
<Button
type="submit"
icon={SaveIcon}
loading={mutation.isLoading}
>
Create
</Button>
</DialogFooter>
</form>
</DialogContent>
</>
)}
</Dialog>
);
}
// <div>
// <div className="text-lg">
// Select your framework and we'll generate a client for you.
// </div>
// <div className="flex flex-wrap gap-2 mt-8">
// <FeatureButton
// name="React"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
// />
// <FeatureButton
// name="React Native"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
// />
// <FeatureButton
// name="Next.js"
// logo="https://static-00.iconduck.com/assets.00/nextjs-icon-512x512-y563b8iq.png"
// />
// <FeatureButton
// name="Remix"
// logo="https://www.datocms-assets.com/205/1642515307-square-logo.svg"
// />
// <FeatureButton
// name="Vue"
// logo="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0UhQnp6TUPCwAr3ruTEwBDiTN5HLAWaoUD3AJIgtepQ&s"
// />
// <FeatureButton
// name="HTML"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/240px-HTML5_logo_and_wordmark.svg.png"
// />
// </div>
// </div>

View File

@@ -0,0 +1,139 @@
'use client';
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { LazyChart } from '@/components/report/chart/LazyChart';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useAppParams } from '@/hooks/useAppParams';
import { cn } from '@/utils/cn';
import {
getDefaultIntervalByDates,
getDefaultIntervalByRange,
} from '@openpanel/constants';
import type { getReportsByDashboardId } from '@openpanel/db';
import { ChevronRight, MoreHorizontal, PlusIcon, Trash } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { OverviewReportRange } from '../../overview-sticky-header';
interface ListReportsProps {
reports: Awaited<ReturnType<typeof getReportsByDashboardId>>;
}
export function ListReports({ reports }: ListReportsProps) {
const router = useRouter();
const params = useAppParams<{ dashboardId: string }>();
const { range, startDate, endDate } = useOverviewOptions();
return (
<>
<StickyBelowHeader className="p-4 items-center justify-between flex">
<OverviewReportRange />
<Button
icon={PlusIcon}
onClick={() => {
router.push(
`/${params.organizationId}/${
params.projectId
}/reports?${new URLSearchParams({
dashboardId: params.dashboardId,
}).toString()}`
);
}}
>
<span className="max-sm:hidden">Create report</span>
<span className="sm:hidden">Report</span>
</Button>
</StickyBelowHeader>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4">
{reports.map((report) => {
const chartRange = report.range; // timeRanges[report.range];
return (
<div className="card" key={report.id}>
<Link
href={`/${params.organizationId}/${params.projectId}/reports/${report.id}`}
className="flex border-b border-border p-4 leading-none [&_svg]:hover:opacity-100 items-center justify-between"
shallow
>
<div>
<div className="font-medium">{report.name}</div>
{chartRange !== null && (
<div className="mt-2 text-sm flex gap-2">
<span
className={
range !== null || (startDate && endDate)
? 'line-through'
: ''
}
>
{chartRange}
</span>
{startDate && endDate ? (
<span>Custom dates</span>
) : (
range !== null && <span>{range}</span>
)}
</div>
)}
</div>
<div className="flex items-center gap-4">
<DropdownMenu>
<DropdownMenuTrigger className="h-8 w-8 hover:border rounded justify-center items-center flex">
<MoreHorizontal size={16} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[200px]">
<DropdownMenuGroup>
<DropdownMenuItem
className="text-destructive"
onClick={(event) => {
// event.stopPropagation();
// deletion.mutate({
// reportId: report.id,
// });
}}
>
<Trash size={16} className="mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
<ChevronRight
className="opacity-10 transition-opacity"
size={16}
/>
</div>
</Link>
<div
className={cn(
'p-4',
report.chartType === 'bar' && 'overflow-auto max-h-[300px]'
)}
>
<LazyChart
{...report}
range={range ?? report.range}
startDate={startDate}
endDate={endDate}
interval={
getDefaultIntervalByDates(startDate, endDate) ||
(range ? getDefaultIntervalByRange(range) : report.interval)
}
editMode={false}
/>
</div>
</div>
);
})}
</div>
</>
);
}

View File

@@ -0,0 +1,34 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getDashboardById, getReportsByDashboardId } from '@openpanel/db';
import { notFound } from 'next/navigation';
import { ListReports } from './list-reports';
interface PageProps {
params: {
organizationId: string;
projectId: string;
dashboardId: string;
};
}
export default async function Page({
params: { organizationId, projectId, dashboardId },
}: PageProps) {
const [dashboard, reports] = await Promise.all([
getDashboardById(dashboardId, projectId),
getReportsByDashboardId(dashboardId),
getExists(organizationId),
]);
if (!dashboard) {
return notFound();
}
return (
<PageLayout title={dashboard.name} organizationSlug={organizationId}>
<ListReports reports={reports} />
</PageLayout>
);
}

View File

@@ -0,0 +1,26 @@
'use client';
import { Button } from '@/components/ui/button';
import { pushModal } from '@/modals';
import { PlusIcon } from 'lucide-react';
import { StickyBelowHeader } from '../layout-sticky-below-header';
export function HeaderDashboards() {
return (
<StickyBelowHeader>
<div className="p-4 flex justify-between items-center">
<div />
<Button
icon={PlusIcon}
onClick={() => {
pushModal('AddDashboard');
}}
>
<span className="max-sm:hidden">Create dashboard</span>
<span className="sm:hidden">Dashboard</span>
</Button>
</div>
</StickyBelowHeader>
);
}

View File

@@ -0,0 +1,104 @@
'use client';
import { api, handleErrorToastOptions } from '@/app/_trpc/client';
import { Card, CardActions, CardActionsItem } from '@/components/Card';
import { FullPageEmptyState } from '@/components/FullPageEmptyState';
import { Button } from '@/components/ui/button';
import { ToastAction } from '@/components/ui/toast';
import { useAppParams } from '@/hooks/useAppParams';
import { pushModal } from '@/modals';
import type { IServiceDashboards } from '@openpanel/db';
import { LayoutPanelTopIcon, Pencil, PlusIcon, Trash } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
interface ListDashboardsProps {
dashboards: IServiceDashboards;
}
export function ListDashboards({ dashboards }: ListDashboardsProps) {
const router = useRouter();
const params = useAppParams();
const { organizationId, projectId } = params;
const deletion = api.dashboard.delete.useMutation({
onError: (error, variables) => {
return handleErrorToastOptions({
action: {
label: 'Force delete',
onClick: () => {
deletion.mutate({
forceDelete: true,
id: variables.id,
});
},
},
})(error);
},
onSuccess() {
router.refresh();
toast('Success', {
description: 'Dashboard deleted.',
});
},
});
if (dashboards.length === 0) {
return (
<FullPageEmptyState title="No dashboards" icon={LayoutPanelTopIcon}>
<p>You have not created any dashboards for this project yet</p>
<Button
onClick={() => pushModal('AddDashboard')}
className="mt-14"
icon={PlusIcon}
>
Create dashboard
</Button>
</FullPageEmptyState>
);
}
return (
<>
<div className="grid sm:grid-cols-2 gap-4 p-4">
{dashboards.map((item) => (
<Card key={item.id} hover>
<div>
<Link
href={`/${organizationId}/${projectId}/dashboards/${item.id}`}
className="block p-4 flex flex-col"
>
<span className="font-medium">{item.name}</span>
</Link>
</div>
<CardActions>
<CardActionsItem className="w-full" asChild>
<button
onClick={() => {
pushModal('EditDashboard', item);
}}
>
<Pencil size={16} />
Edit
</button>
</CardActionsItem>
<CardActionsItem className="text-destructive w-full" asChild>
<button
onClick={() => {
deletion.mutate({
id: item.id,
});
}}
>
<Trash size={16} />
Delete
</button>
</CardActionsItem>
</CardActions>
</Card>
))}
</div>
</>
);
}

View File

@@ -0,0 +1,29 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getDashboardsByProjectId } from '@openpanel/db';
import { HeaderDashboards } from './header-dashboards';
import { ListDashboards } from './list-dashboards';
interface PageProps {
params: {
projectId: string;
organizationId: string;
};
}
export default async function Page({
params: { projectId, organizationId },
}: PageProps) {
const [dashboards] = await Promise.all([
getDashboardsByProjectId(projectId),
await getExists(organizationId, projectId),
]);
return (
<PageLayout title="Dashboards" organizationSlug={organizationId}>
{dashboards.length > 0 && <HeaderDashboards />}
<ListDashboards dashboards={dashboards} />
</PageLayout>
);
}

View File

@@ -0,0 +1,41 @@
import { ChartSwitchShortcut } from '@/components/report/chart';
import type { IChartEvent } from '@openpanel/validation';
interface Props {
projectId: string;
events?: string[];
filters?: any[];
}
export function EventChart({ projectId, filters, events }: Props) {
const fallback: IChartEvent[] = [
{
id: 'A',
name: '*',
displayName: 'All events',
segment: 'event',
filters: filters ?? [],
},
];
return (
<div className="card p-4 mb-8">
<ChartSwitchShortcut
projectId={projectId}
range="1m"
chartType="histogram"
events={
events && events.length > 0
? events.map((name) => ({
id: name,
name,
displayName: name,
segment: 'event',
filters: filters ?? [],
}))
: fallback
}
/>
</div>
);
}

View File

@@ -0,0 +1,217 @@
'use client';
import type { Dispatch, SetStateAction } from 'react';
import { ChartSwitchShortcut } from '@/components/report/chart';
import { KeyValue } from '@/components/ui/key-value';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import {
useEventQueryFilters,
useEventQueryNamesFilter,
} from '@/hooks/useEventQueryFilters';
import type { IServiceCreateEventPayload } from '@openpanel/db';
import { round } from 'mathjs';
interface Props {
event: IServiceCreateEventPayload;
open: boolean;
setOpen: Dispatch<SetStateAction<boolean>>;
}
export function EventDetails({ event, open, setOpen }: Props) {
const { name } = event;
const [, setFilter] = useEventQueryFilters({ shallow: false });
const [, setEvents] = useEventQueryNamesFilter({ shallow: false });
const common = [
{
name: 'Duration',
value: event.duration ? round(event.duration / 1000, 1) : undefined,
},
{
name: 'Referrer',
value: event.referrer,
onClick() {
setFilter('referrer', event.referrer ?? '');
},
},
{
name: 'Referrer name',
value: event.referrerName,
onClick() {
setFilter('referrer_name', event.referrerName ?? '');
},
},
{
name: 'Referrer type',
value: event.referrerType,
onClick() {
setFilter('referrer_type', event.referrerType ?? '');
},
},
{
name: 'Brand',
value: event.brand,
onClick() {
setFilter('brand', event.brand ?? '');
},
},
{
name: 'Model',
value: event.model,
onClick() {
setFilter('model', event.model ?? '');
},
},
{
name: 'Browser',
value: event.browser,
onClick() {
setFilter('browser', event.browser ?? '');
},
},
{
name: 'Browser version',
value: event.browserVersion,
onClick() {
setFilter('browser_version', event.browserVersion ?? '');
},
},
{
name: 'OS',
value: event.os,
onClick() {
setFilter('os', event.os ?? '');
},
},
{
name: 'OS version',
value: event.osVersion,
onClick() {
setFilter('os_version', event.osVersion ?? '');
},
},
{
name: 'City',
value: event.city,
onClick() {
setFilter('city', event.city ?? '');
},
},
{
name: 'Region',
value: event.region,
onClick() {
setFilter('region', event.region ?? '');
},
},
{
name: 'Country',
value: event.country,
onClick() {
setFilter('country', event.country ?? '');
},
},
{
name: 'Continent',
value: event.continent,
onClick() {
setFilter('continent', event.continent ?? '');
},
},
{
name: 'Device',
value: event.device,
onClick() {
setFilter('device', event.device ?? '');
},
},
].filter((item) => typeof item.value === 'string' && item.value);
const properties = Object.entries(event.properties)
.map(([name, value]) => ({
name,
value: value as string | number | undefined,
}))
.filter((item) => typeof item.value === 'string' && item.value);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent>
<div>
<div className="flex flex-col gap-8">
<SheetHeader>
<SheetTitle>{name.replace('_', ' ')}</SheetTitle>
</SheetHeader>
{properties.length > 0 && (
<div>
<div className="text-sm font-medium mb-2">Params</div>
<div className="flex gap-2 flex-wrap">
{properties.map((item) => (
<KeyValue
key={item.name}
name={item.name}
value={item.value}
onClick={() => {
setFilter(
`properties.${item.name}`,
item.value ? String(item.value) : '',
'is'
);
}}
/>
))}
</div>
</div>
)}
<div>
<div className="text-sm font-medium mb-2">Common</div>
<div className="flex gap-2 flex-wrap">
{common.map((item) => (
<KeyValue
key={item.name}
name={item.name}
value={item.value}
onClick={item.onClick}
/>
))}
</div>
</div>
<div>
<div className="flex justify-between text-sm font-medium mb-2">
<div>Similar events</div>
<button
className="hover:underline text-muted-foreground"
onClick={() => {
setEvents([event.name]);
setOpen(false);
}}
>
Show all
</button>
</div>
<ChartSwitchShortcut
projectId={event.projectId}
chartType="histogram"
events={[
{
id: 'A',
name: event.name,
displayName: 'Similar events',
segment: 'event',
filters: [],
},
]}
/>
</div>
</div>
</div>
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,176 @@
import type { Dispatch, SetStateAction } from 'react';
import { useEffect, useState } from 'react';
import { api } from '@/app/_trpc/client';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { cn } from '@/utils/cn';
import type { IServiceCreateEventPayload } from '@openpanel/db';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import {
EventIconColors,
EventIconMapper,
EventIconRecords,
} from './event-icon';
interface Props {
event: IServiceCreateEventPayload;
open: boolean;
setOpen: Dispatch<SetStateAction<boolean>>;
}
export function EventEdit({ event, open, setOpen }: Props) {
const router = useRouter();
const { name, meta, projectId } = event;
const [selectedIcon, setIcon] = useState(
meta?.icon ??
EventIconRecords[name]?.icon ??
EventIconRecords.default?.icon ??
''
);
const [selectedColor, setColor] = useState(
meta?.color ??
EventIconRecords[name]?.color ??
EventIconRecords.default?.color ??
''
);
const [conversion, setConversion] = useState(!!meta?.conversion);
useEffect(() => {
if (meta?.icon) {
setIcon(meta.icon);
}
}, [meta?.icon]);
useEffect(() => {
if (meta?.color) {
setColor(meta.color);
}
}, [meta?.color]);
useEffect(() => {
setConversion(meta?.conversion ?? false);
}, [meta?.conversion]);
const SelectedIcon = EventIconMapper[selectedIcon]!;
const mutation = api.event.updateEventMeta.useMutation({
onSuccess() {
// @ts-expect-error
document.querySelector('#close-sheet')?.click();
toast('Event updated');
router.refresh();
},
});
const getBg = (color: string) => `bg-${color}-200`;
const getText = (color: string) => `text-${color}-700`;
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent>
<SheetHeader>
<SheetTitle>Edit "{name}"</SheetTitle>
</SheetHeader>
<div className="flex flex-col gap-8 my-8">
<div>
<Label className="mb-4 block">Conversion</Label>
<label className="cursor-pointer flex items-center select-none border border-border rounded-md p-4 gap-4">
<Checkbox
checked={conversion}
onCheckedChange={(checked) => {
if (checked === 'indeterminate') return;
setConversion(checked);
}}
/>
<div>
<span>Yes, this event is important!</span>
</div>
</label>
</div>
<div>
<Label className="mb-4 block">Pick a icon</Label>
<div className="flex flex-wrap gap-4">
{Object.entries(EventIconMapper).map(([name, Icon]) => (
<button
key={name}
onClick={() => {
setIcon(name);
}}
className={cn(
'flex-shrink-0 rounded-md w-8 h-8 cursor-pointer inline-flex transition-all bg-slate-100 flex items-center justify-center',
name === selectedIcon
? 'scale-110 ring-1 ring-black'
: '[&_svg]:opacity-50'
)}
>
<Icon size={16} />
</button>
))}
</div>
</div>
<div>
<Label className="mb-4 block">Pick a color</Label>
<div className="flex flex-wrap gap-4">
{EventIconColors.map((color) => (
<button
key={color}
onClick={() => {
setColor(color);
}}
className={cn(
'flex-shrink-0 rounded-md w-8 h-8 cursor-pointer transition-all flex justify-center items-center',
color === selectedColor ? 'ring-1 ring-black' : '',
getBg(color)
)}
>
{SelectedIcon ? (
<SelectedIcon size={16} />
) : (
<svg
className={`${getText(color)} opacity-70`}
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="currentColor"
stroke="currentColor"
stroke-width="2"
>
<circle cx="12.1" cy="12.1" r="4" />
</svg>
)}
</button>
))}
</div>
</div>
</div>
<SheetFooter>
<Button
className="w-full"
onClick={() =>
mutation.mutate({
projectId,
name,
icon: selectedIcon,
color: selectedColor,
conversion,
})
}
>
Update event
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,160 @@
import { useEffect, useState } from 'react';
import { api } from '@/app/_trpc/client';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet';
import { cn } from '@/utils/cn';
import type { EventMeta } from '@openpanel/db';
import type { VariantProps } from 'class-variance-authority';
import { cva } from 'class-variance-authority';
import type { LucideIcon } from 'lucide-react';
import * as Icons from 'lucide-react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
const variants = cva('flex items-center justify-center shrink-0 rounded-full', {
variants: {
size: {
sm: 'w-6 h-6',
default: 'w-10 h-10',
},
},
defaultVariants: {
size: 'default',
},
});
type EventIconProps = VariantProps<typeof variants> & {
name: string;
meta?: EventMeta;
projectId: string;
className?: string;
};
export const EventIconRecords: Record<
string,
{
icon: string;
color: string;
}
> = {
default: {
icon: 'BotIcon',
color: 'slate',
},
screen_view: {
icon: 'MonitorPlayIcon',
color: 'blue',
},
session_start: {
icon: 'ActivityIcon',
color: 'teal',
},
link_out: {
icon: 'ExternalLinkIcon',
color: 'indigo',
},
};
export const EventIconMapper: Record<string, LucideIcon> = {
DownloadIcon: Icons.DownloadIcon,
BotIcon: Icons.BotIcon,
BoxIcon: Icons.BoxIcon,
AccessibilityIcon: Icons.AccessibilityIcon,
ActivityIcon: Icons.ActivityIcon,
AirplayIcon: Icons.AirplayIcon,
AlarmCheckIcon: Icons.AlarmCheckIcon,
AlertTriangleIcon: Icons.AlertTriangleIcon,
BellIcon: Icons.BellIcon,
BoltIcon: Icons.BoltIcon,
CandyIcon: Icons.CandyIcon,
ConeIcon: Icons.ConeIcon,
MonitorPlayIcon: Icons.MonitorPlayIcon,
PizzaIcon: Icons.PizzaIcon,
SearchIcon: Icons.SearchIcon,
HomeIcon: Icons.HomeIcon,
MailIcon: Icons.MailIcon,
AngryIcon: Icons.AngryIcon,
AnnoyedIcon: Icons.AnnoyedIcon,
ArchiveIcon: Icons.ArchiveIcon,
AwardIcon: Icons.AwardIcon,
BadgeCheckIcon: Icons.BadgeCheckIcon,
BeerIcon: Icons.BeerIcon,
BluetoothIcon: Icons.BluetoothIcon,
BookIcon: Icons.BookIcon,
BookmarkIcon: Icons.BookmarkIcon,
BookCheckIcon: Icons.BookCheckIcon,
BookMinusIcon: Icons.BookMinusIcon,
BookPlusIcon: Icons.BookPlusIcon,
CalendarIcon: Icons.CalendarIcon,
ClockIcon: Icons.ClockIcon,
CogIcon: Icons.CogIcon,
LoaderIcon: Icons.LoaderIcon,
CrownIcon: Icons.CrownIcon,
FileIcon: Icons.FileIcon,
KeyRoundIcon: Icons.KeyRoundIcon,
GemIcon: Icons.GemIcon,
GlobeIcon: Icons.GlobeIcon,
LightbulbIcon: Icons.LightbulbIcon,
LightbulbOffIcon: Icons.LightbulbOffIcon,
LockIcon: Icons.LockIcon,
MessageCircleIcon: Icons.MessageCircleIcon,
RadioIcon: Icons.RadioIcon,
RepeatIcon: Icons.RepeatIcon,
ShareIcon: Icons.ShareIcon,
ExternalLinkIcon: Icons.ExternalLinkIcon,
};
export const EventIconColors = [
'rose',
'pink',
'fuchsia',
'purple',
'violet',
'indigo',
'blue',
'sky',
'cyan',
'teal',
'emerald',
'green',
'lime',
'yellow',
'amber',
'orange',
'red',
'stone',
'neutral',
'zinc',
'grey',
'slate',
];
export function EventIcon({ className, name, size, meta }: EventIconProps) {
const Icon =
EventIconMapper[
meta?.icon ??
EventIconRecords[name]?.icon ??
EventIconRecords.default?.icon ??
''
]!;
const color =
meta?.color ??
EventIconRecords[name]?.color ??
EventIconRecords.default?.color ??
'';
return (
<div className={cn(`bg-${color}-200`, variants({ size }), className)}>
<Icon size={20} className={`text-${color}-700`} />
</div>
);
}

View File

@@ -0,0 +1,132 @@
'use client';
import { useState } from 'react';
import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
import { SerieIcon } from '@/components/report/chart/SerieIcon';
import { KeyValueSubtle } from '@/components/ui/key-value';
import { useAppParams } from '@/hooks/useAppParams';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import { useNumber } from '@/hooks/useNumerFormatter';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
import type { IServiceCreateEventPayload } from '@openpanel/db';
import { EventDetails } from './event-details';
import { EventEdit } from './event-edit';
import { EventIcon } from './event-icon';
type EventListItemProps = IServiceCreateEventPayload;
export function EventListItem(props: EventListItemProps) {
const {
profile,
createdAt,
name,
path,
duration,
brand,
browser,
city,
country,
device,
os,
projectId,
meta,
} = props;
const params = useAppParams();
const [, setFilter] = useEventQueryFilters({ shallow: false });
const [isDetailsOpen, setIsDetailsOpen] = useState(false);
const [isEditOpen, setIsEditOpen] = useState(false);
const number = useNumber();
return (
<>
<EventDetails
event={props}
open={isDetailsOpen}
setOpen={setIsDetailsOpen}
/>
<EventEdit event={props} open={isEditOpen} setOpen={setIsEditOpen} />
<div
className={cn(
'p-4 flex flex-col gap-2 hover:bg-slate-50 rounded-lg transition-colors',
meta?.conversion && `bg-${meta.color}-50 hover:bg-${meta.color}-100`
)}
>
<div className="flex justify-between items-center">
<div className="flex gap-4 items-center">
<button onClick={() => setIsEditOpen(true)}>
<EventIcon name={name} meta={meta} projectId={projectId} />
</button>
<button
onClick={() => setIsDetailsOpen(true)}
className="text-left font-semibold hover:underline"
>
{name.replace(/_/g, ' ')}
</button>
</div>
<div className="text-muted-foreground text-sm">
{createdAt.toLocaleTimeString()}
</div>
</div>
<div className="flex flex-wrap gap-2">
{path && (
<KeyValueSubtle
name={'Path'}
value={
path +
(duration
? ` (${number.shortWithUnit(duration / 1000, 'min')})`
: '')
}
/>
)}
{profile && (
<KeyValueSubtle
name={'Profile'}
value={
<>
{profile.avatar && <ProfileAvatar size="xs" {...profile} />}
{getProfileName(profile)}
</>
}
href={`/${params.organizationId}/${params.projectId}/profiles/${profile.id}`}
/>
)}
<KeyValueSubtle
name={'From'}
onClick={() => setFilter('city', city)}
value={
<>
{country && <SerieIcon name={country} />}
{city}
</>
}
/>
<KeyValueSubtle
name={'Device'}
onClick={() => setFilter('device', device)}
value={
<>
{device && <SerieIcon name={device} />}
{brand || os}
</>
}
/>
{browser !== 'WebKit' && browser !== '' && (
<KeyValueSubtle
name={'Browser'}
onClick={() => setFilter('browser', browser)}
value={
<>
{browser && <SerieIcon name={browser} />}
{browser}
</>
}
/>
)}
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,89 @@
'use client';
import { Fragment, Suspense } from 'react';
import { FullPageEmptyState } from '@/components/FullPageEmptyState';
import { Pagination } from '@/components/Pagination';
import { ChartSwitch, ChartSwitchShortcut } from '@/components/report/chart';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { useCursor } from '@/hooks/useCursor';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import type { IServiceCreateEventPayload } from '@openpanel/db';
import { isSameDay } from 'date-fns';
import { GanttChartIcon } from 'lucide-react';
import { EventListItem } from './event-list-item';
import EventListener from './event-listener';
function showDateHeader(a: Date, b?: Date) {
if (!b) return true;
return !isSameDay(a, b);
}
interface EventListProps {
data: IServiceCreateEventPayload[];
count: number;
}
export function EventList({ data, count }: EventListProps) {
const { cursor, setCursor } = useCursor();
const [filters] = useEventQueryFilters();
return (
<>
{data.length === 0 ? (
<FullPageEmptyState title="No events here" icon={GanttChartIcon}>
{cursor !== 0 ? (
<>
<p>Looks like you have reached the end of the list</p>
<Button
className="mt-4"
variant="outline"
size="sm"
onClick={() => setCursor((p) => Math.max(0, p - 1))}
>
Go back
</Button>
</>
) : (
<>
{filters.length ? (
<p>Could not find any events with your filter</p>
) : (
<p>We have not recieved any events yet</p>
)}
</>
)}
</FullPageEmptyState>
) : (
<>
<div className="flex flex-col md:flex-row justify-between gap-2">
<EventListener />
<Pagination
cursor={cursor}
setCursor={setCursor}
count={count}
take={50}
/>
</div>
<div className="flex flex-col my-4 card p-4 gap-0.5">
{data.map((item, index, list) => (
<Fragment key={item.id}>
{showDateHeader(item.createdAt, list[index - 1]?.createdAt) && (
<div className="text-muted-foreground font-medium text-sm [&:not(:first-child)]:mt-12 text-center">
{item.createdAt.toLocaleDateString()}
</div>
)}
<EventListItem {...item} />
</Fragment>
))}
</div>
<Pagination
cursor={cursor}
setCursor={setCursor}
count={count}
take={50}
/>
</>
)}
</>
);
}

View File

@@ -0,0 +1,91 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { useAppParams } from '@/hooks/useAppParams';
import { cn } from '@/utils/cn';
import type { IServiceCreateEventPayload } from '@openpanel/db';
import { useQueryClient } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import useWebSocket from 'react-use-websocket';
import { toast } from 'sonner';
const AnimatedNumbers = dynamic(() => import('react-animated-numbers'), {
ssr: false,
loading: () => <div>0</div>,
});
export default function EventListener() {
const router = useRouter();
const { projectId } = useAppParams();
const ws = String(process.env.NEXT_PUBLIC_API_URL)
.replace(/^https/, 'wss')
.replace(/^http/, 'ws');
const [counter, setCounter] = useState(0);
const [socketUrl] = useState(`${ws}/live/events/${projectId}`);
useWebSocket(socketUrl, {
shouldReconnect: () => true,
onMessage(payload) {
const event = JSON.parse(payload.data) as IServiceCreateEventPayload;
if (event?.name) {
setCounter((prev) => prev + 1);
toast(`New event ${event.name} from ${event.country}!`);
}
},
});
return (
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={() => {
setCounter(0);
router.refresh();
}}
className="bg-white border border-border rounded h-8 px-3 leading-none flex items-center text-sm font-medium gap-2"
>
<div className="relative">
<div
className={cn(
'bg-emerald-500 h-3 w-3 rounded-full animate-ping opacity-100 transition-all'
)}
></div>
<div
className={cn(
'bg-emerald-500 h-3 w-3 rounded-full absolute top-0 left-0 transition-all'
)}
></div>
</div>
{counter === 0 ? (
'Listening to events'
) : (
<>
<AnimatedNumbers
includeComma
transitions={(index) => ({
type: 'spring',
duration: index + 0.3,
damping: 10,
stiffness: 200,
})}
animateToNumber={counter}
locale="en"
/>
new events
</>
)}
</button>
</TooltipTrigger>
<TooltipContent side="bottom">
{counter === 0 ? 'Listening to new events' : 'Click to refresh'}
</TooltipContent>
</Tooltip>
);
}

View File

@@ -0,0 +1,82 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons';
import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer';
import {
eventQueryFiltersParser,
eventQueryNamesFilter,
} from '@/hooks/useEventQueryFilters';
import { getExists } from '@/server/pageExists';
import { getEventList, getEventsCount } from '@openpanel/db';
import { parseAsInteger } from 'nuqs';
import { StickyBelowHeader } from '../layout-sticky-below-header';
import { EventChart } from './event-chart';
import { EventList } from './event-list';
interface PageProps {
params: {
projectId: string;
organizationId: string;
};
searchParams: {
events?: string;
cursor?: string;
f?: string;
};
}
const nuqsOptions = {
shallow: false,
};
export default async function Page({
params: { projectId, organizationId },
searchParams,
}: PageProps) {
const filters =
eventQueryFiltersParser.parseServerSide(searchParams.f ?? '') ?? undefined;
const eventsFilter = eventQueryNamesFilter.parseServerSide(
searchParams.events ?? ''
);
const [events, count] = await Promise.all([
getEventList({
cursor:
parseAsInteger.parseServerSide(searchParams.cursor ?? '') ?? undefined,
projectId,
take: 50,
events: eventsFilter,
filters,
}),
getEventsCount({
projectId,
events: eventsFilter,
filters,
}),
getExists(organizationId, projectId),
]);
return (
<PageLayout title="Events" organizationSlug={organizationId}>
<StickyBelowHeader className="p-4 flex justify-between">
<OverviewFiltersDrawer
mode="events"
projectId={projectId}
nuqsOptions={nuqsOptions}
enableEventsFilter
/>
<OverviewFiltersButtons
className="p-0 justify-end"
nuqsOptions={nuqsOptions}
/>
</StickyBelowHeader>
<div className="p-4">
<EventChart
projectId={projectId}
events={eventsFilter}
filters={filters}
/>
<EventList data={events} count={count} />
</div>
</PageLayout>
);
}

View File

@@ -0,0 +1,160 @@
'use client';
import { useEffect } from 'react';
import { useAppParams } from '@/hooks/useAppParams';
import { cn } from '@/utils/cn';
import { useUser } from '@clerk/nextjs';
import type { IServiceDashboards } from '@openpanel/db';
import {
BuildingIcon,
CogIcon,
DotIcon,
GanttChartIcon,
KeySquareIcon,
LayoutPanelTopIcon,
UserIcon,
UsersIcon,
WallpaperIcon,
WarehouseIcon,
} from 'lucide-react';
import type { LucideProps } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
function LinkWithIcon({
href,
icon: Icon,
label,
active: overrideActive,
className,
}: {
href: string;
icon: React.ElementType<LucideProps>;
label: React.ReactNode;
active?: boolean;
className?: string;
}) {
const pathname = usePathname();
const active = overrideActive || href === pathname;
return (
<Link
className={cn(
'text-slate-800 text-sm font-medium flex gap-2 items-center px-3 py-2 transition-colors hover:bg-blue-100 leading-none rounded-md transition-all',
active && 'bg-blue-50',
className
)}
href={href}
>
<Icon size={20} />
<div className="flex-1">{label}</div>
</Link>
);
}
interface LayoutMenuProps {
dashboards: IServiceDashboards;
}
export default function LayoutMenu({ dashboards }: LayoutMenuProps) {
const { user } = useUser();
const pathname = usePathname();
const params = useAppParams();
const hasProjectId =
params.projectId &&
params.projectId !== 'null' &&
params.projectId !== 'undefined';
const projectId = hasProjectId
? params.projectId
: (user?.unsafeMetadata.projectId as string);
useEffect(() => {
if (hasProjectId) {
user?.update({
unsafeMetadata: {
projectId: params.projectId,
},
});
}
}, [params.projectId, hasProjectId]);
return (
<>
<LinkWithIcon
icon={WallpaperIcon}
label="Overview"
href={`/${params.organizationId}/${projectId}`}
/>
<LinkWithIcon
icon={LayoutPanelTopIcon}
label="Dashboards"
href={`/${params.organizationId}/${projectId}/dashboards`}
/>
<LinkWithIcon
icon={GanttChartIcon}
label="Events"
href={`/${params.organizationId}/${projectId}/events`}
/>
<LinkWithIcon
icon={UsersIcon}
label="Profiles"
href={`/${params.organizationId}/${projectId}/profiles`}
/>
<LinkWithIcon
icon={CogIcon}
label="Settings"
href={`/${params.organizationId}/${projectId}/settings/organization`}
/>
{pathname?.includes('/settings/') && (
<div className="pl-7 flex flex-col gap-1">
<LinkWithIcon
icon={BuildingIcon}
label="Organization"
href={`/${params.organizationId}/${projectId}/settings/organization`}
/>
<LinkWithIcon
icon={WarehouseIcon}
label="Projects"
href={`/${params.organizationId}/${projectId}/settings/projects`}
/>
<LinkWithIcon
icon={KeySquareIcon}
label="Clients"
href={`/${params.organizationId}/${projectId}/settings/clients`}
/>
<LinkWithIcon
icon={UserIcon}
label="Profile (yours)"
href={`/${params.organizationId}/${projectId}/settings/profile`}
/>
<LinkWithIcon
icon={UserIcon}
label="References"
href={`/${params.organizationId}/${projectId}/settings/references`}
/>
</div>
)}
{dashboards.length > 0 && (
<div className="mt-8">
<div className="font-medium mb-2 text-sm">Your dashboards</div>
<div className="flex flex-col gap-2">
{dashboards.map((item) => (
<LinkWithIcon
key={item.id}
icon={LayoutPanelTopIcon}
label={
<div className="flex justify-between gap-0.5 items-center">
<span>{item.name}</span>
<span className="text-xs text-muted-foreground">
{item.project.name}
</span>
</div>
}
href={`/${item.organization_slug}/${item.project_id}/dashboards/${item.id}`}
/>
))}
</div>
</div>
)}
</>
);
}

View File

@@ -0,0 +1,46 @@
'use client';
import { Combobox } from '@/components/ui/combobox';
import { useAppParams } from '@/hooks/useAppParams';
import type { IServiceOrganization } from '@openpanel/db';
import { Building } from 'lucide-react';
import { useRouter } from 'next/navigation';
interface LayoutOrganizationSelectorProps {
organizations: IServiceOrganization[];
}
export default function LayoutOrganizationSelector({
organizations,
}: LayoutOrganizationSelectorProps) {
const params = useAppParams();
const router = useRouter();
const organization = organizations.find(
(item) => item.slug === params.organizationId
);
if (!organization) {
return null;
}
return (
<Combobox
className="w-full"
placeholder="Select organization"
icon={Building}
value={organization.slug}
items={
organizations
.filter((item) => item.slug)
.map((item) => ({
label: item.name,
value: item.slug!,
})) ?? []
}
onChange={(value) => {
router.push(`/${value}`);
}}
/>
);
}

View File

@@ -0,0 +1,44 @@
'use client';
import { Combobox } from '@/components/ui/combobox';
import { useAppParams } from '@/hooks/useAppParams';
import type { getProjectsByOrganizationSlug } from '@openpanel/db';
import { usePathname, useRouter } from 'next/navigation';
interface LayoutProjectSelectorProps {
projects: Awaited<ReturnType<typeof getProjectsByOrganizationSlug>>;
}
export default function LayoutProjectSelector({
projects,
}: LayoutProjectSelectorProps) {
const router = useRouter();
const { organizationId, projectId } = useAppParams();
const pathname = usePathname() || '';
return (
<div>
<Combobox
portal
align="end"
className="w-auto min-w-0 max-sm:max-w-[100px]"
placeholder={'Select project'}
onChange={(value) => {
if (organizationId && projectId) {
const split = pathname.replace(projectId, value).split('/');
// slicing here will remove everything after /{orgId}/{projectId}/dashboards [slice here] /xxx/xxx/xxx
router.push(split.slice(0, 4).join('/'));
} else {
router.push(`/${organizationId}/${value}`);
}
}}
value={projectId}
items={
projects.map((item) => ({
label: item.name,
value: item.id,
})) ?? []
}
/>
</div>
);
}

View File

@@ -0,0 +1,82 @@
'use client';
import { useEffect, useState } from 'react';
import { Logo } from '@/components/Logo';
import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/utils/cn';
import type { IServiceDashboards, IServiceOrganization } from '@openpanel/db';
import { Rotate as Hamburger } from 'hamburger-react';
import { PlusIcon } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import LayoutMenu from './layout-menu';
import LayoutOrganizationSelector from './layout-organization-selector';
interface LayoutSidebarProps {
organizations: IServiceOrganization[];
dashboards: IServiceDashboards;
organizationId: string;
projectId: string;
}
export function LayoutSidebar({
organizations,
dashboards,
organizationId,
projectId,
}: LayoutSidebarProps) {
const [active, setActive] = useState(false);
const pathname = usePathname();
useEffect(() => {
setActive(false);
}, [pathname]);
return (
<>
<button
onClick={() => setActive(false)}
className={cn(
'fixed top-0 left-0 right-0 bottom-0 backdrop-blur-sm z-30 transition-opacity',
active
? 'opacity-100 pointer-events-auto'
: 'opacity-0 pointer-events-none'
)}
/>
<div
className={cn(
'fixed top-0 left-0 h-screen border-r border-border w-72 bg-white flex flex-col z-30 transition-transform',
'-translate-x-72 lg:-translate-x-0', // responsive
active && 'translate-x-0' // force active on mobile
)}
>
<div className="absolute -right-12 h-16 flex items-center lg:hidden">
<Hamburger toggled={active} onToggle={setActive} size={20} />
</div>
<div className="h-16 border-b border-border px-4 shrink-0 flex items-center">
<Link href="/">
<Logo />
</Link>
</div>
<div className="flex flex-col p-4 gap-2 flex-grow overflow-auto">
<LayoutMenu dashboards={dashboards} />
{/* Placeholder for LayoutOrganizationSelector */}
<div className="h-32 block shrink-0"></div>
</div>
<div className="fixed bottom-0 left-0 right-0">
<div className="bg-gradient-to-t from-white to-white/0 h-8 w-full"></div>
<div className="bg-white p-4 pt-0 flex flex-col gap-2">
<Link
className={cn('flex gap-2', buttonVariants())}
href={`/${organizationId}/${projectId}/reports`}
>
<PlusIcon size={16} />
Create a report
</Link>
<LayoutOrganizationSelector organizations={organizations} />
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,22 @@
import { cn } from '@/utils/cn';
interface StickyBelowHeaderProps {
children: React.ReactNode;
className?: string;
}
export function StickyBelowHeader({
children,
className,
}: StickyBelowHeaderProps) {
return (
<div
className={cn(
'md:sticky bg-white border-b border-border z-20 [[id=dashboard]_&]:top-16 [[id=dashboard]_&]:rounded-none rounded-lg top-0',
className
)}
>
{children}
</div>
);
}

View File

@@ -0,0 +1,34 @@
import {
getCurrentOrganizations,
getDashboardsByOrganization,
getDashboardsByProjectId,
} from '@openpanel/db';
import { LayoutSidebar } from './layout-sidebar';
interface AppLayoutProps {
children: React.ReactNode;
params: {
organizationId: string;
projectId: string;
};
}
export default async function AppLayout({
children,
params: { organizationId, projectId },
}: AppLayoutProps) {
const [organizations, dashboards] = await Promise.all([
getCurrentOrganizations(),
getDashboardsByProjectId(projectId),
]);
return (
<div id="dashboard">
<LayoutSidebar
{...{ organizationId, projectId, organizations, dashboards }}
/>
<div className="lg:pl-72 transition-all">{children}</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
'use client';
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { ReportRange } from '@/components/report/ReportRange';
import { endOfDay, startOfDay } from 'date-fns';
export function OverviewReportRange() {
const { range, setRange, setEndDate, setStartDate, startDate, endDate } =
useOverviewOptions();
return (
<ReportRange
range={range}
onRangeChange={(value) => {
setRange(value);
setStartDate(null);
setEndDate(null);
}}
dates={{
startDate,
endDate,
}}
onDatesChange={(val) => {
if (!val) return;
if (val.from && val.to) {
setRange(null);
setStartDate(startOfDay(val.from).toISOString());
setEndDate(endOfDay(val.to).toISOString());
} else if (val.from) {
setStartDate(startOfDay(val.from).toISOString());
} else if (val.to) {
setEndDate(endOfDay(val.to).toISOString());
}
}}
/>
);
}

View File

@@ -0,0 +1,27 @@
import { getProjectsByOrganizationSlug } from '@openpanel/db';
import LayoutProjectSelector from './layout-project-selector';
interface PageLayoutProps {
children: React.ReactNode;
title: React.ReactNode;
organizationSlug: string;
}
export default async function PageLayout({
children,
title,
organizationSlug,
}: PageLayoutProps) {
const projects = await getProjectsByOrganizationSlug(organizationSlug);
return (
<>
<div className="h-16 border-b border-border flex-shrink-0 sticky top-0 bg-white px-4 flex items-center justify-between z-20 pl-12 lg:pl-4">
<div className="text-xl font-medium">{title}</div>
{projects.length > 0 && <LayoutProjectSelector projects={projects} />}
</div>
<div>{children}</div>
</>
);
}

View File

@@ -0,0 +1,68 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons';
import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer';
import ServerLiveCounter from '@/components/overview/live-counter';
import { OverviewLiveHistogram } from '@/components/overview/overview-live-histogram';
import { OverviewShare } from '@/components/overview/overview-share';
import OverviewTopDevices from '@/components/overview/overview-top-devices';
import OverviewTopEvents from '@/components/overview/overview-top-events';
import OverviewTopGeo from '@/components/overview/overview-top-geo';
import OverviewTopPages from '@/components/overview/overview-top-pages';
import OverviewTopSources from '@/components/overview/overview-top-sources';
import { getExists } from '@/server/pageExists';
import { db } from '@openpanel/db';
import OverviewMetrics from '../../../../components/overview/overview-metrics';
import { CreateClient } from './create-client';
import { StickyBelowHeader } from './layout-sticky-below-header';
import { OverviewReportRange } from './overview-sticky-header';
interface PageProps {
params: {
organizationId: string;
projectId: string;
};
}
export default async function Page({
params: { organizationId, projectId },
}: PageProps) {
const [share] = await Promise.all([
db.shareOverview.findUnique({
where: {
project_id: projectId,
},
}),
getExists(organizationId, projectId),
]);
return (
<PageLayout title="Overview" organizationSlug={organizationId}>
<CreateClient />
<StickyBelowHeader>
<div className="p-4 flex gap-2 justify-between">
<div className="flex gap-2">
<OverviewReportRange />
<OverviewFiltersDrawer projectId={projectId} mode="events" />
</div>
<div className="flex gap-2">
<ServerLiveCounter projectId={projectId} />
<OverviewShare data={share} />
</div>
</div>
<OverviewFiltersButtons />
</StickyBelowHeader>
<div className="p-4 grid gap-4 grid-cols-6">
<div className="col-span-6">
<OverviewLiveHistogram projectId={projectId} />
</div>
<OverviewMetrics projectId={projectId} />
<OverviewTopSources projectId={projectId} />
<OverviewTopPages projectId={projectId} />
<OverviewTopDevices projectId={projectId} />
<OverviewTopEvents projectId={projectId} />
<OverviewTopGeo projectId={projectId} />
</div>
</PageLayout>
);
}

View File

@@ -0,0 +1,176 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons';
import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer';
import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
import { ChartSwitch } from '@/components/report/chart';
import { KeyValue } from '@/components/ui/key-value';
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
import {
eventQueryFiltersParser,
eventQueryNamesFilter,
} from '@/hooks/useEventQueryFilters';
import { getExists } from '@/server/pageExists';
import { cn } from '@/utils/cn';
import { getProfileName } from '@/utils/getters';
import type { GetEventListOptions } from '@openpanel/db';
import {
getConversionEventNames,
getEventList,
getEventsCount,
getProfileById,
} from '@openpanel/db';
import type { IChartEvent, IChartInput } from '@openpanel/validation';
import { notFound } from 'next/navigation';
import { parseAsInteger, parseAsString } from 'nuqs';
import { EventList } from '../../events/event-list';
import { StickyBelowHeader } from '../../layout-sticky-below-header';
interface PageProps {
params: {
projectId: string;
profileId: string;
organizationId: string;
};
searchParams: {
events?: string;
cursor?: string;
f?: string;
startDate: string;
endDate: string;
};
}
export default async function Page({
params: { projectId, profileId, organizationId },
searchParams,
}: PageProps) {
const eventListOptions: GetEventListOptions = {
projectId,
profileId,
take: 50,
cursor:
parseAsInteger.parseServerSide(searchParams.cursor ?? '') ?? undefined,
events: eventQueryNamesFilter.parseServerSide(searchParams.events ?? ''),
filters:
eventQueryFiltersParser.parseServerSide(searchParams.f ?? '') ??
undefined,
};
const startDate = parseAsString.parseServerSide(searchParams.startDate);
const endDate = parseAsString.parseServerSide(searchParams.endDate);
const [profile, events, count, conversions] = await Promise.all([
getProfileById(profileId),
getEventList(eventListOptions),
getEventsCount(eventListOptions),
getConversionEventNames(projectId),
getExists(organizationId, projectId),
]);
const chartSelectedEvents: IChartEvent[] = [
{
segment: 'event',
filters: [
{
id: 'profile_id',
name: 'profile_id',
operator: 'is',
value: [profileId],
},
],
id: 'A',
name: '*',
displayName: 'Events',
},
];
if (conversions.length) {
chartSelectedEvents.push({
segment: 'event',
filters: [
{
id: 'profile_id',
name: 'profile_id',
operator: 'is',
value: [profileId],
},
{
id: 'name',
name: 'name',
operator: 'is',
value: conversions.map((c) => c.name),
},
],
id: 'B',
name: '*',
displayName: 'Conversions',
});
}
const profileChart: IChartInput = {
projectId,
startDate,
endDate,
chartType: 'histogram',
events: chartSelectedEvents,
breakdowns: [],
lineType: 'monotone',
interval: 'day',
name: 'Events',
range: '7d',
previous: false,
metric: 'sum',
};
if (!profile) {
return notFound();
}
return (
<PageLayout
organizationSlug={organizationId}
title={
<div className="flex items-center gap-2">
<ProfileAvatar {...profile} size="sm" className="hidden sm:block" />
{getProfileName(profile)}
</div>
}
>
<StickyBelowHeader className="p-4 flex justify-between">
<OverviewFiltersDrawer
projectId={projectId}
mode="events"
nuqsOptions={{ shallow: false }}
/>
<OverviewFiltersButtons
nuqsOptions={{ shallow: false }}
className="p-0 justify-end"
/>
</StickyBelowHeader>
<div className="p-4">
<div className="grid gap-4 grid-cols-1 md:grid-cols-2 mb-8">
<Widget>
<WidgetHead>
<span className="title">Properties</span>
</WidgetHead>
<WidgetBody className="flex gap-2 flex-wrap">
{Object.entries(profile.properties)
.filter(([, value]) => !!value)
.map(([key, value]) => (
<KeyValue key={key} name={key} value={value} />
))}
</WidgetBody>
</Widget>
<Widget>
<WidgetHead>
<span className="title">Events per day</span>
</WidgetHead>
<WidgetBody className="flex gap-2">
<ChartSwitch {...profileChart} />
</WidgetBody>
</Widget>
</div>
<EventList data={events} count={count} />
</div>
</PageLayout>
);
}

View File

@@ -0,0 +1,61 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons';
import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer';
import { eventQueryFiltersParser } from '@/hooks/useEventQueryFilters';
import { getExists } from '@/server/pageExists';
import { getProfileList, getProfileListCount } from '@openpanel/db';
import { parseAsInteger } from 'nuqs';
import { StickyBelowHeader } from '../layout-sticky-below-header';
import { ProfileList } from './profile-list';
interface PageProps {
params: {
organizationId: string;
projectId: string;
};
searchParams: {
f?: string;
cursor?: string;
};
}
const nuqsOptions = {
shallow: false,
};
export default async function Page({
params: { organizationId, projectId },
searchParams: { cursor, f },
}: PageProps) {
const [profiles, count] = await Promise.all([
getProfileList({
projectId,
take: 50,
cursor: parseAsInteger.parseServerSide(cursor ?? '') ?? undefined,
filters: eventQueryFiltersParser.parseServerSide(f ?? '') ?? undefined,
}),
getProfileListCount({
projectId,
filters: eventQueryFiltersParser.parseServerSide(f ?? '') ?? undefined,
}),
getExists(organizationId, projectId),
]);
return (
<PageLayout title="Profiles" organizationSlug={organizationId}>
<StickyBelowHeader className="p-4 flex justify-between">
<OverviewFiltersDrawer
projectId={projectId}
nuqsOptions={nuqsOptions}
mode="events"
/>
<OverviewFiltersButtons
className="p-0 justify-end"
nuqsOptions={nuqsOptions}
/>
</StickyBelowHeader>
<ProfileList data={profiles} count={count} />
</PageLayout>
);
}

View File

@@ -0,0 +1,58 @@
'use client';
import { ExpandableListItem } from '@/components/general/ExpandableListItem';
import { ProfileAvatar } from '@/components/profiles/ProfileAvatar';
import { KeyValue, KeyValueSubtle } from '@/components/ui/key-value';
import { useAppParams } from '@/hooks/useAppParams';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import { getProfileName } from '@/utils/getters';
import type { IServiceProfile } from '@openpanel/db';
type ProfileListItemProps = IServiceProfile;
export function ProfileListItem(props: ProfileListItemProps) {
const { id, properties, createdAt } = props;
const params = useAppParams();
const [, setFilter] = useEventQueryFilters({ shallow: false });
const renderContent = () => {
return (
<>
<KeyValueSubtle name="Time" value={createdAt.toLocaleString()} />
<KeyValueSubtle
href={`/${params.organizationId}/${params.projectId}/profiles/${id}`}
name="Details"
value={'See profile'}
/>
</>
);
};
return (
<ExpandableListItem
title={getProfileName(props)}
content={renderContent()}
image={<ProfileAvatar {...props} />}
>
<>
{properties && (
<div className="bg-white p-4 flex flex-col gap-4">
<div className="font-medium">Properties</div>
<div className="flex flex-wrap gap-x-4 gap-y-2">
{Object.entries(properties)
.filter(([, value]) => !!value)
.map(([key, value]) => (
<KeyValue
onClick={() => setFilter(`properties.${key}`, value)}
key={key}
name={key}
value={value}
/>
))}
</div>
</div>
)}
</>
</ExpandableListItem>
);
}

View File

@@ -0,0 +1,73 @@
'use client';
import { Suspense } from 'react';
import { FullPageEmptyState } from '@/components/FullPageEmptyState';
import { Pagination } from '@/components/Pagination';
import { Button } from '@/components/ui/button';
import { useCursor } from '@/hooks/useCursor';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import type { IServiceProfile } from '@openpanel/db';
import { UsersIcon } from 'lucide-react';
import { ProfileListItem } from './profile-list-item';
interface ProfileListProps {
data: IServiceProfile[];
count: number;
}
export function ProfileList({ data, count }: ProfileListProps) {
const { cursor, setCursor } = useCursor();
const [filters] = useEventQueryFilters();
return (
<Suspense>
<div className="p-4">
{data.length === 0 ? (
<FullPageEmptyState title="No profiles here" icon={UsersIcon}>
{cursor !== 0 ? (
<>
<p>Looks like you have reached the end of the list</p>
<Button
className="mt-4"
variant="outline"
size="sm"
onClick={() => setCursor((p) => Math.max(0, p - 1))}
>
Go back
</Button>
</>
) : (
<>
{filters.length ? (
<p>Could not find any profiles with your filter</p>
) : (
<p>No profiles have been created yet</p>
)}
</>
)}
</FullPageEmptyState>
) : (
<>
<Pagination
cursor={cursor}
setCursor={setCursor}
count={count}
take={50}
/>
<div className="flex flex-col gap-4 my-4">
{data.map((item) => (
<ProfileListItem key={item.id} {...item} />
))}
</div>
<Pagination
cursor={cursor}
setCursor={setCursor}
count={count}
take={50}
/>
</>
)}
</div>
</Suspense>
);
}

View File

@@ -0,0 +1,42 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getOrganizationBySlug, getReportById } from '@openpanel/db';
import { Pencil } from 'lucide-react';
import { notFound } from 'next/navigation';
import ReportEditor from '../report-editor';
interface PageProps {
params: {
projectId: string;
reportId: string;
organizationId: string;
};
}
export default async function Page({
params: { reportId, organizationId, projectId },
}: PageProps) {
const [report] = await Promise.all([
getReportById(reportId),
getExists(organizationId, projectId),
]);
if (!report) {
return notFound();
}
return (
<PageLayout
organizationSlug={organizationId}
title={
<div className="flex gap-2 items-center cursor-pointer">
{report.name}
<Pencil size={16} />
</div>
}
>
<ReportEditor report={report} />
</PageLayout>
);
}

View File

@@ -0,0 +1,34 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getOrganizationBySlug } from '@openpanel/db';
import { Pencil } from 'lucide-react';
import { notFound } from 'next/navigation';
import ReportEditor from './report-editor';
interface PageProps {
params: {
organizationId: string;
projectId: string;
};
}
export default async function Page({
params: { organizationId, projectId },
}: PageProps) {
await getExists(organizationId, projectId);
return (
<PageLayout
organizationSlug={organizationId}
title={
<div className="flex gap-2 items-center cursor-pointer">
Unnamed report
<Pencil size={16} />
</div>
}
>
<ReportEditor report={null} />
</PageLayout>
);
}

View File

@@ -0,0 +1,109 @@
'use client';
import { useEffect } from 'react';
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { ChartSwitch } from '@/components/report/chart';
import { ReportChartType } from '@/components/report/ReportChartType';
import { ReportInterval } from '@/components/report/ReportInterval';
import { ReportLineType } from '@/components/report/ReportLineType';
import { ReportRange } from '@/components/report/ReportRange';
import { ReportSaveButton } from '@/components/report/ReportSaveButton';
import {
changeDateRanges,
changeDates,
changeEndDate,
changeStartDate,
ready,
reset,
setReport,
} from '@/components/report/reportSlice';
import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar';
import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/useAppParams';
import { useDispatch, useSelector } from '@/redux';
import type { IServiceReport } from '@openpanel/db';
import { endOfDay, startOfDay } from 'date-fns';
import { GanttChartSquareIcon } from 'lucide-react';
interface ReportEditorProps {
report: IServiceReport | null;
}
export default function ReportEditor({
report: initialReport,
}: ReportEditorProps) {
const { projectId } = useAppParams();
const dispatch = useDispatch();
const report = useSelector((state) => state.report);
// Set report if reportId exists
useEffect(() => {
if (initialReport) {
dispatch(setReport(initialReport));
} else {
dispatch(ready());
}
return () => {
dispatch(reset());
};
}, [initialReport, dispatch]);
return (
<Sheet>
<StickyBelowHeader className="p-4 grid grid-cols-2 gap-2 md:grid-cols-6">
<SheetTrigger asChild>
<div>
<Button icon={GanttChartSquareIcon} variant="cta">
Pick events
</Button>
</div>
</SheetTrigger>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2 col-span-4">
<ReportChartType className="min-w-0 flex-1" />
<ReportRange
className="min-w-0 flex-1"
range={report.range}
onRangeChange={(value) => {
dispatch(changeDateRanges(value));
}}
dates={{
startDate: report.startDate,
endDate: report.endDate,
}}
onDatesChange={(val) => {
if (!val) return;
if (val.from && val.to) {
dispatch(
changeDates({
startDate: startOfDay(val.from).toISOString(),
endDate: endOfDay(val.to).toISOString(),
})
);
} else if (val.from) {
dispatch(changeStartDate(startOfDay(val.from).toISOString()));
} else if (val.to) {
dispatch(changeEndDate(endOfDay(val.to).toISOString()));
}
}}
/>
<ReportInterval className="min-w-0 flex-1" />
<ReportLineType className="min-w-0 flex-1" />
</div>
<div className="col-start-2 md:col-start-6 row-start-1 text-right">
<ReportSaveButton />
</div>
</StickyBelowHeader>
<div className="flex flex-col gap-4 p-4">
{report.ready && (
<ChartSwitch {...report} projectId={projectId} editMode />
)}
</div>
<SheetContent className="!max-w-lg" side="left">
<ReportSidebar />
</SheetContent>
</Sheet>
);
}

View File

@@ -0,0 +1,37 @@
'use client';
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { columns } from '@/components/clients/table';
import { DataTable } from '@/components/DataTable';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { pushModal } from '@/modals';
import type { getClientsByOrganizationId } from '@openpanel/db';
import { PlusIcon } from 'lucide-react';
interface ListClientsProps {
clients: Awaited<ReturnType<typeof getClientsByOrganizationId>>;
}
export default function ListClients({ clients }: ListClientsProps) {
const organizationId = useAppParams().organizationId;
return (
<>
<StickyBelowHeader>
<div className="p-4 flex items-center justify-between">
<div />
<Button
icon={PlusIcon}
onClick={() => pushModal('AddClient', { organizationId })}
>
<span className="max-sm:hidden">Create client</span>
<span className="sm:hidden">Client</span>
</Button>
</div>
</StickyBelowHeader>
<div className="p-4">
<DataTable data={clients} columns={columns} />
</div>
</>
);
}

View File

@@ -0,0 +1,22 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getClientsByOrganizationId } from '@openpanel/db';
import ListClients from './list-clients';
interface PageProps {
params: {
organizationId: string;
};
}
export default async function Page({ params: { organizationId } }: PageProps) {
await getExists(organizationId);
const clients = await getClientsByOrganizationId(organizationId);
return (
<PageLayout title="Clients" organizationSlug={organizationId}>
<ListClients clients={clients} />
</PageLayout>
);
}

View File

@@ -0,0 +1,65 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
import type { getOrganizationBySlug } from '@openpanel/db';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const validator = z.object({
id: z.string().min(2),
name: z.string().min(2),
});
type IForm = z.infer<typeof validator>;
interface EditOrganizationProps {
organization: Awaited<ReturnType<typeof getOrganizationBySlug>>;
}
export default function EditOrganization({
organization,
}: EditOrganizationProps) {
const router = useRouter();
const { register, handleSubmit, formState, reset } = useForm<IForm>({
defaultValues: organization ?? undefined,
});
const mutation = api.organization.update.useMutation({
onSuccess(res) {
toast('Organization updated', {
description: 'Your organization has been updated.',
});
reset(res);
router.refresh();
},
onError: handleError,
});
return (
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<Widget>
<WidgetHead className="flex items-center justify-between">
<span className="title">Org. details</span>
<Button size="sm" type="submit" disabled={!formState.isDirty}>
Save
</Button>
</WidgetHead>
<WidgetBody>
<InputWithLabel
label="Name"
{...register('name')}
defaultValue={organization?.name}
/>
</WidgetBody>
</Widget>
</form>
);
}

View File

@@ -0,0 +1,59 @@
import { api } from '@/app/_trpc/client';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { zInviteUser } from '@openpanel/validation';
import { SendIcon } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import type { z } from 'zod';
type IForm = z.infer<typeof zInviteUser>;
export function InviteUser() {
const router = useRouter();
const { organizationId: organizationSlug } = useAppParams();
const { register, handleSubmit, formState, reset } = useForm<IForm>({
resolver: zodResolver(zInviteUser),
defaultValues: {
organizationSlug,
email: '',
role: 'org:member',
},
});
const mutation = api.organization.inviteUser.useMutation({
onSuccess() {
toast('User invited!', {
description: 'The user has been invited to the organization.',
});
reset();
router.refresh();
},
});
return (
<form
onSubmit={handleSubmit((values) => mutation.mutate(values))}
className="flex items-end gap-4"
>
<InputWithLabel
className="w-full max-w-sm"
label="Email"
placeholder="Who do you want to invite?"
{...register('email')}
/>
<Button
icon={SendIcon}
type="submit"
disabled={!formState.isDirty}
loading={mutation.isLoading}
>
Invite user
</Button>
</form>
);
}

View File

@@ -0,0 +1,64 @@
'use client';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
import type { IServiceInvites } from '@openpanel/db';
import { InviteUser } from './invite-user';
interface InvitedUsersProps {
invites: IServiceInvites;
}
export default function InvitedUsers({ invites }: InvitedUsersProps) {
return (
<Widget>
<WidgetHead className="flex items-center justify-between">
<span className="title">Invites</span>
</WidgetHead>
<WidgetBody>
<InviteUser />
<div className="font-medium mt-8 mb-2">Invited users</div>
<Table className="mini">
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Role</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{invites.map((item) => {
return (
<TableRow key={item.id}>
<TableCell className="font-medium">{item.email}</TableCell>
<TableCell>{item.role}</TableCell>
<TableCell>{item.status}</TableCell>
<TableCell>
{new Date(item.createdAt).toLocaleString()}
</TableCell>
</TableRow>
);
})}
{invites.length === 0 && (
<TableRow>
<TableCell colSpan={2} className="italic">
No invites
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</WidgetBody>
</Widget>
);
}

View File

@@ -0,0 +1,32 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { clerkClient } from '@clerk/nextjs';
import { getInvites, getOrganizationBySlug } from '@openpanel/db';
import { notFound } from 'next/navigation';
import EditOrganization from './edit-organization';
import InvitedUsers from './invited-users';
interface PageProps {
params: {
organizationId: string;
};
}
export default async function Page({ params: { organizationId } }: PageProps) {
const organization = await getOrganizationBySlug(organizationId);
if (!organization) {
return notFound();
}
const invites = await getInvites(organization.id);
return (
<PageLayout title={organization.name} organizationSlug={organizationId}>
<div className="p-4 grid grid-cols-1 gap-4">
<EditOrganization organization={organization} />
<InvitedUsers invites={invites} />
</div>
</PageLayout>
);
}

View File

@@ -0,0 +1 @@
export { default } from './organization/page';

View File

@@ -0,0 +1,84 @@
'use client';
import { api, handleError } from '@/app/_trpc/client';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
import { zodResolver } from '@hookform/resolvers/zod';
import type { getUserById } from '@openpanel/db';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const validator = z.object({
firstName: z.string().min(2),
lastName: z.string().min(2),
email: z.string().email(),
});
type IForm = z.infer<typeof validator>;
interface EditProfileProps {
profile: Awaited<ReturnType<typeof getUserById>>;
}
export default function EditProfile({ profile }: EditProfileProps) {
const router = useRouter();
const { register, handleSubmit, reset, formState } = useForm<IForm>({
resolver: zodResolver(validator),
defaultValues: {
firstName: profile.firstName ?? '',
lastName: profile.lastName ?? '',
email: profile.email ?? '',
},
});
const mutation = api.user.update.useMutation({
onSuccess(res) {
toast('Profile updated', {
description: 'Your profile has been updated.',
});
reset(res);
router.refresh();
},
onError: handleError,
});
return (
<form
onSubmit={handleSubmit((values) => {
mutation.mutate(values);
})}
>
<Widget>
<WidgetHead className="flex items-center justify-between">
<span className="title">Your profile</span>
<Button size="sm" type="submit" disabled={!formState.isDirty}>
Save
</Button>
</WidgetHead>
<WidgetBody className="flex flex-col gap-4">
<InputWithLabel
label="First name"
placeholder="Your first name"
defaultValue={profile.firstName ?? ''}
{...register('firstName')}
/>
<InputWithLabel
label="Last name"
placeholder="Your last name"
defaultValue={profile.lastName ?? ''}
{...register('lastName')}
/>
<InputWithLabel
disabled
label="Email"
placeholder="Your email"
defaultValue={profile.email ?? ''}
{...register('email')}
/>
</WidgetBody>
</Widget>
</form>
);
}

View File

@@ -0,0 +1,20 @@
'use client';
import { Widget, WidgetBody, WidgetHead } from '@/components/Widget';
import { SignOutButton } from '@clerk/nextjs';
export function Logout() {
return (
<Widget className="border-destructive">
<WidgetHead className="border-destructive">
<span className="title text-destructive">Sad part</span>
</WidgetHead>
<WidgetBody>
<p className="mb-4">
Sometime&apos;s you need to go. See you next time
</p>
<SignOutButton />
</WidgetBody>
</Widget>
);
}

View File

@@ -0,0 +1,27 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { auth } from '@clerk/nextjs';
import { getUserById } from '@openpanel/db';
import EditProfile from './edit-profile';
import { Logout } from './logout';
interface PageProps {
params: {
organizationId: string;
};
}
export default async function Page({ params: { organizationId } }: PageProps) {
const { userId } = auth();
await getExists(organizationId);
const profile = await getUserById(userId!);
return (
<PageLayout title={profile.lastName} organizationSlug={organizationId}>
<div className="p-4 flex flex-col gap-4">
<EditProfile profile={profile} />
<Logout />
</div>
</PageLayout>
);
}

View File

@@ -0,0 +1,40 @@
'use client';
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { DataTable } from '@/components/DataTable';
import { columns } from '@/components/projects/table';
import { Button } from '@/components/ui/button';
import { useAppParams } from '@/hooks/useAppParams';
import { pushModal } from '@/modals';
import type { getProjectsByOrganizationSlug } from '@openpanel/db';
import { PlusIcon } from 'lucide-react';
interface ListProjectsProps {
projects: Awaited<ReturnType<typeof getProjectsByOrganizationSlug>>;
}
export default function ListProjects({ projects }: ListProjectsProps) {
const organizationId = useAppParams().organizationId;
return (
<>
<StickyBelowHeader>
<div className="p-4 flex items-center justify-between">
<div />
<Button
icon={PlusIcon}
onClick={() =>
pushModal('AddProject', {
organizationId,
})
}
>
<span className="max-sm:hidden">Create project</span>
<span className="sm:hidden">Project</span>
</Button>
</div>
</StickyBelowHeader>
<div className="p-4">
<DataTable data={projects} columns={columns} />
</div>
</>
);
}

View File

@@ -0,0 +1,22 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getProjectsByOrganizationSlug } from '@openpanel/db';
import ListProjects from './list-projects';
interface PageProps {
params: {
organizationId: string;
};
}
export default async function Page({ params: { organizationId } }: PageProps) {
await getExists(organizationId);
const projects = await getProjectsByOrganizationSlug(organizationId);
return (
<PageLayout title="Projects" organizationSlug={organizationId}>
<ListProjects projects={projects} />
</PageLayout>
);
}

View File

@@ -0,0 +1,32 @@
'use client';
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { DataTable } from '@/components/DataTable';
import { columns } from '@/components/references/table';
import { Button } from '@/components/ui/button';
import { pushModal } from '@/modals';
import type { IServiceReference } from '@openpanel/db';
import { PlusIcon } from 'lucide-react';
interface ListProjectsProps {
data: IServiceReference[];
}
export default function ListReferences({ data }: ListProjectsProps) {
return (
<>
<StickyBelowHeader>
<div className="p-4 flex items-center justify-between">
<div />
<Button icon={PlusIcon} onClick={() => pushModal('AddReference')}>
<span className="max-sm:hidden">Create reference</span>
<span className="sm:hidden">Reference</span>
</Button>
</div>
</StickyBelowHeader>
<div className="p-4">
<DataTable data={data} columns={columns} />
</div>
</>
);
}

View File

@@ -0,0 +1,31 @@
import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout';
import { getExists } from '@/server/pageExists';
import { getReferences } from '@openpanel/db';
import ListReferences from './list-references';
interface PageProps {
params: {
organizationId: string;
projectId: string;
};
}
export default async function Page({
params: { organizationId, projectId },
}: PageProps) {
await getExists(organizationId, projectId);
const references = await getReferences({
where: {
project_id: projectId,
},
take: 50,
skip: 0,
});
return (
<PageLayout title="References" organizationSlug={organizationId}>
<ListReferences data={references} />
</PageLayout>
);
}

View File

@@ -0,0 +1,21 @@
import { Funnel } from '@/components/report/funnel';
import PageLayout from '../page-layout';
export const metadata = {
title: 'Funnel - Openpanel.dev',
};
interface PageProps {
params: {
organizationId: string;
};
}
export default function Page({ params: { organizationId } }: PageProps) {
return (
<PageLayout title="Funnel" organizationSlug={organizationId}>
<Funnel />
</PageLayout>
);
}

View File

@@ -0,0 +1,113 @@
'use client';
import { LogoSquare } from '@/components/Logo';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAppParams } from '@/hooks/useAppParams';
import { zodResolver } from '@hookform/resolvers/zod';
import { SaveIcon } from 'lucide-react';
import { useRouter } from 'next/navigation';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { api, handleError } from '../../_trpc/client';
const validation = z.object({
name: z.string().min(1),
});
type IForm = z.infer<typeof validation>;
export function CreateProject() {
const params = useAppParams();
const router = useRouter();
const form = useForm<IForm>({
resolver: zodResolver(validation),
});
const mutation = api.project.create.useMutation({
onError: handleError,
onSuccess() {
toast.success('Project created');
router.refresh();
},
});
const onSubmit: SubmitHandler<IForm> = (values) => {
mutation.mutate({
name: values.name,
organizationId: params.organizationId,
});
};
return (
<>
<div>
<LogoSquare className="w-20 md:w-28 mb-8" />
<h1 className="font-medium text-3xl">Create your first project</h1>
<div className="text-lg">
A project is just a container for your events. You can create as many
as you want.
</div>
<form
className="mt-8 flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<div>
<Label>Project name</Label>
<Input
placeholder="My App"
size="large"
error={form.formState.errors.name?.message}
{...form.register('name')}
/>
</div>
<div className="flex justify-end">
<Button
type="submit"
size="lg"
icon={SaveIcon}
loading={mutation.isLoading}
>
Create project
</Button>
</div>
</form>
</div>
</>
);
}
// <div>
// <div className="text-lg">
// Select your framework and we'll generate a client for you.
// </div>
// <div className="flex flex-wrap gap-2 mt-8">
// <FeatureButton
// name="React"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
// />
// <FeatureButton
// name="React Native"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/2300px-React-icon.svg.png"
// />
// <FeatureButton
// name="Next.js"
// logo="https://static-00.iconduck.com/assets.00/nextjs-icon-512x512-y563b8iq.png"
// />
// <FeatureButton
// name="Remix"
// logo="https://www.datocms-assets.com/205/1642515307-square-logo.svg"
// />
// <FeatureButton
// name="Vue"
// logo="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0UhQnp6TUPCwAr3ruTEwBDiTN5HLAWaoUD3AJIgtepQ&s"
// />
// <FeatureButton
// name="HTML"
// logo="https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/240px-HTML5_logo_and_wordmark.svg.png"
// />
// </div>
// </div>

View File

@@ -0,0 +1,64 @@
import { LogoSquare } from '@/components/Logo';
import { ProjectCard } from '@/components/projects/project-card';
import {
getOrganizationBySlug,
getProjectsByOrganizationSlug,
} from '@openpanel/db';
import { notFound, redirect } from 'next/navigation';
import { CreateProject } from './create-project';
interface PageProps {
params: {
organizationId: string;
};
}
export default async function Page({ params: { organizationId } }: PageProps) {
const [organization, projects] = await Promise.all([
getOrganizationBySlug(organizationId),
getProjectsByOrganizationSlug(organizationId),
]);
if (!organization) {
return notFound();
}
if (process.env.BLOCK) {
return (
<div className="flex items-center justify-center h-screen">
<div className="max-w-lg w-full">
<LogoSquare className="w-20 md:w-28 mb-8" />
<h1 className="font-medium text-3xl">Not quite there yet</h1>
<div className="text-lg">
We're still working on Openpanel, but we're not quite there yet.
We'll let you know when we're ready to go!
</div>
</div>
</div>
);
}
if (projects.length === 0) {
return (
<div className="flex items-center justify-center h-screen">
<div className="max-w-lg w-full">
<CreateProject />
</div>
</div>
);
}
if (projects.length === 1 && projects[0]) {
return redirect(`/${organizationId}/${projects[0].id}`);
}
return (
<div className="max-w-xl w-full mx-auto flex flex-col gap-4 pt-20">
<h1 className="font-medium text-xl">Select project</h1>
{projects.map((item) => (
<ProjectCard key={item.id} {...item} />
))}
</div>
);
}

View File

@@ -0,0 +1,86 @@
'use client';
import { LogoSquare } from '@/components/Logo';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { zodResolver } from '@hookform/resolvers/zod';
import { SaveIcon } from 'lucide-react';
import { useRouter } from 'next/navigation';
import type { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { api, handleError } from '../_trpc/client';
const validation = z.object({
organization: z.string().min(4),
project: z.string().optional(),
});
type IForm = z.infer<typeof validation>;
export function CreateOrganization() {
const router = useRouter();
const form = useForm<IForm>({
resolver: zodResolver(validation),
});
const mutation = api.onboarding.organziation.useMutation({
onError: handleError,
onSuccess({ organization, project }) {
let url = `/${organization.slug}`;
if (project) {
url += `/${project.id}`;
}
router.replace(url);
},
});
const onSubmit: SubmitHandler<IForm> = (values) => {
mutation.mutate(values);
};
return (
<>
<div>
<LogoSquare className="w-20 md:w-28 mb-8" />
<h1 className="font-medium text-3xl">Welcome to Openpanel</h1>
<div className="text-lg">
Create your organization below (can be personal or a company) and
optionally your first project 🤠
</div>
<form
className="mt-8 flex flex-col gap-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<div>
<Label>Organization name *</Label>
<Input
placeholder="Organization name"
size="large"
error={form.formState.errors.organization?.message}
{...form.register('organization')}
/>
</div>
<div>
<Label>Project name</Label>
<Input
placeholder="Project name"
size="large"
error={form.formState.errors.project?.message}
{...form.register('project')}
/>
</div>
<div className="flex justify-end">
<Button
type="submit"
size="lg"
icon={SaveIcon}
loading={mutation.isLoading}
>
Create
</Button>
</div>
</form>
</div>
</>
);
}

View File

@@ -0,0 +1,38 @@
// import { CreateOrganization } from '@clerk/nextjs';
import { LogoSquare } from '@/components/Logo';
import { getCurrentOrganizations } from '@openpanel/db';
import { redirect } from 'next/navigation';
import { CreateOrganization } from './create-organization';
export default async function Page() {
const organizations = await getCurrentOrganizations();
if (process.env.BLOCK) {
return (
<div className="flex items-center justify-center h-screen">
<div className="max-w-lg w-full">
<LogoSquare className="w-20 md:w-28 mb-8" />
<h1 className="font-medium text-3xl">Not quite there yet</h1>
<div className="text-lg">
We're still working on Openpanel, but we're not quite there yet.
We'll let you know when we're ready to go!
</div>
</div>
</div>
);
}
if (organizations.length > 0) {
return redirect(`/${organizations[0]?.slug}`);
}
return (
<div className="flex items-center justify-center h-screen">
<div className="max-w-lg w-full">
<CreateOrganization />
</div>
</div>
);
}

View File

@@ -0,0 +1,73 @@
import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header';
import { OverviewReportRange } from '@/app/(app)/[organizationId]/[projectId]/overview-sticky-header';
import { Logo } from '@/components/Logo';
import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons';
import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer';
import ServerLiveCounter from '@/components/overview/live-counter';
import { OverviewLiveHistogram } from '@/components/overview/overview-live-histogram';
import OverviewMetrics from '@/components/overview/overview-metrics';
import OverviewTopDevices from '@/components/overview/overview-top-devices';
import OverviewTopEvents from '@/components/overview/overview-top-events';
import OverviewTopGeo from '@/components/overview/overview-top-geo';
import OverviewTopPages from '@/components/overview/overview-top-pages';
import OverviewTopSources from '@/components/overview/overview-top-sources';
import { getOrganizationBySlug, getShareOverviewById } from '@openpanel/db';
import { notFound } from 'next/navigation';
interface PageProps {
params: {
id: string;
};
}
export default async function Page({ params: { id } }: PageProps) {
const share = await getShareOverviewById(id);
if (!share) {
return notFound();
}
const projectId = share.project_id;
const organization = await getOrganizationBySlug(share.organization_slug);
return (
<div className="p-4 md:p-16 bg-gradient-to-tl from-blue-950 to-blue-600">
<div className="max-w-6xl mx-auto">
<div className="flex justify-between items-end mb-4">
<div className="leading-none">
<span className="text-white mb-4">{organization?.name}</span>
<h1 className="text-white text-xl font-medium">
{share.project?.name}
</h1>
</div>
<a href="https://openpanel.dev?utm_source=openpanel.dev&utm_medium=share">
<Logo className="text-white" />
</a>
</div>
<div className="bg-slate-100 rounded-lg shadow ring-8 ring-blue-600/50">
<StickyBelowHeader>
<div className="p-4 flex gap-2 justify-between">
<div className="flex gap-2">
<OverviewReportRange />
{/* <OverviewFiltersDrawer projectId={projectId} mode="events" /> */}
</div>
<div className="flex gap-2">
<ServerLiveCounter projectId={projectId} />
</div>
</div>
<OverviewFiltersButtons />
</StickyBelowHeader>
<div className="p-4 grid gap-4 grid-cols-6">
<div className="col-span-6">
<OverviewLiveHistogram projectId={projectId} />
</div>
<OverviewMetrics projectId={projectId} />
<OverviewTopSources projectId={projectId} />
<OverviewTopPages projectId={projectId} />
<OverviewTopDevices projectId={projectId} />
<OverviewTopEvents projectId={projectId} />
<OverviewTopGeo projectId={projectId} />
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,39 @@
import type { AppRouter } from '@/server/api/root';
import type { TRPCClientErrorBase } from '@trpc/react-query';
import { createTRPCReact } from '@trpc/react-query';
import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';
import type { ExternalToast } from 'sonner';
import { toast } from 'sonner';
export const api = createTRPCReact<AppRouter>({});
/**
* Inference helper for inputs.
*
* @example type HelloInput = RouterInputs['example']['hello']
*/
export type RouterInputs = inferRouterInputs<AppRouter>;
/**
* Inference helper for outputs.
*
* @example type HelloOutput = RouterOutputs['example']['hello']
*/
export type RouterOutputs = inferRouterOutputs<AppRouter>;
export type IChartData = RouterOutputs['chart']['chart'];
export type IChartSerieDataItem = IChartData['series'][number]['data'][number];
export function handleError(error: TRPCClientErrorBase<any>) {
toast('Error', {
description: error.message,
});
}
export function handleErrorToastOptions(options: ExternalToast) {
return function (error: TRPCClientErrorBase<any>) {
toast('Error', {
description: error.message,
...options,
});
};
}

View File

@@ -0,0 +1,25 @@
import { appRouter } from '@/server/api/root';
import { getAuth } from '@clerk/nextjs/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
const handler = (req: Request) =>
fetchRequestHandler({
endpoint: '/api/trpc',
req,
router: appRouter,
async createContext({ req }) {
const session = getAuth(req as any);
return {
session,
};
},
onError(opts) {
const { error, type, path, input, ctx, req } = opts;
console.error('---- TRPC ERROR');
console.error('Error:', error);
console.error('Context:', ctx);
console.error();
},
});
export { handler as GET, handler as POST };

View File

@@ -0,0 +1,87 @@
'use client';
import { useState } from 'react';
import { InputWithLabel } from '@/components/forms/InputWithLabel';
import { Logo } from '@/components/Logo';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Widget, WidgetBody } from '@/components/Widget';
import { zodResolver } from '@hookform/resolvers/zod';
import { KeySquareIcon } from 'lucide-react';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const validator = z.object({
email: z.string().email(),
password: z.string().min(6),
});
type IForm = z.infer<typeof validator>;
export default function Auth() {
const form = useForm<IForm>({
resolver: zodResolver(validator),
});
const router = useRouter();
const pathname = usePathname();
const [state, setState] = useState<string | null>(null);
return (
<div className="flex items-center justify-center flex-col h-screen p-4">
<Widget className="max-w-md w-full mb-4">
<WidgetBody>
<div className="flex justify-center py-8">
<Logo />
</div>
<form
onSubmit={form.handleSubmit(async (values) => {
const res = await signIn('credentials', {
email: values.email,
password: values.password,
redirect: false,
}).catch(() => {
setState('Something went wrong. Please try again later');
});
if (res?.ok) {
router.refresh();
}
if (res?.status === 401) {
setState('Wrong email or password. Please try again');
}
})}
className="flex flex-col gap-4"
>
<InputWithLabel
label="Email"
placeholder="Your email"
error={form.formState.errors.email?.message}
{...form.register('email')}
/>
<InputWithLabel
label="Password"
placeholder="...and your password"
error={form.formState.errors.password?.message}
{...form.register('password')}
/>
{state !== null && (
<Alert variant="destructive">
<KeySquareIcon className="h-4 w-4" />
<AlertTitle>Failed</AlertTitle>
<AlertDescription>{state}</AlertDescription>
</Alert>
)}
<Button type="submit">Sign in</Button>
<Link href="/register" className="text-center text-sm">
No account?{' '}
<span className="font-medium text-blue-600">Sign up here!</span>
</Link>
</form>
</WidgetBody>
</Widget>
<p className="text-xs">Terms & conditions</p>
</div>
);
}

View File

@@ -0,0 +1,33 @@
import { cn } from '@/utils/cn';
import Providers from './providers';
import '@/styles/globals.css';
import '/node_modules/flag-icons/css/flag-icons.min.css';
export const metadata = {
title: 'Overview - Openpanel.dev',
};
export const viewport = {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
userScalable: 1,
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className="light">
<body
className={cn('min-h-screen font-sans antialiased grainy bg-slate-100')}
>
<Providers>{children}</Providers>
</body>
</html>
);
}

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