Compare commits

..

1 Commits

1050 changed files with 23465 additions and 72938 deletions

View File

@@ -1,4 +1,3 @@
lina
dist
node_modules
.git

View File

@@ -4,17 +4,11 @@ root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{js,jsx,ts,tsx,vue}]
indent_size = 2
[*.py]
indent_size = 4
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

View File

@@ -1,6 +1,8 @@
# 全局环境变量 请勿随意改动
ENV = 'development'
# base api
VUE_APP_BASE_API = ''
VUE_APP_PUBLIC_PATH = '/ui/'
@@ -21,5 +23,4 @@ VUE_APP_LOGOUT_PATH = '/core/auth/logout/'
# Dev server for core proxy
VUE_APP_CORE_HOST = 'http://localhost:8080'
VUE_APP_CORE_WS = 'ws://localhost:8080'
VUE_APP_ENV = 'development'

View File

@@ -1,32 +0,0 @@
name: "Run Build Test"
on:
push:
branches:
- pr@*
- repr@*
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/build-push-action@v3
with:
context: .
push: false
tags: jumpserver/lina:test
file: Dockerfile
cache-from: type=gha
cache-to: type=gha,mode=max
- uses: LouisBrunner/checks-action@v1.5.0
if: always()
with:
token: ${{ secrets.GITHUB_TOKEN }}
name: Check Build
conclusion: ${{ job.status }}

View File

@@ -31,29 +31,16 @@ jobs:
config-name: release-config.yml
version: ${{ steps.get_version.outputs.TAG }}
tag: ${{ steps.get_version.outputs.TAG }}
- uses: actions/setup-node@v2
with:
node-version: '16.20'
- name: Install dependencies
run: yarn install
- name: Build web
run: |
sed -i "s@version-dev@${{ steps.get_version.outputs.TAG }}@g" src/layout/components/NavHeader/About.vue
yarn build
- name: Create Upload Assets
run: |
rm -rf build/*
mv lina lina-${{ steps.get_version.outputs.VERSION }}
tar -czf lina-${{ steps.get_version.outputs.VERSION }}.tar.gz lina-${{ steps.get_version.outputs.VERSION }}
echo $(md5sum lina-${{ steps.get_version.outputs.VERSION }}.tar.gz | awk '{print $1}') > build/lina-${{ steps.get_version.outputs.VERSION }}.tar.gz.md5
mv lina-${{ steps.get_version.outputs.VERSION }}.tar.gz build/
- name: Release Upload Assets
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
build/lina-${{ steps.get_version.outputs.TAG }}.tar.gz
build/lina-${{ steps.get_version.outputs.TAG }}.tar.gz.md5
build-and-release:
needs: create-realese
name: Build and Release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build it and upload
uses: jumpserver/action-build-upload-assets@node10
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-realese.outputs.upload_url }}

2
.gitignore vendored
View File

@@ -15,5 +15,3 @@ tests/**/coverage/
*.ntvs*
*.njsproj
*.sln
.env.development
.python-version

3
.gitmodules vendored
View File

@@ -0,0 +1,3 @@
[submodule "src/views/xpack"]
path = src/views/xpack
url = git@github.com:jumpserver/lina-xpack.git

View File

@@ -1,39 +1,23 @@
FROM node:16.20-bullseye-slim as stage-build
ARG TARGETARCH
ARG DEPENDENCIES=" \
g++ \
make \
python3"
ARG APT_MIRROR=http://mirrors.ustc.edu.cn
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,id=lina \
sed -i "s@http://.*.debian.org@${APT_MIRROR}@g" /etc/apt/sources.list \
&& rm -f /etc/apt/apt.conf.d/docker-clean \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& apt-get update \
&& apt-get install -y --no-install-recommends ${DEPENDENCIES} \
&& echo "no" | dpkg-reconfigure dash \
&& rm -rf /var/lib/apt/lists/*
ARG NPM_REGISTRY="https://registry.npmmirror.com"
RUN set -ex \
&& npm config set registry ${NPM_REGISTRY} \
&& yarn config set registry ${NPM_REGISTRY}
FROM node:10 as stage-build
ARG VERSION
ENV VERSION=$VERSION
ARG NPM_REGISTRY="https://registry.npm.taobao.org"
ENV NPM_REGISTY=$NPM_REGISTRY
ARG SASS_BINARY_SITE="https://npm.taobao.org/mirrors/node-sass"
ENV SASS_BINARY_SITE=$SASS_BINARY_SITE
WORKDIR /data
ADD package.json yarn.lock /data
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn,sharing=locked,id=lina \
yarn install
RUN npm config set sass_binary_site=${SASS_BINARY_SITE}
RUN npm config set registry ${NPM_REGISTRY}
RUN yarn config set registry ${NPM_REGISTRY}
COPY package.json yarn.lock /data/
COPY utils /data/utils/
RUN ls && cd utils && bash -xieu build.sh dep
ARG VERSION
ENV VERSION=$VERSION
ADD . /data
RUN --mount=type=cache,target=/usr/local/share/.cache/yarn,sharing=locked,id=lina \
sed -i "s@version-dev@${VERSION}@g" src/layout/components/NavHeader/About.vue \
&& yarn build
RUN cd utils && bash -xieu build.sh build
FROM nginx:1.24-bullseye
COPY --from=stage-build /data/lina /opt/lina
FROM nginx:alpine
COPY --from=stage-build /data/release/lina /opt/lina
COPY nginx.conf /etc/nginx/conf.d/default.conf

877
LICENSE
View File

@@ -1,622 +1,281 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Version 2, June 1991
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
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
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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.
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
13. Use with the GNU Affero General Public License.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
14. Revised Versions of this License.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
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.
NO WARRANTY
15. Disclaimer of Warranty.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
END OF TERMS AND CONDITIONS
@@ -628,15 +287,15 @@ 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
convey 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>
{description}
Copyright (C) {year} {fullname}
This program is free software: you can redistribute it and/or modify
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
@@ -644,31 +303,37 @@ the "copyright" line and a pointer to where the full notice is found.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -19,7 +19,7 @@ VUE_APP_CORE_HOST = 'JUMPSERVER_APIHOST'
$ yarn serve
4. 构建
$ yarn build:prod
$ yarn build
```
## 生产中部署
@@ -46,4 +46,12 @@ server {
## License & Copyright
Be consistent with [jumpserver](https://github.com/jumpserver/jumpserver)
Copyright (c) 2014-2020 飞致云 FIT2CLOUD, All rights reserved.
Licensed under The GNU General Public License version 2 (GPLv2) (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
https://www.gnu.org/licenses/gpl-2.0.html
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

View File

@@ -1,8 +1,5 @@
module.exports = {
presets: [
'@vue/app'
],
plugins: [
'@babel/plugin-proposal-optional-chaining',
]
}

View File

@@ -24,9 +24,9 @@ if (process.env.npm_config_preview || rawArgv.includes('--preview')) {
)
app.listen(port, function () {
// debug(chalk.green(`> Preview at http://localhost:${port}${publicPath}`))
console.log(chalk.green(`> Preview at http://localhost:${port}${publicPath}`))
if (report) {
// debug(chalk.green(`> Report at http://localhost:${port}${publicPath}report.html`))
console.log(chalk.green(`> Report at http://localhost:${port}${publicPath}report.html`))
}
})

View File

@@ -56,7 +56,7 @@ const responseFake = (url, type, respond) => {
url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`),
type: type || 'get',
response(req, res) {
// debug('request invoke:' + req.path)
console.log('request invoke:' + req.path)
res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
}
}

View File

@@ -59,9 +59,9 @@ module.exports = app => {
mockRoutesLength = mockRoutes.mockRoutesLength
mockStartIndex = mockRoutes.mockStartIndex
// debug(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
} catch (error) {
// debug(chalk.redBright(error))
console.log(chalk.redBright(error))
}
}
})

View File

@@ -1,3 +1,4 @@
const tokens = {
admin: {
token: 'admin-token'
@@ -45,6 +46,7 @@ export default [
}
}
},
// get user info
{
url: '/vue-admin-template/user/info\.*',

View File

@@ -1,19 +1,9 @@
server {
listen 80;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
#gzip_http_version 1.0;
gzip_comp_level 8;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
gzip_static on;
gzip_disable "MSIE [1-6].";
location /ui/ {
try_files $uri / /ui/index.html;
alias /opt/lina/;
try_files $uri / /ui/index.html;
alias /opt/lina/;
}
location / {

View File

@@ -5,43 +5,30 @@
"author": "Pan <panfree23@gmail.com>",
"license": "MIT",
"scripts": {
"dev": "NODE_OPTIONS=--openssl-legacy-provider vue-cli-service serve",
"serve": "NODE_OPTIONS=--openssl-legacy-provider vue-cli-service serve",
"build": "NODE_OPTIONS=--openssl-legacy-provider vue-cli-service build",
"dev": "vue-cli-service serve",
"serve": "vue-cli-service serve",
"build:prod": "vue-cli-service build",
"build:stage": "vue-cli-service build --mode staging",
"preview": "node build/index.js --preview",
"lint": "eslint --ext .js,.vue src",
"fix": "eslint --ext .js,.vue --fix src",
"test:unit": "jest --clearCache && vue-cli-service test:unit",
"test:ci": "npm run lint && npm run test:unit",
"svgo": "svgo -f src/icons/svg --config=src/icas/svgo.yml",
"vue-i18n-extract": "vue-i18n-extract",
"vue-i18n-report": "vue-i18n-extract report -v './src/**/*.?(js|vue)' -l './src/i18n/langs/**/*.json'",
"vue-i18n-report-json": "vue-i18n-extract report -v './src/**/*.?(js|vue)' -l './src/i18n/langs/**/*.json' -o /tmp/abc.json",
"vue-i18n-report-add-miss": "vue-i18n-extract report -v './src/**/*.?(js|vue)' -l './src/i18n/langs/**/*.json' -a",
"diff-i18n": "python ./src/i18n/langs/i18n-util.py diff en ja",
"apply-i18n": "python ./src/i18n/langs/i18n-util.py apply en ja"
"vue-i18n-report": "vue-i18n-extract report -v './src/**/*.?(js|vue)' -l './src/i18n/langs/**/*.json'"
},
"dependencies": {
"@babel/plugin-proposal-optional-chaining": "^7.13.12",
"@ztree/ztree_v3": "3.5.44",
"axios": "0.21.1",
"axios-retry": "^3.1.9",
"cron-parser": "^4.0.0",
"crypto-js": "^4.1.1",
"css-color-function": "^1.3.3",
"axios": "0.18.1",
"deepmerge": "^4.2.2",
"echarts": "^4.7.0",
"element-ui": "2.13.2",
"eslint-plugin-html": "^6.0.0",
"install": "^0.13.0",
"jquery": "^3.6.1",
"jquery": "^3.5.0",
"js-cookie": "2.2.0",
"jsencrypt": "^3.2.1",
"krry-transfer": "^1.7.3",
"less": "^3.10.3",
"less-loader": "^5.0.0",
"lodash": "^4.17.21",
"lodash": "^4.17.15",
"lodash.clonedeep": "^4.5.0",
"lodash.frompairs": "^4.0.1",
"lodash.get": "^4.4.2",
@@ -53,26 +40,21 @@
"lodash.set": "^4.3.2",
"lodash.topairs": "^4.3.0",
"lodash.values": "^4.3.0",
"moment": "^2.29.4",
"moment-parseformat": "^4.0.0",
"moment-parseformat": "^3.0.0",
"normalize.css": "7.0.0",
"npm": "^7.8.0",
"nprogress": "0.2.0",
"path-to-regexp": "2.4.0",
"vue": "2.6.10",
"vue-codemirror": "4.0.6",
"vue-codemirror-lite": "^1.0.4",
"vue-cookie": "^1.1.4",
"vue-echarts": "^5.0.0-beta.0",
"vue-i18n": "^8.15.5",
"vue-json-editor": "^1.4.3",
"vue-markdown": "^2.2.4",
"vue-moment": "^4.1.0",
"vue-password-strength-meter": "^1.7.2",
"vue-router": "3.0.6",
"vue-select": "^3.9.5",
"vuejs-logger": "^1.5.4",
"vuex": "3.1.0",
"xss": "^1.0.14",
"xterm": "^4.5.0",
"xterm-addon-fit": "^0.3.0",
"zxcvbn": "^4.4.2"
@@ -90,20 +72,18 @@
"babel-eslint": "10.0.1",
"babel-jest": "23.6.0",
"chalk": "2.4.2",
"compression-webpack-plugin": "^6.1.1",
"connect": "3.6.6",
"element-theme-chalk": "^2.13.1",
"eslint": "^5.15.3",
"eslint-plugin-vue": "5.2.2",
"eslint-plugin-vue-i18n": "^0.3.0",
"github-markdown-css": "^5.1.0",
"html-webpack-plugin": "3.2.0",
"husky": "^4.2.3",
"less-loader": "^5.0.0",
"lint-staged": "^10.1.2",
"mockjs": "1.0.1-beta3",
"runjs": "^4.3.2",
"sass": "~1.32.6",
"sass": "^1.26.10",
"sass-loader": "^7.1.0",
"script-ext-html-webpack-plugin": "2.1.3",
"script-loader": "0.7.2",

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -3,13 +3,9 @@
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= webpackConfig.name %></title>
<link rel="stylesheet" href="<%= BASE_URL %>theme/element-ui.css">
</head>
<body>
<noscript>
@@ -17,15 +13,9 @@
</noscript>
<script>
window.onload = function() {
if (location.pathname === '/') {
location.pathname = '/ui/'
}
const pathname = window.location.pathname
if (pathname.startsWith('/core')) {
return
}
if(pathname.indexOf('/ui') === -1) {
window.location.href = window.location.origin + '/ui/#' + pathname
const baseUrl = "/ui/"
if (location.pathname === '/' && baseUrl !== '/') {
location.pathname = baseUrl
}
}
</script>

View File

@@ -1,23 +0,0 @@
# 主题颜色
```
alpha-1: "rgba(64, 158, 255, 0.1)"
alpha-2: "rgba(64, 158, 255, 0.2)"
alpha-3: "rgba(64, 158, 255, 0.3)"
alpha-4: "rgba(64, 158, 255, 0.4)"
alpha-5: "rgba(64, 158, 255, 0.5)"
alpha-6: "rgba(64, 158, 255, 0.6)"
alpha-7: "rgba(64, 158, 255, 0.7)"
alpha-8: "rgba(64, 158, 255, 0.8)"
alpha-9: "rgba(64, 158, 255, 0.9)"
light-1: "#53a8ff"
light-2: "#66b1ff"
light-3: "#79bbff"
light-4: "#8cc5ff"
light-5: "#a0cfff"
light-6: "#b3d8ff"
light-7: "#c6e2ff"
light-8: "#d9ecff"
light-9: "#ecf5ff"
primary: "#409EFF"
```
primary是初始主题颜色其他颜色均属于primary的系列颜色

View File

@@ -1,21 +1,11 @@
<template>
<div id="app">
<router-view v-if="isRouterAlive" />
<router-view />
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'App',
computed: {
...mapState({
isRouterAlive: state => state.common.isRouterAlive
})
}
name: 'App'
}
</script>
<style>
</style>

View File

@@ -40,10 +40,3 @@ export function getCommandFilterList(data) {
})
}
export function getCategoryTypes() {
return request({
url: '/api/v1/assets/categories/',
method: 'get'
})
}

View File

@@ -1,13 +1,6 @@
import request from '@/utils/request'
export function createSourceIdCache(ids) {
ids = ids.map(item => {
if (typeof item === 'object' && item.id) {
return item.id
} else {
return item
}
})
return request({
url: '/api/v1/common/resources/cache/',
method: 'post',

View File

@@ -1,43 +0,0 @@
import request from '@/utils/request'
export function updateInterface(formData) {
return request({
url: '/api/v1/xpack/interface/setting/',
method: 'put',
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
})
}
export function getInterfaceInfo() {
return request({
url: '/api/v1/xpack/interface/setting/',
method: 'get'
})
}
export function restoreInterface() {
return request({
url: '/api/v1/xpack/interface/setting/restore/',
method: 'put'
})
}
export function importLicense(formData) {
return request({
url: '/api/v1/xpack/license/import',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
})
}
export function previewThemes() {
return request({
url: `/api/v1/xpack/interface/setting/themes/`,
method: 'get'
})
}

View File

@@ -1,5 +1,12 @@
import request from '@/utils/request'
export function getTaskDetail(id) {
return request({
url: `/api/v1/ops/tasks/${id}/`,
method: 'get'
})
}
export function getAdhocDetail(id) {
return request({
url: `/api/v1/ops/adhoc/${id}/`,
@@ -13,42 +20,3 @@ export function getHistoryExecutionDetail(id) {
method: 'get'
})
}
export function getTaskDetail(id) {
return request({
url: `/api/v1/ops/job-execution/task-detail/${id}/`,
method: 'get'
})
}
export function getJob(id) {
return request({
url: `/api/v1/ops/jobs/${id}/`,
method: 'get'
})
}
export function uploadPlaybook(form) {
return request({
url: '/api/v1/ops/playbooks/',
method: 'post',
headers: { 'Content-Type': 'multipart/form-data' },
data: form
})
}
export function renameFile(playbookId, node) {
return request({
url: `/api/v1/ops/playbook/${playbookId}/file/`,
method: 'patch',
data: node
})
}
export function createJob(form) {
return request({
url: '/api/v1/ops/jobs/',
method: 'post',
data: form
})
}

View File

@@ -1,21 +0,0 @@
import request from '@/utils/request'
export function getOrgDetail(oid) {
return request({
url: `/api/v1/orgs/orgs/current/?oid=${oid}`,
method: 'get'
})
}
export function getCurrentOrg() {
return request({
url: `/api/v1/orgs/orgs/current/`,
method: 'get'
})
}
export default {
getCurrentOrg,
getOrgDetail
}

View File

@@ -0,0 +1,43 @@
import request from '@/utils/request'
export function getAssetPermissionDetail(id) {
return request({
url: `/api/v1/perms/asset-permissions/${id}/`,
method: 'get'
})
}
export function getRemoteAppPermissionDetail(id) {
return request({
url: `/api/v1/perms/remote-app-permissions/${id}/`,
method: 'get'
})
}
export function getDatabaseAppPermissionDetail(id) {
return request({
url: `/api/v1/perms/database-app-permissions/${id}/`,
method: 'get'
})
}
export function getUserAssetGrantedSystemUsers(userId, assetId) {
return request({
url: `/api/v1/perms/users/${userId}/assets/${assetId}/system-users/?cache_policy=1`,
method: 'get'
})
}
export function getMyAssetGrantedSystemUsers(userId, assetId) {
return request({
url: `/api/v1/perms/users/assets/${assetId}/system-users/?cache_policy=1`,
method: 'get'
})
}
export function getUserGroupAssetGrantedSystemUsers(gId, assetId) {
return request({
url: `/api/v1/perms/user-groups/${gId}/assets/${assetId}/system-users/?cache_policy=1`,
method: 'get'
})
}

View File

@@ -8,11 +8,24 @@ export function terminateSession(data) {
})
}
export function toggleLockSession(data) {
export function getSessionDetail(id) {
return request({
url: '/api/v1/terminal/tasks/toggle-lock-session/',
method: 'post',
data: data
url: `/api/v1/terminal/sessions/${id}/`,
method: 'get'
})
}
export function getSessionCommands(id) {
return request({
url: `/api/v1/terminal/commands/?session_id=${id}`,
method: 'get'
})
}
export function getTerminalDetail(id) {
return request({
url: `/api/v1/terminal/terminals/${id}/`,
method: 'get'
})
}
@@ -44,26 +57,6 @@ export function TestReplayStorage(id) {
})
}
function SetToDefaultStorage(url) {
return request({
url: url,
method: 'patch',
data: { 'is_default': true }
})
}
export function SetToDefaultCommandStorage(id) {
return SetToDefaultStorage(
`/api/v1/terminal/command-storages/${id}/`,
)
}
export function SetToDefaultReplayStorage(id) {
return SetToDefaultStorage(
`/api/v1/terminal/replay-storages/${id}/`,
)
}
export function getReplayStorage(id) {
return request({
url: `/api/v1/terminal/replay-storages/${id}/`,

View File

@@ -25,28 +25,12 @@ export function importLicense(formData) {
data: formData
})
}
export function testLdapSetting(data, refresh = true) {
let url = '/api/v1/settings/ldap/testing/config/'
if (refresh) {
url = url + '?refresh=1'
}
return new Promise((resolve, reject) => {
request({
disableFlashErrorMsg: true,
url: url,
method: 'post',
data: data
}).then(res => {
if (res.status !== 'running') {
resolve(res)
} else {
setTimeout(() => {
resolve(testLdapSetting(data, false))
}, 1000)
}
}).catch(error => {
reject(error)
})
export function testLdapSetting(data) {
return request({
disableFlashErrorMsg: true,
url: '/api/v1/settings/ldap/testing/config/',
method: 'post',
data: data
})
}
@@ -67,7 +51,7 @@ export function refreshLdapUserCache() {
})
}
export function startLdapUserCache() {
export function StartLdapUserCache() {
return request({
disableFlashErrorMsg: true,
url: '/api/v1/settings/ldap/users/?cache_police=1',
@@ -84,21 +68,15 @@ export function importLdapUser(data) {
})
}
export function getPublicSettings(isOpen) {
let url
if (isOpen) {
url = '/api/v1/settings/public/open/'
} else {
url = '/api/v1/settings/public/'
}
export function getPublicSettings() {
return request({
url: url,
url: '/api/v1/settings/public/',
method: 'get'
})
}
export function getLogo() {
return request({
url: '/api/v1/xpack/interface/setting/',
url: '/api/v1/xpack/interface/setting',
method: 'get'
})
}

View File

@@ -1,8 +0,0 @@
import request from '@/utils/request'
export function getTicketOpenCount(assign) {
return request({
url: `/api/v1/tickets/tickets/?assignees__id=${assign}&status=open&offset=0&limit=15&display=1&draw=1/`,
method: 'get'
})
}

View File

@@ -65,12 +65,3 @@ export function logout() {
method: 'post'
})
}
export function refreshSessionIdAge() {
return getProfile()
}
export default {
getProfile,
getUserList
}

BIN
src/assets/img/admin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

BIN
src/assets/img/header-profile.png Normal file → Executable file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

BIN
src/assets/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

View File

@@ -1,15 +1,40 @@
<template>
<DataActions :actions="iActions" v-bind="$attrs" />
<div :class="grouped ? 'el-button-group' : ''">
<el-button v-for="item in iActions" :key="item.name" :size="size" v-bind="item" @click="handleClick(item.name)">
<el-tooltip v-if="['actionExport', 'actionImport', 'actionRefresh'].indexOf(item.name) !== -1" effect="dark" :content="item.tip" placement="top">
<i v-if="item.fa" :class="'fa ' + item.fa" />{{ item.title }}
</el-tooltip>
<span v-else>
<i v-if="item.fa" :class="'fa ' + item.fa" />{{ item.title }}
</span>
</el-button>
<el-dropdown v-if="iMoreActions.length > 0" trigger="click" :placement="moreActionsPlacement" @command="handleClick">
<el-button :size="size" :type="moreActionsType" class="btn-more-actions">
{{ iMoreActionsTitle }}<i class="el-icon-arrow-down el-icon--right" />
</el-button>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item v-for="item in iMoreActions" :key="item.name" :command="item.name" v-bind="item" @click="handleClick(item.name)">{{ item.title }} </el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</template>
<script>
import DataActions from '@/components/DataActions'
export default {
name: 'ActionsGroup',
components: {
DataActions
},
props: {
grouped: {
type: Boolean,
default: false
},
size: {
type: String,
default: 'small'
},
type: {
type: String,
default: ''
},
actions: {
type: Array,
default: () => []
@@ -18,16 +43,16 @@ export default {
type: Array,
default: () => []
},
moreActionBtn: {
type: Object,
default: () => ({})
},
moreActionsTitle: {
type: String,
default() {
return this.$t('common.MoreActions')
}
},
moreActionsType: {
type: String,
default: 'default'
},
moreActionsPlacement: {
type: String,
default: 'bottom'
@@ -36,28 +61,73 @@ export default {
},
computed: {
iActions() {
const actions = [...this.actions]
if (this.iMoreAction && this.iMoreAction.dropdown.length > 0) {
actions.push(this.iMoreAction)
return this.cleanActions(this.actions)
},
iMoreActions() {
return this.cleanActions(this.moreActions)
},
totalActions() {
return [...this.actions, ...this.moreActions]
},
totalNamedActions() {
const actions = {}
for (const action of this.totalActions) {
if (!action || !action.hasOwnProperty('name')) {
continue
}
actions[action.name] = action
}
return actions
},
iMoreAction() {
const defaultBtn = {
name: 'moreActions',
title: this.$t('common.MoreActions'),
type: 'primary',
plain: true
iMoreActionsTitle() {
return this.moreActionsTitle || this.$t('common.MoreActions')
}
},
methods: {
handleClick(item) {
const action = this.totalNamedActions[item]
if (action && action.callback) {
action.callback(action)
} else {
this.$log.debug('No callback found')
}
const btn = {
...defaultBtn,
...this.moreActionBtn,
dropdown: this.moreActions || []
this.$emit('actionClick', item)
},
checkItem(item, attr, defaults) {
if (!item) {
return true
}
if (this.moreActionsTitle) {
btn.title = this.moreActionsTitle
let ok = item[attr]
if (ok && typeof ok === 'function') {
ok = ok(item)
} else if (ok == null) {
ok = defaults === undefined ? true : defaults
}
return btn
return ok
},
cleanActions(actions) {
const cleanedActions = []
const cloneActions = _.cloneDeep(actions)
for (const v of cloneActions) {
if (!v) {
continue
}
const action = Object.assign({}, v)
// 是否拥有这个action
const has = this.checkItem(action, 'has')
delete action['has']
if (!has) {
continue
}
// 是否是disabled
const can = this.checkItem(action, 'can')
delete action['can']
action.disabled = !can
cleanedActions.push(action)
// 删掉callback避免前台看到
delete action['callback']
}
return cleanedActions
}
}
}

View File

@@ -1,325 +0,0 @@
<template>
<AutoDataForm
v-if="!loading"
ref="AutoDataForm"
v-bind="$data"
@submit="confirm"
/>
</template>
<script>
import AutoDataForm from '@/components/Form/AutoDataForm/index.vue'
import { UpdateToken, UploadSecret } from '@/components/Form/FormFields'
import Select2 from '@/components/Form/FormFields/Select2.vue'
import AssetSelect from '@/components/Apps/AssetSelect/index.vue'
import { encryptPassword } from '@/utils/crypto'
import { Required, RequiredChange } from '@/components/Form/DataForm/rules'
import AutomationParamsForm from '@/views/assets/Platform/AutomationParamsSetting.vue'
export default {
name: 'AccountCreateForm',
components: {
AutoDataForm
},
props: {
asset: {
type: Object,
default: null
},
platform: {
type: Object,
default: null
},
account: {
type: Object,
default: () => ({})
},
// 默认组件密码加密
encryptPassword: {
type: Boolean,
default: true
},
addTemplate: {
type: Boolean,
default: false
}
},
data() {
return {
loading: true,
usernameChanged: false,
defaultPrivilegedAccounts: ['root', 'administrator'],
iPlatform: {
automation: {},
su_enabled: false,
protocols: [
{
name: 'ssh',
secret_types: ['password', 'ssh_key', 'token', 'access_key', 'api_key']
}
]
},
url: '/api/v1/accounts/accounts/',
form: Object.assign({ 'on_invalid': 'error' }, this.account || {}),
encryptedFields: ['secret'],
fields: [
[this.$t('assets.Asset'), ['assets']],
[this.$t('accounts.AccountTemplate'), ['template']],
[this.$t('common.Basic'), ['name', 'username', 'privileged', 'su_from', 'su_from_username']],
[this.$t('assets.Secret'), [
'secret_type', 'password', 'ssh_key', 'token',
'access_key', 'passphrase', 'api_key'
]],
[this.$t('common.Other'), ['push_now', 'params', 'on_invalid', 'is_active', 'comment']]
],
fieldsMeta: {
assets: {
rules: [Required],
component: AssetSelect,
label: this.$t('assets.Asset'),
el: {
multiple: false
},
hidden: () => {
return this.platform || this.asset
}
},
template: {
component: Select2,
rules: [Required],
el: {
multiple: false,
ajax: {
url: '/api/v1/accounts/account-templates/',
transformOption: (item) => {
return { label: item.name, value: item.id }
}
}
},
hidden: () => {
return this.platform || this.asset || !this.addTemplate
}
},
on_invalid: {
rules: [Required],
label: this.$t('accounts.AccountPolicy'),
helpText: this.$t('accounts.BulkCreateStrategy'),
hidden: () => {
return this.platform || this.asset
}
},
name: {
rules: [RequiredChange],
on: {
input: ([value], updateForm) => {
if (!this.usernameChanged) {
if (!this.account?.name) {
updateForm({ username: value })
}
const maybePrivileged = this.defaultPrivilegedAccounts.includes(value)
if (maybePrivileged) {
updateForm({ privileged: true })
}
}
}
},
hidden: () => {
return this.addTemplate
}
},
username: {
el: {
disabled: !!this.account?.name
},
on: {
input: ([value], updateForm) => {
this.usernameChanged = true
},
change: ([value], updateForm) => {
const maybePrivileged = this.defaultPrivilegedAccounts.includes(value)
if (maybePrivileged) {
updateForm({ privileged: true })
}
}
},
hidden: () => {
return this.addTemplate
}
},
privileged: {
hidden: () => {
return this.addTemplate
}
},
su_from: {
component: Select2,
hidden: (formValue) => {
return !this.asset?.id || !this.iPlatform.su_enabled
},
el: {
multiple: false,
clearable: true,
ajax: {
url: `/api/v1/accounts/accounts/su-from-accounts/?account=${this.account?.id || ''}&asset=${this.asset?.id || ''}`,
transformOption: (item) => {
return { label: `${item.name}(${item.username})`, value: item.id }
}
}
}
},
su_from_username: {
label: this.$t('assets.UserSwitchFrom'),
hidden: (formValue) => {
return this.platform || this.asset || this.addTemplate
}
},
password: {
label: this.$t('assets.Password'),
component: UpdateToken,
hidden: (formValue) => formValue.secret_type !== 'password' || this.addTemplate
},
ssh_key: {
label: this.$t('assets.PrivateKey'),
component: UploadSecret,
hidden: (formValue) => formValue.secret_type !== 'ssh_key' || this.addTemplate
},
passphrase: {
label: this.$t('assets.Passphrase'),
component: UpdateToken,
hidden: (formValue) => formValue.secret_type !== 'ssh_key' || this.addTemplate
},
token: {
label: this.$t('assets.Token'),
component: UploadSecret,
hidden: (formValue) => formValue.secret_type !== 'token' || this.addTemplate
},
access_key: {
id: 'access_key',
label: this.$t('assets.AccessKey'),
component: UploadSecret,
hidden: (formValue) => formValue.secret_type !== 'access_key' || this.addTemplate
},
api_key: {
id: 'api_key',
label: this.$t('assets.ApiKey'),
component: UploadSecret,
hidden: (formValue) => formValue.secret_type !== 'api_key' || this.addTemplate
},
secret_type: {
type: 'radio-group',
options: [],
hidden: () => {
return this.addTemplate
}
},
push_now: {
helpText: this.$t('accounts.AccountPush.WindowsPushHelpText'),
hidden: (formValue) => {
const automation = this.iPlatform.automation || {}
return !automation.push_account_enabled ||
!automation.ansible_enabled ||
!this.$hasPerm('accounts.push_account') ||
(formValue.secret_type === 'ssh_key' && this.iPlatform.type.value === 'windows') ||
this.addTemplate
}
},
params: {
label: this.$t('assets.PushParams'),
component: AutomationParamsForm,
el: {
method: this.asset?.auto_config?.push_account_method
},
hidden: (formValue) => {
const automation = this.iPlatform.automation || {}
return !formValue.push_now ||
!automation.push_account_enabled ||
!automation.ansible_enabled ||
!this.$hasPerm('accounts.push_account') ||
this.addTemplate
}
},
comment: {
hidden: () => {
return this.addTemplate
}
}
},
hasSaveContinue: false
}
},
async mounted() {
try {
await this.getPlatform()
this.setSecretTypeOptions()
} finally {
this.loading = false
}
},
methods: {
async getPlatform() {
if (this.platform) {
this.iPlatform = this.platform
}
if (!this.asset || !this.asset.platform) {
return
}
const platformId = this.asset.platform.id
this.iPlatform = await this.$axios.get(`/api/v1/assets/platforms/${platformId}/`)
},
setSecretTypeOptions() {
const choices = [
{
label: this.$t('assets.Password'),
value: 'password'
},
{
label: this.$t('assets.SSHKey'),
value: 'ssh_key'
},
{
label: this.$t('assets.Token'),
value: 'token'
},
{
label: this.$t('assets.AccessKey'),
value: 'access_key'
},
{
label: this.$t('assets.ApiKey'),
value: 'api_key'
}
]
const secretTypes = []
this.iPlatform.protocols?.forEach(p => {
secretTypes.push(...p['secret_types'])
})
if (!this.form?.secret_type) {
this.form.secret_type = secretTypes[0]
}
this.fieldsMeta.secret_type.options = choices.filter(item => {
return secretTypes.indexOf(item.value) > -1
})
},
confirm(form) {
const secretType = form.secret_type || 'password'
form.secret = form[secretType]
form.secret = this.encryptPassword ? encryptPassword(form.secret) : form.secret
// 如果不删除会明文显示
delete form[secretType]
if (!form.secret) {
delete form['secret']
}
if (this.account?.name) {
this.$emit('edit', form)
} else {
this.$emit('add', form)
}
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,167 +0,0 @@
<template>
<GenericCreateUpdateDrawer v-bind="$attrs">
<AccountCreateUpdateForm
v-if="!loading"
ref="form"
:account="account"
:add-template="addTemplate"
:asset="asset"
@add="addAccount"
@edit="editAccount"
/>
</GenericCreateUpdateDrawer>
</template>
<script>
import GenericCreateUpdateDrawer from '@/layout/components/GenericCreateUpdateDrawer/index.vue'
import AccountCreateUpdateForm from '@/components/Apps/AccountCreateUpdateForm/index.vue'
export default {
name: 'CreateAccountDialog',
components: {
AccountCreateUpdateForm,
GenericCreateUpdateDrawer
},
props: {
visible: {
type: Boolean,
default: false
},
addTemplate: {
type: Boolean,
default: false
},
asset: {
type: Object,
default: null
},
account: {
type: Object,
default: () => ({})
},
title: {
type: String,
default: function() {
return this.$t('assets.AddAccount')
}
}
},
data() {
return {
loading: false,
platform: {}
}
},
computed: {
protocols() {
return this.asset ? this.asset.protocol : []
},
iVisible: {
get() {
return this.visible
},
set(val) {
this.$emit('update:visible', val)
}
}
},
methods: {
addAccount(form) {
const formValue = Object.assign({}, form)
let data, url, iVisible
if (this.asset) {
data = {
asset: this.asset.id,
...formValue
}
iVisible = false
url = `/api/v1/accounts/accounts/`
} else {
iVisible = true
data = formValue
url = `/api/v1/accounts/accounts/bulk/`
if (data.assets.length === 0) {
this.$message.error(this.$tc('assets.PleaseSelectAsset'))
return
}
}
this.$axios.post(url, data, {
disableFlashErrorMsg: iVisible
}).then((data) => {
this.handleResult(data, null)
this.iVisible = iVisible
if (!iVisible) {
this.$emit('add', true)
}
}).catch(error => {
this.iVisible = true
this.handleResult(null, error)
})
},
editAccount(form) {
const data = { ...form }
this.$axios.patch(`/api/v1/accounts/accounts/${this.account.id}/`, data).then(() => {
this.iVisible = false
this.$emit('add', true)
this.$message.success(this.$tc('common.updateSuccessMsg'))
}).catch(error => this.setFieldError(error))
},
handleResult(resp, error) {
let bulkCreate = !this.asset
if (error && !Array.isArray(error?.response?.data)) {
bulkCreate = false
}
if (resp && !Array.isArray(resp)) {
bulkCreate = false
}
if (!bulkCreate) {
if (!error) {
this.$message.success(this.$tc('common.createSuccessMsg'))
} else {
this.setFieldError(error)
}
} else {
let result
if (error) {
result = error.response.data
} else {
result = resp
}
this.$emit('bulk-create-done', result)
}
},
setFieldError(error) {
const response = error.response
const data = response.data
const refsAutoDataForm = this.$refs.form.$refs.AutoDataForm
if (response.status === 400) {
for (const key of Object.keys(data)) {
let err = ''
let current = key
let errorTips = data[current]
if (errorTips instanceof Array) {
errorTips = _.filter(errorTips, (item) => Object.keys(item).length > 0)
for (const i of errorTips) {
if (i instanceof Object) {
err += i?.port?.join(',')
} else {
err += errorTips
}
}
} else {
err = errorTips
}
if (current === 'secret') {
current = refsAutoDataForm.form.secret_type?.value || key
}
refsAutoDataForm.setFieldError(current, err)
}
}
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,428 +0,0 @@
<template>
<div>
<ListTable ref="ListTable" :header-actions="headerActions" :table-config="tableConfig" />
<ViewSecret
v-if="showViewSecretDialog"
:account="account"
:url="secretUrl"
:visible.sync="showViewSecretDialog"
/>
<UpdateSecretInfo
v-if="showUpdateSecretDialog"
:account="account"
:visible.sync="showUpdateSecretDialog"
@updateAuthDone="onUpdateAuthDone"
/>
<AccountCreateUpdate
:url="url"
:asset="iAsset"
:account="account"
:add-template="addTemplate"
:title="accountCreateUpdateTitle"
@add="addAccountSuccess"
@bulk-create-done="showBulkCreateResult($event)"
/>
<ResultDialog
v-if="showResultDialog"
:result="createAccountResults"
:visible.sync="showResultDialog"
/>
</div>
</template>
<script>
import ListTable from '@/components/Table/ListTable/index.vue'
import { ActionsFormatter } from '@/components/Table/TableFormatters'
import ViewSecret from './ViewSecret.vue'
import UpdateSecretInfo from './UpdateSecretInfo.vue'
import AccountCreateUpdate from './AccountCreateUpdate.vue'
import { connectivityMeta } from './const'
import { openTaskPage } from '@/utils/jms'
import ResultDialog from './BulkCreateResultDialog.vue'
export default {
name: 'AccountListTable',
components: {
ResultDialog,
ListTable,
UpdateSecretInfo,
ViewSecret,
AccountCreateUpdate
},
props: {
url: {
type: String,
required: true
},
exportUrl: {
type: String,
default() {
return this.url.replace('/accounts/accounts/', '/accounts/account-secrets/')
}
},
hasLeftActions: {
type: Boolean,
default: false
},
otherActions: {
type: Array,
default: null
},
hasClone: {
type: Boolean,
default: false
},
asset: {
type: Object,
default: null
},
columns: {
type: Array,
default: () => []
},
hasExport: {
type: Boolean,
default: true
},
hasImport: {
type: Boolean,
default: true
},
hasDeleteAction: {
type: Boolean,
default: true
},
columnsMeta: {
type: Object,
default: () => {
}
},
columnsDefault: {
type: Array,
default: () => ([
'name', 'username', 'asset', 'privileged',
'secret_type', 'is_active', 'date_updated'
])
},
headerExtraActions: {
type: Array,
default: () => []
}
},
data() {
const vm = this
return {
showViewSecretDialog: false,
showUpdateSecretDialog: false,
showResultDialog: false,
showAddDialog: false,
showAddTemplateDialog: false,
createAccountResults: [],
addTemplate: false,
accountCreateUpdateTitle: this.$t('assets.AddAccount'),
iAsset: this.asset,
account: {},
secretUrl: '',
tableConfig: {
url: this.url,
permissions: {
app: 'assets',
resource: 'account'
},
extraQuery: {
order: '-date_updated'
},
columnsExclude: ['spec_info'],
columnsShow: {
min: ['name', 'username', 'actions'],
default: this.columnsDefault
},
columnsMeta: {
name: {
formatter: function(row) {
const to = {
name: 'AssetAccountDetail',
params: { id: row.id }
}
if (vm.$hasPerm('accounts.view_account')) {
return <router-link to={to}>{row.name}</router-link>
} else {
return <span>{row.name}</span>
}
}
},
asset: {
label: this.$t('assets.Asset'),
formatter: function(row) {
const to = {
name: 'AssetDetail',
params: { id: row.asset.id }
}
if (vm.$hasPerm('assets.view_asset')) {
return <router-link to={to}>{row.asset.name}</router-link>
} else {
return <span>{row.asset.name}</span>
}
}
},
secret_type: {
width: '100px',
formatter: function(row) {
return row.secret_type.label
}
},
source: {
formatter: function(row) {
return row.source.label
}
},
has_secret: {
width: '100px',
formatterArgs: {
showFalse: false
}
},
privileged: {
label: this.$t('assets.Privileged'),
width: '120px',
formatterArgs: {
showText: false,
showFalse: false
}
},
connectivity: connectivityMeta,
actions: {
formatter: ActionsFormatter,
formatterArgs: {
hasUpdate: false, // can set function(row, value)
hasDelete: false, // can set function(row, value)
hasClone: this.hasClone,
moreActionsTitle: this.$t('common.More'),
extraActions: [
{
name: 'View',
title: this.$t('common.View'),
can: this.$hasPerm('accounts.view_accountsecret'),
type: 'primary',
callback: ({ row }) => {
// debugger
vm.secretUrl = `/api/v1/accounts/account-secrets/${row.id}/`
vm.account = row
vm.showViewSecretDialog = false
setTimeout(() => {
vm.showViewSecretDialog = true
})
}
},
{
name: 'ClearSecret',
title: this.$t('common.ClearSecret'),
can: this.$hasPerm('accounts.change_account'),
type: 'primary',
callback: ({ row }) => {
this.$axios.patch(
`/api/v1/accounts/accounts/clear-secret/`,
{ account_ids: [row.id] }
).then(() => {
this.$message.success(this.$tc('common.ClearSuccessMsg'))
})
}
},
{
name: 'Test',
title: this.$t('common.Test'),
can: ({ row }) =>
!this.$store.getters.currentOrgIsRoot &&
this.$hasPerm('accounts.change_account') &&
row.asset['auto_config'].ansible_enabled &&
row.asset['auto_config'].ping_enabled,
callback: ({ row }) => {
this.$axios.post(
`/api/v1/accounts/accounts/tasks/`,
{ action: 'verify', accounts: [row.id] }
).then(res => {
openTaskPage(res['task'])
})
}
},
{
name: 'Update',
title: this.$t('common.Update'),
can: this.$hasPerm('accounts.change_account') && !this.$store.getters.currentOrgIsRoot,
callback: ({ row, col }) => {
const data = {
...this.asset,
...row.asset
}
vm.account = row
vm.iAsset = data
vm.showAddDialog = false
vm.addTemplate = false
vm.accountCreateUpdateTitle = this.$t('assets.UpdateAccount')
setTimeout(() => {
vm.$eventBus.$emit('showCreateUpdateDrawer', 'update', { url: this.url, row, col })
})
}
}
]
}
},
...this.columnsMeta
}
},
headerActions: {
hasLeftActions: this.hasLeftActions,
hasMoreActions: true,
hasCreate: false,
hasImport: this.hasImport,
hasExport: this.hasExport && this.$hasPerm('accounts.view_accountsecret'),
handleImportClick: ({ selectedRows }) => {
this.$eventBus.$emit('showImportDialog', {
selectedRows,
url: '/api/v1/accounts/accounts/',
name: this?.name
})
},
exportOptions: {
url: this.exportUrl,
mfaVerifyRequired: true,
tips: this.$t('accounts.AccountExportTips')
},
importOptions: {
canImportCreate: this.$hasPerm('accounts.add_account'),
canImportUpdate: this.$hasPerm('accounts.change_account')
},
extraActions: [
{
name: 'add',
title: this.$t('common.Add'),
type: 'primary',
can: () => {
return vm.$hasPerm('accounts.add_account') && !this.$store.getters.currentOrgIsRoot
},
callback: async() => {
await this.getAssetDetail()
setTimeout(() => {
vm.iAsset = this.asset
vm.account = {}
vm.addTemplate = false
vm.accountCreateUpdateTitle = this.$t('assets.AddAccount')
vm.$eventBus.$emit('showCreateUpdateDrawer', 'create', { url: vm.url })
})
}
},
{
name: 'add-template',
title: this.$t('common.TemplateAdd'),
has: !(this.platform || this.asset),
can: () => {
return vm.$hasPerm('accounts.add_account') && !this.$store.getters.currentOrgIsRoot
},
callback: async() => {
await this.getAssetDetail()
setTimeout(() => {
vm.iAsset = this.asset
vm.account = {}
vm.addTemplate = true
vm.accountCreateUpdateTitle = this.$t('assets.AddAccount')
vm.$eventBus.$emit('showCreateUpdateDrawer', 'create', { url: vm.url })
})
}
},
...this.headerExtraActions
],
extraMoreActions: [
{
name: 'ClearSecrets',
title: this.$t('common.ClearSecret'),
type: 'primary',
fa: 'clean',
can: ({ selectedRows }) => {
return selectedRows.length > 0 && vm.$hasPerm('accounts.change_account')
},
callback: function({ selectedRows }) {
const ids = selectedRows.map(v => { return v.id })
this.$axios.patch(
'/api/v1/accounts/accounts/clear-secret/',
{ account_ids: ids }).then(() => {
this.$message.success(this.$tc('common.ClearSuccessMsg'))
}).catch(err => {
this.$message.error(this.$tc('common.bulkClearErrorMsg' + ' ' + err))
})
}.bind(this)
}
],
canBulkDelete: vm.$hasPerm('accounts.delete_account'),
searchConfig: {
getUrlQuery: false,
exclude: ['asset']
},
hasSearch: true
}
}
},
watch: {
url(iNew) {
this.$set(this.tableConfig, 'url', iNew)
this.$set(this.headerActions.exportOptions, 'url', iNew.replace(/(.*)accounts/, '$1account-secrets'))
}
},
mounted() {
if (this.columns.length > 0) {
this.tableConfig.columns = this.columns
}
if (this.otherActions) {
const actionColumn = this.tableConfig.columns[this.tableConfig.columns.length - 1]
for (const item of this.otherActions) {
actionColumn.formatterArgs.extraActions.push(item)
}
}
if (this.hasDeleteAction) {
this.tableConfig.columnsMeta.actions.formatterArgs.extraActions.push(
{
name: 'Delete',
title: this.$t('common.Delete'),
can: this.$hasPerm('accounts.delete_account'),
type: 'primary',
callback: ({ row }) => {
this.$axios.delete(`/api/v1/accounts/accounts/${row.id}/`).then(() => {
this.$message.success(this.$tc('common.deleteSuccessMsg'))
this.$refs.ListTable.reloadTable()
})
}
}
)
}
},
methods: {
onUpdateAuthDone(account) {
Object.assign(this.account, account)
},
addAccountSuccess() {
this.$refs.ListTable.reloadTable()
},
async getAssetDetail() {
const { query: { asset }} = this.$route
if (asset) {
this.iAsset = await this.$axios.get(`/api/v1/assets/assets/${asset}/`)
}
},
refresh() {
this.$refs.ListTable.reloadTable()
},
showBulkCreateResult(results) {
this.showResultDialog = false
this.createAccountResults = results
setTimeout(() => {
this.showResultDialog = true
}, 100)
}
}
}
</script>
<style lang='scss' scoped>
.cell a {
color: var(--color-info);
}
</style>

View File

@@ -1,120 +0,0 @@
<template>
<Dialog
:show-cancel="false"
:title="title"
v-bind="$attrs"
@confirm="closeDialog"
v-on="$listeners"
>
<el-alert style="margin-bottom: 10px" type="success">
<span v-for="item of summary" :key="item.key"><b>{{ item.label }}</b>: {{ item.value }} </span>
</el-alert>
<DataTable :config="config" />
</Dialog>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import DataTable from '@/components/Table/DataTable/index.vue'
export default {
name: 'ResultDialog',
components: {
DataTable,
Dialog
},
props: {
result: {
type: Array,
default: () => []
}
},
data() {
const errorProp = this.$t('common.Error')
const stateMap = {
'created': this.$tc('common.Created'),
'updated': this.$tc('common.Updated'),
'skipped': this.$tc('common.Skipped')
}
const stateClsMap = {
'created': 'color-primary',
'updated': 'color-success',
'skipped': 'color-default'
}
return {
title: this.$t('accounts.AddAccountResult'),
config: {
columns: [
{
prop: 'asset',
label: this.$t('assets.Asset')
},
{
prop: 'state',
label: this.$t('common.Status'),
width: '200px',
formatter: (row) => {
if (row.error) {
return <span class='color-error'>{ errorProp }: { row.error }</span>
} else if (row.state) {
const colorCls = stateClsMap[row.state]
const state = stateMap[row.state]
return <span class={ colorCls }>{ state }</span>
}
}
}
],
totalData: this.result
}
}
},
computed: {
summary() {
const labels = {
total: this.$tc('common.Total'),
created: this.$tc('common.Created'),
updated: this.$tc('common.Updated'),
skipped: this.$tc('common.Skipped'),
error: this.$tc('common.Error')
}
const grouped = _.groupBy(this.result, 'state')
const groupedLength = _.mapValues(grouped, 'length')
groupedLength['total'] = this.result.length
return _.map(groupedLength, (value, key) => {
return {
label: labels[key],
value: value,
key: key
}
})
}
},
methods: {
closeDialog() {
this.$emit('update:visible', false)
}
}
}
</script>
<style scoped>
.color-error {
color: var(--color-danger);
}
.color-primary {
color: var(--color-primary);
}
.color-success {
color: var(--color-success);
}
.color-default {
}
::v-deep .el-data-table .el-table .el-table__row > td > div > span {
white-space: inherit;
}
</style>

View File

@@ -1,78 +0,0 @@
<template>
<GenericListTableDialog :visible.sync="iVisible" v-bind="config" />
</template>
<script>
import { GenericListTableDialog } from '@/layout/components'
import { ShowKeyCopyFormatter } from '@/components/Table/TableFormatters'
export default {
components: {
GenericListTableDialog
},
props: {
account: {
type: Object,
default: () => ({})
},
visible: {
type: Boolean,
default: false
}
},
data() {
return {
config: {
title: this.$t('accounts.HistoryPassword'),
visible: false,
width: '60%',
tableConfig: {
id: 'history_date',
url: `/api/v1/accounts/account-secrets/${this.account.id}/histories/`,
columns: ['secret', 'version', 'history_date'],
columnsMeta: {
secret: {
label: this.$t('assets.Password'),
formatter: ShowKeyCopyFormatter,
formatterArgs: {
hasDownload: false,
name: this.account.name
}
},
history_date: {
label: this.$t('accounts.HistoryDate')
},
secret_type: {
width: '200px'
},
version: {
width: '100px'
},
actions: {
has: false
}
}
},
headerActions: {
hasLeftActions: false,
hasSearch: false
}
}
}
},
computed: {
iVisible: {
get() {
return this.visible
},
set(val) {
this.$emit('update:visible', val)
}
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,99 +0,0 @@
<template>
<Dialog
:destroy-on-close="true"
:title="$tc('assets.UpdateAssetUserToken')"
:visible.sync="visible"
width="50"
@cancel="handleCancel()"
@confirm="handleConfirm()"
v-on="$listeners"
>
<el-form label-position="right" label-width="90px">
<el-form-item :label="$tc('assets.Name')">
<el-input v-model="account['asset_name']" readonly />
</el-form-item>
<el-form-item :label="$tc('assets.Username')">
<el-input v-model="account['username']" readonly />
</el-form-item>
<el-form-item :label="$tc('assets.Password')">
<UpdateToken v-model="authInfo.password" />
</el-form-item>
<el-form-item :label="$tc('assets.SSHSecretKey')">
<UploadKey @input="getFile" />
</el-form-item>
<el-form-item :label="$tc('assets.Passphrase')">
<UpdateToken v-model="authInfo.passphrase" />
</el-form-item>
</el-form>
</Dialog>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import { UpdateToken, UploadKey } from '@/components/Form/FormFields'
import { encryptPassword } from '@/utils/crypto'
export default {
name: 'UpdateSecretInfo',
components: {
Dialog,
UploadKey,
UpdateToken
},
props: {
account: {
type: Object,
default: () => ({})
},
visible: {
type: Boolean,
default: false
}
},
data() {
return {
secretInfo: {
password: '',
private_key: '',
passphrase: ''
}
}
},
methods: {
handleConfirm() {
const data = {}
if (this.secretInfo.password !== '') {
data.password = encryptPassword(this.secretInfo.password)
}
if (this.secretInfo.private_key !== '') {
data.private_key = encryptPassword(this.secretInfo.private_key)
if (this.secretInfo.passphrase) data.passphrase = this.secretInfo.passphrase
}
this.$axios.patch(
`/api/v1/accounts/accounts/${this.account.id}/`,
data,
{ disableFlashErrorMsg: true }
).then(res => {
this.authInfo = { password: '', private_key: '' }
this.$message.success(this.$tc('common.updateSuccessMsg'))
this.$emit('updateAuthDone', res)
this.$emit('update:visible', false)
}).catch(err => {
const errMsg = Object.values(err.response.data).join(', ')
this.$message.error(this.$tc('common.updateErrorMsg') + ' ' + errMsg)
this.$emit('update:visible', true)
})
},
handleCancel() {
this.$emit('update:visible', false)
},
getFile(file) {
this.secretInfo.private_key = file
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,209 +0,0 @@
<template>
<div>
<Dialog
:destroy-on-close="true"
:show-cancel="false"
:title="title"
:visible.sync="showSecret"
:width="'50'"
v-bind="$attrs"
@confirm="accountConfirmHandle"
v-on="$listeners"
>
<el-form :model="secretInfo" class="password-form" label-position="right" label-width="100px">
<el-form-item :label="$tc('assets.Name')">
<span>{{ account['name'] }}</span>
</el-form-item>
<el-form-item :label="$tc('assets.Username')">
<span>{{ account['username'] }}</span>
</el-form-item>
<el-form-item :label="secretTypeLabel">
<ShowKeyCopyFormatter
:cell-value="secretInfo.secret"
:col="{ formatterArgs: {
name: account['name'],
secretType: secretType || ''
}}"
@input="onShowKeyCopyFormatterChange"
/>
</el-form-item>
<el-form-item v-if="secretType === 'ssh_key'" :label="$tc('assets.sshKeyFingerprint')">
<span>{{ sshKeyFingerprint }}</span>
</el-form-item>
<el-form-item :label="$tc('common.DateCreated')">
<span>{{ account['date_created'] | date }}</span>
</el-form-item>
<el-form-item :label="$tc('common.DateUpdated')">
<span>{{ account['date_updated'] | date }}</span>
</el-form-item>
<el-form-item v-if="showPasswordRecord" v-perms="'accounts.view_accountsecret'" :label="$tc('accounts.PasswordRecord')">
<el-link
:underline="false"
type="success"
@click="showHistoryDialog"
>
<span style="padding-right: 30px">
{{ versions }}
</span>
</el-link>
</el-form-item>
</el-form>
</Dialog>
<PasswordHistoryDialog
v-if="showPasswordHistoryDialog"
:account="account"
:visible.sync="showPasswordHistoryDialog"
/>
</div>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import PasswordHistoryDialog from './PasswordHistoryDialog.vue'
import { ShowKeyCopyFormatter } from '@/components/Table/TableFormatters'
import { encryptPassword } from '@/utils/crypto'
export default {
name: 'ShowSecretInfo',
components: {
Dialog,
PasswordHistoryDialog,
ShowKeyCopyFormatter
},
props: {
account: {
type: Object,
default: () => ({})
},
visible: {
type: Boolean,
default: false
},
url: {
type: String,
default: ''
},
title: {
type: String,
default: function() {
return this.$tc('assets.AccountDetail')
}
},
showPasswordRecord: {
type: Boolean,
default: true
}
},
data() {
return {
modifiedSecret: '',
secretInfo: {},
versions: '-',
showSecret: false,
mfaDialogVisible: true,
sshKeyFingerprint: '-',
historyCount: 0,
showPasswordHistoryDialog: false
}
},
computed: {
secretTypeLabel() {
return this.account['secret_type'].label || 'Password'
},
secretType() {
return this.account['secret_type'].value
}
},
mounted() {
if (this.showPasswordRecord) {
const url = `/api/v1/accounts/account-secrets/${this.account.id}/histories/?limit=1`
this.$axios.get(url, { disableFlashErrorMsg: true }).then(resp => {
this.versions = resp.count
this.showSecretDialog()
})
} else {
this.showSecretDialog()
}
},
methods: {
accountConfirmHandle() {
this.modifiedSecret && this.onChangeSecretSubmit()
this.showSecret = false
this.mfaDialogVisible = false
},
onChangeSecretSubmit() {
const params = {
name: this.secretInfo.name,
secret: encryptPassword(this.modifiedSecret)
}
this.$axios.patch(`/api/v1/accounts/accounts/${this.account.id}/`, params).then(() => {
this.$message.success(this.$tc('common.updateSuccessMsg'))
})
},
showSecretDialog() {
return this.$axios.get(this.url, { disableFlashErrorMsg: true }).then((res) => {
this.secretInfo = res
this.sshKeyFingerprint = res?.spec_info?.ssh_key_fingerprint || '-'
this.showSecret = true
})
},
exit() {
this.$emit('update:visible', false)
},
showHistoryDialog() {
this.showPasswordHistoryDialog = true
},
onShowKeyCopyFormatterChange(value) {
if (value === this.secretInfo.secret) return
this.modifiedSecret = value
}
}
}
</script>
<style lang="scss" scoped>
.item-textarea >>> .el-textarea__inner {
height: 110px;
}
.el-form-item {
border-bottom: 1px solid #EBEEF5;
padding: 5px 0;
margin-bottom: 0;
&:last-child {
border-bottom: none;
}
>>> .el-form-item__label {
padding-right: 20px;
line-height: 30px;
}
>>> .el-form-item__content {
line-height: 30px;
pre {
margin: 0;
}
}
}
ul {
margin: 0;
}
li {
display: block;
font-size: 13px;
margin-bottom: 8px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.title {
color: #303133;
font-weight: 500;
}
}
</style>

View File

@@ -1,26 +0,0 @@
import i18n from '@/i18n/i18n'
import { ChoicesFormatter } from '@/components/Table/TableFormatters'
export const connectivityMeta = {
label: i18n.t('assets.Connectivity'),
formatter: ChoicesFormatter,
formatterArgs: {
faChoices: {
'-': '',
ok: 'fa-check-circle',
err: 'fa-times-circle'
},
classChoices: {
ok: 'text-primary',
err: 'text-danger'
},
getText({ cellValue }) {
if (cellValue?.value === '-' || cellValue?.value === 'unknown') {
return '-'
} else {
return cellValue?.label
}
}
},
width: '100px'
}

View File

@@ -1,192 +0,0 @@
<template>
<Dialog
:title="$tc('assets.Assets')"
custom-class="asset-select-dialog"
top="1vh"
v-bind="$attrs"
width="80vw"
@cancel="handleCancel"
@close="handleClose"
@confirm="handleConfirm"
v-on="$listeners"
>
<AssetTreeTable
ref="ListPage"
:header-actions="headerActions"
:node-url="baseNodeUrl"
:table-config="tableConfig"
:tree-url="`${baseNodeUrl}children/tree/`"
:url="baseUrl"
class="tree-table"
v-bind="$attrs"
/>
</Dialog>
</template>
<script>
import AssetTreeTable from '@/components/Apps/AssetTreeTable/index.vue'
import Dialog from '@/components/Dialog/index.vue'
export default {
componentName: 'AssetSelectDialog',
components: { AssetTreeTable, Dialog },
props: {
baseUrl: {
type: String,
default: '/api/v1/assets/assets/'
},
baseNodeUrl: {
type: String,
default: '/api/v1/assets/nodes/'
},
value: {
type: Array,
default: () => []
},
canSelect: {
type: Function,
default(row, index) {
return true
}
},
disabled: {
type: [Boolean, Function],
default: false
}
},
data() {
const vm = this
return {
dialogVisible: false,
rowSelected: _.cloneDeep(this.value) || [],
rowsAdd: [],
tableConfig: {
url: this.baseUrl,
hasTree: true,
canSelect: this.canSelect,
columns: [
{
prop: 'name',
label: this.$t('assets.Name'),
sortable: true
},
{
prop: 'address',
label: this.$t('assets.ipDomain'),
sortable: 'custom'
},
{
prop: 'platform',
label: this.$t('assets.Platform'),
sortable: true,
formatter: function(row) {
return row.platform.name
}
},
{
prop: 'protocols',
formatter: function(row) {
const data = row.protocols?.map(p => {
return <el-tag size='mini'>{p.name}/{p.port} </el-tag>
})
return <span> {data} </span>
},
label: this.$t('assets.Protocols')
},
{
prop: 'actions',
has: false
}
],
listeners: {
'toggle-row-selection': (isSelected, row) => {
if (isSelected) {
vm.addRowToSelect(row)
} else {
vm.removeRowFromSelect(row)
}
}
},
theRowDefaultIsSelected: (row) => {
return this.value.indexOf(row.id) > -1
}
},
headerActions: {
hasLeftActions: false,
hasRightActions: false,
searchConfig: {
getUrlQuery: false
}
}
}
},
methods: {
handleClose() {
this.$eventBus.$emit('treeComponentKey')
},
handleConfirm() {
this.$emit('confirm', this.rowSelected, this.rowsAdd)
if (this.rowSelected.length > 0) {
this.handleClose()
}
},
handleCancel() {
this.$emit('cancel')
this.handleClose()
},
addRowToSelect(row) {
const selectValueIndex = this.rowSelected.indexOf(row.id)
if (selectValueIndex === -1) {
this.rowSelected.push(row.id)
this.rowsAdd.push(row)
}
},
removeRowFromSelect(row) {
const selectValueIndex = this.rowSelected.indexOf(row.id)
if (selectValueIndex > -1) {
this.rowSelected.splice(selectValueIndex, 1)
}
}
}
}
</script>
<style lang="scss" scoped>
.page ::v-deep .page-heading {
display: none;
}
.el-dialog__wrapper ::v-deep .el-dialog__body {
padding: 0 0 0 3px;
.tree-table {
.search {
}
.left {
padding: 5px;
}
.right {
height: calc(100vh - 200px);
overflow: auto;
}
.mini {
padding-top: 8px;
}
.transition-box {
padding: 10px 5px;
}
}
}
.page ::v-deep .treebox .ztree {
}
.asset-select-dialog ::v-deep .el-icon-circle-check {
display: none;
}
</style>

View File

@@ -1,154 +0,0 @@
<template>
<div class="asset-select-formatter">
<Select2
ref="select2"
v-model="select2Config.value"
v-bind="select2Config"
@input="onInputChange"
v-on="$listeners"
@focus.stop="handleFocus"
/>
<AssetSelectDialog
v-if="dialogVisible"
ref="dialog"
:base-node-url="baseNodeUrl"
:base-url="baseUrl"
:tree-url-query="treeUrlQuery"
:value="value"
:visible.sync="dialogVisible"
v-bind="$attrs"
@cancel="handleCancel"
@confirm="handleConfirm"
v-on="$listeners"
/>
</div>
</template>
<script>
import Select2 from '@/components/Form/FormFields/Select2.vue'
import AssetSelectDialog from './dialog.vue'
import { b } from 'css-color-function/lib/adjusters'
export default {
componentName: 'AssetSelect',
components: { AssetSelectDialog, Select2 },
props: {
baseUrl: {
type: String,
default: '/api/v1/assets/assets/'
},
baseNodeUrl: {
type: String,
default: '/api/v1/assets/nodes/'
},
treeUrlQuery: {
type: Object,
default: () => {}
},
value: {
type: Array,
default: () => []
}
},
data() {
const iValue = []
for (const item of this.value) {
if (typeof item === 'object') {
iValue.push(item.id)
} else {
iValue.push(item)
}
}
return {
dialogVisible: false,
initialValue: _.cloneDeep(iValue),
select2Config: {
value: iValue,
multiple: true,
clearable: true,
ajax: {
url: this.baseUrl,
transformOption: (item) => {
return { label: item.name + '(' + item.address + ')', value: item.id }
}
}
}
}
},
methods: {
b,
handleFocus() {
this.$refs.select2.selectRef.blur()
this.dialogVisible = true
},
handleConfirm(valueSelected, rowsAdd) {
if (valueSelected === undefined) {
return
}
this.$refs.select2.iValue = valueSelected
this.addRowsToSelect(rowsAdd)
this.onInputChange(valueSelected)
this.dialogVisible = false
},
handleCancel() {
this.dialogVisible = false
},
onInputChange(val) {
this.$emit('change', val)
},
addToSelect(options, row) {
const selectOptionsHas = options.find(item => item.value === row.id)
// 如果select2的options中没有那么可能无法显示正常的值
if (selectOptionsHas === undefined) {
const option = {
label: `${row.name}(${row.address})`,
value: row.id
}
options.push(option)
}
},
addRowsToSelect(rows) {
const outSelectOptions = this.$refs.select2.options
for (const row of rows) {
this.addToSelect(outSelectOptions, row)
}
}
}
}
</script>
<style lang="scss" scoped>
.el-select {
width: 100%;
}
.page ::v-deep .page-heading {
display: none;
}
.el-dialog__wrapper ::v-deep .el-dialog__body {
padding: 0 0 0 3px;
.tree-table {
.left {
padding: 5px;
.ztree {
height: calc(100vh - 250px) !important;
}
}
.mini {
padding-top: 8px;
}
.transition-box {
padding: 10px 5px;
}
}
}
.page ::v-deep .treebox {
height: inherit !important;
}
</style>

View File

@@ -1,175 +0,0 @@
<template>
<TreeTable
ref="TreeList"
:active-menu.sync="treeTableConfig.activeMenu"
:table-config="tableConfig"
:tree-tab-config="treeTableConfig"
component="TabTree"
v-bind="$attrs"
v-on="$listeners"
>
<template #table>
<slot name="table" />
</template>
<div slot="rMenu" slot-scope="{data}">
<slot :data="data" name="rMenu" />
</div>
</TreeTable>
</template>
<script>
import TreeTable from '../../Table/TreeTable/index.vue'
import { setRouterQuery, setUrlParam } from '@/utils/common'
import $ from '@/utils/jquery-vendor'
export default {
components: {
TreeTable
},
props: {
url: {
type: String,
default: '/api/v1/assets/assets/'
},
nodeUrl: {
type: String,
default: '/api/v1/assets/nodes/'
},
treeUrl: {
type: String,
default: '/api/v1/assets/nodes/children/tree/'
},
treeUrlQuery: {
type: Object,
default: () => ({})
},
treeSetting: {
type: Object,
default: () => ({})
},
tableConfig: {
type: Object,
default: () => ({})
},
showAssets: {
type: Boolean,
default: false
}
},
data() {
const showAssets = this.treeSetting?.showAssets || this.showAssets
const treeUrlQuery = this.setTreeUrlQuery()
const assetTreeUrl = `${this.treeUrl}?assets=${showAssets ? '1' : '0'}&${treeUrlQuery}`
return {
treeTabConfig: {
activeMenu: 'CustomTree',
submenu: [
{
title: this.$t('assets.AssetTree'),
name: 'CustomTree',
treeSetting: {
showAssets,
showMenu: false,
showRefresh: true,
showCreate: true,
showUpdate: true,
showDelete: true,
hasRightMenu: true,
showSearch: true,
url: this.url,
nodeUrl: this.nodeUrl,
treeUrl: assetTreeUrl,
callback: {
onSelected: (event, treeNode) => this.getAssetsUrl(treeNode)
},
...this.treeSetting
}
},
{
title: this.$t('assets.BuiltinTree'),
name: 'BuiltinTree',
treeSetting: {
showRefresh: true,
showAssets: false,
showSearch: false,
customTreeHeaderName: this.$t('assets.BuiltinTree'),
url: '/api/v1/assets/nodes/category/tree/',
nodeUrl: this.treeSetting?.nodeUrl || this.nodeUrl,
treeUrl: `/api/v1/assets/nodes/category/tree/?assets=${showAssets ? '1' : '0'}&count_resource=${this.treeSetting.countResource || 'asset'}`,
callback: {
onSelected: (event, treeNode) => this.getAssetsUrl(treeNode)
}
}
}
]
}
}
},
computed: {
treeTableConfig() {
if (this.treeSetting.notShowBuiltinTree) {
// eslint-disable-next-line vue/no-side-effects-in-computed-properties
this.treeTabConfig.submenu.splice(1, 1)
}
return this.treeTabConfig
}
},
mounted() {
this.decorateRMenu()
const treeSetting = this.treeTabConfig.submenu[0].treeSetting
treeSetting.hasRightMenu = !this.currentOrgIsRoot
treeSetting.showCreate = this.$hasPerm('assets.add_node')
treeSetting.showUpdate = this.$hasPerm('assets.change_node')
treeSetting.showDelete = this.$hasPerm('assets.delete_node')
},
methods: {
setTreeUrlQuery() {
let str = ''
for (const key in this.treeUrlQuery) {
str += `${key}=${this.treeUrlQuery[key]}&`
}
str = str.substr(0, str.length - 1)
return str
},
decorateRMenu() {
const show_current_asset = this.$cookie.get('show_current_asset') || '0'
if (show_current_asset === '1') {
$('#m_show_asset_all_children_node').css('color', '#606266')
$('#m_show_asset_only_current_node').css('color', 'green')
} else {
$('#m_show_asset_all_children_node').css('color', 'green')
$('#m_show_asset_only_current_node').css('color', '#606266')
}
},
getAssetsUrl(treeNode) {
let url = this.treeSetting?.url || this.url
if (treeNode.meta.type === 'node') {
const nodeId = treeNode.meta.data.id
url = setUrlParam(url, 'node_id', nodeId)
url = setUrlParam(url, 'asset_id', '')
} else if (treeNode.meta.type === 'asset') {
const assetId = treeNode.meta.data?.id || treeNode.id
url = setUrlParam(url, 'node_id', '')
url = setUrlParam(url, 'asset_id', assetId)
} else if (treeNode.meta.type === 'category') {
url = setUrlParam(url, 'category', treeNode.meta.category)
} else if (treeNode.meta.type === 'type') {
url = setUrlParam(url, 'category', treeNode.meta.category)
url = setUrlParam(url, 'type', treeNode.meta._type)
} else if (treeNode.meta.type === 'platform') {
url = setUrlParam(url, 'platform', treeNode.id)
}
const query = this.setTreeUrlQuery()
url = query ? `${url}&${query}` : url
this.$set(this.tableConfig, 'url', url)
setRouterQuery(this, url)
}
}
}
</script>
<style lang='scss' scoped>
</style>

View File

@@ -1,203 +0,0 @@
<template>
<div>
<div>
<el-button
:disabled="isDisabled"
size="mini"
type="primary"
@click="onOpenDialog"
>
{{ $tc('common.Setting') }}
</el-button>
</div>
<Dialog
v-if="visible"
:destroy-on-close="true"
:show-cancel="false"
:show-confirm="false"
:title="title"
:visible.sync="visible"
v-bind="$attrs"
width="60%"
v-on="$listeners"
>
<AutoDataForm
ref="autoDataForm"
:form="form"
class="data-form"
v-bind="config"
@submit="onSubmit"
/>
</Dialog>
</div>
</template>
<script>
import Dialog from '../../Dialog'
import AutoDataForm from '../../Form/AutoDataForm'
export default {
componentName: 'AutomationParams',
components: {
Dialog,
AutoDataForm
},
props: {
value: {
type: Object,
default: () => ({})
},
title: {
type: String,
default: function() {
return this.$t('assets.PushParams')
}
},
assets: {
type: Array,
default: () => []
},
nodes: {
type: Array,
default: () => []
},
platforms: {
type: Array,
default: () => []
},
method: {
type: String,
default: ''
},
url: {
type: String,
default: `/api/v1/assets/platform-automation-methods/`
}
},
data() {
const vm = this
return {
remoteMeta: {},
visible: false,
isDisabled: true,
form: this.value,
config: {
url: this.url,
hasSaveContinue: false,
hasButtons: true,
method: 'get',
fields: [],
fieldsMeta: {}
},
onFieldChangeHandler: _.debounce(vm.handleFieldChange, 1000)
}
},
computed: {
refForm() {
return this.$refs.autoDataForm
}
},
watch: {
nodes: {
handler() {
this.onFieldChangeHandler()
},
deep: true
},
assets: {
handler() {
this.onFieldChangeHandler()
},
deep: true
},
platforms: {
handler(newVal) {
this.onFieldChangeHandler()
},
deep: true,
immediate: true
}
},
async mounted() {
await this.getUrlMeta()
},
methods: {
async getUrlMeta() {
const data = await this.$store.dispatch('common/getUrlMeta', { url: this.url })
this.remoteMeta = data.actions[this.config.method.toUpperCase()] || {}
},
async getFilterPlatforms() {
return await this.$axios.post(
'/api/v1/assets/platforms/filter-nodes-assets/',
{
'node_ids': this.nodes,
'asset_ids': this.assets,
'platform_ids': this.platforms.map(i => i.id || i.pk || i)
}
)
},
async handleFieldChange() {
const platforms = await this.getFilterPlatforms()
let pushAccountMethods = platforms.map(i => i.automation[this.method])
pushAccountMethods = _.uniq(pushAccountMethods)
// 检测是否有可设置的推送方式
const hasCanSettingPushMethods = _.intersection(pushAccountMethods, Object.keys(this.remoteMeta))
this.setFormConfig(hasCanSettingPushMethods)
this.isDisabled = hasCanSettingPushMethods.length <= 0
},
setFormConfig(methods) {
const newForm = {}
const fields = []
const fieldsMeta = {}
this.config.fields = []
// Todo: 未来改成后端处理,生成 serializer, 这里就不用判断类型了
const typeMapper = {
'string': 'input',
'boolean': 'switch'
}
for (const method of methods) {
const filterField = this.remoteMeta[method] || {}
// 修改资产、节点时不点击设置按钮也需要获取form表单值暴露出去
if (this.form.hasOwnProperty(method)) {
newForm[method] = this.form[method]
}
fields.push([filterField.label, [method]])
fieldsMeta[method] = {
fields: [],
fieldsMeta: {}
}
if (Object.keys(filterField?.children || {}).length > 0) {
for (const [k, v] of Object.entries(filterField.children)) {
const item = {
...v,
type: typeMapper[v.type] || 'input'
}
delete item.default
fieldsMeta[method].fields.push(k)
fieldsMeta[method].fieldsMeta[k] = item
}
}
}
this.form = newForm
this.config.fields = fields
this.config.fieldsMeta = fieldsMeta
},
onOpenDialog() {
this.visible = true
},
onSubmit(form) {
this.form = form
this.$emit('input', form)
setTimeout(() => {
this.visible = false
}, 100)
this.$log.debug('Auto push form:', form)
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,97 +0,0 @@
<template>
<ListTable ref="ListTable" :table-config="tableConfig" :header-actions="headerActions" />
</template>
<script>
import ListTable from '@/components/Table/ListTable/index.vue'
export default {
name: 'BlockedIPList',
components: {
ListTable
},
props: {
object: {
type: Object,
required: false,
default: () => ({})
}
},
data() {
const vm = this
return {
tableConfig: {
url: '/api/v1/settings/security/block-ip/',
columns: [
'ip', 'actions'
],
columnsMeta: {
ip: {
label: this.$t('assets.ip')
},
actions: {
formatterArgs: {
hasDelete: false,
hasUpdate: false,
hasClone: false,
extraActions: [
{
name: 'UnlockIP',
title: this.$t('setting.Unblock'),
can: this.$hasPerm('settings.change_security'),
type: 'primary',
callback: ({ row }) => {
this.$axios.post(
'/api/v1/settings/security/unlock-ip/',
{ ips: [row.ip] }
).then(() => {
vm.$message.success(this.$tc('common.UnlockSuccessMsg'))
vm.$refs.ListTable.reloadTable()
})
}
}
]
}
}
}
},
headerActions: {
hasExport: false,
hasImport: false,
hasCreate: false,
hasSearch: false,
hasRefresh: true,
hasBulkDelete: false,
hasBulkUpdate: false,
hasLeftActions: true,
hasRightActions: true,
extraMoreActions: [
{
name: 'UnlockSelected',
title: this.$t('setting.BulkUnblock'),
type: 'primary',
can: ({ selectedRows }) => {
return selectedRows.length > 0
},
callback: function({ selectedRows }) {
vm.$axios.post(
'/api/v1/settings/security/unlock-ip/',
{
ips: selectedRows.map(v => { return v.ip })
}
).then(res => {
vm.$message.success(vm.$tc('common.UnlockSuccessMsg'))
vm.$refs.ListTable.reloadTable()
})
}
}
]
}
}
}
}
</script>
<style lang='less' scoped>
</style>

View File

@@ -1,75 +0,0 @@
<template>
<div>
<div>
<el-button
size="mini"
type="primary"
@click="onOpenDialog"
>{{ $tc('common.View') }}</el-button>
</div>
<Dialog
v-if="visible"
:visible.sync="visible"
:title="title"
width="40%"
:show-cancel="false"
:show-confirm="false"
:destroy-on-close="true"
v-bind="$attrs"
v-on="$listeners"
>
<BlockedIPList />
</Dialog>
</div>
</template>
<script>
import { Dialog } from '@/components'
import BlockedIPList from '@/components/Apps/BlockedIPs/BlockedIPList'
export default {
componentName: 'BlockedIPs',
components: {
BlockedIPList,
Dialog
},
props: {
value: {
type: Object,
default: () => ({})
},
title: {
type: String,
default: function() {
return this.$t('setting.BlockedIPS')
}
},
url: {
type: String,
default: `/api/v1/assets/platform-automation-methods/`
}
},
data() {
return {
remoteMeta: {},
visible: false,
form: this.value,
config: {
url: this.url,
hasSaveContinue: false,
hasButtons: true,
fields: [],
fieldsMeta: {}
}
}
},
methods: {
onOpenDialog() {
this.visible = true
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,92 +0,0 @@
<template>
<Dialog
v-if="iVisible"
:destroy-on-close="true"
:show-cancel="false"
:show-confirm="false"
:title="$tc('assets.TestGatewayTestConnection')"
:visible.sync="iVisible"
top="35vh"
width="40%"
>
<el-row :gutter="20">
<el-col :md="4" :sm="24">
<div style="line-height: 34px">{{ $t('assets.SSHPort') }}</div>
</el-col>
<el-col :md="14" :sm="24">
<el-input v-model="port" />
<span class="help-tips help-block">{{ $t('assets.TestGatewayHelpMessage') }}</span>
</el-col>
<el-col :md="4" :sm="24">
<el-button
:loading="loading"
size="mini"
style="line-height:20px "
type="primary"
@click="dialogConfirm"
>
{{ this.$t('common.Confirm') }}
</el-button>
</el-col>
</el-row>
</Dialog>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
import { openTaskPage } from '@/utils/jms'
export default {
name: 'GatewayDialog',
components: {
Dialog
},
props: {
visible: {
type: Boolean,
default: false
},
loading: {
type: Boolean,
default: false
},
port: {
type: Number,
default: 0
},
cell: {
type: String,
default: ''
}
},
data() {
return {}
},
computed: {
iVisible: {
get() {
return this.visible
},
set(val) {
this.$emit('update:visible', val)
}
}
},
methods: {
dialogConfirm() {
if (isNaN(this.port)) {
return this.$message.error(this.$tc('common.TestPortErrorMsg'))
}
this.$axios.post(
`/api/v1/assets/gateways/${this.cell}/test-connective/`,
{ port: this.port }
)
.then((res) => {
openTaskPage(res['task'])
}).finally(() => {
this.iVisible = false
})
}
}
}
</script>

View File

@@ -1,71 +0,0 @@
<template>
<el-row :gutter="24">
<el-col :md="20" :sm="22">
<ListTable v-bind="config" />
</el-col>
</el-row>
</template>
<script>
import ListTable from '@/components/Table/ListTable/index.vue'
import { toM2MJsonParams } from '@/utils/jms'
export default {
name: 'AssetJsonTab',
components: {
ListTable
},
props: {
object: {
type: Object,
default: () => {}
}
},
data() {
const [key, value] = toM2MJsonParams(this.object.assets)
return {
config: {
headerActions: {
hasLeftActions: false,
hasImport: false,
hasExport: false
},
tableConfig: {
url: `/api/v1/assets/assets/?${key}=${value}`,
columns: ['name', 'address', 'platform',
'type', 'is_active'
],
columnsMeta: {
name: {
label: this.$t('assets.Asset'),
formatter: (row) => {
const to = {
name: 'AssetDetail',
params: { id: row.id }
}
if (this.$hasPerm('assets.view_asset')) {
return <router-link to={to} class='text-link'>{row.name}</router-link>
} else {
return <span>{row.name}</span>
}
}
},
actions: {
has: false
}
}
}
}
}
},
computed: {
iUrl() {
return `/api/v1/users/users/`
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,91 +0,0 @@
<template>
<el-row :gutter="24">
<el-col :md="20" :sm="22">
<ListTable v-bind="config" />
</el-col>
</el-row>
</template>
<script>
import ListTable from '@/components/Table/ListTable/index.vue'
import { toM2MJsonParams } from '@/utils/jms'
export default {
name: 'User',
components: {
ListTable
},
props: {
object: {
type: Object,
default: () => {}
}
},
data() {
const [key, value] = toM2MJsonParams(this.object.users)
return {
config: {
headerActions: {
hasLeftActions: false,
hasImport: false,
hasExport: false
},
tableConfig: {
url: `/api/v1/users/users/?${key}=${value}`,
columns: [
'name', 'username', 'groups', 'system_roles',
'org_roles', 'source', 'is_valid'
],
columnsMeta: {
name: {
label: this.$t('common.Name'),
formatter: (row) => {
const to = {
name: 'UserDetail',
params: { id: row.id }
}
if (this.$hasPerm('users.view_user')) {
return <router-link to={to} class='text-link'>{row.name}</router-link>
} else {
return <span>{row.name}</span>
}
}
},
system_roles: {
label: this.$t('users.SystemRoles'),
formatter: (row) => {
return row['system_roles'].map(item => item['display_name']).join(', ') || '-'
},
filters: [],
columnKey: 'system_roles'
},
org_roles: {
label: this.$t('users.OrgRoles'),
formatter: (row) => {
return row['org_roles'].map(item => item['display_name']).join(', ') || '-'
},
filters: [],
columnKey: 'org_roles',
has: () => {
return this.$store.getters.hasValidLicense && !this.currentOrgIsRoot
}
},
actions: {
has: false
}
}
}
}
}
},
computed: {
iUrl() {
return `/api/v1/users/users/`
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,92 +0,0 @@
<template>
<div>
<el-row :gutter="20">
<el-col :md="12" :sm="24">
<IBox :title="title" class="block" v-bind="$attrs">
<el-timeline>
<el-timeline-item
v-for="(activity, index) in activities"
:key="index"
:size="activity.size"
:timestamp="activity.timestamp"
:type="activity.type"
placement="bottom"
>
{{ activity.content }}
<el-link
v-if="activity['detail_url']"
type="primary"
@click.native="onClick(activity)"
>
{{ $tc('common.Detail') }}
</el-link>
</el-timeline-item>
</el-timeline>
</IBox>
</el-col>
</el-row>
<DiffDetail ref="DetailDialog" :title="$tc('route.OperateLog')" />
</div>
</template>
<script>
import IBox from '@/components/IBox/index.vue'
import DiffDetail from '@/components/Dialog/DiffDetail.vue'
import { openTaskPage } from '@/utils/jms'
export default {
name: 'ResourceActivity',
components: {
IBox,
DiffDetail
},
props: {
object: {
type: Object,
default: () => ({})
}
},
data() {
return {
activityUrl: `/api/v1/audits/activities/?resource_id=${this.object.id}`,
title: `${this.$t('common.Activity')} - ${this.$t('common.Last30')}`,
activities: [
{
content: this.$t('common.Now'),
timestamp: this.$moment().format('YYYY-MM-DD HH:mm:ss'),
type: 'primary'
}
]
}
},
mounted() {
this.getActivities()
},
methods: {
getActivities() {
this.$axios.get(this.activityUrl).then(res => {
for (const i in res) {
this.activities.push(res[i])
}
})
},
onClick(activity) {
const type = activity['r_type']
const taskUrl = activity['detail_url']
if (type === 'O') {
this.$axios.get(taskUrl).then(
res => {
this.$refs.DetailDialog.show(res.diff)
}
)
} else {
openTaskPage('', 'celery', taskUrl)
}
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,224 +0,0 @@
<template>
<Dialog
:close-on-click-modal="false"
:destory-on-close="true"
:show-cancel="false"
:show-confirm="false"
:title="title"
:visible.sync="visible"
class="dialog-content"
v-bind="$attrs"
width="600px"
@confirm="visible = false"
v-on="$listeners"
>
<div v-if="confirmTypeRequired === 'relogin'">
<el-row :gutter="24" style="margin: 0 auto;">
<el-col :md="24" :sm="24">
<el-alert
:title="$tc('auth.ReLoginTitle')"
center
style="margin-bottom: 20px;"
type="error"
/>
</el-col>
</el-row>
<el-row :gutter="24" style="margin: 0 auto;">
<el-col :md="24" :sm="24">
<el-button class="confirm-btn" size="mini" type="primary" @click="logout">
{{ this.$t('auth.ReLogin') }}
</el-button>
</el-col>
</el-row>
</div>
<div v-else>
<el-row :gutter="24" style="margin: 0 auto;">
<el-col :md="24" :sm="24" :span="24" class="add">
<el-select
v-model="subTypeSelected"
style="width: 100%; margin-bottom: 20px;"
@change="handleSubTypeChange"
>
<el-option
v-for="item of subTypeChoices"
:key="item.name"
:disabled="item.disabled"
:label="item.display_name"
:value="item.name"
/>
</el-select>
</el-col>
</el-row>
<el-row :gutter="24" style="margin: 0 auto;">
<el-col :md="24" :sm="24" style="display: flex; margin-bottom: 20px;">
<el-input v-model="secretValue" :placeholder="inputPlaceholder" :show-password="showPassword" />
<span v-if="subTypeSelected === 'sms'" style="margin: -1px 0 0 20px;">
<el-button
:disabled="smsBtnDisabled"
size="mini"
style="line-height:20px; float: right;"
type="primary"
@click="sendSMSCode"
>
{{ smsBtnText }}
</el-button>
</span>
</el-col>
</el-row>
<el-row :gutter="24" style="margin: 10px auto;">
<el-col :md="24" :sm="24">
<el-button class="confirm-btn" size="mini" type="primary" @click="handleConfirm">
{{ this.$t('common.Confirm') }}
</el-button>
</el-col>
</el-row>
</div>
</Dialog>
</template>
<script>
import Dialog from '@/components/Dialog/index.vue'
export default {
name: 'UserConfirmDialog',
components: {
Dialog
},
props: {
url: {
type: String,
default: ''
},
handler: {
type: Function,
default: null
}
},
data() {
return {
title: this.$t('common.CurrentUserVerify'),
smsWidth: 0,
subTypeSelected: '',
inputPlaceholder: '',
smsBtnText: this.$t('common.SendVerificationCode'),
smsBtnDisabled: false,
confirmTypeRequired: '',
subTypeChoices: [],
secretValue: '',
visible: false,
callback: null,
cancel: null,
processing: false
}
},
computed: {
showPassword() {
return this.confirmTypeRequired === 'password'
}
},
mounted() {
// const onRecvCallback = _.debounce(this.performConfirm, 500)
this.$eventBus.$on('showConfirmDialog', this.performConfirm)
},
methods: {
handleSubTypeChange(val) {
this.inputPlaceholder = this.subTypeChoices.filter(item => item.name === val)[0]?.placeholder
this.smsWidth = val === 'sms' ? 6 : 0
},
performConfirm({ response, callback, cancel }) {
if (this.processing || this.visible) {
return
}
this.processing = true
this.callback = callback
this.cancel = cancel
this.$log.debug('perform confirm action')
const confirmType = response.data?.code
const confirmUrl = '/api/v1/authentication/confirm/'
this.$axios.get(confirmUrl, { params: { confirm_type: confirmType }}).then((data) => {
this.confirmTypeRequired = data.confirm_type
if (this.confirmTypeRequired === 'relogin') {
this.$axios.post(confirmUrl, { 'confirm_type': 'relogin', 'secret_key': 'x' }).then(() => {
this.callback()
this.visible = false
}).catch(() => {
this.title = this.$t('auth.NeedReLogin')
this.visible = true
})
}
this.subTypeChoices = data.content
const defaultSubType = this.subTypeChoices.filter(item => !item.disabled)[0]
this.subTypeSelected = defaultSubType.name
this.inputPlaceholder = defaultSubType.placeholder
this.visible = true
}).catch((err) => {
const data = err.response?.data
const msg = data?.error || data?.detail || data?.msg || this.$t('common.GetConfirmTypeFailed')
this.$message.error(msg)
this.cancel(err)
}).finally(() => {
this.processing = false
})
},
logout() {
window.location.href = `${process.env.VUE_APP_LOGOUT_PATH}?next=${this.$route.fullPath}`
},
sendSMSCode() {
this.$axios.post(`/api/v1/authentication/mfa/select/`, { type: 'sms' }).then(res => {
this.$message.success(this.$tc('common.VerificationCodeSent'))
let time = 60
const interval = setInterval(() => {
const originText = this.smsBtnText
this.smsBtnText = this.$t('common.Pending') + `: ${time}`
this.smsBtnDisabled = true
time -= 1
if (time === 0) {
this.smsBtnText = originText
this.smsBtnDisabled = false
clearInterval(interval)
}
}, 1000)
})
},
handleConfirm() {
if (this.confirmTypeRequired === 'relogin') {
return this.logout()
}
if (this.subTypeSelected === 'otp' && this.secretValue.length !== 6) {
return this.$message.error(this.$tc('common.MFAErrorMsg'))
}
const data = {
confirm_type: this.confirmTypeRequired,
mfa_type: this.confirmTypeRequired === 'mfa' ? this.subTypeSelected : '',
secret_key: this.secretValue
}
this.$axios.post(`/api/v1/authentication/confirm/`, data).then(res => {
this.callback()
this.visible = false
})
}
}
}
</script>
<style lang="scss" scoped>
.dialog-content >>> .el-dialog__footer {
padding: 0;
}
.dialog-content >>> .el-dialog {
padding: 8px;
.el-dialog__body {
padding-top: 30px;
padding-bottom: 30px;
}
}
.confirm-btn {
width: 100%;
line-height: 20px;
}
</style>

View File

@@ -1,14 +1,14 @@
<template>
<IBox :fa="icon" :title="title" :type="type" v-bind="$attrs">
<IBox :fa="icon" :type="type" :title="title" v-bind="$attrs">
<table style="width: 100%">
<tr>
<td colspan="2">
<AssetSelect ref="assetSelect" :can-select="canSelect" :disabled="disabled" />
<AssetSelect ref="assetSelect" />
</td>
</tr>
<tr>
<td colspan="2">
<el-button :disabled="disabled" :type="type" size="small" @click="addObjects">{{ $t('common.Add') }}</el-button>
<el-button :type="type" size="small" @click="addObjects">{{ $t('common.Add') }}</el-button>
</td>
</tr>
</table>
@@ -16,8 +16,8 @@
</template>
<script>
import IBox from '@/components/IBox/index.vue'
import AssetSelect from '@/components/Apps/AssetSelect/index.vue'
import IBox from '@/components/IBox'
import AssetSelect from '@/components/AssetSelect'
export default {
name: 'AssetRelationCard',
@@ -38,10 +38,6 @@ export default {
type: String,
default: 'primary'
},
disabled: {
type: [Boolean, Function],
default: false
},
value: {
type: [Array, Number, String],
default: () => []
@@ -53,12 +49,6 @@ export default {
onAddSuccess: {
type: Function,
default: (objects, that) => {}
},
canSelect: {
type: Function,
default(row, index) {
return true
}
}
},
data() {

View File

@@ -0,0 +1,176 @@
<template>
<div class="asset-select-dialog">
<Select2 ref="select2" v-bind="select2Config" @input="onInputChange" @focus.stop="handleFocus" v-on="$listeners" />
<Dialog
v-if="dialogVisible"
:title="this.$t('assets.Assets')"
:visible.sync="dialogVisible"
custom-class="asset-select-dialog"
width="70%"
top="1vh"
@confirm="handleConfirm"
@cancel="handleCancel"
>
<TreeTable
ref="ListPage"
:tree-setting="treeSetting"
:table-config="tableConfig"
:header-actions="headerActions"
/>
</Dialog>
</div>
</template>
<script>
import TreeTable from '@/components/TreeTable'
import { DetailFormatter } from '@/components/ListTable/formatters'
import Select2 from '@/components/Select2'
import Dialog from '@/components/Dialog'
export default {
componentName: 'AssetSelect',
components: { TreeTable, Select2, Dialog },
props: {
value: {
type: Array,
default: () => []
}
},
data() {
const select2Config = {
value: this.value,
multiple: true,
clearable: true,
ajax: {
url: '/api/v1/assets/assets/?fields_size=mini',
transformOption: (item) => {
return { label: item.hostname + '(' + item.ip + ')', value: item.id }
}
}
}
const vm = this
return {
dialogVisible: false,
initialValue: _.cloneDeep(this.value),
rowSelected: [],
initSelection: null,
treeSetting: {
showMenu: false,
showRefresh: true,
showAssets: false,
url: '/api/v1/assets/assets/?fields_size=mini',
nodeUrl: '/api/v1/assets/nodes/',
// ?assets=0不显示资产. =1显示资产
treeUrl: '/api/v1/assets/nodes/children/tree/?assets=0'
},
select2Config: select2Config,
dialogSelect2Config: select2Config,
tableConfig: {
url: '/api/v1/assets/assets/',
hasTree: true,
columns: [
{
prop: 'hostname',
label: this.$t('assets.Hostname'),
sortable: true,
showOverflowTooltip: true,
formatter: DetailFormatter,
formatterArgs: {
route: 'AssetDetail'
}
},
{
prop: 'ip',
label: this.$t('assets.ip'),
sortable: 'custom'
}
],
listeners: {
'toggle-row-selection': (isSelected, row) => {
if (isSelected) {
vm.addRowToSelect(row)
} else {
vm.removeRowFromSelect(row)
}
}
},
theRowDefaultIsSelected: (row) => {
return this.value.indexOf(row.id) > -1
}
},
headerActions: {
hasLeftActions: false,
hasRightActions: false
}
}
},
methods: {
handleFocus() {
this.$refs.select2.selectRef.blur()
this.dialogVisible = true
},
handleConfirm() {
this.dialogVisible = false
},
handleCancel() {
this.$refs.select2.iValue = this.initialValue
this.dialogVisible = false
},
onInputChange(val) {
this.$emit('change', val)
},
addToSelect(options, row) {
const selectOptionsHas = options.find(item => item.value === row.id)
// 如果select2的options中没有那么可能无法显示正常的值
if (selectOptionsHas === undefined) {
const option = {
label: `${row.hostname}(${row.ip})`,
value: row.id
}
options.push(option)
}
},
addRowToSelect(row) {
const outSelectOptions = this.$refs.select2.options
this.addToSelect(outSelectOptions, row)
const selectValue = this.$refs.select2.iValue
const selectValueIndex = selectValue.indexOf(row.id)
if (selectValueIndex === -1) {
selectValue.push(row.id)
}
this.onInputChange(selectValue)
},
removeRowFromSelect(row) {
const selectValue = this.$refs.select2.iValue
const selectValueIndex = selectValue.indexOf(row.id)
if (selectValueIndex > -1) {
selectValue.splice(selectValueIndex, 1)
}
}
}
}
</script>
<style lang='scss' scoped>
.el-select{
width: 100%;
}
.page ::v-deep .page-heading{
display: none;
}
.el-dialog__wrapper ::v-deep .el-dialog__body{
padding: 5px 10px;
}
.page ::v-deep .treebox{
height: inherit !important;
}
.asset-select-dialog >>> .transition-box:first-child {
background-color: #f3f3f3 ;
}
.el-dialog__wrapper ::v-deep .el-dialog__body .wrapper-content {
padding: 10px;
}
</style>

View File

@@ -0,0 +1,363 @@
<template><div>
<div>
<ListTable ref="ListTable" :table-config="tableConfig" :header-actions="headerActions" />
<Dialog v-if="showMFADialog" width="50" :title="this.$t('common.MFAConfirm')" :visible.sync="showMFADialog" :show-confirm="false" :show-cancel="false" :destroy-on-close="true">
<div v-if="MFAConfirmed">
<el-form label-position="right" label-width="80px" :model="MFAInfo">
<el-form-item :label="this.$t('assets.Hostname')">
<el-input v-model="MFAInfo.hostname" disabled />
</el-form-item>
<el-form-item :label="this.$t('assets.Username')">
<el-input v-model="MFAInfo.username" disabled />
</el-form-item>
<el-form-item :label="this.$t('assets.Password')">
<el-input v-model="MFAInfo.password" type="password" show-password />
</el-form-item>
</el-form>
</div>
<el-row v-else :gutter="20">
<el-col :span="4">
<div style="line-height: 34px;text-align: center">MFA</div>
</el-col>
<el-col :span="14">
<el-input v-model="MFAInput" />
<span class="help-tips help-block">{{ $t('common.MFARequireForSecurity') }}</span>
</el-col>
<el-col :span="4">
<el-button size="mini" type="primary" style="line-height:20px " @click="MFAConfirm">{{ this.$t('common.Confirm') }}</el-button>
</el-col>
</el-row>
</Dialog>
<Dialog width="50" :title="this.$t('assets.UpdateAssetUserToken')" :visible.sync="showDialog" @confirm="handleConfirm()" @cancel="handleCancel()">
<el-form label-position="right" label-width="80px" :model="dialogInfo">
<el-form-item :label="this.$t('assets.Hostname')">
<el-input v-model="dialogInfo.hostname" disabled />
</el-form-item>
<el-form-item :label="this.$t('assets.Username')">
<el-input v-model="dialogInfo.username" disabled />
</el-form-item>
<el-form-item :label="this.$t('assets.Password')">
<el-input v-model="dialogInfo.password" type="password" />
</el-form-item>
<el-form-item :label="this.$t('assets.sshkey')">
<input type="file" @change="Onchange">
</el-form-item>
</el-form>
</Dialog>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import ListTable from '@/components/ListTable/index'
import Dialog from '@/components/Dialog'
import { ActionsFormatter, DateFormatter } from '@/components/ListTable/formatters'
export default {
name: 'Detail',
components: {
ListTable,
Dialog
},
props: {
url: {
type: String,
required: true
},
hasLeftActions: {
type: Boolean,
default: false
},
otherActions: {
type: Array,
default: null
},
handleExport: {
type: Function,
default: null
},
handleImport: {
type: Function,
default: null
},
hasImport: {
type: Boolean,
default: true
},
hasExport: {
type: Boolean,
default: true
}
},
data() {
return {
MFAConfirmed: false,
MFAInput: '',
MFAInfo: {
asset: '',
username: '',
hostname: '',
password: ''
},
showDialog: false,
showMFADialog: false,
dialogInfo: {
asset: '',
username: '',
hostname: '',
password: '',
key: ''
},
tableConfig: {
url: this.url,
columns: [
{
prop: 'hostname',
label: this.$t('assets.Hostname'),
showOverflowTooltip: true
},
{
prop: 'ip',
label: this.$t('assets.ip'),
width: '120px'
},
{
prop: 'username',
label: this.$t('assets.Username'),
showOverflowTooltip: true
},
{
prop: 'version',
label: this.$t('assets.Version'),
width: '70px'
},
{
prop: 'date_created',
label: this.$t('assets.date_joined'),
formatter: DateFormatter
},
{
prop: 'id',
label: this.$t('common.Action'),
align: 'center',
width: 150,
formatter: ActionsFormatter,
formatterArgs: {
hasUpdate: false, // can set function(row, value)
hasDelete: false, // can set function(row, value)
moreActionsTitle: this.$t('common.More'),
extraActions: [
{
name: 'View',
title: this.$t('common.View'),
type: 'primary',
callback: function(val) {
this.MFAInfo.asset = val.cellValue
if (this.MFAVerifyAt + this.MFA_TTl * 1000 > (new Date()).valueOf()) {
this.showMFADialog = true
this.MFAConfirmed = true
this.$axios.get(`/api/v1/assets/asset-user-auth-infos/${this.MFAInfo.asset}/`).then(res => {
this.MFAConfirmed = true
this.MFAInfo.hostname = res.hostname
this.MFAInfo.password = res.password
this.MFAInfo.username = res.username
})
} else {
this.showMFADialog = true
}
}.bind(this)
},
{
name: 'Delete',
title: this.$t('common.Delete'),
type: 'primary',
callback: (val) => {
this.$axios.delete(`/api/v1/assets/asset-users/${val.cellValue}/`).then(() => {
this.$message.success(this.$t('common.deleteSuccessMsg'))
this.$refs.ListTable.reloadTable()
})
}
},
{
name: 'Test',
title: this.$t('common.Test'),
callback: (val) => {
this.$axios.post(
`/api/v1/assets/asset-users/tasks/?id=${val.cellValue}`,
{ action: 'test' }
).then(res => {
window.open(`/#/ops/celery/task/${res.task}/log/`, '', 'width=900,height=600')
})
}
},
{
name: 'Update',
title: this.$t('common.Update'),
callback: function(val) {
this.showDialog = true
this.dialogInfo.asset = val.row.asset
this.dialogInfo.hostname = val.row.hostname
this.dialogInfo.username = val.row.username
}.bind(this)
}
]
}
}
],
extraQuery: {
latest: 1
}
},
headerActions: {
hasLeftActions: this.hasLeftActions,
hasBulkDelete: false,
hasImport: this.hasImport,
hasExport: this.hasExport,
hasSearch: true,
searchConfig: {
options: [
{
label: this.$t('assets.OnlyLatestVersion'),
value: 'latest',
children: [
{
label: this.$t('common.Yes'),
value: 1
},
{
label: this.$t('common.No'),
value: 0
}
]
}
]
}
}
}
},
computed: {
...mapGetters([
'MFA_TTl',
'MFAVerifyAt'
]),
needMFAVerify() {
if (!this.publicSettings.SECURITY_VIEW_AUTH_NEED_MFA) {
return false
}
const ttl = this.publicSettings.SECURITY_MFA_VERIFY_TTL
const now = new Date()
return !(this.MFAVerifyAt && (now - this.MFAVerifyAt) < ttl * 1000)
}
},
watch: {
url(iNew) {
this.$set(this.tableConfig, 'url', iNew)
}
},
mounted() {
if (this.otherActions) {
const actionColumn = this.tableConfig.columns[this.tableConfig.columns.length - 1]
for (const item of this.otherActions) {
actionColumn.formatterArgs.extraActions.push(item)
}
}
},
created() {
if (this.handleExport) {
this.headerActions.handleExport = this.handleExport
}
if (this.handleImport) {
this.headerActions.handleImport = this.handleImport
}
},
methods: {
MFAConfirm() {
if (this.MFAInput.length !== 6) {
return this.$message.error(this.$t('common.MFAErrorMsg'))
}
this.$axios.post(
`/api/v1/authentication/otp/verify/`, {
code: this.MFAInput
}
).then(
res => {
this.$store.dispatch('users/setMFAVerify')
this.$axios.get(`/api/v1/assets/asset-user-auth-infos/${this.MFAInfo.asset}/`).then(res => {
this.MFAConfirmed = true
this.MFAInfo.hostname = res.hostname
this.MFAInfo.password = res.password
this.MFAInfo.username = res.username
})
}
)
},
handleMFAConfirm() {
this.MFAInfo = {
asset: '',
username: '',
hostname: '',
password: ''
}
this.MFAInput = ''
this.showMFADialog = false
this.MFAConfirmed = false
},
handleCancel() {
this.dialogInfo = {
asset: '',
username: '',
hostname: '',
password: '',
key: ''
}
this.showDialog = false
this.$refs.ListTable.reloadTable()
},
Onchange(e) {
const vm = this
// TODO 校验文件类型
const reader = new FileReader()
reader.onload = function() {
vm.dialogInfo.key = this.result
}
reader.readAsText(
e.target.files[0]
)
},
handleConfirm() {
const data = {
asset: this.dialogInfo.asset,
username: this.dialogInfo.username
}
if (this.dialogInfo.password !== '') {
data.password = this.dialogInfo.password
}
if (this.dialogInfo.key !== '') {
data.key = this.dialogInfo.key
}
this.$axios.post(
`/api/v1/assets/asset-users/`,
data
).then(res => {
this.$message.success(this.$t('common.updateSuccessMsg'))
}).catch(err => {
this.$message.error(this.$t('common.updateErrorMsg' + ' ' + err))
})
this.dialogInfo = {
asset: '',
username: '',
hostname: '',
password: '',
key: ''
}
this.showDialog = false
this.$refs.ListTable.reloadTable()
}
}
}
</script>
<style lang='less' scoped>
</style>

View File

@@ -0,0 +1,188 @@
<template>
<DataForm ref="dataForm" v-loading="loading" :fields="totalFields" v-bind="$attrs" v-on="$listeners">
<FormGroupHeader v-for="(group, i) in groups" :slot="'id:'+group.name" :key="'group-'+group.name" :title="group.title" :line="i != 0" />
</DataForm>
</template>
<script>
import DataForm from '../DataForm'
import FormGroupHeader from '@/components/FormGroupHeader'
// import { optionUrlMeta } from '@/api/common'
import rules from '@/components/DataForm/rules'
import Select2 from '@/components/Select2'
export default {
name: 'AutoDataForm',
components: {
DataForm,
FormGroupHeader
},
props: {
url: {
type: String,
required: true
},
method: {
type: String,
default: 'post'
},
fields: {
type: Array,
default: () => {
return []
}
},
fieldsMeta: {
type: Object,
default: () => ({})
}
},
data() {
return {
meta: {},
totalFields: [],
loading: true,
groups: []
}
},
mounted() {
this.optionUrlMeta()
},
methods: {
optionUrlMeta() {
this.$store.dispatch('common/getUrlMeta', { url: this.url }).then(data => {
this.meta = data.actions[this.method.toUpperCase()] || {}
this.generateColumns()
}).catch(err => {
console.error(err)
}).finally(() => {
this.loading = false
})
},
generateFieldByType(type, field, fieldMeta) {
switch (type) {
case 'choice':
type = 'radio-group'
field.options = fieldMeta.choices.map(v => {
return { label: v.display_name, value: v.value }
})
break
case 'datetime':
type = 'date-picker'
field.el = {
type: 'datetime'
}
break
case 'field':
type = ''
field.component = Select2
if (fieldMeta.required) {
field.el.clearable = false
}
break
case 'string':
type = 'input'
if (!fieldMeta.max_length) {
field.el.type = 'textarea'
field.el.rows = 3
}
break
default:
type = 'input'
break
}
if (type === 'radio-group') {
const options = fieldMeta.choices.map(v => {
return { label: v.display_name, value: v.value }
})
if (options.length > 4) {
type = 'select'
field.el.filterable = true
}
}
field.type = type
return field
},
generateFieldByName(name, field) {
switch (name) {
case 'email':
field.el.type = 'email'
break
case 'password':
field.el.type = 'password'
break
case 'comment':
field.el.type = 'textarea'
break
}
return field
},
generateFieldByOther(field, fieldMeta) {
const filedRules = field.rules || []
if (fieldMeta.required) {
if (field.type === 'input') {
filedRules.push(rules.Required)
} else {
filedRules.push(rules.RequiredChange)
}
}
field.rules = filedRules
return field
},
generateField(name) {
let field = { id: name, prop: name, el: {}, attrs: {}}
const fieldMeta = this.meta[name] || {}
field.label = fieldMeta.label
field = this.generateFieldByType(fieldMeta.type, field, fieldMeta)
field = this.generateFieldByName(name, field)
field = this.generateFieldByOther(field, fieldMeta)
field = Object.assign(field, this.fieldsMeta[name] || {})
_.set(field, 'attrs.error', '')
return field
},
generateFieldGroup(data) {
const [groupTitle, fields] = data
this.groups.push({
id: groupTitle,
title: groupTitle,
name: fields[0]
})
return this.generateFields(fields)
},
generateFields(data) {
let fields = []
for (let field of data) {
if (field instanceof Array) {
const items = this.generateFieldGroup(field)
fields = [...fields, ...items]
} else if (typeof field === 'string') {
field = this.generateField(field)
fields.push(field)
} else if (field instanceof Object) {
this.errors[field.prop] = ''
_.set(field, 'attrs.error', '')
fields.push(field)
}
}
return fields
},
generateColumns() {
this.totalFields = this.generateFields(this.fields)
},
setFieldError(name, error) {
const field = this.totalFields.find((v) => v.prop === name)
if (!field) {
return
}
if (field.attrs.error === error) {
error += '.'
}
field.attrs.error = error
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,16 +1,12 @@
<template>
<TagSearch :options="iOption" v-bind="$attrs" v-on="$listeners" />
<TagSearch :options="options" v-bind="$attrs" v-on="$listeners" />
</template>
<script>
import TagSearch from '@/components/Table/TagSearch/index.vue'
import i18n from '@/i18n/i18n'
import TagSearch from '@/components/TagSearch'
export default {
name: 'AutoDataSearch',
components: {
TagSearch
},
components: { TagSearch },
props: {
url: {
type: String,
@@ -27,23 +23,9 @@ export default {
default: () => []
}
},
data() {
return {
internalOptions: []
}
},
computed: {
iOption() {
const options = this.options.concat(this.internalOptions)
return _.uniqWith(options, _.isEqual)
}
},
watch: {
options() {
// 便
},
url() {
this.genericOptions()
}
},
mounted() {
@@ -54,7 +36,6 @@ export default {
methods: {
async genericOptions() {
const vm = this // This
vm.internalOptions = [] //
const data = await this.optionUrlMeta()
const meta = data.actions['GET'] || {}
for (const [name, field] of Object.entries(meta)) {
@@ -68,29 +49,27 @@ export default {
label: field.label,
type: field.type,
value: name
}
if (['choice', 'labeled_choice'].indexOf(field.type) > -1 && field.choices) {
if (field.type === 'choice' && field.choices) {
option.children = field.choices.map(item => {
if (typeof (item.value) === 'boolean') {
if (item.value) {
return { label: item.label, value: 'True' }
return { label: item.display_name, value: 'True' }
} else {
return { label: item.label, value: 'False' }
return { label: item.display_name, value: 'False' }
}
}
return { label: item.label, value: item.value }
return { label: item.display_name, value: item.value }
})
}
if (field.type === 'boolean') {
option.children = [
{ label: i18n.t('common.Yes'), value: true },
{ label: i18n.t('common.No'), value: false }
{ label: this.$t('common.Yes'), value: true },
{ label: this.$t('common.No'), value: false }
]
}
if (option.value === 'id') {
option.label = 'ID'
}
vm.internalOptions.push(option)
vm.options.push(option)
}
},
optionUrlMeta() {
@@ -102,4 +81,5 @@ export default {
</script>
<style lang='less' scoped>
</style>

View File

@@ -0,0 +1,152 @@
<template>
<DataTable v-if="!loading" ref="dataTable" v-loading="loading" :config="iConfig" v-bind="$attrs" v-on="$listeners" />
</template>
<script type="text/jsx">
import DataTable from '../DataTable'
import { DateFormatter, DetailFormatter, DisplayFormatter, BooleanFormatter, ActionsFormatter } from '@/components/ListTable/formatters'
import i18n from '@/i18n/i18n'
export default {
name: 'AutoDataTable',
components: {
DataTable
},
props: {
config: {
type: Object,
default: () => ({})
}
},
data() {
return {
loading: true,
method: 'get',
autoConfig: {},
iConfig: {},
meta: {}
}
},
watch: {
config: {
handler(iNew) {
this.optionUrlMetaAndGenCols()
this.$log.debug('AutoDataTable Config change found')
},
deep: true
}
},
created() {
this.optionUrlMetaAndGenCols()
},
methods: {
async optionUrlMetaAndGenCols() {
const url = (this.config.url.indexOf('?') === -1) ? `${this.config.url}?draw=1&display=1` : `${this.config.url}&draw=1&display=1`
this.$store.dispatch('common/getUrlMeta', { url: url }).then(data => {
this.meta = data.actions[this.method.toUpperCase()] || {}
this.generateColumns()
}).catch((error) => {
this.$log.error('Error occur: ', error)
}).finally(() => {
this.loading = false
})
},
generateColumnByName(name, col) {
switch (name) {
case 'name':
col.formatter = DetailFormatter
col.sortable = 'custom'
col.showOverflowTooltip = true
break
case 'actions':
col = {
prop: 'id',
label: i18n.t('common.Actions'),
align: 'center',
width: '150px',
formatter: ActionsFormatter,
formatterArgs: {}
}
break
case 'is_valid':
col.label = i18n.t('common.Validity')
col.formatter = BooleanFormatter
col.align = 'center'
col.width = '80px'
break
case 'datetime':
case 'date_start':
col.formatter = DateFormatter
break
case 'comment':
col.showOverflowTooltip = true
}
return col
},
generateColumnByType(type, col) {
switch (type) {
case 'choice':
col.sortable = 'custom'
col.formatter = DisplayFormatter
break
case 'boolean':
col.formatter = BooleanFormatter
col.align = 'center'
col.width = '80px'
break
case 'datetime':
col.formatter = DateFormatter
col.width = '160px'
}
return col
},
addHelpTipsIfNeed(col) {
const helpTips = col.helpTips
if (!helpTips) {
return col
}
col.renderHeader = (h, { column, $index }) => {
return (
<span>{column.label}
<el-tooltip placement='bottom' effect='light' popperClass='help-tips'>
<div slot='content' domPropsInnerHTML={helpTips} />
<el-button style='padding: 0'>
<i class='fa fa-info-circle' />
</el-button>
</el-tooltip>
</span>
)
}
return col
},
generateColumn(name) {
const colMeta = this.meta[name] || {}
const customMeta = this.config.columnsMeta ? this.config.columnsMeta[name] : {}
let col = { prop: name, label: colMeta.label }
col = this.generateColumnByName(name, col)
col = this.generateColumnByType(colMeta.type, col)
col = Object.assign(col, customMeta)
col = this.addHelpTipsIfNeed(col)
return col
},
generateColumns() {
const config = _.cloneDeep(this.config)
const columns = []
for (let col of config.columns) {
if (typeof col === 'object') {
columns.push(col)
} else if (typeof col === 'string') {
col = this.generateColumn(col)
columns.push(col)
}
}
config.columns = columns
this.iConfig = config
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,14 +1,14 @@
<template>
<DataZTree ref="dataztree" :setting="treeSetting" class="data-z-tree" v-on="$listeners">
<slot v-if="treeSetting.hasRightMenu" slot="rMenu">
<li v-if="treeSetting.showCreate" id="m_create" class="rmenu" tabindex="-1" @click="createTreeNode">
<i class="fa fa-plus-square-o" /> {{ this.$t('tree.CreateNode') }}
<DataZTree ref="dataztree" :setting="treeSetting">
<slot slot="rMenu">
<li id="m_create" class="rmenu" tabindex="-1" @click="createTreeNode">
<i class="fa fa-plus-square-o" /> {{ this.$t('tree.CreateNode') }}
</li>
<li v-if="treeSetting.showUpdate" id="m_edit" class="rmenu" tabindex="-1" @click="editTreeNode">
<i class="fa fa-pencil-square-o" /> {{ this.$t('tree.RenameNode') }}
<li id="m_edit" class="rmenu" tabindex="-1" @click="editTreeNode">
<i class="fa fa-pencil-square-o" /> {{ this.$t('tree.RenameNode') }}
</li>
<li v-if="treeSetting.showDelete" id="m_del" class="rmenu" tabindex="-1" @click="removeTreeNode">
<i class="fa fa-minus-square" /> {{ this.$t('tree.DeleteNode') }}
<li id="m_del" class="rmenu" tabindex="-1" @click="removeTreeNode">
<i class="fa fa-minus-square" /> {{ this.$t('tree.DeleteNode') }}
</li>
<slot name="rMenu" />
</slot>
@@ -16,9 +16,8 @@
</template>
<script>
import DataZTree from '../DataZTree/index.vue'
import DataZTree from '../DataZTree'
import $ from '@/utils/jquery-vendor'
import { mapGetters } from 'vuex'
export default {
name: 'AutoDataZTree',
@@ -35,20 +34,13 @@ export default {
data() {
return {
defaultSetting: {
showCreate: true,
showDelete: true,
showUpdate: true,
showSearch: false,
customTreeHeaderName: this.$t('assets.AssetTree'),
async: {
enable: true,
url: (process.env.VUE_APP_ENV === 'production')
? (`${this.setting.treeUrl}`)
: (`${process.env.VUE_APP_BASE_API}${this.setting.treeUrl}`),
url: (process.env.VUE_APP_ENV === 'production') ? (`${this.setting.treeUrl}`) : (`${process.env.VUE_APP_BASE_API}${this.setting.treeUrl}`),
autoParam: ['id=key', 'name=n', 'level=lv'],
type: 'get',
headers: {
'X-JMS-ORG': this.$store.getters.currentOrg ? this.$store.getters.currentOrg.id : ''
'X-JMS-ORG': JSON.parse(this.$cookie.get('jms_current_org')) ? JSON.parse(this.$cookie.get('jms_current_org')).id : ''
}
},
callback: {
@@ -57,26 +49,20 @@ export default {
onSelected: this.onSelected.bind(this),
beforeDrop: this.beforeDrop.bind(this),
onDrop: this.onDrop.bind(this),
refresh: this.refresh.bind(this),
onAsyncSuccess: this.onAsyncSuccess.bind(this)
refresh: this.refresh.bind(this)
//
// beforeClick
// beforeDrag
// onDrag
// beforeAsync: this.defaultCallback.bind(this, 'beforeAsync')
},
hasRightMenu: true
}
},
currentNode: '',
currentNodeId: ''
}
},
computed: {
...mapGetters([
'currentOrg'
]),
treeSetting() {
this.$log.debug('Settings: ', this.setting)
return _.merge(this.defaultSetting, this.setting)
},
zTree() {
@@ -90,20 +76,6 @@ export default {
$('body').unbind('mousedown')
},
methods: {
onAsyncSuccess(event, treeId, treeNode, msg) {
const nodes = JSON.parse(msg)
nodes.forEach((node) => {
if (treeNode.checked) {
const currentNode = this.zTree.getNodeByParam('id', node.id, null)
currentNode.checked = true
this.zTree.updateNode(currentNode)
}
})
},
refreshTree: function() {
// const refreshIconRef = $('#tree-refresh')
// refreshIconRef.click()
},
editTreeNode: function() {
this.hideRMenu()
const currentNode = this.zTree.getSelectedNodes()[0]
@@ -111,7 +83,7 @@ export default {
return
}
if (currentNode) {
currentNode.name = currentNode.meta.data.value
currentNode.name = currentNode.meta.node.value
}
this.zTree.editName(currentNode)
},
@@ -122,29 +94,19 @@ export default {
// Request URL: http://localhost/api/v1/assets/assets/?node_id=d8212328-538d-41a6-bcfd-1e8cc7e3aed4&show_current_asset=null&draw=2&limit=15&offset=0&_=1587022917769
onSelected: function(event, treeNode) {
const show_current_asset = this.$cookie.get('show_current_asset') || '0'
if (!this.setting.url) {
return
}
let combinator = '?'
if (this.setting.url.indexOf('?') !== -1) {
combinator = '&'
}
let url = ''
const query = Object.assign({}, this.$route.query)
const objectId = treeNode.meta.data.id
if (treeNode.meta.type === 'node') {
this.currentNode = treeNode
this.currentNodeId = treeNode.meta.data.id
query['node'] = this.currentNodeId
query['asset'] = ''
url = `${this.setting.url}${combinator}node_id=${objectId}&show_current_asset=${show_current_asset}`
this.currentNodeId = treeNode.meta.node.id
this.$route.query['node'] = this.currentNodeId
this.$emit('urlChange', `${this.setting.url}${combinator}node_id=${treeNode.meta.node.id}&show_current_asset=${show_current_asset}`)
} else if (treeNode.meta.type === 'asset') {
query['asset'] = treeNode.meta.data?.id || treeNode.id
query['node'] = ''
url = `${this.setting.url}${combinator}asset_id=${query.asset}&show_current_asset=${show_current_asset}`
this.$route.query['asset'] = treeNode.meta.asset.id
this.$emit('urlChange', `${this.setting.url}${combinator}asset_id=${treeNode.meta.asset.id}&show_current_asset=${show_current_asset}`)
}
this.$router.push({ query })
this.$emit('urlChange', url)
},
removeTreeNode: function() {
this.hideRMenu()
@@ -153,32 +115,32 @@ export default {
return
}
this.$axios.delete(
`${this.treeSetting.nodeUrl}${currentNode.meta.data.id}/`
`${this.treeSetting.nodeUrl}${currentNode.meta.node.id}/`
).then(() => {
this.$message.success(this.$tc('common.deleteSuccessMsg'))
this.$message.success(this.$t('common.deleteSuccessMsg'))
this.zTree.removeNode(currentNode)
this.refreshTree()
}).catch(() => {
// this.$message.error(this.$tc('common.deleteErrorMsg') + ' ' + error)
// this.$message.error(this.$t('common.deleteErrorMsg' + ' ' + error))
})
},
onRename: function(event, treeId, treeNode, isCancel) {
const currentNodeId = this.currentNodeId || treeNode.meta.data?.id || ''
const url = `${this.treeSetting.nodeUrl}${currentNodeId}/`
const url = `${this.treeSetting.nodeUrl}${this.currentNodeId}/`
if (isCancel) {
return
}
this.$axios.patch(url, { 'value': treeNode.name }).then(res => {
let assetsAmount = treeNode.meta.data['assetsAmount']
this.$axios.patch(
url,
{ 'value': treeNode.name }
).then(res => {
let assetsAmount = treeNode.meta.node.assetsAmount
if (!assetsAmount) {
assetsAmount = 0
}
treeNode.name = treeNode.name + ' (' + assetsAmount + ')'
treeNode.meta.data = res
this.zTree.updateNode(treeNode)
this.$message.success(this.$tc('common.updateSuccessMsg'))
}).finally(() => {
this.refreshTree()
this.$message.success(this.$t('common.updateSuccessMsg'))
}).catch(error => {
this.$message.error(this.$t('common.updateErrorMsg' + ' ' + error))
})
},
onBodyMouseDown: function(event) {
@@ -191,17 +153,12 @@ export default {
const rMenuID = this.$refs.dataztree.$refs.ztree.iRMenuID
const zTreeID = this.$refs.dataztree.$refs.ztree.iZTreeID
const offset = $(`#${zTreeID}`).offset()
const scrollTop = document.querySelector('.treebox')?.scrollTop
const scrollTop = document.querySelector('.treebox').scrollTop
x -= offset.left
// Tmp
y -= (offset.top + scrollTop) / 3 - 10
x += document.body.scrollLeft
y += document.body.scrollTop + document.documentElement.scrollTop
if (y + $(`#${rMenuID} ul`).height() >= window.innerHeight) {
y -= $(`#${rMenuID} ul`).height()
}
this.rMenu.css({ 'top': y + 'px', 'left': x + 'px', 'visibility': 'visible' })
$(`#${rMenuID} ul`).show()
$('body').bind('mousedown', this.onBodyMouseDown)
@@ -211,7 +168,7 @@ export default {
return
}
//
if (treeNode?.id === '-12') {
if (treeNode.id === '-12') {
return
}
if (!treeNode && event.target.tagName.toLowerCase() !== 'button' && $(event.target).parents('a').length === 0) {
@@ -219,9 +176,6 @@ export default {
this.showRMenu('root', event.clientX, event.clientY)
} else if (treeNode && !treeNode.noR) {
this.zTree.selectNode(treeNode)
if (treeNode.meta?.data?.id) {
this.currentNodeId = treeNode.meta.data.id
}
this.showRMenu('node', event.clientX, event.clientY)
}
},
@@ -240,18 +194,18 @@ export default {
onDrop: function(event, treeId, treeNodes, targetNode, moveType) {
const treeNodesIds = []
$.each(treeNodes, function(index, value) {
treeNodesIds.push(value.meta.data.id)
treeNodesIds.push(value.meta.node.id)
})
const theUrl = `${this.treeSetting.nodeUrl}${targetNode.meta.data.id}/children/add/`
const theUrl = `${this.treeSetting.nodeUrl}${targetNode.meta.node.id}/children/add/`
this.$axios.put(
theUrl, {
nodes: treeNodesIds
}
).then((res) => {
this.$message.success(this.$tc('common.updateSuccessMsg'))
this.$message.success(this.$t('common.updateSuccessMsg'))
}).catch(error => {
this.$message.error(this.$tc('common.updateErrorMsg' + ' ' + error))
}).finally()
this.$message.error(this.$t('common.updateErrorMsg' + ' ' + error))
})
},
createTreeNode: function() {
this.hideRMenu()
@@ -261,70 +215,61 @@ export default {
}
this.zTree.expandNode(parentNode, true, false, true, false)
// http://localhost/api/v1/assets/nodes/85aa4ee2-0bd9-41db-9079-aa3646448d0c/children/
const url = `${this.treeSetting.nodeUrl}${parentNode.meta.data.id}/children/`
const url = `${this.treeSetting.nodeUrl}${parentNode.meta.node.id}/children/`
this.$axios.post(url, {}).then(data => {
const newNode = {
id: data['key'],
name: data['value'],
pId: parentNode.id,
isParent: true,
meta: {
data: data,
type: 'node'
'node': data
}
}
newNode.checked = this.zTree.getSelectedNodes()[0].checked
this.zTree.addNodes(parentNode, 0, newNode)
// vm.$refs.dataztree.refresh()
const node = this.zTree.getNodeByParam('id', newNode.id, parentNode)
this.currentNodeId = node.meta.data.id || newNode.id
this.currentNodeId = node.meta.node.id || newNode.id
this.zTree.editName(node)
this.$message.success(this.$tc('common.createSuccessMsg'))
this.$message.success(this.$t('common.createSuccessMsg'))
}).catch(error => {
this.$message.error(this.$tc('common.createErrorMsg') + ' ' + error)
this.$message.error(this.$t('common.createErrorMsg') + ' ' + error)
})
},
refresh: function() {
this.$axios.post(
'/api/v1/assets/nodes/00000000-0000-0000-0000-000000000000/tasks/',
{ action: 'refresh_cache' }
)
},
getSelectedNodes: function() {
return this.zTree.getSelectedNodes()
},
getNodes: function() {
return this.zTree.getNodes()
},
selectNode: function(node) {
return this.zTree.selectNode(node)
}
}
}
</script>
<style scoped>
.rmenu {
font-size: 12px;
padding: 0 16px;
position: relative;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #606266;
height: 24px;
line-height: 24px;
box-sizing: border-box;
cursor: pointer;
}
<style lang='less' scoped>
.rmenu {
font-size: 12px;
padding: 0 16px;
position: relative;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #606266;
height: 24px;
line-height: 24px;
box-sizing: border-box;
cursor: pointer;
}
.rmenu > a:hover, .dropdown-menu > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.rmenu:hover {
background-color: #f5f7fa;
}
.data-z-tree >>> .fa {
width: 10px;
margin-right: 3px;
}
.rmenu > a:hover, .dropdown-menu > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.rmenu:hover{
background-color: #f5f7fa;
}
</style>

View File

@@ -1,106 +0,0 @@
<script type="text/jsx">
import { toSafeLocalDateStr } from '@/utils/common'
export default {
name: 'ItemValue',
props: {
value: {
type: [String, Number, Function, Array, Object, Boolean],
default: ''
},
item: {
type: Object,
default: () => ({})
},
formatter: {
type: Function,
default: null
}
},
data() {
return {
formatterData: ''
}
},
computed: {
displayValue() {
if ([null, undefined, ''].includes(this.value)) {
return '-'
}
if (typeof this.value === 'boolean') {
return this.toChoicesDisplay(this.value)
} else if (typeof this.value === 'object') {
return this.value
} else if (this.value instanceof Array) {
return this.value.map(item => {
if (typeof item === 'object') {
return item.label || item.title
} else {
return item
}
}).join(', ')
} else if (this.isDatetime(this.value)) {
return toSafeLocalDateStr(this.value)
} else {
return this.value
}
}
},
methods: {
toChoicesDisplay(value) {
if (!value) {
return this.$t('common.No')
}
return this.$t('common.Yes')
},
isDatetime(value) {
if (typeof value !== 'string') {
return false
}
if (value.split(' ').length !== 3) {
return false
}
if (value.split(' ')[1].split(':').length !== 3) {
return false
}
if (isNaN(value) && !isNaN(Date.parse(value))) {
return true
}
}
},
render(h) {
if (typeof this.formatter === 'function') {
const data = this.formatter(this.item, this.value)
if (data instanceof Promise) {
data.then(res => {
this.formatterData = res
})
} else {
this.formatterData = data
}
return (
<span>{this.formatterData}</span>
)
}
if (this.value instanceof Array) {
const newArr = this.value || []
return (
<span>
{
newArr.map((item, index) => <div key={index}>{item.key}{item.value} </div>)
}
</span>
)
}
return (
<span>{this.displayValue}</span>
)
}
}
</script>
<style scoped>
a {
color: var(--color-success);
}
</style>

View File

@@ -1,173 +0,0 @@
<template>
<DetailCard v-if="!loading && hasObject && items.length > 0" :items="items" v-bind="$attrs" />
</template>
<script>
import DetailCard from './index.vue'
import { copy, toSafeLocalDateStr } from '@/utils/common'
export default {
name: 'AutoDetailCard',
components: { DetailCard },
props: {
object: {
type: Object,
default: () => ({})
},
url: {
type: String,
required: true
},
fields: {
type: Array,
default: null
},
excludes: {
type: Array,
default: null
},
showUndefine: {
type: Boolean,
default: true
},
formatters: {
type: Object,
default: () => ({})
},
nested: {
type: String,
default: null
}
},
data() {
return {
items: [],
loading: true
}
},
computed: {
iObject() {
if (this.nested) {
return this.object[this.nested] || {}
} else {
return this.object
}
},
hasObject() {
return Object.keys(this.iObject).length > 0
}
},
async mounted() {
await this.optionAndGenFields()
this.loading = false
},
methods: {
defaultFormatter(fields) {
const formatter = {}
for (const name of fields) {
formatter[name] = function(item, val) {
if (val === '-') {
return <span>{'-'}</span>
}
return (<span style={{ cursor: 'pointer' }} onClick={() => copy(val)}>
{val}
</span>)
}
}
return formatter
},
async optionAndGenFields() {
const data = await this.$store.dispatch('common/getUrlMeta', { url: this.url })
let remoteMeta = data.actions['GET'] || {}
if (this.nested) {
remoteMeta = remoteMeta[this.nested]?.children || {}
}
let fields = this.fields
fields = fields || Object.keys(remoteMeta)
const defaultExcludes = ['org_id']
const excludes = (this.excludes || []).concat(defaultExcludes)
fields = fields.filter(item => !excludes.includes(item))
const defaultFormatter = this.defaultFormatter(fields)
for (const name of fields) {
if (typeof name === 'object') {
this.items.push(name)
continue
}
const fieldMeta = remoteMeta[name]
if (!fieldMeta) {
continue
}
if (fieldMeta['write_only']) {
continue
}
let value = this.iObject[name]
const label = fieldMeta.label
if (Array.isArray(value)) {
if (typeof value[0] === 'object') {
value.forEach(item => {
const fieldName = `${name}.${item.name}`
if (excludes.includes(fieldName)) {
return
}
this.items.push({
key: item.label,
value: item.value
})
})
} else if (typeof value[0] === 'string') {
value.forEach((item, index) => {
let data = {}
if (index === 0) {
data = {
key: label,
value: value[index]
}
} else {
data = {
value: value[index]
}
}
this.items.push(data)
})
}
continue
}
if (value === null || value === '') {
value = '-'
} else if (fieldMeta.type === 'datetime') {
value = toSafeLocalDateStr(value)
} else if (fieldMeta.type === 'labeled_choice') {
value = value?.['label']
} else if (fieldMeta.type === 'related_field' || fieldMeta.type === 'nested object') {
value = value?.['name']
} else if (fieldMeta.type === 'm2m_related_field') {
value = value?.map(item => item['name']).join(', ')
} else if (fieldMeta.type === 'boolean') {
value = value ? this.$t('common.Yes') : this.$t('common.No')
}
if (value === undefined) {
if (this.showUndefine) {
value = '-'
} else {
continue
}
}
const item = {
key: label,
value: value,
formatter: this.formatters[name] || defaultFormatter[name]
}
this.items.push(item)
}
}
}
}
</script>
<style scoped>
</style>

View File

@@ -1,82 +0,0 @@
<template>
<IBox :fa="fa" :title="title">
<el-form class="content" label-position="left" label-width="25%">
<el-form-item v-for="item in items" :key="item.key" :label="item.key">
<ItemValue :value="item.value" class="item-value" v-bind="item" />
</el-form-item>
</el-form>
<slot />
</IBox>
</template>
<script>
import IBox from '../../IBox/index.vue'
import ItemValue from './ItemValue.vue'
export default {
name: 'DetailCard',
components: { IBox, ItemValue },
props: {
title: {
type: String,
default() {
return this.$t('common.BasicInfo')
}
},
fa: {
type: String,
default: 'fa-info-circle'
},
items: {
type: Array,
default: () => []
},
align: {
type: String,
default: 'left'
}
}
}
</script>
<style lang="scss" scoped>
.el-card__body {
padding: 20px 40px;
}
.el-form-item {
border-bottom: 1px dashed #EBEEF5;
padding: 1px 0;
margin-bottom: 0;
&:last-child {
border-bottom: none;
}
&:hover {
}
>>> .el-form-item__label {
padding-right: 8%;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
>>> .el-form-item__content {
font-size: 13px;
}
>>> .el-tag--mini {
margin-right: 3px;
}
}
.item-value span {
word-break: break-word;
}
.content {
font-size: 13px;
line-height: 2.5;
}
</style>

View File

@@ -1,210 +0,0 @@
<template>
<div :class="grouped ? 'el-button-group' : 'el-button-ungroup'" class="layout">
<template v-for="action in iActions">
<el-dropdown
v-if="action.dropdown"
v-show="action.dropdown.length > 0"
:key="action.name"
class="action-item"
trigger="click"
placement="bottom-start"
@command="handleDropdownCallback"
>
<el-button class="more-action" :size="size" v-bind="cleanButtonAction(action)">
{{ action.title }}<i class="el-icon-arrow-down el-icon--right" />
</el-button>
<el-dropdown-menu slot="dropdown" style="overflow: auto;max-height: 60vh">
<template v-for="option in action.dropdown">
<div
v-if="option.group"
:key="'group:'+option.name"
class="dropdown-menu-title"
style="width:130px"
>
{{ option.group }}
</div>
<el-dropdown-item
:key="option.name"
:command="[option, action]"
v-bind="option"
>
<span v-if="option.fa">
<i v-if="option.fa.startsWith('fa-')" :class="'fa ' + option.fa" />
<svg-icon v-else :icon-class="option.fa" style="font-size: 14px; margin-right: 2px; margin-left: -2px;" />
</span>
{{ option.title }}
</el-dropdown-item>
</template>
</el-dropdown-menu>
</el-dropdown>
<el-button
v-else
:key="action.name"
:size="size"
v-bind="cleanButtonAction(action)"
class="action-item"
@click="handleClick(action)"
>
<el-tooltip :disabled="!action.tip" :content="action.tip" placement="top">
<span>
<span v-if="action.fa" style="vertical-align: initial;">
<i v-if="action.fa.startsWith('fa-')" :class="'fa ' + action.fa" />
<svg-icon v-else :icon-class="action.fa" style="font-size: 14px;" />
</span>
{{ action.title }}
</span>
</el-tooltip>
</el-button>
</template>
</div>
</template>
<script>
export default {
name: 'DataActions',
props: {
grouped: {
type: Boolean,
default: false
},
size: {
type: String,
default: 'small'
},
type: {
type: String,
default: ''
},
actions: {
type: Array,
default: () => []
}
},
computed: {
iActions() {
return this.cleanActions(this.actions)
}
},
methods: {
handleDropdownCallback(command) {
const [option, dropdown] = command
const defaultCallback = () => this.$log.debug('No callback found: ', option, dropdown)
let callback = option.callback
if (!callback) {
callback = dropdown.callback
}
if (!callback) {
callback = defaultCallback
}
return callback(option)
},
handleClick(action) {
if (action && action.callback) {
action.callback(action)
} else {
this.$log.debug('No callback found')
}
this.$emit('actionClick', action)
},
checkItem(item, attr, defaults) {
if (!item) {
return true
}
let ok = item[attr]
if (ok && typeof ok === 'function') {
ok = ok(item)
} else if (ok == null) {
ok = defaults === undefined ? true : defaults
}
return ok
},
cleanButtonAction(action) {
action = _.cloneDeep(action)
delete action['dropdown']
delete action['callback']
delete action['name']
delete action['can']
return action
},
cleanActions(actions) {
const cleanedActions = []
const cloneActions = _.cloneDeep(actions)
for (const v of cloneActions) {
if (!v) {
continue
}
const action = Object.assign({}, v)
// 是否拥有这个action
const has = this.checkItem(action, 'has')
delete action['has']
if (!has) {
continue
}
// 是否有分割线
action.divided = this.checkItem(action, 'divided', false)
// 是否是disabled
const can = this.checkItem(action, 'can')
action.disabled = !can
if (action.dropdown) {
// const dropdown = this.cleanActions(action.dropdown)
action.dropdown = this.cleanActions(action.dropdown)
}
cleanedActions.push(action)
}
return cleanedActions
}
}
}
</script>
<style lang="scss" scoped>
.layout {
display: flex;
justify-content: center;
}
.dropdown-menu-title {
text-align: left;
font-size: 12px;
color: #909399;
line-height: 30px;
padding-left: 10px;
padding-top: 10px;
border-top: solid 1px #e4e7ed;
}
.dropdown-menu-title:first-child {
padding-top: 0;
border-top: none;
}
.el-button-ungroup .action-item {
margin-left: 4px;
}
.el-button-ungroup .action-item:first-child {
margin-left: 0;
}
::v-deep .more-batch-processing {
&.el-dropdown-menu__item--divided {
margin-top: 0;
border-top: none;
color: #909399;
cursor: auto;
font-size: 12px;
line-height: 30px;
border-bottom: 1px solid #E4E7ED;
&:before {
height: 0;
}
}
&.el-dropdown-menu__item:not(.is-disabled):hover {
color: #909399;
background-color: #FFFFFF;
}
}
</style>

View File

@@ -43,25 +43,16 @@
<template v-for="opt in options">
<el-option
v-if="data.type === 'select'"
:key="opt.label"
:key="opt.value"
v-bind="opt"
/>
<el-checkbox-button
v-else-if="data.type === 'checkbox-group' && data.style === 'button'"
:key="opt.value"
v-bind="opt"
:label="'value' in opt ? opt.value : opt.label"
>
{{ opt.label }}
</el-checkbox-button>
<!-- TODO: 支持 el-checkbox-button 变体 -->
<el-checkbox
v-else-if="data.type === 'checkbox-group' && data.style !== 'button'"
:key="opt.value"
v-else-if="data.type === 'checkbox-group'"
:key="opt.label"
v-bind="opt"
:label="'value' in opt ? opt.value : opt.label"
>
{{ opt.label }}
{{ opt.value }}
</el-checkbox>
<!-- WARNING: radio label 属性来表示 value 的含义 -->
<!-- FYI: radio value 属性可以在没有 radio-group 时用来关联到同一个 v-model -->
@@ -106,7 +97,6 @@ export default {
}
},
props: {
// eslint-disable-next-line vue/require-default-prop
data: Object,
prop: {
type: String,
@@ -114,13 +104,10 @@ export default {
return this.data.id
}
},
// eslint-disable-next-line vue/require-prop-types,vue/require-default-prop
itemValue: {},
// eslint-disable-next-line vue/require-default-prop
value: Object,
disabled: Boolean,
readonly: Boolean,
// eslint-disable-next-line vue/require-default-prop
options: Array
},
data() {
@@ -238,9 +225,7 @@ export default {
.then(resp => {
if (isOptionsCase) {
let formRenderer = this.$parent
while (formRenderer.$options._componentTag !== 'el-form-renderer') {
formRenderer = formRenderer.$parent
}
while (formRenderer.$options._componentTag !== 'el-form-renderer') { formRenderer = formRenderer.$parent }
formRenderer.setOptions(this.prop, resp)
} else {
this.propsInner = { [prop]: resp }

View File

@@ -1,7 +1,7 @@
<template>
<el-form ref="elForm" v-bind="$attrs" :model="value" class="el-form-renderer">
<template v-for="item in innerContent">
<slot v-if="!isHidden(item)" :name="`id:${item.id}`" />
<slot :name="`id:${item.id}`" />
<component
:is="item.type === GROUP ? 'render-form-group' : 'render-form-item'"
:key="item.id"
@@ -13,7 +13,7 @@
:options="options[item.id]"
@updateValue="updateValue"
/>
<slot v-if="!isHidden(item)" :name="`$id:${item.id}`" />
<slot :name="`$id:${item.id}`" />
</template>
<slot />
</el-form>
@@ -146,7 +146,7 @@ export default {
* - el-form resetFields 不会触发 input & change 事件无法监听
* - bug1: https://github.com/FEMessage/el-data-table/issues/176#issuecomment-587280825
* - bug2:
* 0. 建议先在监听器 watch.value // debug(v.name, oldV.name)
* 0. 建议先在监听器 watch.value console.log(v.name, oldV.name)
* 1. 打开 basic 示例
* 2. label name 的输入框里输入 1此时 log'1' ''
* 3. 点击 reset 按钮此时 log 两条数据 '1' '1', '' ''
@@ -202,18 +202,6 @@ export default {
setOptions(id, options) {
_set(this.options, id, options)
this.options = { ...this.options } // options
},
isHidden(item) {
if (!item.el || !item.el['hiddenGroup']) {
return false
}
if (item.hidden === true) {
return true
}
if (typeof item.hidden === 'function') {
return item.hidden(this.value)
}
return false
}
}
}

View File

@@ -0,0 +1,122 @@
<template>
<ElFormRender
ref="form"
:content="fields"
:form="basicForm"
label-position="right"
label-width="17%"
v-bind="$attrs"
v-on="$listeners"
>
<!-- slot 透传 -->
<slot v-for="item in fields" :slot="`id:${item.id}`" :name="`id:${item.id}`" />
<slot v-for="item in fields" :slot="`$id:${item.id}`" :name="`$id:${item.id}`" />
<el-form-item>
<el-button v-for="button in moreButtons" :key="button.title" size="small" v-bind="button" @click="handleClick(button)">{{ button.title }}</el-button>
<el-button v-if="defaultButton && hasReset" size="small" @click="resetForm('form')">{{ $t('common.Reset') }}</el-button>
<el-button v-if="defaultButton" size="small" :loading="isSubmitting" type="primary" @click="submitForm('form')">{{ $t('common.Submit') }}</el-button>
</el-form-item>
</ElFormRender>
</template>
<script>
import ElFormRender from './components/el-form-renderer'
export default {
components: {
ElFormRender
},
props: {
defaultButton: {
type: Boolean,
default: true
},
hasReset: {
type: Boolean,
default: true
},
fields: {
type: Array,
default: () => []
},
// 初始值
form: {
type: Object,
default: () => { return {} }
},
moreButtons: {
type: Array,
default: () => []
},
isSubmitting: {
type: Boolean,
default: false
}
},
data() {
return {
basicForm: this.form
}
},
methods: {
// 获取表单数据
submitForm(formName) {
const form = this.$refs[formName]
form.validate((valid) => {
if (valid) {
this.$emit('submit', form.getFormValue(), form)
} else {
this.$emit('invalid', valid)
return false
}
})
},
// 重置表单
resetForm(formName) {
this.$refs[formName].resetFields()
},
handleClick(button) {
const callback = button.callback || function(values, form) {
console.log('Click ', button.title, ': ', values)
}
const form = this.$refs['form']
const values = form.getFormValue()
callback(values, form)
}
}
}
</script>
<style lang="less" scoped>
.el-form ::v-deep .el-form-item {
margin-bottom: 12px;
}
.el-form ::v-deep .el-form-item__content {
width: 75%;
}
.el-form ::v-deep .el-form-item__label {
padding: 0 30px 0 0;
}
.el-form ::v-deep .el-form-item__error {
position: inherit;
}
.el-form ::v-deep .form-group-header {
margin-left: 50px;
}
.el-form ::v-deep .help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #999;
font-size: 12px;
line-height: 18px;
}
.el-form ::v-deep .help-block a {
color: #1c84c6;
}
</style>

View File

@@ -0,0 +1,14 @@
import i18n from '@/i18n/i18n'
export const Required = {
required: true, message: i18n.t('common.fieldRequiredError'), trigger: 'blur'
}
export const RequiredChange = {
required: true, message: i18n.t('common.fieldRequiredError'), trigger: 'change'
}
export default {
Required,
RequiredChange
}

View File

@@ -8,13 +8,12 @@
<el-table
ref="table"
v-loading="loading"
v-bind="tableAttrs"
:data="data"
:row-class-name="rowClassName"
v-bind="tableAttrs"
@select="selectStrategy.onSelect"
v-on="$listeners"
@selection-change="selectStrategy.onSelectionChange"
@select-all="selectStrategy.onSelectAll($event, canSelect)"
@select="selectStrategy.onSelect"
@select-all="selectStrategy.onSelectAll($event, selectable)"
@sort-change="onSortChange"
>
<!--TODO 不用jsx写, 感觉template逻辑有点不清晰了-->
@@ -91,13 +90,10 @@
<!--非树-->
<template v-else>
<el-data-table-column v-if="hasSelection" :align="selectionAlign" :selectable="canSelect" type="selection" />
<el-data-table-column v-if="hasSelection" type="selection" :align="selectionAlign" />
<el-data-table-column
v-for="col in columns"
:key="col.prop"
:filter-method="typeof col.filterMethod === 'function' ? col.filterMethod : null"
:filter-multiple="false"
:filters="col.filters || null"
:formatter="typeof col.formatter === 'function' ? col.formatter : null"
v-bind="{align: columnsAlign, ...col}"
>
@@ -105,14 +101,14 @@
<div
:is="col.formatter"
:key="row.id"
:cell-value="row[col.prop]"
:col="col"
:table-data="data"
:row="row"
:column="column"
:index="index"
:reload="getList"
:row="row"
:table-data="data"
:url="url"
:reload="getList"
:col="col"
:cell-value="row[col.prop]"
/>
</template>
</el-data-table-column>
@@ -122,12 +118,13 @@
<el-pagination
v-if="hasPagination"
:background="paginationBackground"
:current-page="page"
:layout="paginationLayout"
:page-size="size"
:page-sizes="paginationSizes"
:page-size="size"
:total="total"
:background="paginationBackground"
style="text-align: right; padding: 10px 0;"
:layout="paginationLayout"
v-bind="extraPaginationAttrs"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
@@ -135,18 +132,18 @@
<the-dialog
ref="dialog"
:button-size="buttonSize"
:dialog-attrs="dialogAttrs"
:new-title="dialogNewTitle"
:edit-title="dialogEditTitle"
:view-title="dialogViewTitle"
:form="form"
:form-attrs="formAttrs"
:new-title="dialogNewTitle"
:view-title="dialogViewTitle"
:dialog-attrs="dialogAttrs"
:button-size="buttonSize"
@confirm="onConfirm"
>
<template v-slot="scope">
<!-- @slot 表单作用域插槽当编辑查看时传入row新增时row=null -->
<slot :row="scope.row" name="form" />
<slot name="form" :row="scope.row" />
</template>
</the-dialog>
</template>
@@ -166,8 +163,7 @@ import getLocatedSlotKeys from './utils/extract-keys'
import transformSearchImmediatelyItem from './utils/search-immediately-item'
import isFalsey from './utils/is-falsey'
import merge from 'deepmerge'
const defaultFirstPage = 1
const defaultFirstPage = 0
const noPaginationDataPath = 'payload'
export default {
@@ -268,8 +264,7 @@ export default {
*/
beforeSearch: {
type: Function,
default() {
}
default() {}
},
/**
* 单选, 适用场景: 不可以批量删除
@@ -361,36 +356,28 @@ export default {
*/
newText: {
type: String,
default: function() {
return this.$t('ops.Add')
}
default: '新增'
},
/**
* 修改按钮文案
*/
editText: {
type: String,
default: function() {
return this.$t('ops.Modify')
}
default: '修改'
},
/**
* 查看按钮文案
*/
viewText: {
type: String,
default: function() {
return this.$t('ops.View')
}
default: '查看'
},
/**
* 删除按钮文案
*/
deleteText: {
type: String,
default: function() {
return this.$t('ops.Delete')
}
default: '删除'
},
/**
* 删除提示语接受要删除的数据单个对象或数组返回字符串
@@ -400,7 +387,7 @@ export default {
deleteMessage: {
type: Function,
default() {
return this.$t('ops.Confirm') + this.deleteText + '?'
return `确认${this.deleteText}吗?`
}
},
/**
@@ -435,6 +422,7 @@ export default {
onEdit: {
type: Function,
default(row) {
console.log('On delete row')
}
},
/**
@@ -459,7 +447,7 @@ export default {
onSuccess: {
type: Function,
default() {
return this.$message.success(this.$t('ops.SuccessfulOperation'))
return this.$message.success('操作成功')
}
},
/**
@@ -716,8 +704,7 @@ export default {
},
extraPaginationAttrs: {
type: Object,
default: () => {
}
default: () => {}
},
hasSelection: {
type: Boolean,
@@ -726,16 +713,6 @@ export default {
hasDetail: {
type: Boolean,
default: true
},
canSelect: {
type: Function,
default(row, index) {
return true
}
},
totalData: {
type: Array,
default: null
}
},
data() {
@@ -823,13 +800,6 @@ export default {
},
_searchForm() {
return transformSearchImmediatelyItem(this.collapseForm, this)
},
lastPageNum() {
// page
const pageOffset = this.firstPage - defaultFirstPage
const pageCount = Math.ceil(this.total / this.size)
const lastPageNum = pageCount + pageOffset
return lastPageNum
}
},
watch: {
@@ -848,13 +818,6 @@ export default {
* @property {array} rows - 已选中的行数据的数组
*/
this.$emit('selection-change', val)
},
totalData(val) {
if (val && val.length !== this.total) {
this.page = defaultFirstPage
this.total = val.length
this.getList()
}
}
},
mounted() {
@@ -871,9 +834,6 @@ export default {
}
}
}
if (this.totalData) {
this.getList()
}
},
methods: {
getQuery() {
@@ -907,58 +867,12 @@ export default {
}
return query
},
getPageData() {
return this.data
},
async gotoNextPage() {
if (!this.hasNextPage()) {
return false
}
this.page += 1
await this.getList({ loading: true })
},
hasNextPage() {
return this.page < this.lastPageNum
},
getList({ loading = true } = {}) {
const { url } = this
if (url) {
return this.getListFromRemote({ loading: loading })
}
if (this.totalData) {
return this.getListFromStaticData({ loading: true })
}
// this.$log.debug("last page is: ", this.lastPageNum)
},
getListFromStaticData({ loading = true } = {}) {
if (loading) {
this.loading = true
}
if (!this.hasPagination) {
this.data = this.totalData
this.loading = false
if (this.isTree) {
this.data = this.tree2Array(this.data, this.expandAll)
}
return this.data
}
// page
const pageOffset = this.firstPage - defaultFirstPage
const page = this.page === 0 ? 1 : this.page
const start = (page + pageOffset - 1) * this.size
const end = (page + pageOffset) * this.size
this.$log.debug(`page: ${page}, size: ${this.size}, start: ${start}, end: ${end}`)
this.data = this.totalData.slice(start, end)
this.loading = false
this.data = this.tree2Array(this.data, this.expandAll)
return this.data
},
/**
* 手动刷新列表数据选项的默认值为: { loading: true }
* @public
* @param {object} options 方法选项
*/
getListFromRemote({ loading = true } = {}) {
getList({ loading = true } = {}) {
const { url } = this
if (!url) {
return
@@ -1047,7 +961,6 @@ export default {
} else {
this.innerQuery = merge(this.innerQuery, attrs)
}
this.selected.splice(0, this.selected.length)
return this.getList()
},
searchDate(attrs) {
@@ -1087,7 +1000,7 @@ export default {
},
handleSizeChange(val) {
if (this.size === val) return
this.$emit('sizeChange', val)
this.page = defaultFirstPage
this.size = val
this.getList()
@@ -1167,7 +1080,7 @@ export default {
* @param {object|object[]} - 要删除的数据对象或数组
*/
onDefaultDelete(data) {
this.$confirm(this.deleteMessage(data), this.$t('common.Info'), {
this.$confirm(this.deleteMessage(data), '提示', {
type: 'warning',
confirmButtonClass: 'el-button--danger',
beforeClose: async(action, instance, done) => {
@@ -1210,13 +1123,11 @@ export default {
remain === 0 &&
this.page === lastPage &&
this.page > defaultFirstPage
) {
this.page--
}
) { this.page-- }
},
// table
// https://github.com/PanJiaChen/vue-element-admin/tree/master/@/components/TreeTable
// https://github.com/PanJiaChen/vue-element-admin/tree/master/src/components/TreeTable
tree2Array(data, expandAll, parent = null, level = null) {
let tmp = []
data.forEach(record => {

View File

@@ -0,0 +1,16 @@
.el-data-table ::v-deep .el-pagination{
text-align: center !important;
}
.el-data-table ::v-deep .el-table td{
padding: 4px 0;
}
.el-data-table ::v-deep .el-table th{
padding: 4px 0;
}
.el-data-table ::v-deep .el-form-item{
margin-bottom:10px !important ;
margin-top:10px;
}
.el-data-table ::v-deep .el-pagination{
padding:15px 0 !important ;
}

View File

@@ -1,17 +1,9 @@
<template>
<ElDatableTable
ref="table"
class="el-data-table"
v-bind="tableConfig"
@sizeChange="handleSizeChange"
@update="onUpdate"
v-on="iListeners"
/>
<ElDatableTable ref="table" class="el-table" v-bind="tableConfig" @update="onUpdate" v-on="iListeners" />
</template>
<script>
import { default as ElDatableTable } from './compenents/el-data-table'
import { mapGetters } from 'vuex'
export default {
name: 'DataTable',
@@ -21,8 +13,7 @@ export default {
props: {
config: {
type: Object,
default: () => {
}
default: () => {}
}
},
data() {
@@ -50,11 +41,7 @@ export default {
stripe: false, //
border: true, //
fit: true, // ,
tooltipEffect: 'dark',
rowClassName: ({ row }) => {
const selected = this.dataTable.selected.find(item => item.id === row.id)
return selected ? 'selected-row' : ''
}
tooltipEffect: 'dark'
},
extraButtons: userTableActions.extraButtons,
onEdit: (row) => {
@@ -70,8 +57,8 @@ export default {
},
pageCount: 5,
paginationLayout: 'total, sizes, prev, pager, next',
paginationSize: JSON.parse(localStorage.getItem('paginationSize')) || 15,
paginationSizes: [15, 30, 50, 100],
paginationSize: 15,
paginationBackground: true,
transformQuery: query => {
if (query.page && query.size) {
@@ -92,40 +79,31 @@ export default {
}
return query
},
theRowDefaultIsSelected: (row) => {
return false
}
theRowDefaultIsSelected: (row) => { return false }
}
}
},
computed: {
iListeners() {
const defaultListeners = {}
return Object.assign(defaultListeners, this.$listeners, this.tableConfig?.listeners)
},
dataTable() {
return this.$refs.table
},
tableConfig() {
const tableDefaultConfig = this.defaultConfig
let tableAttrs = tableDefaultConfig.tableAttrs
if (this.config.tableAttrs) {
tableAttrs = Object.assign(tableAttrs, this.config.tableAttrs)
}
const config = Object.assign(tableDefaultConfig, this.config)
config.tableAttrs = tableAttrs
this.$log.debug('elTableConfig', config)
const config = Object.assign(this.defaultConfig, this.config)
return config
},
...mapGetters({
'globalTableConfig': 'tableConfig'
})
iListeners() {
return Object.assign({}, this.$listeners, this.tableConfig.listeners)
}
},
watch: {
config: {
handler() {
// this.getList()
},
deep: true
}
},
watch: {},
methods: {
getList() {
this.$refs.table?.clearSelection()
return this.$refs.table?.getList()
this.$refs.table.clearSelection()
return this.$refs.table.getList()
},
getData() {
return this.$refs.table.data
@@ -153,19 +131,42 @@ export default {
this.toggleRowSelection(row, true)
}
}
},
handleSizeChange(val) {
localStorage.setItem('paginationSize', val)
this.$store.commit('table/SET_TABLE_CONFIG',
{
key: 'paginationSize',
value: val
}
)
}
}
}
</script>
<style lang="scss" scoped>
<style lang="less" scoped>
.el-table ::v-deep .el-table__row > td {
line-height: 1.5;
padding: 8px 0;
}
.el-table ::v-deep .el-table__row > td> div > span {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.el-table ::v-deep .el-table__header > thead > tr >th {
padding: 8px 0;
background-color: #F5F5F6;
font-size: 13px;
line-height: 1.5;
}
.table{
margin-top: 15px;
}
//
.el-pagination ::v-deep .el-pagination__total{
float: left;
}
.el-pagination ::v-deep .el-pagination__sizes{
float: left;
}
//
// .el-button--text{
// color: #409EFF;
// }
</style>

View File

@@ -0,0 +1,188 @@
<template>
<div>
<div class="treebox">
<ul :id="iZTreeID" class="ztree">
{{ this.$t('common.tree.Loading') }}...
</ul>
<div v-if="treeSetting.treeUrl===''">
{{ this.$t('common.tree.Empty') }}<a id="tree-refresh"><i class="fa fa-refresh" /></a>
</div>
</div>
<div :id="iRMenuID" class="rMenu">
<ul class="dropdown-menu menu-actions">
<slot name="rMenu" />
</ul>
</div>
</div>
</template>
<script>
// 导入JQuery
// eslint-disable-next-line no-unused-vars
import $ from '@/utils/jquery-vendor.js'
import '@ztree/ztree_v3/js/jquery.ztree.all.min.js'
import '@/styles/ztree.css'
const defaultObject = {
type: Object,
default: () => {}
}
export default {
name: 'ZTree',
components: {
},
props: {
setting: defaultObject
},
data() {
return {
iZTreeID: `zTree_${this._uid}`,
iRMenuID: `rMenu_${this._uid}`,
zTree: '',
rMenu: ''
}
},
computed: {
treeSetting() {
return this.setting
}
},
mounted() {
this.initTree()
// $('.treebox').css('height', window.innerHeight - 60)
},
beforeDestroy() {
$.fn.zTree.destroy(this.iZTreeID)
},
methods: {
initTree: function() {
this.$axios.get(this.treeSetting.treeUrl).then(res => {
if (!res) {
res = []
}
if (res.length === 0) {
res.push({
name: this.$t('common.tree.Empty')
})
}
this.zTree = $.fn.zTree.init($(`#${this.iZTreeID}`), this.treeSetting, res)
if (this.treeSetting.showRefresh) {
this.rootNodeAddDom(
this.zTree,
this.treeSetting.callback.refresh
)
}
if (this.treeSetting.showMenu) {
this.rMenu = $(`#${this.iRMenuID}`)
}
if (this.treeSetting.otherMenu) {
$('.menu-actions').append(this.otherMenu)
}
})
},
rootNodeAddDom: function(ztree, callback) {
const vm = this
const refreshIcon = "<a id='tree-refresh'><i class='fa fa-refresh'></i></a>"
const rootNode = ztree.getNodes()[0]
let $rootNodeRef
if (rootNode) {
$rootNodeRef = $('#' + rootNode.tId + '_a')
$rootNodeRef.after(refreshIcon)
} else {
$rootNodeRef = $('#' + ztree.setting.treeId)
$rootNodeRef.html(refreshIcon)
}
const refreshIconRef = $('#tree-refresh')
refreshIconRef.bind('click', function() {
ztree.destroy()
const result = callback()
if (result && result.then) {
result.finally(() => {
vm.initTree()
})
} else {
vm.initTree()
}
})
},
refresh: function() {
const refreshIconRef = $('#tree-refresh')
refreshIconRef.click()
},
getCheckedNodes: function() {
return this.zTree.getCheckedNodes(true)
}
}
}
</script>
<style lang='less' scoped>
div.rMenu {
position: absolute;
visibility: hidden;
text-align: left;
top: 0;
left: 0;
z-index: 999;
float: left;
padding: 0 0;
margin: 2px 0 0;
list-style: none;
background-clip: padding-box;
}
.dataTables_wrapper .dataTables_processing {
opacity: .9;
border: none;
}
div.rMenu li{
margin: 6px 0;
cursor: pointer;
list-style: none outside none;
}
.dropdown-menu {
border: medium none;
min-width: 160px;
background-color: #fff;
border-radius: 3px;
box-shadow: 0 0 3px rgba(86, 96, 117, 0.7);
display: block;
float: left;
font-size: 12px;
left: 0;
list-style: none outside none;
padding: 0;
position: absolute;
text-shadow: none;
top: 100%;
z-index: 1000;
}
.ztree ::v-deep .fa-refresh {
font: normal normal normal 14px/1 FontAwesome !important;
}
.dropdown a:hover {
background-color: #f1f1f1
}
.dropdown-menu > li > a {
border-radius: 3px;
color: inherit;
line-height: 25px;
margin: 4px;
text-align: left;
font-weight: normal;
display: block;
padding: 3px 20px;
clear: both;
white-space: nowrap;
}
.dropdown-menu>li>a:hover, .dropdown-menu>li>a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.treebox {
height: 80vh;
overflow: auto;
}
</style>

View File

@@ -1,15 +1,14 @@
<template>
<ZTree ref="ztree" :setting="treeSetting" v-on="$listeners">
<ZTree ref="ztree" :setting="treeSetting">
<!--Slot透传-->
<div slot="rMenu" slot-scope="{data}">
<slot :data="data" name="rMenu" />
<slot name="rMenu" :data="data" />
</div>
</ZTree>
</template>
<script>
import ZTree from './components/ZTree/index.vue'
import ZTree from './components/ZTree'
export default {
name: 'DataZTree',
components: {
@@ -38,8 +37,8 @@ export default {
showRemoveBtn: false,
showRenameBtn: false,
drag: {
isCopy: false,
isMove: false
isCopy: true,
isMove: true
}
},
callback: {
@@ -73,7 +72,7 @@ export default {
},
methods: {
defaultCallback: function(action) {
// debug(action)
console.log(action)
}
}
}

View File

@@ -2,9 +2,9 @@
<el-date-picker
v-model="value"
type="datetimerange"
:range-separator="$tc('common.To')"
:start-placeholder="$tc('common.DateStart')"
:end-placeholder="$tc('common.DateEnd')"
:range-separator="this.$t('common.To')"
:start-placeholder="this.$t('common.DateStart')"
:end-placeholder="this.$t('common.DateEnd')"
size="small"
:clearable="false"
class="datepicker"
@@ -41,23 +41,37 @@ export default {
shortcuts: [
{
text: this.$t('common.DateLast24Hours'),
onClick: (picker) => this.onShortcutClick(picker, 1)
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24)
picker.$emit('pick', [start, end])
}
},
{
text: this.$t('common.DateLastWeek'),
onClick: (picker) => this.onShortcutClick(picker, 7)
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
picker.$emit('pick', [start, end])
}
}, {
text: this.$t('common.DateLastMonth'),
onClick: (picker) => this.onShortcutClick(picker, 30)
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
picker.$emit('pick', [start, end])
}
}, {
text: this.$t('common.DateLast3Months'),
onClick: (picker) => this.onShortcutClick(picker, 90)
}, {
text: this.$t('common.DateLastHarfYear'),
onClick: (picker) => this.onShortcutClick(picker, 183)
}, {
text: this.$t('common.DateLastYear'),
onClick: (picker) => this.onShortcutClick(picker, 365)
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
picker.$emit('pick', [start, end])
}
}
]
}
@@ -72,38 +86,24 @@ export default {
this.$log.debug('Date change: ', val)
this.$emit('dateChange', val)
}
},
onShortcutClick(picker, day) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * day)
picker.$emit('pick', [start, end])
}
}
}
</script>
<style lang='scss' scoped>
.datepicker {
width: 233px;
& >>> .el-range__icon {
margin-top: 2px;
margin-right: 3px;
}
& >>> .el-range-input {
width: 49%;
}
<style lang='less' scoped>
.datepicker{
width: 240px;
}
.el-input__inner {
.el-input__inner{
border: 1px solid #dcdee2;
border-radius: 3px;
height: 32px;
height: 36px;
}
.el-date-editor ::v-deep .el-range-separator {
/*.el-date-editor ::v-deep .el-input__icon{*/
/* line-height: 28px;*/
/*}*/
.el-date-editor ::v-deep .el-range-separator{
line-height: 28px;
}
</style>

View File

@@ -0,0 +1,40 @@
<script type="text/jsx">
export default {
name: 'ItemValue',
props: {
value: {
type: [String, Number, Function, Array, Object, Boolean],
default: ''
},
item: {
type: Object,
default: () => ({})
},
formatter: {
type: Function,
default: null
}
},
methods: {
toChoicesDisplay(value) {
if (!value) {
return this.$t('common.No')
}
return this.$t('common.Yes')
}
},
render(h) {
if (typeof this.formatter === 'function') {
return this.formatter(this.item, this.value)
}
if (typeof this.value === 'boolean') {
return <span>{this.toChoicesDisplay(this.value)}</span>
}
return <span>{this.value}</span>
}
}
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,54 @@
<template>
<IBox :title="title" fa="fa-info-circle">
<div class="content">
<el-row v-if="this.$route.params.id" :gutter="10" class="item">
<el-col :span="6"><div :style="{ 'text-align': align }" class="item-label"><label>ID: </label></div></el-col>
<el-col :span="18"><div class="item-text">{{ this.$route.params.id }}</div></el-col>
</el-row>
<el-row v-for="item in items" :key="'card-' + item.key" :gutter="10" class="item">
<el-col :span="6">
<div :style="{ 'text-align': align }" class="item-label"><label>{{ item.key }}: </label></div>
</el-col>
<el-col :span="18">
<div class="item-text">
<ItemValue :value="item.value" v-bind="item" />
</div>
</el-col>
</el-row>
<slot />
</div>
</IBox>
</template>
<script>
import IBox from '../IBox'
import ItemValue from './ItemValue'
export default {
name: 'DetailCard',
components: { IBox, ItemValue },
props: {
title: {
type: String,
default() {
return this.$t('common.BasicInfo')
}
},
items: {
type: Array,
default: () => []
},
align: {
type: String,
default: 'left'
}
}
}
</script>
<style scoped>
.content {
font-size: 13px;
line-height: 2.5;
}
</style>

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