Version 3 - hold onto your butts

This commit is contained in:
snipe 2016-03-25 01:18:05 -07:00
commit fe00b0e401
4229 changed files with 577913 additions and 0 deletions

5
.dockerignore Normal file
View file

@ -0,0 +1,5 @@
.git
.dockerignore
app/storage/logs/*
app/storage/views/*
vendor/*

75
.env.example Normal file
View file

@ -0,0 +1,75 @@
# --------------------------------------------
# REQUIRED: BASIC APP SETTINGS
# --------------------------------------------
APP_ENV=production
APP_DEBUG=false
APP_KEY=ChangeMe
APP_URL=null
APP_TIMEZONE='US/Pacific'
APP_LOCALE=en
# --------------------------------------------
# REQUIRED: DATABASE SETTINGS
# --------------------------------------------
DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=null
DB_USERNAME=null
DB_PASSWORD=null
# --------------------------------------------
# REQUIRED: OUTGOING MAIL SERVER SETTINGS
# --------------------------------------------
MAIL_DRIVER=smtp
MAIL_HOST=email-smtp.us-west-2.amazonaws.com
MAIL_PORT=587
MAIL_USERNAME=YOURUSERNAME
MAIL_PASSWORD=YOURPASSWORD
MAIL_ENCRYPTION=null
MAIL_FROM_ADDR=you@example.com
MAIL_FROM_NAME=Snipe-IT
# --------------------------------------------
# REQUIRED: IMAGE LIBRARY
# This should be gd or imagick
# --------------------------------------------
IMAGE_LIB=gd
# --------------------------------------------
# OPTIONAL: SESSION SETTINGS
# --------------------------------------------
SESSION_LIFETIME=12000
EXPIRE_ON_CLOSE=false
ENCRYPT=false
COOKIE_NAME=snipeit_session
COOKIE_DOMAIN=null
SECURE_COOKIES=false
# --------------------------------------------
# OPTIONAL: CACHE SETTINGS
# --------------------------------------------
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
# --------------------------------------------
# OPTIONAL: AWS S3 SETTINGS
# --------------------------------------------
AWS_SECRET=null
AWS_KEY=null
AWS_REGION=null
AWS_BUCKET=null
# --------------------------------------------
# OPTIONAL: MISC
# --------------------------------------------
APP_LOG=single
APP_LOCKED=false
FILESYSTEM_DISK=local

71
.env.testing Normal file
View file

@ -0,0 +1,71 @@
# --------------------------------------------
# REQUIRED: BASIC APP SETTINGS
# --------------------------------------------
APP_ENV=testing-ci
APP_DEBUG=true
APP_KEY=ChangeMe
APP_URL=null
APP_TIMEZONE='US/Pacific'
APP_LOCALE=en
FILESYSTEM_DISK=local
# --------------------------------------------
# REQUIRED: DATABASE SETTINGS
# --------------------------------------------
DB_CONNECTION=sqlite
DB_HOST=localhost
DB_DATABASE=sqlite_testing.sqlite
DB_USERNAME=null
DB_PASSWORD=null
# --------------------------------------------
# REQUIRED: OUTGOING MAIL SERVER SETTINGS
# --------------------------------------------
MAIL_DRIVER=smtp
MAIL_HOST=email-smtp.us-west-2.amazonaws.com
MAIL_PORT=587
MAIL_USERNAME=YOURUSERNAME
MAIL_PASSWORD=YOURPASSWORD
MAIL_ENCRYPTION=null
MAIL_FROM_ADDR=you@example.com
MAIL_FROM_NAME=Snipe-IT
# --------------------------------------------
# REQUIRED: IMAGE LIBRARY
# This should be gd or imagick
# --------------------------------------------
IMAGE_LIB=gd
# --------------------------------------------
# OPTIONAL: AWS S3 SETTINGS
# --------------------------------------------
AWS_SECRET=null
AWS_KEY=null
AWS_REGION=null
AWS_BUCKET=null
# --------------------------------------------
# OPTIONAL: CACHE SETTINGS
# --------------------------------------------
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
# --------------------------------------------
# OPTIONAL: SESSION SETTINGS
# --------------------------------------------
SESSION_LIFETIME=12000
EXPIRE_ON_CLOSE=false
ENCRYPT=false
COOKIE_NAME=snipeit_session
COOKIE_DOMAIN=null
SECURE_COOKIES=false
# --------------------------------------------
# OPTIONAL: APP LOG FORMAT
# --------------------------------------------
APP_LOG=single

1
.gitattributes vendored Executable file
View file

@ -0,0 +1 @@
* text=auto

31
.github/ISSUE_TEMPLATE.md vendored Normal file
View file

@ -0,0 +1,31 @@
#### Expected Behavior (or desired behavior if a feature request)
(what you expect to happen goes here)
-----
#### Actual Behavior
(what actually happens goes here)
-----
#### Please confirm you have done the following before posting your bug report:
- [ ] I have enabled debug mode
- [ ] I have read [checked the Common Issues page](http://docs.snipeitapp.com/common-issues.html)
-----
#### Please provide answers to these questions before posting your bug report:
- Version of Snipe-IT you're running
- What OS and web server you're running Snipe-IT on
- What method you used to install Snipe-IT (install.sh, manual installation, docker, etc)
- If you're getting an error in your browser, include that error
- What specific Snipe-IT page you're on, and what specific element you're interacting with to trigger the error
- If a stacktrace is provided in the error, include that too.
- Any errors that appear in your browser's error console.
- Confirm whether the error is [reproduceable on the demo](https://snipeitapp.com/demo).
- Include any additional information you can find in `app/storage/logs` and your webserver's logs.
- Include what you've done so far in the installation, and if you got any error messages along the way.
- Indicate whether or not you've manually edited any data directly in the database

49
.gitignore vendored Executable file
View file

@ -0,0 +1,49 @@
/vendor
/node_modules
Homestead.yaml
Homestead.json
.env
tests/_output/*
.DS_Store
public/uploads/models/*
public/uploads/avatars/*
public/uploads/suppliers/*
public/uploads/assets/*
public/uploads/*.gif
public/uploads/*.jpg
public/uploads/*.png
public/uploads/*.tif
public/uploads/*.svg
storage/app/private_uploads/users/*
phpDocumentor.phar
output
tests/_support/_generated/*
/bootstrap/compiled.php
composer.phar
/app/config/database.php
/app/config/mail.php
/app/database/*.sqlite
/app/storage/meta/services.json
/app/config/*/mail.php
/app/config/*/session.php
/app/config/*/database.php
/app/config/*/app.php
/app/config/*/ldap.php
public/packages/*
/app/storage/views/*
/app/storage/logs/*
/app/storage/debugbar/
/bin/
.idea
crowdin.yaml
public/uploads/logo.gif
public/uploads/logo.png
.siteflow
public/assets/.siteflow
app/config/local/session.php
.couscous
app/storage/dumps/*
tests/_data/scenarios

64
.travis.yml Normal file
View file

@ -0,0 +1,64 @@
addons:
hosts:
- localhost
sudo: false
# see http://about.travis-ci.org/docs/user/languages/php/ for more hints
language: php
# list any PHP version you want to test against
php:
- 5.5
- 5.6
- 7.0
# optionally specify a list of environments, for example to test different RDBMS
env:
- DB=sqlite
# execute any number of scripts before the test run, custom env's are available as variables
before_script:
# - php -S localhost:8000 &
- phantomjs --webdriver=4444 &
- sleep 10
- touch database/testing.sqlite
- composer self-update
- composer install -n --prefer-source
- cp .env.testing .env
- chmod -R 777 storage
- php artisan migrate --database=sqlite_testing --force
- ./vendor/bin/codecept build
- php artisan key:generate
- php artisan db:seed --database=sqlite_testing --force
- php artisan admin:create --first_name=Alison --last_name=Foobar --email=me@example.com --username=snipe --password=password
- php artisan serve --port=8000 --host=localhost &
- sleep 5
- pip install --user codecov
- sleep 5
# omitting "script:" will default to phpunit
# use the $DB env variable to determine the phpunit.xml to use
# script: ./vendor/bin/codecept run --env testing-ci <-- this doesn't work
# script: ./vendor/bin/codecept run unit
script: ./vendor/bin/codecept run
after_success:
- codecov
after_failure:
- cat tests/_output/AccessoriesCept.fail.html
# - curl http://localhost:4444
- curl http://localhost:8000
# configure notifications (email, IRC, campfire etc)
notifications:
email: false
slack:
secure: vv9we1RxB9RsrMbomSdq6D7vz/okobw87pEkgIZjB+hj1QpQ2by90gsPsOa+NgsJEFaEP7e4KlT6SH8kK+zhbmuKaUd3d1//XdcancE22LZXi6tkiB5yuR/Jhhb1LLDqyGJTB4D92hMnnCPiUjpxNA3r437ttNeYRdYIEEP3drA=
webhooks:
urls:
- https://webhooks.gitter.im/e/5e136eb0c1965f3918d0
on_success: change # options: [always|never|change] default: always
on_failure: change # options: [always|never|change] default: always
on_start: false # default: false

78
Dockerfile Normal file
View file

@ -0,0 +1,78 @@
FROM ubuntu
MAINTAINER Brady Wetherington <uberbrady@gmail.com>
RUN apt-get update && apt-get install -y \
apache2-bin \
libapache2-mod-php5 \
php5-curl \
php5-ldap \
php5-mysql \
php5-mcrypt \
php5-gd \
patch \
curl \
vim \
git
RUN php5enmod mcrypt
RUN php5enmod gd
RUN sed -i 's/variables_order = .*/variables_order = "EGPCS"/' /etc/php5/apache2/php.ini
RUN sed -i 's/variables_order = .*/variables_order = "EGPCS"/' /etc/php5/cli/php.ini
RUN useradd --uid 1000 --gid 50 docker
RUN echo export APACHE_RUN_USER=docker >> /etc/apache2/envvars
RUN echo export APACHE_RUN_GROUP=staff >> /etc/apache2/envvars
COPY docker/000-default.conf /etc/apache2/sites-enabled/000-default.conf
#SSL
COPY docker/001-default-ssl.conf /etc/apache2/sites-enabled/001-default-ssl.conf
#COPY docker/001-default-ssl.conf /etc/apache2/sites-available/001-default-ssl.conf
RUN a2enmod ssl
#RUN a2ensite 001-default-ssl.conf
COPY . /var/www/html
RUN a2enmod rewrite
############ INITIAL APPLICATION SETUP #####################
WORKDIR /var/www/html
#Append to bootstrap file (less brittle than 'patch')
RUN sed -i 's/return $app;/$env="production";\nreturn $app;/' bootstrap/start.php
#copy all configuration files
COPY docker/*.php /var/www/html/app/config/production/
RUN chown -R docker /var/www/html
############## DEPENDENCIES via COMPOSER ###################
#global install of composer
RUN cd /tmp;curl -sS https://getcomposer.org/installer | php;mv /tmp/composer.phar /usr/local/bin/composer
# Get dependencies
RUN cd /var/www/html;composer install
############### APPLICATION INSTALL/INIT #################
#RUN php artisan app:install
# too interactive! Try something else
#COPY docker/app_install.exp /tmp/app_install.exp
#RUN chmod +x /tmp/app_install.exp
#RUN /tmp/app_install.exp
##### START SERVER
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
EXPOSE 80
EXPOSE 443

661
LICENSE Executable file
View file

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

View file

@ -0,0 +1,468 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Models\Location;
use App\Models\Category;
use App\Models\AssetModel;
use App\Models\Company;
use App\Models\Asset;
use App\Models\Manufacturer;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\Command;
use League\Csv\Reader;
class AssetImportCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'asset-import:csv';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import Assets from CSV';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$filename = $this->argument('filename');
if (!$this->option('testrun')=='true') {
$this->comment('======= Importing Assets from '.$filename.' =========');
} else {
$this->comment('====== TEST ONLY Asset Import for '.$filename.' ====');
$this->comment('============== NO DATA WILL BE WRITTEN ==============');
}
if (! ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", '1');
}
$csv = Reader::createFromPath($this->argument('filename'));
$csv->setNewline("\r\n");
$csv->setOffset(1);
$duplicates = '';
// Loop through the records
$nbInsert = $csv->each(function ($row) use ($duplicates) {
$status_id = 1;
// Let's just map some of these entries to more user friendly words
// User's name
if (array_key_exists('0',$row)) {
$user_name = trim($row[0]);
} else {
$user_name = '';
}
// User's email
if (array_key_exists('1',$row)) {
$user_email = trim($row[1]);
} else {
$user_email = '';
}
// User's email
if (array_key_exists('2',$row)) {
$user_username = trim($row[2]);
} else {
$user_username = '';
}
// Asset Name
if (array_key_exists('3',$row)) {
$user_asset_asset_name = trim($row[3]);
} else {
$user_asset_asset_name = '';
}
// Asset Category
if (array_key_exists('4',$row)) {
$user_asset_category = trim($row[4]);
} else {
$user_asset_category = '';
}
// Asset Name
if (array_key_exists('5',$row)) {
$user_asset_name = trim($row[5]);
} else {
$user_asset_name = '';
}
// Asset Manufacturer
if (array_key_exists('6',$row)) {
$user_asset_mfgr = trim($row[6]);
} else {
$user_asset_mfgr = '';
}
// Asset model number
if (array_key_exists('7',$row)) {
$user_asset_modelno = trim($row[7]);
} else {
$user_asset_modelno = '';
}
// Asset serial number
if (array_key_exists('8',$row)) {
$user_asset_serial = trim($row[8]);
} else {
$user_asset_serial = '';
}
// Asset tag
if (array_key_exists('9',$row)) {
$user_asset_tag = trim($row[9]);
} else {
$user_asset_tag = '';
}
// Asset location
if (array_key_exists('10',$row)) {
$user_asset_location = trim($row[10]);
} else {
$user_asset_location = '';
}
// Asset notes
if (array_key_exists('11',$row)) {
$user_asset_notes = trim($row[11]);
} else {
$user_asset_notes = '';
}
// Asset purchase date
if (array_key_exists('12',$row)) {
if ($row[12]!='') {
$user_asset_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12]));
} else {
$user_asset_purchase_date = '';
}
} else {
$user_asset_purchase_date = '';
}
// Asset purchase cost
if (array_key_exists('13',$row)) {
if ($row[13]!='') {
$user_asset_purchase_cost = trim($row[13]);
} else {
$user_asset_purchase_cost = '';
}
} else {
$user_asset_purchase_cost = '';
}
// Asset Company Name
if (array_key_exists('14',$row)) {
if ($row[14]!='') {
$user_asset_company_name = trim($row[14]);
} else {
$user_asset_company_name= '';
}
} else {
$user_asset_company_name = '';
}
// A number was given instead of a name
if (is_numeric($user_name)) {
$this->comment('User '.$user_name.' is not a name - assume this user already exists');
$user_username = '';
$first_name = '';
$last_name = '';
// No name was given
} elseif ($user_name=='') {
$this->comment('No user data provided - skipping user creation, just adding asset');
$first_name = '';
$last_name = '';
//$user_username = '';
} else {
$user_email_array = User::generateFormattedNameFromFullName($this->option('email_format'), $user_name);
$first_name = $user_email_array['first_name'];
$last_name = $user_email_array['last_name'];
if ($user_email=='') {
$user_email = $user_email_array['username'].'@'.config('app.domain');
}
if ($user_username=='') {
if ($this->option('username_format')=='email') {
$user_username = $user_email;
} else {
$user_name_array = User::generateFormattedNameFromFullName($this->option('username_format'), $user_name);
$user_username = $user_name_array['username'];
}
}
}
$this->comment('Full Name: '.$user_name);
$this->comment('First Name: '.$first_name);
$this->comment('Last Name: '.$last_name);
$this->comment('Username: '.$user_username);
$this->comment('Email: '.$user_email);
$this->comment('Category Name: '.$user_asset_category);
$this->comment('Item: '.$user_asset_name);
$this->comment('Manufacturer ID: '.$user_asset_mfgr);
$this->comment('Model No: '.$user_asset_modelno);
$this->comment('Serial No: '.$user_asset_serial);
$this->comment('Asset Tag: '.$user_asset_tag);
$this->comment('Location: '.$user_asset_location);
$this->comment('Purchase Date: '.$user_asset_purchase_date);
$this->comment('Purchase Cost: '.$user_asset_purchase_cost);
$this->comment('Notes: '.$user_asset_notes);
$this->comment('Company Name: '.$user_asset_company_name);
$this->comment('------------- Action Summary ----------------');
if ($user_username!='') {
if ($user = User::MatchEmailOrUsername($user_username, $user_email)
->whereNotNull('username')->first()) {
$this->comment('User '.$user_username.' already exists');
} else {
$user = new \App\Models\User;
$password = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->username = $user_username;
$user->email = $user_email;
$user->permissions = '{user":1}';
$user->password = bcrypt($password);
$user->activated = 1;
if ($user->save()) {
$this->comment('User '.$first_name.' created');
} else {
$this->comment('ERROR CREATING User '.$first_name.' '.$last_name);
$this->comment($user->getErrors());
}
}
} else {
$user = new User;
}
// Check for the location match and create it if it doesn't exist
if ($location = Location::where('name', e($user_asset_location))->first()) {
$this->comment('Location '.$user_asset_location.' already exists');
} else {
$location = new Location();
if ($user_asset_location!='')
{
$location->name = e($user_asset_location);
$location->address = '';
$location->city = '';
$location->state = '';
$location->country = '';
$location->user_id = 1;
if (!$this->option('testrun')=='true') {
if ($location->save()) {
$this->comment('Location '.$user_asset_location.' was created');
} else {
$this->comment('Something went wrong! Location '.$user_asset_location.' was NOT created');
$this->comment($location->getErrors());
}
}
else
{
$this->comment('Location '.$user_asset_location.' was (not) created - test run only');
}
}
else
{
$this->comment('No location given, so none created.');
}
}
if (e($user_asset_category)=='') {
$category_name = 'Unnamed Category';
} else {
$category_name = e($user_asset_category);
}
// Check for the category match and create it if it doesn't exist
if ($category = Category::where('name', e($category_name))->where('category_type', 'asset')->first()) {
$this->comment('Category '.$category_name.' already exists');
} else {
$category = new Category();
$category->name = e($category_name);
$category->category_type = 'asset';
$category->user_id = 1;
if ($category->save()) {
$this->comment('Category '.$user_asset_category.' was created');
} else {
$this->comment('Something went wrong! Category '.$user_asset_category.' was NOT created');
$this->comment($category->getErrors());
}
}
// Check for the manufacturer match and create it if it doesn't exist
if ($manufacturer = Manufacturer::where('name', e($user_asset_mfgr))->first()) {
$this->comment('Manufacturer '.$user_asset_mfgr.' already exists');
} else {
$manufacturer = new Manufacturer();
$manufacturer->name = e($user_asset_mfgr);
$manufacturer->user_id = 1;
if ($manufacturer->save()) {
$this->comment('Manufacturer '.$user_asset_mfgr.' was created');
} else {
$this->comment('Something went wrong! Manufacturer '.$user_asset_mfgr.' was NOT created: '. $manufacturer->getErrors()->first());
}
}
// Check for the asset model match and create it if it doesn't exist
if ($asset_model = AssetModel::where('name', e($user_asset_name))->where('modelno', e($user_asset_modelno))->where('category_id', $category->id)->where('manufacturer_id', $manufacturer->id)->first()) {
$this->comment('The Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' already exists');
} else {
$asset_model = new AssetModel();
$asset_model->name = e($user_asset_name);
$asset_model->manufacturer_id = $manufacturer->id;
$asset_model->modelno = e($user_asset_modelno);
$asset_model->category_id = $category->id;
$asset_model->user_id = 1;
if ($asset_model->save()) {
$this->comment('Asset Model '.$user_asset_name.' with model number '.$user_asset_modelno.' was created');
} else {
$this->comment('Something went wrong! Asset Model '.$user_asset_name.' was NOT created: '.$asset_model->getErrors()->first());
}
}
// Check for the asset company match and create it if it doesn't exist
if ($user_asset_company_name!='') {
if ($company = Company::where('name', e($user_asset_company_name))->first()) {
$this->comment('Company '.$user_asset_company_name.' already exists');
} else {
$company = new Company();
$company->name = e($user_asset_company_name);
if ($company->save()) {
$this->comment('Company '.$user_asset_company_name.' was created');
} else {
$this->comment('Something went wrong! Company '.$user_asset_company_name.' was NOT created: '.$company->getErrors()->first());
}
}
} else {
$company = new Company();
}
// Check for the asset match and create it if it doesn't exist
if ($asset = Asset::where('asset_tag', e($user_asset_tag))->first()) {
$this->comment('The Asset with asset tag '.$user_asset_tag.' already exists');
} else {
$asset = new Asset();
$asset->name = e($user_asset_asset_name);
if ($user_asset_purchase_date!='') {
$asset->purchase_date = $user_asset_purchase_date;
} else {
$asset->purchase_date = NULL;
}
if ($user_asset_purchase_cost!='') {
$asset->purchase_cost = ParseFloat(e($user_asset_purchase_cost));
} else {
$asset->purchase_cost = 0.00;
}
$asset->serial = e($user_asset_serial);
$asset->asset_tag = e($user_asset_tag);
$asset->model_id = $asset_model->id;
$asset->assigned_to = $user->id;
$asset->rtd_location_id = $location->id;
$asset->user_id = 1;
$asset->status_id = $status_id;
$asset->company_id = $company->id;
if ($user_asset_purchase_date!='') {
$asset->purchase_date = $user_asset_purchase_date;
} else {
$asset->purchase_date = NULL;
}
$asset->notes = e($user_asset_notes);
if ($asset->save()) {
$this->comment('Asset '.$user_asset_name.' with serial number '.$user_asset_serial.' was created');
} else {
$this->comment('Something went wrong! Asset '.$user_asset_name.' was NOT created: '.$asset->getErrors()->first());
}
}
$this->comment('=====================================');
return true;
});
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('filename', InputArgument::REQUIRED, 'File for the CSV import.'),
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null),
array('username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null),
array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null),
);
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CreateAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'admin:create {--first_name=} {--last_name=} {--email=} {--username=} {--password=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create an admin user via command line.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$first_name = $this->option('first_name');
$last_name = $this->option('last_name');
$username = $this->option('username');
$email = $this->option('email');
$password = $this->option('password');
if (($first_name=='') || ($last_name=='') || ($username=='') || ($email=='') || ($password=='')) {
$this->info('ERROR: All fields are required.');
} else {
$user = new \App\Models\User;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->username = $username;
$user->email = $email;
$user->permissions = '{"admin":1,"user":1,"superuser":1,"reports":1}';
$user->password = bcrypt($password);
$user->activated = 1;
if ($user->save()) {
$this->info('New user created');
$user->groups()->attach(1);
} else {
$this->info('Admin user was not created');
$errors = $user->getErrors();
foreach ($errors->all() as $error) {
$this->info('ERROR:'. $error);
}
}
}
}
// protected function getArguments()
// {
// return array(
// array('username', InputArgument::REQUIRED, 'Username'),
// );
// }
}

View file

@ -0,0 +1,382 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use League\Csv\Reader;
class LicenseImportCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'license-import:csv';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import Licenses from CSV';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$filename = $this->argument('filename');
if (!$this->option('testrun')=='true') {
$this->comment('======= Importing Licenses from '.$filename.' =========');
} else {
$this->comment('====== TEST ONLY License Import for '.$filename.' ====');
$this->comment('============== NO DATA WILL BE WRITTEN ==============');
}
if (! ini_get("auto_detect_line_endings")) {
ini_set("auto_detect_line_endings", '1');
}
$csv = Reader::createFromPath($this->argument('filename'));
$csv->setNewline("\r\n");
$csv->setOffset(1);
$duplicates = '';
// Loop through the records
$nbInsert = $csv->each(function ($row) use ($duplicates) {
$status_id = 1;
// Let's just map some of these entries to more user friendly words
if (array_key_exists('0',$row)) {
$user_name = trim($row[0]);
} else {
$user_name = '';
}
if (array_key_exists('1',$row)) {
$user_email = trim($row[1]);
} else {
$user_email = '';
}
if (array_key_exists('2',$row)) {
$user_username = trim($row[2]);
} else {
$user_username = '';
}
if (array_key_exists('3',$row)) {
$user_license_name = trim($row[3]);
} else {
$user_license_name = '';
}
if (array_key_exists('4',$row)) {
$user_license_serial = trim($row[4]);
} else {
$user_license_serial = '';
}
if (array_key_exists('5',$row)) {
$user_licensed_to_name = trim($row[5]);
} else {
$user_licensed_to_name = '';
}
if (array_key_exists('6',$row)) {
$user_licensed_to_email = trim($row[6]);
} else {
$user_licensed_to_email = '';
}
if (array_key_exists('7',$row)) {
$user_license_seats = trim($row[7]);
} else {
$user_license_seats = '';
}
if (array_key_exists('8',$row)) {
$user_license_reassignable = trim($row[8]);
if ($user_license_reassignable!='') {
if ((strtolower($user_license_reassignable)=='yes') || (strtolower($user_license_reassignable)=='true') || ($user_license_reassignable=='1')) {
$user_license_reassignable = 1;
}
} else {
$user_license_reassignable = 0;
}
} else {
$user_license_reassignable = 0;
}
if (array_key_exists('9',$row)) {
$user_license_supplier = trim($row[9]);
} else {
$user_license_supplier = '';
}
if (array_key_exists('10',$row)) {
$user_license_maintained = trim($row[10]);
if ($user_license_maintained!='') {
if ((strtolower($user_license_maintained)=='yes') || (strtolower($user_license_maintained)=='true') || ($user_license_maintained=='1')) {
$user_license_maintained = 1;
}
} else {
$user_license_maintained = 0;
}
} else {
$user_license_maintained = '';
}
if (array_key_exists('11',$row)) {
$user_license_notes = trim($row[11]);
} else {
$user_license_notes = '';
}
if (array_key_exists('12',$row)) {
if ($row[12]!='') {
$user_license_purchase_date = date("Y-m-d 00:00:01", strtotime($row[12]));
} else {
$user_license_purchase_date = '';
}
} else {
$user_license_purchase_date = 0;
}
// A number was given instead of a name
if (is_numeric($user_name)) {
$this->comment('User '.$user_name.' is not a name - assume this user already exists');
$user_username = '';
// No name was given
} elseif ($user_name=='') {
$this->comment('No user data provided - skipping user creation, just adding license');
$first_name = '';
$last_name = '';
$user_username = '';
} else {
$name = explode(" ", $user_name);
$first_name = $name[0];
$email_last_name = '';
$email_prefix = $first_name;
if (!array_key_exists(1, $name)) {
$last_name='';
$email_last_name = $last_name;
$email_prefix = $first_name;
} else {
$last_name = str_replace($first_name,'',$user_name);
if ($this->option('email_format')=='filastname') {
$email_last_name.=str_replace(' ','',$last_name);
$email_prefix = $first_name[0].$email_last_name;
} elseif ($this->option('email_format')=='firstname.lastname') {
$email_last_name.=str_replace(' ','',$last_name);
$email_prefix = $first_name.'.'.$email_last_name;
} elseif ($this->option('email_format')=='firstname') {
$email_last_name.=str_replace(' ','',$last_name);
$email_prefix = $first_name;
}
}
$user_username = $email_prefix;
// Generate an email based on their name if no email address is given
if ($user_email=='') {
if ($first_name=='Unknown') {
$status_id = 7;
}
$email = strtolower($email_prefix).'@'.$this->option('domain');
$user_email = str_replace("'",'',$email);
}
}
$this->comment('Full Name: '.$user_name);
$this->comment('First Name: '.$first_name);
$this->comment('Last Name: '.$last_name);
$this->comment('Username: '.$user_username);
$this->comment('Email: '.$user_email);
$this->comment('License Name: '.$user_license_name);
$this->comment('Serial No: '.$user_license_serial);
$this->comment('Licensed To Name: '.$user_licensed_to_name);
$this->comment('Licensed To Email: '.$user_licensed_to_email);
$this->comment('Seats: '.$user_license_seats);
$this->comment('Reassignable: '.$user_license_reassignable);
$this->comment('Supplier: '.$user_license_supplier);
$this->comment('Maintained: '.$user_license_maintained);
$this->comment('Notes: '.$user_license_notes);
$this->comment('Purchase Date: '.$user_license_purchase_date);
$this->comment('------------- Action Summary ----------------');
if ($user_username!='') {
if ($user = User::where('username', $user_username)->whereNotNull('username')->first()) {
$this->comment('User '.$user_username.' already exists');
} else {
// Create the user
$user = Sentry::createUser(array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $user_email,
'username' => $user_username,
'password' => substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10),
'activated' => true,
'permissions' => array(
'admin' => 0,
'user' => 1,
),
'notes' => 'User importerd through license importer'
));
// Find the group using the group id
$userGroup = Sentry::findGroupById(3);
// Assign the group to the user
$user->addGroup($userGroup);
$this->comment('User '.$first_name.' created');
}
} else {
$user = new User;
$user->user_id = NULL;
}
// Check for the supplier match and create it if it doesn't exist
if ($supplier = Supplier::where('name', $user_license_supplier)->first()) {
$this->comment('Supplier '.$user_license_supplier.' already exists');
} else {
$supplier = new Supplier();
$supplier->name = e($user_license_supplier);
$supplier->user_id = 1;
if ($supplier->save()) {
$this->comment('Supplier '.$user_license_supplier.' was created');
} else {
$this->comment('Something went wrong! Supplier '.$user_license_supplier.' was NOT created');
}
}
// Add the license
$license = new License();
$license->name = e($user_license_name);
if ($user_license_purchase_date!='') {
$license->purchase_date = $user_license_purchase_date;
} else {
$license->purchase_date = NULL;
}
$license->serial = e($user_license_serial);
$license->seats = e($user_license_seats);
$license->supplier_id = $supplier->id;
$license->user_id = 1;
if ($user_license_purchase_date!='') {
$license->purchase_date = $user_license_purchase_date;
} else {
$license->purchase_date = NULL;
}
$license->license_name = $user_licensed_to_name;
$license->license_email = $user_licensed_to_email;
$license->notes = e($user_license_notes);
if ($license->save()) {
$this->comment('License '.$user_license_name.' with serial number '.$user_license_serial.' was created');
$license_seat_created = 0;
for ($x = 0; $x < $user_license_seats; $x++) {
// Create the license seat entries
$license_seat = new LicenseSeat();
$license_seat->license_id = $license->id;
// Only assign the first seat to the user
if ($x==0) {
$license_seat->assigned_to = $user->id;
} else {
$license_seat->assigned_to = NULL;
}
if ($license_seat->save()) {
$license_seat_created++;
}
}
if ($license_seat_created > 0) {
$this->comment($license_seat_created.' seats were created');
} else {
$this->comment('Something went wrong! NO seats for '.$user_license_name.' were created');
}
} else {
$this->comment('Something went wrong! License '.$user_license_name.' was NOT created');
}
$this->comment('=====================================');
return true;
});
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('filename', InputArgument::REQUIRED, 'File for the CSV import.'),
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('domain', null, InputOption::VALUE_REQUIRED, 'Email domain for generated email addresses.', null),
array('email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null),
array('testrun', null, InputOption::VALUE_REQUIRED, 'Test the output without writing to the database or not.', null),
);
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class PaveIt extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'pave';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pave the database to start over. This should ALMOST NEVER BE USED. (It is primarily a quick tool for developers.)';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if ($this->confirm("\n****************************************************\nTHIS WILL DROP ALL OF THE TABLES IN YOUR DATABASE. \nThere is NO undo. This WILL destroy ALL of your data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) {
\DB::statement('drop table IF EXISTS accessories_users');
\DB::statement('drop table IF EXISTS accessories');
\DB::statement('drop table IF EXISTS asset_logs');
\DB::statement('drop table IF EXISTS asset_maintenances');
\DB::statement('drop table IF EXISTS asset_uploads');
\DB::statement('drop table IF EXISTS assets');
\DB::statement('drop table IF EXISTS categories');
\DB::statement('drop table IF EXISTS companies');
\DB::statement('drop table IF EXISTS consumables_users');
\DB::statement('drop table IF EXISTS consumables');
\DB::statement('drop table IF EXISTS custom_field_custom_fieldset');
\DB::statement('drop table IF EXISTS custom_fields');
\DB::statement('drop table IF EXISTS custom_fieldsets');
\DB::statement('drop table IF EXISTS depreciations');
\DB::statement('drop table IF EXISTS groups');
//\DB::statement('drop table IF EXISTS history');
\DB::statement('drop table IF EXISTS license_seats');
\DB::statement('drop table IF EXISTS licenses');
\DB::statement('drop table IF EXISTS locations');
\DB::statement('drop table IF EXISTS manufacturers');
\DB::statement('drop table IF EXISTS models');
\DB::statement('drop table IF EXISTS migrations');
\DB::statement('drop table IF EXISTS password_resets');
\DB::statement('drop table IF EXISTS requested_assets');
\DB::statement('drop table IF EXISTS requests');
\DB::statement('drop table IF EXISTS settings');
\DB::statement('drop table IF EXISTS status_labels');
\DB::statement('drop table IF EXISTS suppliers');
\DB::statement('drop table IF EXISTS throttle');
\DB::statement('drop table IF EXISTS users_groups');
\DB::statement('drop table IF EXISTS users');
}
}
}

View file

@ -0,0 +1,134 @@
<?php
namespace App\Console\Commands;
use App\Models\Asset;
use App\Models\License;
use App\Models\Setting;
use DB;
use Illuminate\Console\Command;
class SendExpirationAlerts extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'alerts:expiring';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Check for expiring warrantees and service agreements, and sends out an alert email.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
// Expiring Assets
$expiring_assets = Asset::getExpiringWarrantee(60);
$this->info(count($expiring_assets).' expiring assets');
$asset_data['count'] = count($expiring_assets);
$asset_data['email_content'] ='';
$now = date("Y-m-d");
foreach ($expiring_assets as $asset) {
$expires = $asset->warrantee_expires();
$difference = round(abs(strtotime($expires) - strtotime($now))/86400);
if ($difference > 30) {
$asset_data['email_content'] .= '<tr style="background-color: #fcffa3;">';
} else {
$asset_data['email_content'] .= '<tr style="background-color:#d9534f;">';
}
$asset_data['email_content'] .= '<td><a href="'.config('app.url').'/hardware/'.$asset->id.'/view">';
$asset_data['email_content'] .= $asset->showAssetName().'</a></td><td>'.$asset->asset_tag.'</td>';
$asset_data['email_content'] .= '<td>'.$asset->warrantee_expires().'</td>';
$asset_data['email_content'] .= '<td>'.$difference.' days</td>';
$asset_data['email_content'] .= '</tr>';
}
// Expiring licenses
$expiring_licenses = License::getExpiringLicenses(60);
$this->info(count($expiring_licenses).' expiring licenses');
$license_data['count'] = count($expiring_licenses);
$license_data['email_content'] = '';
foreach ($expiring_licenses as $license) {
$expires = $license->expiration_date;
$difference = round(abs(strtotime($expires) - strtotime($now))/86400);
if ($difference > 30) {
$license_data['email_content'] .= '<tr style="background-color: #fcffa3;">';
} else {
$license_data['email_content'] .= '<tr style="background-color:#d9534f;">';
}
$license_data['email_content'] .= '<td><a href="'.config('app.url').'/admin/licenses/'.$license->id.'/view">';
$license_data['email_content'] .= $license->name.'</a></td>';
$license_data['email_content'] .= '<td>'.$license->expiration_date.'</td>';
$license_data['email_content'] .= '<td>'.$difference.' days</td>';
$license_data['email_content'] .= '</tr>';
}
if ((Setting::getSettings()->alert_email!='') && (Setting::getSettings()->alerts_enabled==1)) {
if (count($expiring_assets) > 0) {
Mail::send('emails.expiring-assets-report', $asset_data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Expiring Assets Report');
});
}
if (count($expiring_licenses) > 0) {
Mail::send('emails.expiring-licenses-report', $license_data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Expiring Licenses Report');
});
}
} else {
if (Setting::getSettings()->alert_email=='') {
echo "Could not send email. No alert email configured in settings. \n";
} elseif (Setting::getSettings()->alerts_enabled!=1) {
echo "Alerts are disabled in the settings. No mail will be sent. \n";
}
}
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace App\Console\Commands;
use App\Models\Setting;
use DB;
use Mail;
use App\Helpers\Helper;
use Illuminate\Console\Command;
class SendInventoryAlerts extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'alerts:inventory';
/**
* The console command description.
*
* @var string
*/
protected $description = 'This command checks for low inventory, and sends out an alert email.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if ((Setting::getSettings()->alert_email!='') && (Setting::getSettings()->alerts_enabled==1)) {
$data['data'] = Helper::checkLowInventory();
$data['count'] = count($data['data']);
if (count($data['data']) > 0) {
Mail::send('emails.low-inventory', $data, function ($m) {
$m->to(explode(',',Setting::getSettings()->alert_email), Setting::getSettings()->site_name);
$m->subject('Low Inventory Report');
});
}
} else {
if (Setting::getSettings()->alert_email=='') {
echo "Could not send email. No alert email configured in settings. \n";
} elseif (Setting::getSettings()->alerts_enabled!=1) {
echo "Alerts are disabled in the settings. No mail will be sent. \n";
}
}
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SystemBackup extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'snipeit:backup';
/**
* The console command description.
*
* @var string
*/
protected $description = 'This command creates a database dump and zips up all of the uploaded files in the upload directories.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
//
$files['avatars'] = glob(public_path().'/uploads/avatars/*');
$files['models'] = glob(public_path().'/uploads/models/*');
$files['suppliers'] = glob(public_path().'/uploads/suppliers/*');
$files['private_uploads'] = glob(storage_path().'/app/private_uploads/*');
$base_filename = date('Ymdgis');
$zip_file = app_path().'/storage/dumps/'.$base_filename.'-backup.zip';
$db_dump = config('backup::path').$base_filename.'-db.sql';
$this->call('db:backup', array('filename' => $db_dump));
Zipper::make($zip_file)
->folder('avatars')->add($files['avatars'])
->folder('models')->add($files['models'])
->folder('suppliers')->add($files['suppliers'])
->folder('private_uploads')->add($files['private_uploads'])
->folder('database')->add($db_dump)->close();
$this->info('Backup file created at '.$zip_file);
$this->info('Removing SQL dump at '.$db_dump);
unlink($db_dump);
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace App\Console\Commands;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Console\Command;
class Versioning extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'versioning:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate and update app\'s version via git.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
// Path to the file containing your version
// This will be overwritten everything you commit a message
$versionFile = app_path().'/config/version.php';
// The git's output
// get the argument passed in the git command
$hash_version = $this->argument('app_version');
// discard the commit hash
$version = explode('-', $hash_version);
$realVersion = $version[0] . '-' . $version[1];
// save the version array to a variable
$array = var_export(array('app_version' => $realVersion,'hash_version' => $hash_version), true);
// Construct our file content
$content = <<<CON
<?php
return $array;
CON;
// And finally write the file and output the current version
\File::put($versionFile, $content);
$this->line('Setting version: '. \config('version.latest'));
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('app_version', InputArgument::REQUIRED, 'version number is required.'),
);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
);
}
}

39
app/Console/Kernel.php Normal file
View file

@ -0,0 +1,39 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\PaveIt::class,
Commands\CreateAdmin::class,
Commands\SendExpirationAlerts::class,
Commands\SendInventoryAlerts::class,
Commands\AssetImportCommand::class,
Commands\LicenseImportCommand::class,
Commands\Versioning::class,
Commands\SystemBackup::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('alerts:inventory')->daily();
$schedule->command('alerts:expiring')->daily();
$schedule->command('snipeit:backup')->weekly();
}
}

8
app/Events/Event.php Normal file
View file

@ -0,0 +1,8 @@
<?php
namespace App\Events;
abstract class Event
{
//
}

View file

@ -0,0 +1,67 @@
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->back()->with('error', trans('general.token_expired'));
}
if ($this->isHttpException($e)) {
$statusCode = $e->getStatusCode();
switch ($statusCode) {
case '404':
return response()->view('layouts/basic', [
'content' => view('errors/404')
]);
}
}
return parent::render($request, $e);
}
}

263
app/Helpers/Helper.php Normal file
View file

@ -0,0 +1,263 @@
<?php
namespace App\Helpers;
use DB;
use App\Models\Statuslabel;
use App\Models\Location;
use App\Models\Company;
use App\Models\User;
use App\Models\Manufacturer;
use App\Models\Supplier;
use App\Models\Category;
use App\Models\Depreciation;
use App\Models\CustomFieldset;
use App\Models\CustomField;
use App\Models\Component;
use App\Models\Accessory;
use App\Models\Consumable;
use App\Models\Asset;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class Helper
{
// This doesn't do anything yet
public static function parseEmailList($emails)
{
$emails_array = explode(',', $emails);
return array_walk($emails_array, 'trim_value');
}
// This doesn't do anything yet
public static function trim_value(&$value)
{
return trim($value);
}
public static function ParseFloat($floatString)
{
// use comma for thousands until local info is property used
$LocaleInfo = localeconv();
$floatString = str_replace(",", "", $floatString);
$floatString = str_replace($LocaleInfo["decimal_point"], ".", $floatString);
return floatval($floatString);
}
public static function modelList()
{
$model_list = array('' => trans('general.select_model')) + DB::table('models')
->select(DB::raw('IF (modelno="" OR modelno IS NULL,name,concat(name, " / ",modelno)) as name, id'))
->orderBy('name', 'asc')
->whereNull('deleted_at')
->pluck('name', 'id');
return $model_list;
}
public static function companyList()
{
$company_list = array('0' => trans('general.select_company')) + DB::table('companies')
->orderBy('name', 'asc')
->pluck('name', 'id');
return $company_list;
}
public static function categoryList()
{
$category_list = array('' => '') + Category::orderBy('name', 'asc')
->whereNull('deleted_at')
->orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $category_list;
}
public static function suppliersList()
{
$supplier_list = array('' => trans('general.select_supplier')) + Supplier::orderBy('name', 'asc')
->orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $supplier_list;
}
public static function statusLabelList()
{
$statuslabel_list = array('' => trans('general.select_statuslabel')) + Statuslabel::orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $statuslabel_list;
}
public static function locationsList()
{
$location_list = array('' => trans('general.select_location')) + Location::orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $location_list;
}
public static function manufacturerList()
{
$manufacturer_list = array('' => 'Select One') +
Manufacturer::orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $manufacturer_list;
}
public static function statusTypeList()
{
$statuslabel_types = array('' => trans('admin/hardware/form.select_statustype')) + array('undeployable' => trans('admin/hardware/general.undeployable')) + array('pending' => trans('admin/hardware/general.pending')) + array('archived' => trans('admin/hardware/general.archived')) + array('deployable' => trans('admin/hardware/general.deployable'));
return $statuslabel_types;
}
public static function managerList()
{
$manager_list = array('' => '') + User::select(DB::raw('concat(last_name,", ",first_name," (",username,")") as full_name, id'))
->whereNull('deleted_at', 'and')
->orderBy('last_name', 'asc')
->orderBy('first_name', 'asc')
->pluck('full_name', 'id')->toArray();
return $manager_list;
}
public static function depreciationList()
{
$depreciation_list = ['' => 'Do Not Depreciate'] + Depreciation::orderBy('name', 'asc')
->pluck('name', 'id')->toArray();
return $depreciation_list;
}
public static function categoryTypeList()
{
$category_types = array('' => '','accessory' => 'Accessory', 'asset' => 'Asset', 'consumable' => 'Consumable','component' => 'Component');
return $category_types;
}
public static function usersList()
{
$users_list = array('' => trans('general.select_user')) + DB::table('users')
->select(DB::raw('concat(last_name,", ",first_name," (",username,")") as full_name, id'))
->whereNull('deleted_at')
->orderBy('last_name', 'asc')
->orderBy('first_name', 'asc')
->pluck('full_name', 'id');
return $users_list;
}
public static function assetsList()
{
$assets_list = array('' => trans('general.select_asset')) + Asset::orderBy('name', 'asc')
->whereNull('deleted_at')
->pluck('name', 'id')->toArray();
return $assets_list;
}
public static function customFieldsetList()
{
$customfields = array('' => trans('admin/models/general.no_custom_field')) + CustomFieldset::pluck('name', 'id')->toArray();
return $customfields;
}
public static function predefined_formats()
{
$keys=array_keys(CustomField::$PredefinedFormats);
$stuff=array_combine($keys, $keys);
return $stuff+["" => "Custom Format..."];
}
public static function barcodeDimensions($barcode_type = 'QRCODE')
{
if ($barcode_type == 'C128') {
$size['height'] = '-1';
$size['width'] = '-10';
} elseif ($barcode_type == 'PDF417') {
$size['height'] = '-3';
$size['width'] = '-10';
} else {
$size['height'] = '-3';
$size['width'] = '-3';
}
return $size;
}
public static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/**
* This nasty little method gets the low inventory info for the
* alert dropdown
**/
public static function checkLowInventory()
{
$consumables = Consumable::with('users')->whereNotNull('min_amt')->get();
$accessories = Accessory::with('users')->whereNotNull('min_amt')->get();
$components = Component::with('assets')->whereNotNull('min_amt')->get();
$avail_consumables = 0;
$items_array = array();
$all_count = 0;
foreach ($consumables as $consumable) {
$avail = $consumable->numRemaining();
if ($avail < ($consumable->min_amt) + 3) {
$percent = number_format((($consumable->numRemaining() / $consumable->qty) * 100), 0);
$items_array[$all_count]['id'] = $consumable->id;
$items_array[$all_count]['name'] = $consumable->name;
$items_array[$all_count]['type'] = 'consumables';
$items_array[$all_count]['percent'] = $percent;
$items_array[$all_count]['remaining']=$consumable->numRemaining();
$items_array[$all_count]['min_amt']=$consumable->min_amt;
$all_count++;
}
}
foreach ($accessories as $accessory) {
$avail = $accessory->numRemaining();
if ($avail < ($accessory->min_amt) + 3) {
$percent = number_format((($accessory->numRemaining() / $accessory->qty) * 100), 0);
$items_array[$all_count]['id'] = $accessory->id;
$items_array[$all_count]['name'] = $accessory->name;
$items_array[$all_count]['type'] = 'accessories';
$items_array[$all_count]['percent'] = $percent;
$items_array[$all_count]['remaining']=$accessory->numRemaining();
$items_array[$all_count]['min_amt']=$accessory->min_amt;
$all_count++;
}
}
foreach ($components as $component) {
$avail = $component->numRemaining();
if ($avail < ($component->min_amt) + 3) {
$percent = number_format((($component->numRemaining() / $component->total_qty) * 100), 0);
$items_array[$all_count]['id'] = $component->id;
$items_array[$all_count]['name'] = $component->name;
$items_array[$all_count]['type'] = 'components';
$items_array[$all_count]['percent'] = $percent;
$items_array[$all_count]['remaining']=$component->numRemaining();
$items_array[$all_count]['min_amt']=$component->min_amt;
$all_count++;
}
}
return $items_array;
}
}

View file

@ -0,0 +1,672 @@
<?php
/**
* This controller handles all actions related to Accessories for
* the Snipe-IT Asset Management application.
*
* PHP version 5.5.9
* @package Snipe-IT
* @version v3.0
*/
namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Company;
use App\Models\Setting;
use App\Models\User;
use Config;
use DB;
use Input;
use Lang;
use Mail;
use Redirect;
use Slack;
use Str;
use View;
use Auth;
/**
* This class controls all actions related to accessories
*/
class AccessoriesController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the accessories listing, which is generated in getDatatable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see AccessoriesController::getDatatable() method that generates the JSON response
* @since [v1.0]
* @return View
*/
public function getIndex()
{
return View::make('accessories/index');
}
/**
* Returns a view with a form to create a new Accessory.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @return View
*/
public function getCreate()
{
// Show the page
$category_list = array('' => '') + DB::table('categories')->where('category_type', '=', 'accessory')->whereNull('deleted_at')->orderBy('name', 'ASC')->lists('name', 'id');
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('accessories/edit')
->with('accessory', new Accessory)
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Validate and save new Accessory from form post
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$accessory = new Accessory();
// Update the accessory data
$accessory->name = e(Input::get('name'));
$accessory->category_id = e(Input::get('category_id'));
$accessory->location_id = e(Input::get('location_id'));
$accessory->min_amt = e(Input::get('min_amt'));
$accessory->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$accessory->order_number = e(Input::get('order_number'));
if (e(Input::get('purchase_date')) == '') {
$accessory->purchase_date = null;
} else {
$accessory->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$accessory->purchase_cost = null;
} else {
$accessory->purchase_cost = e(Input::get('purchase_cost'));
}
$accessory->qty = e(Input::get('qty'));
$accessory->user_id = Auth::user()->id;
// Was the accessory created?
if ($accessory->save()) {
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($accessory->getErrors());
}
/**
* Return view for the Accessory update form, prepopulated with existing data
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return View
*/
public function getEdit($accessoryId = null)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
$category_list = array('' => '') + DB::table('categories')->where('category_type', '=', 'accessory')->whereNull('deleted_at')->orderBy('name', 'ASC')->lists('name', 'id');
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('accessories/edit', compact('accessory'))
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Save edited Accessory from form post
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return Redirect
*/
public function postEdit($accessoryId = null)
{
// Check if the blog post exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
// Update the accessory data
$accessory->name = e(Input::get('name'));
if (e(Input::get('location_id')) == '') {
$accessory->location_id = null;
} else {
$accessory->location_id = e(Input::get('location_id'));
}
$accessory->min_amt = e(Input::get('min_amt'));
$accessory->category_id = e(Input::get('category_id'));
$accessory->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$accessory->order_number = e(Input::get('order_number'));
if (e(Input::get('purchase_date')) == '') {
$accessory->purchase_date = null;
} else {
$accessory->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$accessory->purchase_cost = null;
} else {
$accessory->purchase_cost = e(Input::get('purchase_cost'));
}
$accessory->qty = e(Input::get('qty'));
// Was the accessory created?
if ($accessory->save()) {
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($accessory->getErrors());
}
/**
* Delete the given accessory.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return Redirect
*/
public function getDelete($accessoryId)
{
// Check if the blog post exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
if ($accessory->hasUsers() > 0) {
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.assoc_users', array('count'=> $accessory->hasUsers())));
} else {
$accessory->delete();
// Redirect to the locations management page
return Redirect::to('admin/accessories')->with('success', Lang::get('admin/accessories/message.delete.success'));
}
}
/**
* Returns a view that invokes the ajax table which contains
* the content for the accessory detail view, which is generated in getDataView.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @see AccessoriesController::getDataView() method that generates the JSON response
* @since [v1.0]
* @return View
*/
public function getView($accessoryID = null)
{
$accessory = Accessory::find($accessoryID);
if (isset($accessory->id)) {
if (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
} else {
return View::make('accessories/view', compact('accessory'));
}
} else {
// Prepare the error message
$error = Lang::get('admin/accessories/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('accessories')->with('error', $error);
}
}
/**
* Return the form to checkout an Accessory to a user.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return View
*/
public function getCheckout($accessoryId)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the accessory management page with error
return Redirect::to('accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
// Get the dropdown of users and then pass it to the checkout view
$users_list = array('' => 'Select a User') + DB::table('users')->select(DB::raw('concat(last_name,", ",first_name," (",username,")") as full_name, id'))->whereNull('deleted_at')->orderBy('last_name', 'asc')->orderBy('first_name', 'asc')->lists('full_name', 'id');
return View::make('accessories/checkout', compact('accessory'))->with('users_list', $users_list);
}
/**
* Save the Accessory checkout information.
*
* If Slack is enabled and/or asset acceptance is enabled, it will also
* trigger a Slack message and send an email.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return Redirect
*/
public function postCheckout($accessoryId)
{
// Check if the accessory exists
if (is_null($accessory = Accessory::find($accessoryId))) {
// Redirect to the accessory management page with error
return Redirect::to('accessories')->with('error', Lang::get('admin/accessories/message.user_not_found'));
} elseif (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
if (!$user = User::find(Input::get('assigned_to'))) {
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
// Update the accessory data
$accessory->assigned_to = e(Input::get('assigned_to'));
$accessory->users()->attach($accessory->id, array(
'accessory_id' => $accessory->id,
'assigned_to' => e(Input::get('assigned_to'))));
$admin_user = Auth::user();
$logaction = new Actionlog();
$logaction->accessory_id = $accessory->id;
$logaction->checkedout_to = $accessory->assigned_to;
$logaction->asset_type = 'accessory';
$logaction->location_id = Auth::user()->location_id;
$logaction->user_id = $admin_user->id;
$logaction->note = e(Input::get('note'));
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => strtoupper($logaction->asset_type).' <'.config('app.url').'/admin/accessories/'.$accessory->id.'/view'.'|'.$accessory->name.'> checked out to <'.config('app.url').'/admin/users/'.$user->id.'/view|'.$user->fullName().'> by <'.config('app.url').'/admin/users/'.$admin_user->id.'/view'.'|'.$admin_user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('Accessory Checked Out');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkout');
$accessory_user = DB::table('accessories_users')->where('assigned_to', '=', $accessory->assigned_to)->where('accessory_id', '=', $accessory->id)->first();
$data['log_id'] = $logaction->id;
$data['eula'] = $accessory->getEula();
$data['first_name'] = $user->first_name;
$data['item_name'] = $accessory->name;
$data['checkout_date'] = $logaction->created_at;
$data['item_tag'] = '';
$data['expected_checkin'] = '';
$data['note'] = $logaction->note;
$data['require_acceptance'] = $accessory->requireAcceptance();
if (($accessory->requireAcceptance()=='1') || ($accessory->getEula())) {
Mail::send('emails.accept-accessory', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->subject('Confirm accessory delivery');
});
}
// Redirect to the new accessory page
return Redirect::to("admin/accessories")->with('success', Lang::get('admin/accessories/message.checkout.success'));
}
/**
* Check the accessory back into inventory
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return View
**/
public function getCheckin($accessoryUserId = null, $backto = null)
{
// Check if the accessory exists
if (is_null($accessory_user = DB::table('accessories_users')->find($accessoryUserId))) {
// Redirect to the accessory management page with error
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
$accessory = Accessory::find($accessory_user->accessory_id);
if (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
} else {
return View::make('accessories/checkin', compact('accessory'))->with('backto', $backto);
}
}
/**
* Check in the item so that it can be checked out again to someone else
*
* @uses Accessory::checkin_email() to determine if an email can and should be sent
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return Redirect
**/
public function postCheckin($accessoryUserId = null, $backto = null)
{
// Check if the accessory exists
if (is_null($accessory_user = DB::table('accessories_users')->find($accessoryUserId))) {
// Redirect to the accessory management page with error
return Redirect::to('admin/accessories')->with('error', Lang::get('admin/accessories/message.not_found'));
}
$accessory = Accessory::find($accessory_user->accessory_id);
if (!Company::isCurrentUserHasAccess($accessory)) {
return Redirect::to('admin/accessories')->with('error', Lang::get('general.insufficient_permissions'));
}
$logaction = new Actionlog();
$logaction->checkedout_to = $accessory_user->assigned_to;
$return_to = $accessory_user->assigned_to;
$admin_user = Auth::user();
// Was the accessory updated?
if (DB::table('accessories_users')->where('id', '=', $accessory_user->id)->delete()) {
$logaction->accessory_id = $accessory->id;
$logaction->location_id = null;
$logaction->asset_type = 'accessory';
$logaction->user_id = $admin_user->id;
$logaction->note = e(Input::get('note'));
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked In:',
'value' => strtoupper($logaction->asset_type).' <'.config('app.url').'/admin/accessories/'.$accessory->id.'/view'.'|'.$accessory->name.'> checked in by <'.config('app.url').'/admin/users/'.$admin_user->id.'/view'.'|'.$admin_user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('Accessory Checked In');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkin from');
if (!is_null($accessory_user->assigned_to)) {
$user = User::find($accessory_user->assigned_to);
}
$data['log_id'] = $logaction->id;
$data['first_name'] = $user->first_name;
$data['item_name'] = $accessory->name;
$data['checkin_date'] = $logaction->created_at;
$data['item_tag'] = '';
$data['note'] = $logaction->note;
if (($accessory->checkin_email()=='1')) {
Mail::send('emails.checkin-asset', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->subject('Confirm Accessory Checkin');
});
}
if ($backto=='user') {
return Redirect::to("admin/users/".$return_to.'/view')->with('success', Lang::get('admin/accessories/message.checkin.success'));
} else {
return Redirect::to("admin/accessories/".$accessory->id."/view")->with('success', Lang::get('admin/accessories/message.checkin.success'));
}
}
// Redirect to the accessory management page with error
return Redirect::to("admin/accessories")->with('error', Lang::get('admin/accessories/message.checkin.error'));
}
/**
* Generates the JSON response for accessories listing view.
*
* Example:
* {
* "actions": "(links to available actions)",
* "category": "(link to category)",
* "companyName": "My Company",
* "location": "My Location",
* "min_amt": 2,
* "name": "(link to accessory),
* "numRemaining": 6,
* "order_number": null,
* "purchase_cost": "0.00",
* "purchase_date": null,
* "qty": 7
* },
*
* The names of the fields in the returns JSON correspond directly to the the
* names of the fields in the bootstrap-tables in the view.
*
* For debugging, see at /api/accessories/list
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return string JSON containing accessories and their associated atrributes.
**/
public function getDatatable()
{
$accessories = Accessory::select('accessories.*')->with('category', 'company')
->whereNull('accessories.deleted_at');
if (Input::has('search')) {
$accessories = $accessories->TextSearch(Input::get('search'));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['name','min_amt','order_number','purchase_date','purchase_cost','companyName','category'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
switch ($sort) {
case 'category':
$accessories = $accessories->OrderCategory($order);
break;
case 'companyName':
$accessories = $accessories->OrderCompany($order);
break;
default:
$accessories = $accessories->orderBy($sort, $order);
break;
}
$accessCount = $accessories->count();
$accessories = $accessories->skip($offset)->take($limit)->get();
$rows = array();
foreach ($accessories as $accessory) {
$actions = '<nobr><a href="'.route('checkout/accessory', $accessory->id).'" style="margin-right:5px;" class="btn btn-info btn-sm" '.(($accessory->numRemaining() > 0 ) ? '' : ' disabled').'>'.Lang::get('general.checkout').'</a><a href="'.route('update/accessory', $accessory->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/accessory', $accessory->id).'" data-content="'.Lang::get('admin/accessories/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($accessory->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></nobr>';
$company = $accessory->company;
$rows[] = array(
'name' => '<a href="'.url('admin/accessories/'.$accessory->id).'/view">'. $accessory->name.'</a>',
'category' => ($accessory->category) ? (string)link_to('admin/settings/categories/'.$accessory->category->id.'/view', $accessory->category->name) : '',
'qty' => $accessory->qty,
'order_number' => $accessory->order_number,
'min_amt' => $accessory->min_amt,
'location' => ($accessory->location) ? $accessory->location->name: '',
'purchase_date' => $accessory->purchase_date,
'purchase_cost' => number_format($accessory->purchase_cost, 2),
'numRemaining' => $accessory->numRemaining(),
'actions' => $actions,
'companyName' => is_null($company) ? '' : e($company->name)
);
}
$data = array('total'=>$accessCount, 'rows'=>$rows);
return $data;
}
/**
* Generates the JSON response for accessory detail view.
*
* Example:
* <code>
* {
* "rows": [
* {
* "actions": "(link to available actions)",
* "name": "(link to user)"
* }
* ],
* "total": 1
* }
* </code>
*
* The names of the fields in the returns JSON correspond directly to the the
* names of the fields in the bootstrap-tables in the view.
*
* For debugging, see at /api/accessories/$accessoryID/view
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @param int $accessoryId
* @return string JSON containing accessories and their associated atrributes.
**/
public function getDataView($accessoryID)
{
$accessory = Accessory::find($accessoryID);
if (!Company::isCurrentUserHasAccess($accessory)) {
return ['total' => 0, 'rows' => []];
}
$accessory_users = $accessory->users;
$count = $accessory_users->count();
$rows = array();
foreach ($accessory_users as $user) {
$actions = '<a href="'.route('checkin/accessory', $user->pivot->id).'" class="btn btn-info btn-sm">Checkin</a>';
$rows[] = array(
'name' =>(string) link_to('/admin/users/'.$user->id.'/view', $user->fullName()),
'actions' => $actions
);
}
$data = array('total'=>$count, 'rows'=>$rows);
return $data;
}
}

View file

@ -0,0 +1,485 @@
<?php
namespace App\Http\Controllers;
use App\Models\AssetMaintenance;
use Carbon\Carbon;
use App\Models\Company;
use DB;
use Input;
use Lang;
use Log;
use Mail;
use Redirect;
use Response;
use Slack;
use Str;
use App\Models\Supplier;
use TCPDF;
use Validator;
use View;
use App\Models\Setting;
use App\Models\Asset;
use App\Helpers\Helper;
class AssetMaintenancesController extends Controller
{
private static function getInsufficientPermissionsRedirect()
{
return redirect()->route('asset_maintenances')
->with('error', Lang::get('general.insufficient_permissions'));
}
/**
* getIndex
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getIndex()
{
return View::make('asset_maintenances/index');
}
/**
* getDatatable
* Gets the datatable for the index page
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getDatatable()
{
$maintenances = AssetMaintenance::with('asset', 'supplier', 'asset.company')
->whereNull('deleted_at');
if (Input::has('search')) {
$maintenances = $maintenances->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','title','asset_maintenance_time','asset_maintenance_type','cost','start_date','completion_date','notes'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$maintenances->orderBy($sort, $order);
$maintenancesCount = $maintenances->count();
$maintenances = $maintenances->skip($offset)->take($limit)->get();
$rows = array();
$settings = Setting::getSettings();
foreach ($maintenances as $maintenance) {
$actions = '<nobr><a href="'.route('update/asset_maintenance', $maintenance->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/asset_maintenance', $maintenance->id).'" data-content="'.Lang::get('admin/asset_maintenances/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($maintenance->title).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></nobr>';
if (($maintenance->cost) && ($maintenance->asset->assetloc) && ($maintenance->asset->assetloc->currency!='')) {
$maintenance_cost = $maintenance->asset->assetloc->currency.$maintenance->cost;
} else {
$maintenance_cost = $settings->default_currency.$maintenance->cost;
}
$company = $maintenance->asset->company;
$rows[] = array(
'id' => $maintenance->id,
'asset_name' => (string)link_to('/hardware/'.$maintenance->asset->id.'/view', $maintenance->asset->showAssetName()) ,
'title' => $maintenance->title,
'notes' => $maintenance->notes,
'supplier' => $maintenance->supplier->name,
'cost' => $maintenance_cost,
'asset_maintenance_type' => e($maintenance->asset_maintenance_type),
'start_date' => $maintenance->start_date,
'asset_maintenance_time' => $maintenance->asset_maintenance_time,
'completion_date' => $maintenance->completion_date,
'actions' => $actions,
'companyName' => is_null($company) ? '' : $company->name
);
}
$data = array('total' => $maintenancesCount, 'rows' => $rows);
return $data;
}
/**
* getCreate
*
* @param null $assetId
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getCreate($assetId = null)
{
// Prepare Asset Maintenance Type List
$assetMaintenanceType = [
'' => 'Select an asset maintenance type',
] + AssetMaintenance::getImprovementOptions();
// Mark the selected asset, if it came in
$selectedAsset = $assetId;
// Get the possible assets using a left join to get a list of assets and some other helpful info
$asset = Company::scopeCompanyables(DB::table('assets'), 'assets.company_id')
->leftJoin('users', 'users.id', '=', 'assets.assigned_to')
->leftJoin('models', 'assets.model_id', '=', 'models.id')
->select(
'assets.id',
'assets.name',
'first_name',
'last_name',
'asset_tag',
DB::raw('concat(first_name," ",last_name) as full_name, assets.id as id, models.name as modelname')
)
->whereNull('assets.deleted_at')
->get();
$asset_array = json_decode(json_encode($asset), true);
$asset_element[ '' ] = 'Please select an asset';
// Build a list out of the data results
for ($x = 0; $x < count($asset_array); $x++) {
if ($asset_array[ $x ][ 'full_name' ] != '') {
$full_name = ' (' . $asset_array[ $x ][ 'full_name' ] . ') ' . $asset_array[ $x ][ 'modelname' ];
} else {
$full_name = ' (Unassigned) ' . $asset_array[ $x ][ 'modelname' ];
}
$asset_element[ $asset_array[ $x ][ 'id' ] ] =
$asset_array[ $x ][ 'asset_tag' ] . ' - ' . $asset_array[ $x ][ 'name' ] . $full_name;
}
// Get Supplier List
$supplier_list = Helper::suppliersList();
// Render the view
return View::make('asset_maintenances/edit')
->with('asset_list', $asset_element)
->with('selectedAsset', $selectedAsset)
->with('supplier_list', $supplier_list)
->with('assetMaintenanceType', $assetMaintenanceType)
->with('assetMaintenance', new AssetMaintenance);
}
/**
* postCreate
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new model instance
$assetMaintenance = new AssetMaintenance();
if (e(Input::get('supplier_id')) == '') {
$assetMaintenance->supplier_id = null;
} else {
$assetMaintenance->supplier_id = e(Input::get('supplier_id'));
}
if (e(Input::get('is_warranty')) == '') {
$assetMaintenance->is_warranty = 0;
} else {
$assetMaintenance->is_warranty = e(Input::get('is_warranty'));
}
if (e(Input::get('cost')) == '') {
$assetMaintenance->cost = '';
} else {
$assetMaintenance->cost = e(Input::get('cost'));
}
if (e(Input::get('notes')) == '') {
$assetMaintenance->notes = null;
} else {
$assetMaintenance->notes = e(Input::get('notes'));
}
$asset = Asset::find(e(Input::get('asset_id')));
if (!Company::isCurrentUserHasAccess($asset)) {
return static::getInsufficientPermissionsRedirect();
}
// Save the asset maintenance data
$assetMaintenance->asset_id = e(Input::get('asset_id'));
$assetMaintenance->asset_maintenance_type = e(Input::get('asset_maintenance_type'));
$assetMaintenance->title = e(Input::get('title'));
$assetMaintenance->start_date = e(Input::get('start_date'));
$assetMaintenance->completion_date = e(Input::get('completion_date'));
if (( $assetMaintenance->completion_date == "" )
|| ( $assetMaintenance->completion_date == "0000-00-00" )
) {
$assetMaintenance->completion_date = null;
}
if (( $assetMaintenance->completion_date !== "" )
&& ( $assetMaintenance->completion_date !== "0000-00-00" )
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
$assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate);
}
// Was the asset maintenance created?
if ($assetMaintenance->save()) {
// Redirect to the new asset maintenance page
return Redirect::to("admin/asset_maintenances")
->with('success', Lang::get('admin/asset_maintenances/message.create.success'));
}
return redirect()->back()->withInput()->withErrors($assetMaintenance->getErrors());
}
/**
* getEdit
*
* @param null $assetMaintenanceId
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getEdit($assetMaintenanceId = null)
{
// Check if the asset maintenance exists
if (is_null($assetMaintenance = AssetMaintenance::find($assetMaintenanceId))) {
// Redirect to the improvement management page
return Redirect::to('admin/asset_maintenances')
->with('error', Lang::get('admin/asset_maintenances/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return static::getInsufficientPermissionsRedirect();
}
if ($assetMaintenance->completion_date == '0000-00-00') {
$assetMaintenance->completion_date = null;
}
if ($assetMaintenance->start_date == '0000-00-00') {
$assetMaintenance->start_date = null;
}
if ($assetMaintenance->cost == '0.00') {
$assetMaintenance->cost = null;
}
// Prepare Improvement Type List
$assetMaintenanceType = [
'' => 'Select an improvement type',
] + AssetMaintenance::getImprovementOptions();
// Get the possible assets using a left join to get a list of assets and some other helpful info
$asset = Company::scopeCompanyables(DB::table('assets'), 'assets.company_id')
->leftJoin('users', 'users.id', '=', 'assets.assigned_to')
->leftJoin('models', 'assets.model_id', '=', 'models.id')
->select(
'assets.id',
'assets.name',
'first_name',
'last_name',
'asset_tag',
DB::raw('concat(first_name," ",last_name) as full_name, assets.id as id, models.name as modelname')
)
->whereNull('assets.deleted_at')
->get();
$asset_array = json_decode(json_encode($asset), true);
$asset_element[ '' ] = 'Please select an asset';
// Build a list out of the data results
for ($x = 0; $x < count($asset_array); $x++) {
if ($asset_array[ $x ][ 'full_name' ] != '') {
$full_name = ' (' . $asset_array[ $x ][ 'full_name' ] . ') ' . $asset_array[ $x ][ 'modelname' ];
} else {
$full_name = ' (Unassigned) ' . $asset_array[ $x ][ 'modelname' ];
}
$asset_element[ $asset_array[ $x ][ 'id' ] ] =
$asset_array[ $x ][ 'asset_tag' ] . ' - ' . $asset_array[ $x ][ 'name' ] . $full_name;
}
// Get Supplier List
$supplier_list = Helper::suppliersList();
// Render the view
return View::make('asset_maintenances/edit')
->with('asset_list', $asset_element)
->with('selectedAsset', null)
->with('supplier_list', $supplier_list)
->with('assetMaintenanceType', $assetMaintenanceType)
->with('assetMaintenance', $assetMaintenance);
}
/**
* postEdit
*
* @param null $assetMaintenanceId
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function postEdit($assetMaintenanceId = null)
{
// get the POST data
$new = Input::all();
// Check if the asset maintenance exists
if (is_null($assetMaintenance = AssetMaintenance::find($assetMaintenanceId))) {
// Redirect to the asset maintenance management page
return Redirect::to('admin/asset_maintenances')
->with('error', Lang::get('admin/asset_maintenances/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return static::getInsufficientPermissionsRedirect();
}
if (e(Input::get('supplier_id')) == '') {
$assetMaintenance->supplier_id = null;
} else {
$assetMaintenance->supplier_id = e(Input::get('supplier_id'));
}
if (e(Input::get('is_warranty')) == '') {
$assetMaintenance->is_warranty = 0;
} else {
$assetMaintenance->is_warranty = e(Input::get('is_warranty'));
}
if (e(Input::get('cost')) == '') {
$assetMaintenance->cost = '';
} else {
$assetMaintenance->cost = e(Input::get('cost'));
}
if (e(Input::get('notes')) == '') {
$assetMaintenance->notes = null;
} else {
$assetMaintenance->notes = e(Input::get('notes'));
}
$asset = Asset::find(e(Input::get('asset_id')));
if (!Company::isCurrentUserHasAccess($asset)) {
return static::getInsufficientPermissionsRedirect();
}
// Save the asset maintenance data
$assetMaintenance->asset_id = e(Input::get('asset_id'));
$assetMaintenance->asset_maintenance_type = e(Input::get('asset_maintenance_type'));
$assetMaintenance->title = e(Input::get('title'));
$assetMaintenance->start_date = e(Input::get('start_date'));
$assetMaintenance->completion_date = e(Input::get('completion_date'));
if (( $assetMaintenance->completion_date == "" )
|| ( $assetMaintenance->completion_date == "0000-00-00" )
) {
$assetMaintenance->completion_date = null;
if (( $assetMaintenance->asset_maintenance_time !== 0 )
|| ( !is_null($assetMaintenance->asset_maintenance_time) )
) {
$assetMaintenance->asset_maintenance_time = null;
}
}
if (( $assetMaintenance->completion_date !== "" )
&& ( $assetMaintenance->completion_date !== "0000-00-00" )
&& ( $assetMaintenance->start_date !== "" )
&& ( $assetMaintenance->start_date !== "0000-00-00" )
) {
$startDate = Carbon::parse($assetMaintenance->start_date);
$completionDate = Carbon::parse($assetMaintenance->completion_date);
$assetMaintenance->asset_maintenance_time = $completionDate->diffInDays($startDate);
}
// Was the asset maintenance created?
if ($assetMaintenance->save()) {
// Redirect to the new asset maintenance page
return Redirect::to("admin/asset_maintenances")
->with('success', Lang::get('admin/asset_maintenances/message.create.success'));
}
return Redirect::back() ->withInput()->withErrors($assetMaintenance->getErrors());
}
/**
* getDelete
*
* @param $assetMaintenanceId
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getDelete($assetMaintenanceId)
{
// Check if the asset maintenance exists
if (is_null($assetMaintenance = AssetMaintenance::find($assetMaintenanceId))) {
// Redirect to the asset maintenance management page
return Redirect::to('admin/asset_maintenances')
->with('error', Lang::get('admin/asset_maintenances/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return static::getInsufficientPermissionsRedirect();
}
// Delete the asset maintenance
$assetMaintenance->delete();
// Redirect to the asset_maintenance management page
return Redirect::to('admin/asset_maintenances')
->with('success', Lang::get('admin/asset_maintenances/message.delete.success'));
}
/**
* getView
*
* @param $assetMaintenanceId
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getView($assetMaintenanceId)
{
// Check if the asset maintenance exists
if (is_null($assetMaintenance = AssetMaintenance::find($assetMaintenanceId))) {
// Redirect to the asset maintenance management page
return Redirect::to('admin/asset_maintenances')
->with('error', Lang::get('admin/asset_maintenances/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($assetMaintenance->asset)) {
return static::getInsufficientPermissionsRedirect();
}
return View::make('asset_maintenances/view')->with('assetMaintenance', $assetMaintenance);
}
}

View file

@ -0,0 +1,550 @@
<?php
/**
* This controller handles all actions related to Asset Models for
* the Snipe-IT Asset Management application.
*
* PHP version 5.5.9
* @package Snipe-IT
* @version v1.0
*/
namespace App\Http\Controllers;
use Image;
use Input;
use Lang;
use App\Models\AssetModel;
use Redirect;
use App\Models\Setting;
use Auth;
use DB;
use App\Models\Depreciation;
use App\Models\Manufacturer;
use Str;
use Validator;
use View;
use App\Models\Asset;
use App\Models\Company;
use Config;
use App\Helpers\Helper;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* This class controls all actions related to asset models
*/
class AssetModelsController extends Controller
{
/**
* Returns a view that invokes the ajax tables which actually contains
* the content for the accessories listing, which is generated in getDatatable.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @see AssetModelsController::getDatatable() method that generates the JSON response
* @since [v1.0]
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('models/index');
}
/**
* Returns a view containing the asset model creation form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return View
*/
public function getCreate()
{
// Show the page
$depreciation_list = \App\Helpers\Helper::depreciationList();
$manufacturer_list = \App\Helpers\Helper::manufacturerList();
$category_list = \App\Helpers\Helper::categoryList();
return View::make('models/edit')
->with('category_list', $category_list)
->with('depreciation_list', $depreciation_list)
->with('manufacturer_list', $manufacturer_list)
->with('model', new AssetModel);
}
/**
* Validate and process the new Asset Model data.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return Redirect
*/
public function postCreate()
{
// Create a new asset model
$model = new AssetModel;
if (e(Input::get('depreciation_id')) == '') {
$model->depreciation_id = 0;
} else {
$model->depreciation_id = e(Input::get('depreciation_id'));
}
if (e(Input::get('eol')) == '') {
$model->eol = 0;
} else {
$model->eol = e(Input::get('eol'));
}
// Save the model data
$model->name = e(Input::get('name'));
$model->modelno = e(Input::get('modelno'));
$model->manufacturer_id = e(Input::get('manufacturer_id'));
$model->category_id = e(Input::get('category_id'));
$model->note = e(Input::get('note'));
$model->user_id = Auth::user()->id;
if (Input::get('custom_fieldset')!='') {
$model->fieldset_id = e(Input::get('custom_fieldset'));
}
//$model->show_mac_address = e(Input::get('show_mac_address', '0'));
if (Input::file('image')) {
$image = Input::file('image');
$file_name = str_random(25).".".$image->getClientOriginalExtension();
$path = public_path('uploads/models/'.$file_name);
// Image::make($image->getRealPath())->resize(300, null, function ($constraint) {
// $constraint->aspectRatio();
// $constraint->upsize();
// })->save($path);
$model->image = $file_name;
}
// Was it created?
if ($model->save()) {
// Redirect to the new model page
return Redirect::to("hardware/models")->with('success', Lang::get('admin/models/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($model->getErrors());
}
/**
* Validates and stores new Asset Model data created from the
* modal form on the Asset Creation view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @return String JSON
*/
public function store()
{
//COPYPASTA!!!! FIXME
$model = new \App\Models\AssetModel;
$settings=Input::all();
$settings['eol']=0;
//
$model->name=e(Input::get('name'));
$model->manufacturer_id = e(Input::get('manufacturer_id'));
$model->category_id = e(Input::get('category_id'));
$model->modelno = e(Input::get('modelno'));
$model->user_id = Auth::user()->id;
$model->note = e(Input::get('note'));
$model->eol=0;
if ($model->save()) {
return JsonResponse::create($model);
} else {
return JsonResponse::create(["error" => "Failed validation: ".print_r($model->getErrors()->all('<li>:message</li>'), true)], 500);
}
}
/**
* Returns a view containing the asset model edit form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return View
*/
public function getEdit($modelId = null)
{
// Check if the model exists
if (is_null($model = AssetModel::find($modelId))) {
// Redirect to the model management page
return Redirect::to('assets/models')->with('error', Lang::get('admin/models/message.does_not_exist'));
}
$depreciation_list = \App\Helpers\Helper::depreciationList();
$manufacturer_list = \App\Helpers\Helper::manufacturerList();
$category_list = \App\Helpers\Helper::categoryList();
$view = View::make('models/edit', compact('model'));
$view->with('category_list', $category_list);
$view->with('depreciation_list', $depreciation_list);
$view->with('manufacturer_list', $manufacturer_list);
return $view;
}
/**
* Validates and processes form data from the edit
* Asset Model form based on the model ID passed.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return Redirect
*/
public function postEdit($modelId = null)
{
// Check if the model exists
if (is_null($model = AssetModel::find($modelId))) {
// Redirect to the models management page
return Redirect::to('admin/models')->with('error', Lang::get('admin/models/message.does_not_exist'));
}
if (e(Input::get('depreciation_id')) == '') {
$model->depreciation_id = 0;
} else {
$model->depreciation_id = e(Input::get('depreciation_id'));
}
if (e(Input::get('eol')) == '') {
$model->eol = 0;
} else {
$model->eol = e(Input::get('eol'));
}
// Update the model data
$model->name = e(Input::get('name'));
$model->modelno = e(Input::get('modelno'));
$model->manufacturer_id = e(Input::get('manufacturer_id'));
$model->category_id = e(Input::get('category_id'));
$model->note = e(Input::get('note'));
if (Input::get('custom_fieldset')=='') {
$model->fieldset_id = null;
} else {
$model->fieldset_id = e(Input::get('custom_fieldset'));
}
if (Input::file('image')) {
$image = Input::file('image');
$file_name = str_random(25).".".$image->getClientOriginalExtension();
$path = public_path('uploads/models/'.$file_name);
Image::make($image->getRealPath())->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->save($path);
$model->image = $file_name;
}
if (Input::get('image_delete') == 1 && Input::file('image') == "") {
$model->image = null;
}
// Was it created?
if ($model->save()) {
// Redirect to the new model page
return Redirect::to("hardware/models")->with('success', Lang::get('admin/models/message.update.success'));
} else {
return redirect()->back()->withInput()->withErrors($model->getErrors());
}
// Redirect to the model create page
return Redirect::to("hardware/models/$modelId/edit")->with('error', Lang::get('admin/models/message.update.error'));
}
/**
* Validate and delete the given Asset Model. An Asset Model
* cannot be deleted if there are associated assets.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return Redirect
*/
public function getDelete($modelId)
{
// Check if the model exists
if (is_null($model = AssetModel::find($modelId))) {
// Redirect to the blogs management page
return Redirect::to('hardware/models')->with('error', Lang::get('admin/models/message.not_found'));
}
if ($model->assets->count() > 0) {
// Throw an error that this model is associated with assets
return Redirect::to('hardware/models')->with('error', Lang::get('admin/models/message.assoc_users'));
} else {
// Delete the model
$model->delete();
// Redirect to the models management page
return Redirect::to('hardware/models')->with('success', Lang::get('admin/models/message.delete.success'));
}
}
/**
* Restore a given Asset Model (mark as un-deleted)
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return Redirect
*/
public function getRestore($modelId = null)
{
// Get user information
$model = AssetModel::withTrashed()->find($modelId);
if (isset($model->id)) {
// Restore the model
$model->restore();
// Prepare the success message
$success = Lang::get('admin/models/message.restore.success');
// Redirect back
return Redirect::back()->with('success', $success);
} else {
return Redirect::back()->with('error', Lang::get('admin/models/message.not_found'));
}
}
/**
* Get the model information to present to the model view page
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return View
*/
public function getView($modelId = null)
{
$model = AssetModel::withTrashed()->find($modelId);
if (isset($model->id)) {
return View::make('models/view', compact('model'));
} else {
// Prepare the error message
$error = Lang::get('admin/models/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('models')->with('error', $error);
}
}
/**
* Get the clone page to clone a model
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @param int $modelId
* @return View
*/
public function getClone($modelId = null)
{
// Check if the model exists
if (is_null($model_to_clone = AssetModel::find($modelId))) {
// Redirect to the model management page
return Redirect::to('assets/models')->with('error', Lang::get('admin/models/message.does_not_exist'));
}
$model = clone $model_to_clone;
$model->id = null;
// Show the page
$depreciation_list = array('' => 'Do Not Depreciate') + Depreciation::lists('name', 'id');
$manufacturer_list = array('' => 'Select One') + Manufacturer::lists('name', 'id');
$category_list = array('' => '') + DB::table('categories')->whereNull('deleted_at')->lists('name', 'id');
$view = View::make('models/edit');
$view->with('category_list', $category_list);
$view->with('depreciation_list', $depreciation_list);
$view->with('manufacturer_list', $manufacturer_list);
$view->with('model', $model);
$view->with('clone_model', $model_to_clone);
return $view;
}
/**
* Get the custom fields form
*
* @author [B. Wetherington] [<uberbrady@gmail.com>]
* @since [v2.0]
* @param int $modelId
* @return View
*/
public function getCustomFields($modelId)
{
$model=AssetModel::find($modelId);
return View::make("models.custom_fields_form")->with("model", $model);
}
/**
* Get the JSON response to populate the data tables on the
* Asset Model listing page.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @param string $status
* @return String JSON
*/
public function getDatatable($status = null)
{
$models = AssetModel::with('category', 'assets', 'depreciation');
switch ($status) {
case 'Deleted':
$models->withTrashed()->Deleted();
break;
}
if (Input::has('search')) {
$models = $models->TextSearch(Input::get('search'));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','modelno'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$models = $models->orderBy($sort, $order);
$modelCount = $models->count();
$models = $models->skip($offset)->take($limit)->get();
$rows = array();
foreach ($models as $model) {
if ($model->deleted_at == '') {
$actions = '<div style=" white-space: nowrap;"><a href="'.route('update/model', $model->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/model', $model->id).'" data-content="'.Lang::get('admin/models/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($model->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></div>';
} else {
$actions = '<a href="'.route('restore/model', $model->id).'" class="btn btn-warning btn-sm"><i class="fa fa-recycle icon-white"></i></a>';
}
$rows[] = array(
'id' => $model->id,
'manufacturer' => (string)link_to('/admin/settings/manufacturers/'.$model->manufacturer->id.'/view', $model->manufacturer->name),
'name' => (string)link_to('/hardware/models/'.$model->id.'/view', $model->name),
'image' => ($model->image!='') ? '<img src="'.config('app.url').'/uploads/models/'.$model->image.'" height=50 width=50>' : '',
'modelnumber' => $model->modelno,
'numassets' => $model->assets->count(),
'depreciation' => (($model->depreciation)&&($model->depreciation->id > 0)) ? $model->depreciation->name.' ('.$model->depreciation->months.')' : Lang::get('general.no_depreciation'),
'category' => ($model->category) ? $model->category->name : '',
'eol' => ($model->eol) ? $model->eol.' '.Lang::get('general.months') : '',
'note' => $model->getNote(),
'actions' => $actions
);
}
$data = array('total' => $modelCount, 'rows' => $rows);
return $data;
}
/**
* Get the asset information to present to the model view detail page
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v2.0]
* @param int $modelId
* @return String JSON
*/
public function getDataView($modelID)
{
$assets = Asset::where('model_id', '=', $modelID)->withTrashed()->with('company');
if (Input::has('search')) {
$assets = $assets->TextSearch(Input::get('search'));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['name', 'serial','asset_tag'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$assets = $assets->orderBy($sort, $order);
$assetsCount = $assets->count();
$assets = $assets->skip($offset)->take($limit)->get();
$rows = array();
foreach ($assets as $asset) {
$actions = '';
if ($asset->assetstatus) {
if ($asset->assetstatus->deployable != 0) {
if (($asset->assigned_to !='') && ($asset->assigned_to > 0)) {
$actions = '<a href="'.route('checkin/hardware', $asset->id).'" class="btn btn-primary btn-sm">'.Lang::get('general.checkin').'</a>';
} else {
$actions = '<a href="'.route('checkout/hardware', $asset->id).'" class="btn btn-info btn-sm">'.Lang::get('general.checkout').'</a>';
}
}
}
$rows[] = array(
'id' => $asset->id,
'name' => (string)link_to('/hardware/'.$asset->id.'/view', $asset->showAssetName()),
'asset_tag' => (string)link_to('hardware/'.$asset->id.'/view', $asset->asset_tag),
'serial' => $asset->serial,
'assigned_to' => ($asset->assigned_to) ? (string)link_to('/admin/users/'.$asset->assigned_to.'/view', $asset->assigneduser->fullName()) : '',
'actions' => $actions,
'companyName' => Company::getName($asset)
);
}
$data = array('total' => $assetsCount, 'rows' => $rows);
return $data;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,279 @@
<?php
namespace App\Http\Controllers\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
//use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
//use Socialite;
use Auth;
use Config;
use Illuminate\Http\Request;
use Input;
use Redirect;
use Log;
use View;
use App\Models\User;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use ThrottlesLogins;
// This tells the auth controller to use username instead of email address
protected $username = 'username';
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
function showLoginForm()
{
// Is the user logged in?
if (Auth::check()) {
return redirect()->intended('dashboard');
}
// Show the page
return View::make('auth.login');
}
/**
* Authenticates a user to LDAP
*
* @param $username
* @param $password
* @param bool|false $returnUser
* @return bool true if the username and/or password provided are valid
* false if the username and/or password provided are invalid
* array of ldap_attributes if $returnUser is true
*/
function ldap($username, $password, $returnUser = false)
{
$ldaphost = \App\Models\Setting::getSettings()->ldap_server;
$ldaprdn = \App\Models\Setting::getSettings()->ldap_uname;
$ldappass = \Crypt::decrypt(\App\Models\Setting::getSettings()->ldap_pword);
$baseDn = \App\Models\Setting::getSettings()->ldap_basedn;
$filterQuery = \App\Models\Setting::getSettings()->ldap_auth_filter_query . $username;
$ldapversion = \App\Models\Setting::getSettings()->ldap_version;
$ldap_server_cert_ignore = \App\Models\Setting::getSettings()->ldap_server_cert_ignore;
// If we are ignoring the SSL cert we need to setup the environment variable
// before we create the connection
if ($ldap_server_cert_ignore) {
putenv('LDAPTLS_REQCERT=never');
}
// Connecting to LDAP
$connection = ldap_connect($ldaphost) or die("Could not connect to {$ldaphost}");
// Needed for AD
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapversion);
try {
if ($connection) {
// binding to ldap server
$ldapbind = ldap_bind($connection, $ldaprdn, $ldappass);
if (($results = @ldap_search($connection, $baseDn, $filterQuery)) != false) {
$entry = ldap_first_entry($connection, $results);
if (($userDn = @ldap_get_dn($connection, $entry)) != false) {
if (($isBound = ldap_bind($connection, $userDn, $password)) == "true") {
return $returnUser ?
array_change_key_case(ldap_get_attributes($connection, $entry), CASE_LOWER)
: true;
}
}
}
}
} catch (Exception $e) {
LOG::error($e->getMessage());
}
ldap_close($connection);
return false;
}
/**
* Create user from LDAP attributes
*
* @param $ldapatttibutes
* @return array|bool
*/
function createUserFromLdap($ldapatttibutes)
{
//Get LDAP attribute config
$ldap_result_username = \App\Models\Setting::getSettings()->ldap_username_field;
$ldap_result_emp_num = \App\Models\Setting::getSettings()->ldap_emp_num;
$ldap_result_last_name = \App\Models\Setting::getSettings()->ldap_lname_field;
$ldap_result_first_name = \App\Models\Setting::getSettings()->ldap_fname_field;
$ldap_result_email = \App\Models\Setting::getSettings()->ldap_email;
//Get LDAP user data
$item = array();
$item["username"] = isset($ldapatttibutes[$ldap_result_username][0]) ? $ldapatttibutes[$ldap_result_username][0] : "";
$item["employee_number"] = isset($ldapatttibutes[$ldap_result_emp_num][0]) ? $ldapatttibutes[$ldap_result_emp_num][0] : "";
$item["lastname"] = isset($ldapatttibutes[$ldap_result_last_name][0]) ? $ldapatttibutes[$ldap_result_last_name][0] : "";
$item["firstname"] = isset($ldapatttibutes[$ldap_result_first_name][0]) ? $ldapatttibutes[$ldap_result_first_name][0] : "";
$item["email"] = isset($ldapatttibutes[$ldap_result_email][0]) ? $ldapatttibutes[$ldap_result_email][0] : "" ;
//create user
if (!empty($item["username"])) {
//$pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
$newuser = array(
'first_name' => $item["firstname"],
'last_name' => $item["lastname"],
'username' => $item["username"],
'email' => $item["email"],
'employee_num' => $item["employee_number"],
'password' => bcrypt(Input::get("password")), //$pass,
'activated' => 1,
'permissions' => ["user" => 1], //'{"user":1}',
'notes' => 'Imported from LDAP'
);
\App\Models\User::save($newuser);
} else {
throw new Cartalyst\Sentry\Users\UserNotFoundException();
}
//$item["note"] = "<strong>created</strong>";
$credentials = array(
'username' => $item["username"],
'password' => Input::get("password")//$pass,
);
return $credentials;
}
/**
* Account sign in form processing.
*
* @return Redirect
*/
public function login()
{
$validator = $this->validator(Input::all());
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
// Should we even check for LDAP users?
if (\App\Models\Setting::getSettings()->ldap_enabled=='1') {
LOG::debug("LDAP is enabled.");
// Check if the user exists in the database
$user = \App\Models\User::where('username', '=', Input::get('username'))->whereNull('deleted_at')->first();
LOG::debug("Auth lookup complete");
// The user does not exist in the database. Try to get them from LDAP.
// If user does not exist and authenticates sucessfully with LDAP we
// will create it on the fly and sign in with default permissions
if (!$user) {
LOG::debug("Local user ".Input::get('username')." does not exist");
if ($userattr = $this->ldap(Input::get('username'), Input::get('password'), true)) {
LOG::debug("Creating local user from authenticated LDAP user.");
$credentials = $this->createUserFromLdap($userattr);
} else {
LOG::debug("User did not authenticate correctly against LDAP. No local user was created.");
}
// If the user exists and they were imported from LDAP already
} else {
LOG::debug("Local user ".Input::get('username')." exists in database. Authenticating existing user against LDAP.");
if ($this->ldap(Input::get('username'), Input::get('password'))) {
LOG::debug("Valid LDAP login. Updating the local data.");
$user = \App\Models\User::find($user->id); //need the Sentry object, not the Eloquent object, to access critical password hashing functions
$user->password = bcrypt(Input::get('password'));
$user->ldap_import = 1;
$user->save();
} else {
LOG::debug("User did not authenticate correctly against LDAP. Local user was not updated.");
}// End LDAP auth
} // End if(!user)
// NO LDAP enabled - just try to login the user normally
}
LOG::debug("Authenticating user against database.");
// Try to log the user in
if (!Auth::attempt(Input::only('username', 'password'), Input::get('remember-me', 0))) {
LOG::debug("Local authentication failed.");
// throw new Cartalyst\Sentry\Users\UserNotFoundException();
return Redirect::back()->withInput()->with('error', trans('auth/message.account_not_found'));
}
// Get the page we were before
$redirect = \Session::get('loginRedirect', 'home');
// Unset the page we were before from the session
\Session::forget('loginRedirect');
// Redirect to the users page
return Redirect::to($redirect)->with('success', trans('auth/message.signin.success'));
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($this->messageBag);
}
/**
* Logout page.
*
* @return Redirect
*/
public function logout()
{
// Log the user out
Auth::logout();
// Redirect to the users page
return Redirect::route('home')->with('success', 'You have successfully logged out!');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required',
'password' => 'required',
]);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}

View file

@ -0,0 +1,326 @@
<?php namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Category as Category;
use App\Models\Company;
use App\Models\Setting;
use Auth;
use DB;
use Input;
use Lang;
use Redirect;
use Str;
use View;
class CategoriesController extends Controller
{
/**
* Show a list of all the categories.
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('categories/index');
}
/**
* Category create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$category_types= Helper::categoryTypeList();
return View::make('categories/edit')->with('category', new Category)
->with('category_types', $category_types);
}
/**
* Category create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$category = new Category();
// Update the category data
$category->name = e(Input::get('name'));
$category->category_type = e(Input::get('category_type'));
$category->eula_text = e(Input::get('eula_text'));
$category->use_default_eula = e(Input::get('use_default_eula', '0'));
$category->require_acceptance = e(Input::get('require_acceptance', '0'));
$category->checkin_email = e(Input::get('checkin_email', '0'));
$category->user_id = Auth::user()->id;
if ($category->save()) {
// Redirect to the new category page
return Redirect::to("admin/settings/categories")->with('success', Lang::get('admin/categories/message.create.success'));
} else {
// The given data did not pass validation
return Redirect::back()->withInput()->withErrors($category->getErrors());
}
// Redirect to the category create page
return Redirect::to('admin/settings/categories/create')->with('error', Lang::get('admin/categories/message.create.error'));
}
/**
* Category update.
*
* @param int $categoryId
* @return View
*/
public function getEdit($categoryId = null)
{
// Check if the category exists
if (is_null($category = Category::find($categoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/categories')->with('error', Lang::get('admin/categories/message.does_not_exist'));
}
// Show the page
//$category_options = array('' => 'Top Level') + Category::lists('name', 'id');
$category_options = array('' => 'Top Level') + DB::table('categories')->where('id', '!=', $categoryId)->lists('name', 'id');
$category_types= Helper::categoryTypeList();
return View::make('categories/edit', compact('category'))
->with('category_options', $category_options)
->with('category_types', $category_types);
}
/**
* Category update form processing page.
*
* @param int $categoryId
* @return Redirect
*/
public function postEdit($categoryId = null)
{
// Check if the blog post exists
if (is_null($category = Category::find($categoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/categories')->with('error', Lang::get('admin/categories/message.does_not_exist'));
}
// Update the category data
$category->name = e(Input::get('name'));
$category->category_type = e(Input::get('category_type'));
$category->eula_text = e(Input::get('eula_text'));
$category->use_default_eula = e(Input::get('use_default_eula', '0'));
$category->require_acceptance = e(Input::get('require_acceptance', '0'));
$category->checkin_email = e(Input::get('checkin_email', '0'));
if ($category->save()) {
// Redirect to the new category page
return Redirect::to("admin/settings/categories")->with('success', Lang::get('admin/categories/message.update.success'));
} // attempt validation
else {
// The given data did not pass validation
return Redirect::back()->withInput()->withErrors($category->getErrors());
}
// Redirect to the category management page
return Redirect::back()->with('error', Lang::get('admin/categories/message.update.error'));
}
/**
* Delete the given category.
*
* @param int $categoryId
* @return Redirect
*/
public function getDelete($categoryId)
{
// Check if the category exists
if (is_null($category = Category::find($categoryId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/categories')->with('error', Lang::get('admin/categories/message.not_found'));
}
if ($category->has_models() > 0) {
// Redirect to the asset management page
return Redirect::to('admin/settings/categories')->with('error', Lang::get('admin/categories/message.assoc_users'));
} else {
$category->delete();
// Redirect to the locations management page
return Redirect::to('admin/settings/categories')->with('success', Lang::get('admin/categories/message.delete.success'));
}
}
/**
* Get the asset information to present to the category view page
*
* @param int $assetId
* @return View
**/
public function getView($categoryID = null)
{
$category = Category::find($categoryID);
if (isset($category->id)) {
return View::make('categories/view', compact('category'));
} else {
// Prepare the error message
$error = Lang::get('admin/categories/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('categories')->with('error', $error);
}
}
public function getDatatable()
{
// Grab all the categories
$categories = Category::with('assets', 'accessories', 'consumables');
if (Input::has('search')) {
$categories = $categories->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','category_type'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$categories = $categories->orderBy($sort, $order);
$catCount = $categories->count();
$categories = $categories->skip($offset)->take($limit)->get();
$rows = array();
foreach ($categories as $category) {
$actions = '<a href="'.route('update/category', $category->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/category', $category->id).'" data-content="'.Lang::get('admin/categories/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($category->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
$rows[] = array(
'id' => $category->id,
'name' => (string)link_to('/admin/settings/categories/'.$category->id.'/view', $category->name) ,
'category_type' => ucwords($category->category_type),
'count' => $category->assets->count(),
'acceptance' => ($category->require_acceptance=='1') ? '<i class="fa fa-check"></i>' : '',
//EULA is still not working correctly
'eula' => ($category->getEula()) ? '<i class="fa fa-check"></i>' : '',
'actions' => $actions
);
}
$data = array('total' => $catCount, 'rows' => $rows);
return $data;
}
public function getDataView($categoryID)
{
$category = Category::find($categoryID);
if ($category->category_type =='asset') {
$category_assets = $category->assets;
} elseif ($category->category_type =='accessory') {
$category_assets = $category->accessories;
} elseif ($category->category_type =='consumable') {
$category_assets = $category->consumables;
} elseif ($category->category_type =='component') {
$category_assets = $category->components;
}
if (Input::has('search')) {
$category_assets = $category_assets->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$allowed_columns = ['id','name','serial','asset_tag'];
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$count = $category_assets->count();
$rows = array();
foreach ($category_assets as $asset) {
$actions = '';
$inout='';
if ($asset->deleted_at=='') {
$actions = '<div style=" white-space: nowrap;"><a href="'.route('clone/hardware', $asset->id).'" class="btn btn-info btn-sm" title="Clone asset"><i class="fa fa-files-o"></i></a> <a href="'.route('update/hardware', $asset->id).'" class="btn btn-warning btn-sm"><i class="fa fa-pencil icon-white"></i></a> <a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/hardware', $asset->id).'" data-content="'.Lang::get('admin/hardware/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($asset->asset_tag).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></div>';
} elseif ($asset->deleted_at!='') {
$actions = '<a href="'.route('restore/hardware', $asset->id).'" class="btn btn-warning btn-sm"><i class="fa fa-recycle icon-white"></i></a>';
}
if ($asset->assetstatus) {
if ($asset->assetstatus->deployable != 0) {
if (($asset->assigned_to !='') && ($asset->assigned_to > 0)) {
$inout = '<a href="'.route('checkin/hardware', $asset->id).'" class="btn btn-primary btn-sm">'.Lang::get('general.checkin').'</a>';
} else {
$inout = '<a href="'.route('checkout/hardware', $asset->id).'" class="btn btn-info btn-sm">'.Lang::get('general.checkout').'</a>';
}
}
}
$rows[] = array(
'id' => $asset->id,
'name' => (string)link_to('/hardware/'.$asset->id.'/view', $asset->name),
//'model' => $asset->model->name,
'asset_tag' => $asset->asset_tag,
'serial' => $asset->serial,
'assigned_to' => ($asset->assigneduser) ? (string)link_to(config('app.url').'/admin/users/'.$asset->assigneduser->id.'/view', $asset->assigneduser->fullName()): '',
'change' => $inout,
'actions' => $actions,
'companyName' => Company::getName($asset),
);
}
$data = array('total' => $count, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers;
use Input;
use Redirect;
use Validator;
use View;
use Config;
use Lang;
class ChangeEmailController extends Controller
{
/**
* User change email page.
*
* @return View
*/
public function getIndex()
{
// Get the user information
$user = Auth::user();
// Show the page
return View::make('account/change-email', compact('user'));
}
/**
* Users change email form processing page.
*
* @return Redirect
*/
public function postIndex()
{
if (config('app.lock_passwords')) {
return Redirect::route('change-password')->with('error', Lang::get('admin/users/table.lock_passwords'));
} else {
// Declare the rules for the form validation
$rules = array(
'current_password' => 'required|between:3,32',
'email' => 'required|email|unique:users,email,'.Auth::user()->email.',email',
'email_confirm' => 'required|same:email',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// Grab the user
$user = Auth::user();
// Check the user current password
if (! $user->checkPassword(Input::get('current_password'))) {
// Set the error message
$this->messageBag->add('current_password', 'Your current password is incorrect');
// Redirect to the change email page
return Redirect::route('change-email')->withErrors($this->messageBag);
}
// Update the user email
$user->email = Input::get('email');
$user->save();
// Redirect to the settings page
return Redirect::route('change-email')->with('success', 'Email successfully updated');
}
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers;
use Input;
use Redirect;
use Validator;
use View;
use Config;
use Lang;
class ChangePasswordController extends Controller
{
/**
* User change password page.
*
* @return View
*/
public function getIndex()
{
// Get the user information
$user = Auth::user();
// Show the page
return View::make('account/change-password', compact('user'));
}
/**
* User change password form processing page.
*
* @return Redirect
*/
protected function postIndex()
{
if (config('app.lock_passwords')) {
return Redirect::route('change-password')->with('error', Lang::get('admin/users/table.lock_passwords'));
} else {
// Declare the rules for the form validation
$rules = array(
'old_password' => 'required|min:6',
'password' => 'required|min:6',
'password_confirm' => 'required|same:password',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// Grab the user
$user = Auth::user();
// Check the user current password
if (! $user->checkPassword(Input::get('old_password'))) {
// Set the error message
$this->messageBag->add('old_password', 'Your current password is incorrect.');
// Redirect to the change password page
return Redirect::route('change-password')->withErrors($this->messageBag);
}
// Update the user password
$user->password = Input::get('password');
$user->save();
}
// Redirect to the change-password page
return Redirect::route('change-password')->with('success', 'Password successfully updated');
}
}

View file

@ -0,0 +1,90 @@
<?php namespace App\Http\Controllers;
use App\Models\Company;
use Input;
use Lang;
use Redirect;
use View;
final class CompaniesController extends Controller
{
public function getIndex()
{
return View::make('companies/index')->with('companies', Company::all());
}
public function getCreate()
{
return View::make('companies/edit')->with('company', new Company);
}
public function postCreate()
{
$company = new Company;
$company->name = e(Input::get('name'));
if ($company->save()) {
return Redirect::to('admin/settings/companies')
->with('success', Lang::get('admin/companies/message.create.success'));
} else {
return Redirect::back()->withInput()->withErrors($company->getErrors());
}
}
public function getEdit($companyId)
{
if (is_null($company = Company::find($companyId))) {
return Redirect::to('admin/settings/companies')
->with('error', Lang::get('admin/companies/message.does_not_exist'));
} else {
return View::make('companies/edit')->with('company', $company);
}
}
public function postEdit($companyId)
{
if (is_null($company = Company::find($companyId))) {
return Redirect::to('admin/settings/companies')->with('error', Lang::get('admin/companies/message.does_not_exist'));
} else {
$company->name = e(Input::get('name'));
if ($company->save()) {
return Redirect::to('admin/settings/companies')
->with('success', Lang::get('admin/companies/message.update.success'));
} else {
return Redirect::to("admin/settings/companies/$companyId/edit")
->with('error', Lang::get('admin/companies/message.update.error'));
}
}
}
public function postDelete($companyId)
{
if (is_null($company = Company::find($companyId))) {
return Redirect::to('admin/settings/companies')
->with('error', Lang::get('admin/companies/message.not_found'));
} else {
try {
$company->delete();
return Redirect::to('admin/settings/companies')
->with('success', Lang::get('admin/companies/message.delete.success'));
} catch (\Illuminate\Database\QueryException $exception) {
/*
* NOTE: This happens when there's a foreign key constraint violation
* For example when rows in other tables are referencing this company
*/
if ($exception->getCode() == 23000) {
return Redirect::to('admin/settings/companies')
->with('error', Lang::get('admin/companies/message.assoc_users'));
} else {
throw $exception;
}
}
}
}
}

View file

@ -0,0 +1,445 @@
<?php namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Actionlog;
use App\Models\Company;
use App\Models\Component;
use App\Models\Setting;
use App\Models\User;
use App\Models\Asset;
use App\Http\Requests\ComponentCheckoutRequest;
use Auth;
use Config;
use DB;
use Input;
use Lang;
use Mail;
use Redirect;
use Slack;
use Str;
use View;
class ComponentsController extends Controller
{
/**
* Show a list of all the components.
*
* @return View
*/
public function getIndex()
{
return View::make('components/index');
}
/**
* Component create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$category_list = array('' => '') + DB::table('categories')->where('category_type', '=', 'component')->whereNull('deleted_at')->orderBy('name', 'ASC')->lists('name', 'id');
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('components/edit')
->with('component', new Component)
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Component create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$component = new Component();
// Update the component data
$component->name = e(Input::get('name'));
$component->category_id = e(Input::get('category_id'));
$component->location_id = e(Input::get('location_id'));
$component->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$component->order_number = e(Input::get('order_number'));
$component->min_amt = e(Input::get('min_amt'));
if (e(Input::get('purchase_date')) == '') {
$component->purchase_date = null;
} else {
$component->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$component->purchase_cost = null;
} else {
$component->purchase_cost = e(Input::get('purchase_cost'));
}
$component->total_qty = e(Input::get('total_qty'));
$component->user_id = Auth::user()->id;
// Was the component created?
if ($component->save()) {
// Redirect to the new component page
return Redirect::to("admin/components")->with('success', Lang::get('admin/components/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($component->getErrors());
}
/**
* Component update.
*
* @param int $componentId
* @return View
*/
public function getEdit($componentId = null)
{
// Check if the component exists
if (is_null($component = Component::find($componentId))) {
// Redirect to the blogs management page
return Redirect::to('admin/components')->with('error', Lang::get('admin/components/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
}
$category_list = Helper::categoryList();
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('components/edit', compact('component'))
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Component update form processing page.
*
* @param int $componentId
* @return Redirect
*/
public function postEdit($componentId = null)
{
// Check if the blog post exists
if (is_null($component = Component::find($componentId))) {
// Redirect to the blogs management page
return Redirect::to('admin/components')->with('error', Lang::get('admin/components/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
}
// Update the component data
$component->name = e(Input::get('name'));
$component->category_id = e(Input::get('category_id'));
$component->location_id = e(Input::get('location_id'));
$component->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$component->order_number = e(Input::get('order_number'));
$component->min_amt = e(Input::get('min_amt'));
if (e(Input::get('purchase_date')) == '') {
$component->purchase_date = null;
} else {
$component->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$component->purchase_cost = null;
} else {
$component->purchase_cost = e(Input::get('purchase_cost'));
}
$component->total_qty = e(Input::get('total_qty'));
// Was the component created?
if ($component->save()) {
// Redirect to the new component page
return Redirect::to("admin/components")->with('success', Lang::get('admin/components/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($component->getErrors());
}
/**
* Delete the given component.
*
* @param int $componentId
* @return Redirect
*/
public function getDelete($componentId)
{
// Check if the blog post exists
if (is_null($component = Component::find($componentId))) {
// Redirect to the blogs management page
return Redirect::to('admin/components')->with('error', Lang::get('admin/components/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
}
$component->delete();
// Redirect to the locations management page
return Redirect::to('admin/components')->with('success', Lang::get('admin/components/message.delete.success'));
}
public function postBulk($componentId = null)
{
echo 'Stubbed - not yet complete';
}
public function postBulkSave($componentId = null)
{
echo 'Stubbed - not yet complete';
}
/**
* Get the component information to present to the component view page
*
* @param int $componentId
* @return View
**/
public function getView($componentID = null)
{
$component = Component::find($componentID);
if (isset($component->id)) {
if (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
} else {
return View::make('components/view', compact('component'));
}
} else {
// Prepare the error message
$error = Lang::get('admin/components/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('components')->with('error', $error);
}
}
/**
* Check out the component to a person
**/
public function getCheckout($componentId)
{
// Check if the component exists
if (is_null($component = Component::find($componentId))) {
// Redirect to the component management page with error
return Redirect::to('components')->with('error', Lang::get('admin/components/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
}
// Get the dropdown of assets and then pass it to the checkout view
$assets_list = Helper::assetsList();
return View::make('components/checkout', compact('component'))->with('assets_list', $assets_list);
}
/**
* Check out the component to a person
**/
public function postCheckout(ComponentCheckoutRequest $request, $componentId)
{
// Check if the component exists
if (is_null($component = Component::find($componentId))) {
// Redirect to the component management page with error
return Redirect::to('components')->with('error', Lang::get('admin/components/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($component)) {
return Redirect::to('admin/components')->with('error', Lang::get('general.insufficient_permissions'));
}
$admin_user = Auth::user();
$asset_id = e(Input::get('asset_id'));
// Check if the user exists
if (is_null($asset = Asset::find($asset_id))) {
// Redirect to the component management page with error
return Redirect::to('admin/components')->with('error', Lang::get('admin/components/message.asset_does_not_exist'));
}
// Update the component data
$component->asset_id = $asset_id;
$component->assets()->attach($component->id, array(
'component_id' => $component->id,
'user_id' => $admin_user->id,
'created_at' => date('Y-m-d h:i:s'),
'assigned_qty' => e(Input::get('assigned_qty')),
'asset_id' => $asset_id));
$logaction = new Actionlog();
$logaction->component_id = $component->id;
$logaction->asset_id = $asset_id;
$logaction->asset_type = 'component';
$logaction->location_id = $asset->location_id;
$logaction->user_id = Auth::user()->id;
$logaction->note = e(Input::get('note'));
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => strtoupper($logaction->asset_type).' <'.config('app.url').'/admin/components/'.$component->id.'/view'.'|'.$component->name.'> checked out to <'.config('app.url').'/hardware/'.$asset->id.'/view|'.$asset->name.'> by <'.config('app.url').'/admin/users/'.$admin_user->id.'/view'.'|'.$admin_user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('Component Checked Out');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkout');
// Redirect to the new component page
return Redirect::to("admin/components")->with('success', Lang::get('admin/components/message.checkout.success'));
}
public function getDatatable()
{
$components = Component::select('components.*')->whereNull('components.deleted_at')
->with('company', 'location', 'category');
if (Input::has('search')) {
$components = $components->TextSearch(Input::get('search'));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','min_amt','order_number','purchase_date','purchase_cost','companyName','category','total_qty'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
switch ($sort) {
case 'category':
$components = $components->OrderCategory($order);
break;
case 'location':
$components = $components->OrderLocation($order);
break;
case 'companyName':
$components = $components->OrderCompany($order);
break;
default:
$components = $components->orderBy($sort, $order);
break;
}
$consumCount = $components->count();
$components = $components->skip($offset)->take($limit)->get();
$rows = array();
foreach ($components as $component) {
$actions = '<nobr><a href="'.route('checkout/component', $component->id).'" style="margin-right:5px;" class="btn btn-info btn-sm" '.(($component->numRemaining() > 0 ) ? '' : ' disabled').'>'.Lang::get('general.checkout').'</a><a href="'.route('update/component', $component->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/component', $component->id).'" data-content="'.Lang::get('admin/components/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($component->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></nobr>';
$company = $component->company;
$rows[] = array(
'checkbox' =>'<div class="text-center"><input type="checkbox" name="component['.$component->id.']" class="one_required"></div>',
'id' => $component->id,
'name' => (string)link_to('admin/components/'.$component->id.'/view', $component->name),
'location' => ($component->location) ? e($component->location->name) : '',
'total_qty' => $component->total_qty,
'min_amt' => $component->min_amt,
'category' => ($component->category) ? $component->category->name : 'Missing category',
'order_number' => $component->order_number,
'purchase_date' => $component->purchase_date,
'purchase_cost' => ($component->purchase_cost!='') ? number_format($component->purchase_cost, 2): '' ,
'numRemaining' => $component->numRemaining(),
'actions' => $actions,
'companyName' => is_null($company) ? '' : e($company->name),
);
}
$data = array('total' => $consumCount, 'rows' => $rows);
return $data;
}
public function getDataView($componentID)
{
//$component = Component::find($componentID);
$component = Component::with('assets')->find($componentID);
// $component->load('componentAssigments.admin','componentAssigments.user');
if (!Company::isCurrentUserHasAccess($component)) {
return ['total' => 0, 'rows' => []];
}
$rows = array();
foreach ($component->assets as $component_assignment) {
$rows[] = array(
'name' => (string)link_to('/hardware/'.$component_assignment->id.'/view', $component_assignment->name),
'qty' => $component_assignment->pivot->assigned_qty,
'created_at' => ($component_assignment->created_at->format('Y-m-d H:i:s')=='-0001-11-30 00:00:00') ? '' : $component_assignment->created_at->format('Y-m-d H:i:s'),
);
}
$componentCount = $component->assets->count();
$data = array('total' => $componentCount, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,458 @@
<?php namespace App\Http\Controllers;
use App\Helpers\Helper;
use App\Models\Actionlog;
use App\Models\Company;
use App\Models\Consumable;
use App\Models\Setting;
use App\Models\User;
use Auth;
use Config;
use DB;
use Input;
use Lang;
use Mail;
use Redirect;
use Slack;
use Str;
use View;
class ConsumablesController extends Controller
{
/**
* Show a list of all the consumables.
*
* @return View
*/
public function getIndex()
{
return View::make('consumables/index');
}
/**
* Consumable create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$category_list = array('' => '') + DB::table('categories')->where('category_type', '=', 'consumable')->whereNull('deleted_at')->orderBy('name', 'ASC')->lists('name', 'id');
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('consumables/edit')
->with('consumable', new Consumable)
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Consumable create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$consumable = new Consumable();
// Update the consumable data
$consumable->name = e(Input::get('name'));
$consumable->category_id = e(Input::get('category_id'));
$consumable->location_id = e(Input::get('location_id'));
$consumable->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$consumable->order_number = e(Input::get('order_number'));
$consumable->min_amt = e(Input::get('min_amt'));
if (e(Input::get('purchase_date')) == '') {
$consumable->purchase_date = null;
} else {
$consumable->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$consumable->purchase_cost = null;
} else {
$consumable->purchase_cost = ParseFloat(e(Input::get('purchase_cost')));
}
$consumable->qty = e(Input::get('qty'));
$consumable->user_id = Auth::user()->id;
// Was the consumable created?
if ($consumable->save()) {
// Redirect to the new consumable page
return Redirect::to("admin/consumables")->with('success', Lang::get('admin/consumables/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($consumable->getErrors());
}
/**
* Consumable update.
*
* @param int $consumableId
* @return View
*/
public function getEdit($consumableId = null)
{
// Check if the consumable exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the blogs management page
return Redirect::to('admin/consumables')->with('error', Lang::get('admin/consumables/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
}
$category_list = Helper::categoryList();
$company_list = Helper::companyList();
$location_list = Helper::locationsList();
return View::make('consumables/edit', compact('consumable'))
->with('category_list', $category_list)
->with('company_list', $company_list)
->with('location_list', $location_list);
}
/**
* Consumable update form processing page.
*
* @param int $consumableId
* @return Redirect
*/
public function postEdit($consumableId = null)
{
// Check if the blog post exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the blogs management page
return Redirect::to('admin/consumables')->with('error', Lang::get('admin/consumables/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
}
// Update the consumable data
$consumable->name = e(Input::get('name'));
$consumable->category_id = e(Input::get('category_id'));
$consumable->location_id = e(Input::get('location_id'));
$consumable->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$consumable->order_number = e(Input::get('order_number'));
$consumable->min_amt = e(Input::get('min_amt'));
if (e(Input::get('purchase_date')) == '') {
$consumable->purchase_date = null;
} else {
$consumable->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('purchase_cost')) == '0.00') {
$consumable->purchase_cost = null;
} else {
$consumable->purchase_cost = ParseFloat(e(Input::get('purchase_cost')));
}
$consumable->qty = e(Input::get('qty'));
// Was the consumable created?
if ($consumable->save()) {
// Redirect to the new consumable page
return Redirect::to("admin/consumables")->with('success', Lang::get('admin/consumables/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($consumable->getErrors());
}
/**
* Delete the given consumable.
*
* @param int $consumableId
* @return Redirect
*/
public function getDelete($consumableId)
{
// Check if the blog post exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the blogs management page
return Redirect::to('admin/consumables')->with('error', Lang::get('admin/consumables/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
}
$consumable->delete();
// Redirect to the locations management page
return Redirect::to('admin/consumables')->with('success', Lang::get('admin/consumables/message.delete.success'));
}
/**
* Get the consumable information to present to the consumable view page
*
* @param int $consumableId
* @return View
**/
public function getView($consumableID = null)
{
$consumable = Consumable::find($consumableID);
if (isset($consumable->id)) {
if (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
} else {
return View::make('consumables/view', compact('consumable'));
}
} else {
// Prepare the error message
$error = Lang::get('admin/consumables/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('consumables')->with('error', $error);
}
}
/**
* Check out the consumable to a person
**/
public function getCheckout($consumableId)
{
// Check if the consumable exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the consumable management page with error
return Redirect::to('consumables')->with('error', Lang::get('admin/consumables/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
}
// Get the dropdown of users and then pass it to the checkout view
$users_list = Helper::usersList();
return View::make('consumables/checkout', compact('consumable'))->with('users_list', $users_list);
}
/**
* Check out the consumable to a person
**/
public function postCheckout($consumableId)
{
// Check if the consumable exists
if (is_null($consumable = Consumable::find($consumableId))) {
// Redirect to the consumable management page with error
return Redirect::to('consumables')->with('error', Lang::get('admin/consumables/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($consumable)) {
return Redirect::to('admin/consumables')->with('error', Lang::get('general.insufficient_permissions'));
}
$admin_user = Auth::user();
$assigned_to = e(Input::get('assigned_to'));
// Check if the user exists
if (is_null($user = User::find($assigned_to))) {
// Redirect to the consumable management page with error
return Redirect::to('admin/consumables')->with('error', Lang::get('admin/consumables/message.user_does_not_exist'));
}
// Update the consumable data
$consumable->assigned_to = e(Input::get('assigned_to'));
$consumable->users()->attach($consumable->id, array(
'consumable_id' => $consumable->id,
'user_id' => $admin_user->id,
'assigned_to' => e(Input::get('assigned_to'))));
$logaction = new Actionlog();
$logaction->consumable_id = $consumable->id;
$logaction->checkedout_to = $consumable->assigned_to;
$logaction->asset_type = 'consumable';
$logaction->location_id = $user->location_id;
$logaction->user_id = Auth::user()->id;
$logaction->note = e(Input::get('note'));
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => strtoupper($logaction->asset_type).' <'.config('app.url').'/admin/consumables/'.$consumable->id.'/view'.'|'.$consumable->name.'> checked out to <'.config('app.url').'/admin/users/'.$user->id.'/view|'.$user->fullName().'> by <'.config('app.url').'/admin/users/'.$admin_user->id.'/view'.'|'.$admin_user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('Consumable Checked Out');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkout');
$consumable_user = DB::table('consumables_users')->where('assigned_to', '=', $consumable->assigned_to)->where('consumable_id', '=', $consumable->id)->first();
$data['log_id'] = $logaction->id;
$data['eula'] = $consumable->getEula();
$data['first_name'] = $user->first_name;
$data['item_name'] = $consumable->name;
$data['checkout_date'] = $logaction->created_at;
$data['item_tag'] = '';
$data['expected_checkin'] = '';
$data['note'] = $logaction->note;
$data['require_acceptance'] = $consumable->requireAcceptance();
if (($consumable->requireAcceptance()=='1') || ($consumable->getEula())) {
Mail::send('emails.accept-asset', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->subject('Confirm consumable delivery');
});
}
// Redirect to the new consumable page
return Redirect::to("admin/consumables")->with('success', Lang::get('admin/consumables/message.checkout.success'));
}
public function getDatatable()
{
$consumables = Consumable::select('consumables.*')->whereNull('consumables.deleted_at')
->with('company', 'location', 'category', 'users');
if (Input::has('search')) {
$consumables = $consumables->TextSearch(Input::get('search'));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','order_number','min_amt','purchase_date','purchase_cost','companyName','category'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
switch ($sort) {
case 'category':
$consumables = $consumables->OrderCategory($order);
break;
case 'location':
$consumables = $consumables->OrderLocation($order);
break;
case 'companyName':
$consumables = $consumables->OrderCompany($order);
break;
default:
$consumables = $consumables->orderBy($sort, $order);
break;
}
$consumCount = $consumables->count();
$consumables = $consumables->skip($offset)->take($limit)->get();
$rows = array();
foreach ($consumables as $consumable) {
$actions = '<nobr><a href="'.route('checkout/consumable', $consumable->id).'" style="margin-right:5px;" class="btn btn-info btn-sm" '.(($consumable->numRemaining() > 0 ) ? '' : ' disabled').'>'.Lang::get('general.checkout').'</a><a href="'.route('update/consumable', $consumable->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/consumable', $consumable->id).'" data-content="'.Lang::get('admin/consumables/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($consumable->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></nobr>';
$company = $consumable->company;
$rows[] = array(
'id' => $consumable->id,
'name' => (string)link_to('admin/consumables/'.$consumable->id.'/view', $consumable->name),
'location' => ($consumable->location) ? e($consumable->location->name) : '',
'min_amt' => $consumable->min_amt,
'qty' => $consumable->qty,
'category' => ($consumable->category) ? $consumable->category->name : 'Missing category',
'order_number' => $consumable->order_number,
'purchase_date' => $consumable->purchase_date,
'purchase_cost' => ($consumable->purchase_cost!='') ? number_format($consumable->purchase_cost, 2): '' ,
'numRemaining' => $consumable->numRemaining(),
'actions' => $actions,
'companyName' => is_null($company) ? '' : e($company->name),
);
}
$data = array('total' => $consumCount, 'rows' => $rows);
return $data;
}
public function getDataView($consumableID)
{
//$consumable = Consumable::find($consumableID);
$consumable = Consumable::with(array('consumableAssigments'=>
function ($query) {
$query->orderBy('created_at', 'DESC');
},
'consumableAssigments.admin'=> function ($query) {
},
'consumableAssigments.user'=> function ($query) {
},
))->find($consumableID);
// $consumable->load('consumableAssigments.admin','consumableAssigments.user');
if (!Company::isCurrentUserHasAccess($consumable)) {
return ['total' => 0, 'rows' => []];
}
$rows = array();
foreach ($consumable->consumableAssigments as $consumable_assignment) {
$rows[] = array(
'name' => (string)link_to('/admin/users/'.$consumable_assignment->user->id.'/view', $consumable_assignment->user->fullName()),
'created_at' => ($consumable_assignment->created_at->format('Y-m-d H:i:s')=='-0001-11-30 00:00:00') ? '' : $consumable_assignment->created_at->format('Y-m-d H:i:s'),
'admin' => ($consumable_assignment->admin) ? $consumable_assignment->admin->fullName() : '',
);
}
$consumableCount = $consumable->users->count();
$data = array('total' => $consumableCount, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
view()->share('signedIn', Auth::check());
view()->share('user', Auth::user());
}
}

View file

@ -0,0 +1,195 @@
<?php
namespace App\Http\Controllers;
use View;
use App\Models\CustomFieldset;
use App\Models\CustomField;
use Input;
use Validator;
use Redirect;
use AssetModel;
use Lang;
use Auth;
class CustomFieldsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
$fieldsets=CustomFieldset::with("fields", "models")->get();
//$fieldsets=CustomFieldset::all();
$fields=CustomField::with("fieldset")->get();
//$fields=CustomField::all();
return View::make("custom_fields.index")->with("custom_fieldsets", $fieldsets)->with("custom_fields", $fields);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
return View::make("custom_fields.create");
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
$cfset=new CustomFieldset(["name" => Input::get("name"),"user_id" => Auth::user()->id]);
$validator=Validator::make(Input::all(), $cfset->rules);
if ($validator->passes()) {
$cfset->save();
return Redirect::route("admin.custom_fields.show", [$cfset->id])->with('success', Lang::get('admin/custom_fields/message.fieldset.create.success'));
} else {
return Redirect::back()->withInput()->withErrors($validator);
}
}
public function associate($id)
{
$set = CustomFieldset::find($id);
foreach ($set->fields as $field) {
if ($field->id == Input::get('field_id')) {
return Redirect::route("admin.custom_fields.show", [$id])->withInput()->withErrors(['field_id' => Lang::get('admin/custom_fields/message.field.already_added')]);
}
}
$results=$set->fields()->attach(Input::get('field_id'), ["required" => (Input::get('required') == "on"),"order" => Input::get('order')]);
return Redirect::route("admin.custom_fields.show", [$id])->with("success", Lang::get('admin/custom_fields/message.field.create.assoc_success'));
}
public function createField()
{
return View::make("custom_fields.create_field");
}
public function storeField()
{
$field=new CustomField(["name" => Input::get("name"),"element" => Input::get("element"),"user_id" => Auth::user()->id]);
if (!in_array(Input::get('format'), array_keys(CustomField::$PredefinedFormats))) {
$field->format=Input::get("custom_format");
} else {
$field->format=Input::get('format');
}
$validator=Validator::make(Input::all(), $field->rules);
if ($validator->passes()) {
$results=$field->save();
//return "postCreateField: $results";
if ($results) {
return Redirect::route("admin.custom_fields.index")->with("success", Lang::get('admin/custom_fields/message.field.create.success'));
} else {
return Redirect::back()->withInput()->with('error', Lang::get('admin/custom_fields/message.field.create.error'));
}
} else {
return Redirect::back()->withInput()->withErrors($validator);
}
}
public function deleteField($field_id)
{
$field=CustomField::find($field_id);
if ($field->fieldset->count()>0) {
return Redirect::back()->withErrors(['message' => "Field is in-use"]);
} else {
$field->delete();
return Redirect::route("admin.custom_fields.index")->with("success", Lang::get('admin/custom_fields/message.field.delete.success'));
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//$id=$parameters[0];
$cfset=CustomFieldset::find($id);
//print_r($parameters);
//
$custom_fields_list=["" => "Add New Field to Fieldset"] + CustomField::lists("name", "id")->toArray();
// print_r($custom_fields_list);
$maxid=0;
foreach ($cfset->fields as $field) {
// print "Looking for: ".$field->id;
if ($field->pivot->order > $maxid) {
$maxid=$field->pivot->order;
}
if (isset($custom_fields_list[$field->id])) {
// print "Found ".$field->id.", so removing it.<br>";
unset($custom_fields_list[$field->id]);
}
}
return View::make("custom_fields.show")->with("custom_fieldset", $cfset)->with("maxid", $maxid+1)->with("custom_fields_list", $custom_fields_list);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
$fieldset=CustomFieldset::find($id);
$models=\App\Models\AssetModel::where("fieldset_id", "=", $id);
if ($models->count()==0) {
$fieldset->delete();
return Redirect::route("admin.custom_fields.index")->with("success", Lang::get('admin/custom_fields/message.fieldset.delete.success'));
} else {
return Redirect::route("admin.custom_fields.index")->with("error", Lang::get('admin/custom_fields/message.fieldset.delete.in_use')); //->with("models",$models);
}
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\AdminController;
use App\Models\Actionlog;
use View;
use Auth;
use Redirect;
use App\Models\Asset;
use App\Models\Company;
class DashboardController extends Controller
{
/**
* Show the administration dashboard page.
*
* @return View
*/
public function getIndex()
{
// Show the page
if (Auth::user()->hasAccess('admin')) {
$recent_activity = Actionlog::orderBy('created_at', 'DESC')
->with('accessorylog', 'consumablelog', 'licenselog', 'assetlog', 'adminlog', 'userlog')
->take(7)
->get();
$asset_stats['total'] = Asset::Hardware()->count();
$asset_stats['rtd']['total'] = Asset::Hardware()->RTD()->count();
if ($asset_stats['rtd']['total'] > 0) {
$asset_stats['rtd']['percent'] = round(($asset_stats['rtd']['total']/$asset_stats['total']) * 100);
} else {
$asset_stats['rtd']['percent'] = 0;
}
$asset_stats['pending']['total'] = Asset::Hardware()->Pending()->count();
if ($asset_stats['pending']['total'] > 0) {
$asset_stats['pending']['percent'] = round(($asset_stats['pending']['total']/$asset_stats['total']) * 100);
} else {
$asset_stats['pending']['percent'] = 0;
}
$asset_stats['deployed']['total'] = Asset::Hardware()->Deployed()->count();
if ($asset_stats['deployed']['total'] > 0) {
$asset_stats['deployed']['percent'] = round(($asset_stats['deployed']['total']/$asset_stats['total']) * 100);
} else {
$asset_stats['deployed']['percent'] = 0;
}
$asset_stats['undeployable']['total'] = Asset::Hardware()->Undeployable()->count();
if ($asset_stats['undeployable']['total'] > 0) {
$asset_stats['undeployable']['percent'] = round(($asset_stats['undeployable']['total']/$asset_stats['total']) * 100);
} else {
$asset_stats['undeployable']['percent'] = 0;
}
$asset_stats['archived']['total'] = Asset::Hardware()->Archived()->count();
if ($asset_stats['archived']['total'] > 0) {
$asset_stats['archived']['percent'] = round(($asset_stats['archived']['total']/$asset_stats['total']) * 100);
} else {
$asset_stats['archived']['percent'] = 0;
}
return View::make('dashboard')->with('asset_stats', $asset_stats)->with('recent_activity', $recent_activity);
} else {
// Redirect to the profile page
return Redirect::route('view-assets');
}
}
}

View file

@ -0,0 +1,198 @@
<?php
namespace App\Http\Controllers;
use Input;
use Lang;
use App\Models\Depreciation;
use Redirect;
use App\Models\Setting;
use DB;
use Str;
use View;
use Auth;
class DepreciationsController extends Controller
{
/**
* Show a list of all the depreciations.
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('depreciations/index', compact('depreciations'));
}
/**
* Depreciation create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$depreciation_options = \App\Helpers\Helper::depreciationList();
return View::make('depreciations/edit')->with('depreciation_options', $depreciation_options)->with('depreciation', new Depreciation);
}
/**
* Depreciation create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new instance
$depreciation = new Depreciation();
// Depreciation data
$depreciation->name = e(Input::get('name'));
$depreciation->months = e(Input::get('months'));
$depreciation->user_id = Auth::user()->id;
// Was the asset created?
if ($depreciation->save()) {
// Redirect to the new depreciation page
return Redirect::to("admin/settings/depreciations")->with('success', Lang::get('admin/depreciations/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($depreciation->getErrors());
}
/**
* Depreciation update.
*
* @param int $depreciationId
* @return View
*/
public function getEdit($depreciationId = null)
{
// Check if the depreciation exists
if (is_null($depreciation = Depreciation::find($depreciationId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/depreciations')->with('error', Lang::get('admin/depreciations/message.does_not_exist'));
}
// Show the page
//$depreciation_options = array('' => 'Top Level') + Depreciation::lists('name', 'id');
$depreciation_options = array('' => 'Top Level') + DB::table('depreciations')->where('id', '!=', $depreciationId)->lists('name', 'id');
return View::make('depreciations/edit', compact('depreciation'))->with('depreciation_options', $depreciation_options);
}
/**
* Depreciation update form processing page.
*
* @param int $depreciationId
* @return Redirect
*/
public function postEdit($depreciationId = null)
{
// Check if the depreciation exists
if (is_null($depreciation = Depreciation::find($depreciationId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/depreciations')->with('error', Lang::get('admin/depreciations/message.does_not_exist'));
}
// Depreciation data
$depreciation->name = e(Input::get('name'));
$depreciation->months = e(Input::get('months'));
// Was the asset created?
if ($depreciation->save()) {
// Redirect to the depreciation page
return Redirect::to("admin/settings/depreciations/")->with('success', Lang::get('admin/depreciations/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($depreciation->getErrors());
}
/**
* Delete the given depreciation.
*
* @param int $depreciationId
* @return Redirect
*/
public function getDelete($depreciationId)
{
// Check if the depreciation exists
if (is_null($depreciation = Depreciation::find($depreciationId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/depreciations')->with('error', Lang::get('admin/depreciations/message.not_found'));
}
if ($depreciation->has_models() > 0) {
// Redirect to the asset management page
return Redirect::to('admin/settings/depreciations')->with('error', Lang::get('admin/depreciations/message.assoc_users'));
} else {
$depreciation->delete();
// Redirect to the depreciations management page
return Redirect::to('admin/settings/depreciations')->with('success', Lang::get('admin/depreciations/message.delete.success'));
}
}
public function getDatatable()
{
$depreciations = Depreciation::select(array('id','name','months'));
if (Input::has('search')) {
$depreciations = $depreciations->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','months'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$depreciations->orderBy($sort, $order);
$depreciationsCount = $depreciations->count();
$depreciations = $depreciations->skip($offset)->take($limit)->get();
$rows = array();
foreach ($depreciations as $depreciation) {
$actions = '<a href="'.route('update/depreciations', $depreciation->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/depreciations', $depreciation->id).'" data-content="'.Lang::get('admin/depreciations/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($depreciation->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
$rows[] = array(
'id' => $depreciation->id,
'name' => $depreciation->name,
'months' => $depreciation->months,
'actions' => $actions
);
}
$data = array('total' => $depreciationsCount, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,212 @@
<?php
namespace App\Http\Controllers;
use Config;
use Input;
use Lang;
use Redirect;
use App\Models\Setting;
use Validator;
use View;
class GroupsController extends Controller
{
/**
* Show a list of all the groups.
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('groups/index', compact('groups'));
}
/**
* Group create.
*
* @return View
*/
public function getCreate()
{
$group = new \App\Models\Group;
// Get all the available permissions
$permissions = config('permissions');
$selectedPermissions = Input::old('permissions', array());
// Show the page
return View::make('groups/edit', compact('permissions', 'selectedPermissions'))->with('group', $group);
}
/**
* Group create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new group instance
$group = new \App\Models\Group();
// Update the consumable data
$group->name = e(Input::get('name'));
// Was the consumable created?
if ($group->save()) {
// Redirect to the new consumable page
return Redirect::to("admin/groups")->with('success', Lang::get('admin/groups/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($group->getErrors());
}
/**
* Group update.
*
* @param int $id
* @return View
*/
public function getEdit($id = null)
{
$group = \App\Models\Group::find($id);
$group->name = e(Input::get('name'));
$group->permissions = json_decode($group->permissions, true);
$permissions = config('permissions');
// Show the page
return View::make('groups/edit', compact('group', 'permissions','allpermissions'));
}
/**
* Group update form processing page.
*
* @param int $id
* @return Redirect
*/
public function postEdit($id = null)
{
if (!$group = \App\Models\Group::find($id)) {
return Redirect::route('groups')->with('error', Lang::get('admin/groups/message.group_not_found', compact('id')));
}
$group->name = e(Input::get('name'));
if (!config('app.lock_passwords')) {
// Was the consumable created?
if ($group->save()) {
// Redirect to the new consumable page
return Redirect::to("admin/groups")->with('success', Lang::get('admin/groups/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($group->getErrors());
} else {
return Redirect::route('update/group', $id)->withInput()->with('error', 'Denied! Editing groups is not allowed in the demo.');
}
}
/**
* Delete the given group.
*
* @param int $id
* @return Redirect
*/
public function getDelete($id = null)
{
if (!config('app.lock_passwords')) {
try {
// Get group information
$group = Sentry::getGroupProvider()->findById($id);
// Delete the group
$group->delete();
// Redirect to the group management page
return Redirect::route('groups')->with('success', Lang::get('admin/groups/message.success.delete'));
} catch (GroupNotFoundException $e) {
// Redirect to the group management page
return Redirect::route('groups')->with('error', Lang::get('admin/groups/message.group_not_found', compact('id')));
}
} else {
return Redirect::route('groups')->with('error', Lang::get('general.feature_disabled'));
}
}
public function getDatatable($status = null)
{
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
if (Input::get('sort')=='name') {
$sort = 'first_name';
} else {
$sort = e(Input::get('sort'));
}
// Grab all the groups
$groups = \App\Models\Group::with('users')->orderBy('name', 'ASC');
//$users = Company::scopeCompanyables($users);
if (Input::has('search')) {
$groups = $users->TextSearch(Input::get('search'));
}
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$allowed_columns =
[
'name','created_at'
];
$sort = in_array($sort, $allowed_columns) ? $sort : 'name';
$groups = $groups->orderBy($sort, $order);
$groupsCount = $groups->count();
$groups = $groups->skip($offset)->take($limit)->get();
$rows = array();
foreach ($groups as $group) {
$group_names = '';
$inout = '';
$actions = '<nobr>';
$actions .= '<a href="' . route('update/group', $group->id) . '" class="btn btn-warning btn-sm"><i class="fa fa-pencil icon-white"></i></a> ';
if (!config('app.lock_passwords')) {
$actions .= '<a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="' . route('delete/group', $group->id) . '" data-content="'.Lang::get('admin/groups/message.delete.confirm').'" data-title="Delete ' . htmlspecialchars($group->name) . '?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a> ';
} else {
$actions .= ' <span class="btn delete-asset btn-danger btn-sm disabled"><i class="fa fa-trash icon-white"></i></span>';
}
$actions .= '</nobr>';
$rows[] = array(
'id' => $group->id,
'name' => $group->name,
'users' => $group->users->count(),
'created_at' => $group->created_at->format('Y-m-d'),
'actions' => ($actions) ? $actions : '',
);
}
$data = array('total'=>$groupsCount, 'rows'=>$rows);
return $data;
}
}

View file

@ -0,0 +1,985 @@
<?php
namespace App\Http\Controllers;
use Assets;
use Input;
use Lang;
use App\Models\License;
use App\Models\Asset;
use App\Models\User;
use App\Models\Actionlog;
use DB;
use Redirect;
use App\Models\LicenseSeat;
use App\Models\Depreciation;
use App\Models\Company;
use App\Models\Setting;
use App\Models\Supplier;
use Validator;
use View;
use Response;
use Slack;
use Config;
use Session;
use App\Helpers\Helper;
use Auth;
class LicensesController extends Controller
{
/**
* Show a list of all the licenses.
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('licenses/index');
}
/**
* License create.
*
* @return View
*/
public function getCreate()
{
// Show the page
// $license_options = array('0' => 'Top Level') + License::lists('name', 'id');
// Show the page
$depreciation_list = Helper::depreciationList();
$supplier_list = Helper::suppliersList();
$maintained_list = array('' => 'Maintained', '1' => 'Yes', '0' => 'No');
$company_list = Helper::companyList();
return View::make('licenses/edit')
//->with('license_options',$license_options)
->with('depreciation_list', $depreciation_list)
->with('supplier_list', $supplier_list)
->with('maintained_list', $maintained_list)
->with('company_list', $company_list)
->with('license', new License);
}
/**
* License create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new model instance
$license = new License();
if (e(Input::get('purchase_cost')) == '') {
$license->purchase_cost = null;
} else {
$license->purchase_cost = e(Input::get('purchase_cost'));
}
if (e(Input::get('supplier_id')) == '') {
$license->supplier_id = null;
} else {
$license->supplier_id = e(Input::get('supplier_id'));
}
if (e(Input::get('maintained')) == '') {
$license->maintained = 0;
} else {
$license->maintained = e(Input::get('maintained'));
}
if (e(Input::get('reassignable')) == '') {
$license->reassignable = 0;
} else {
$license->reassignable = e(Input::get('reassignable'));
}
if (e(Input::get('purchase_order')) == '') {
$license->purchase_order = '';
} else {
$license->purchase_order = e(Input::get('purchase_order'));
}
// Save the license data
$license->name = e(Input::get('name'));
$license->serial = e(Input::get('serial'));
$license->license_email = e(Input::get('license_email'));
$license->license_name = e(Input::get('license_name'));
$license->notes = e(Input::get('notes'));
$license->order_number = e(Input::get('order_number'));
$license->seats = e(Input::get('seats'));
$license->purchase_date = e(Input::get('purchase_date'));
$license->purchase_order = e(Input::get('purchase_order'));
$license->depreciation_id = e(Input::get('depreciation_id'));
$license->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$license->expiration_date = e(Input::get('expiration_date'));
$license->user_id = Auth::user()->id;
if (($license->purchase_date == "") || ($license->purchase_date == "0000-00-00")) {
$license->purchase_date = null;
}
if (($license->expiration_date == "") || ($license->expiration_date == "0000-00-00")) {
$license->expiration_date = null;
}
if (($license->purchase_cost == "") || ($license->purchase_cost == "0.00")) {
$license->purchase_cost = null;
}
// Was the license created?
if ($license->save()) {
$insertedId = $license->id;
// Save the license seat data
for ($x=0; $x<$license->seats; $x++) {
$license_seat = new \App\Models\LicenseSeat();
$license_seat->license_id = $insertedId;
$license_seat->user_id = Auth::user()->id;
$license_seat->assigned_to = null;
$license_seat->notes = null;
$license_seat->save();
}
// Redirect to the new license page
return Redirect::to("admin/licenses")->with('success', Lang::get('admin/licenses/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($license->getErrors());
}
/**
* License update.
*
* @param int $licenseId
* @return View
*/
public function getEdit($licenseId = null)
{
// Check if the license exists
if (is_null($license = License::find($licenseId))) {
// Redirect to the blogs management page
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
if ($license->purchase_date == "0000-00-00") {
$license->purchase_date = null;
}
if ($license->purchase_cost == "0.00") {
$license->purchase_cost = null;
}
// Show the page
$license_options = array('' => 'Top Level') + DB::table('assets')->where('id', '!=', $licenseId)->pluck('name', 'id');
$depreciation_list = array('0' => Lang::get('admin/licenses/form.no_depreciation')) + Depreciation::pluck('name', 'id')->toArray();
$supplier_list = array('' => 'Select Supplier') + Supplier::orderBy('name', 'asc')->pluck('name', 'id')->toArray();
$maintained_list = array('' => 'Maintained', '1' => 'Yes', '0' => 'No');
$company_list = Helper::companyList();
return View::make('licenses/edit', compact('license'))
->with('license_options', $license_options)
->with('depreciation_list', $depreciation_list)
->with('supplier_list', $supplier_list)
->with('company_list', $company_list)
->with('maintained_list', $maintained_list);
}
/**
* License update form processing page.
*
* @param int $licenseId
* @return Redirect
*/
public function postEdit($licenseId = null)
{
// Check if the license exists
if (is_null($license = License::find($licenseId))) {
// Redirect to the blogs management page
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
// Update the license data
$license->name = e(Input::get('name'));
$license->serial = e(Input::get('serial'));
$license->license_email = e(Input::get('license_email'));
$license->license_name = e(Input::get('license_name'));
$license->notes = e(Input::get('notes'));
$license->order_number = e(Input::get('order_number'));
$license->depreciation_id = e(Input::get('depreciation_id'));
$license->company_id = Company::getIdForCurrentUser(Input::get('company_id'));
$license->purchase_order = e(Input::get('purchase_order'));
$license->maintained = e(Input::get('maintained'));
$license->reassignable = e(Input::get('reassignable'));
if (e(Input::get('supplier_id')) == '') {
$license->supplier_id = null;
} else {
$license->supplier_id = e(Input::get('supplier_id'));
}
// Update the asset data
if (e(Input::get('purchase_date')) == '') {
$license->purchase_date = null;
} else {
$license->purchase_date = e(Input::get('purchase_date'));
}
if (e(Input::get('expiration_date')) == '') {
$license->expiration_date = null;
} else {
$license->expiration_date = e(Input::get('expiration_date'));
}
if (e(Input::get('termination_date')) == '') {
$license->termination_date = null;
} else {
$license->termination_date = e(Input::get('termination_date'));
}
if (e(Input::get('purchase_cost')) == '') {
$license->purchase_cost = null;
} else {
$license->purchase_cost = e(Input::get('purchase_cost'));
//$license->purchase_cost = e(Input::get('purchase_cost'));
}
if (e(Input::get('maintained')) == '') {
$license->maintained = 0;
} else {
$license->maintained = e(Input::get('maintained'));
}
if (e(Input::get('reassignable')) == '') {
$license->reassignable = 0;
} else {
$license->reassignable = e(Input::get('reassignable'));
}
if (e(Input::get('purchase_order')) == '') {
$license->purchase_order = '';
} else {
$license->purchase_order = e(Input::get('purchase_order'));
}
//Are we changing the total number of seats?
if ($license->seats != e(Input::get('seats'))) {
//Determine how many seats we are dealing with
$difference = e(Input::get('seats')) - $license->licenseseats()->count();
if ($difference < 0) {
//Filter out any license which have a user attached;
$seats = $license->licenseseats->filter(function ($seat) {
return is_null($seat->user);
});
//If the remaining collection is as large or larger than the number of seats we want to delete
if ($seats->count() >= abs($difference)) {
for ($i=1; $i <= abs($difference); $i++) {
//Delete the appropriate number of seats
$seats->pop()->delete();
}
//Log the deletion of seats to the log
$logaction = new Actionlog();
$logaction->asset_id = $license->id;
$logaction->asset_type = 'software';
$logaction->user_id = Auth::user()->id;
$logaction->note = abs($difference)." seats";
$logaction->checkedout_to = null;
$log = $logaction->logaction('delete seats');
} else {
// Redirect to the license edit page
return Redirect::to("admin/licenses/$licenseId/edit")->with('error', Lang::get('admin/licenses/message.assoc_users'));
}
} else {
for ($i=1; $i <= $difference; $i++) {
//Create a seat for this license
$license_seat = new LicenseSeat();
$license_seat->license_id = $license->id;
$license_seat->user_id = Auth::user()->id;
$license_seat->assigned_to = null;
$license_seat->notes = null;
$license_seat->save();
}
//Log the addition of license to the log.
$logaction = new Actionlog();
$logaction->asset_id = $license->id;
$logaction->asset_type = 'software';
$logaction->user_id = Auth::user()->id;
$logaction->note = abs($difference)." seats";
$log = $logaction->logaction('add seats');
}
$license->seats = e(Input::get('seats'));
}
// Was the asset created?
if ($license->save()) {
// Redirect to the new license page
return Redirect::to("admin/licenses/$licenseId/view")->with('success', Lang::get('admin/licenses/message.update.success'));
}
// Redirect to the license edit page
return Redirect::to("admin/licenses/$licenseId/edit")->with('error', Lang::get('admin/licenses/message.update.error'));
}
/**
* Delete the given license.
*
* @param int $licenseId
* @return Redirect
*/
public function getDelete($licenseId)
{
// Check if the license exists
if (is_null($license = License::find($licenseId))) {
// Redirect to the license management page
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
if (($license->assignedcount()) && ($license->assignedcount() > 0)) {
// Redirect to the license management page
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.assoc_users'));
} else {
// Delete the license and the associated license seats
DB::table('license_seats')
->where('id', $license->id)
->update(array('assigned_to' => null,'asset_id' => null));
$licenseseats = $license->licenseseats();
$licenseseats->delete();
$license->delete();
// Redirect to the licenses management page
return Redirect::to('admin/licenses')->with('success', Lang::get('admin/licenses/message.delete.success'));
}
}
/**
* Check out the asset to a person
**/
public function getCheckout($seatId)
{
// Check if the asset exists
if (is_null($licenseseat = LicenseSeat::find($seatId))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($licenseseat->license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
// Get the dropdown of users and then pass it to the checkout view
$users_list = array('' => 'Select a User') + DB::table('users')->select(DB::raw('concat(last_name,", ",first_name," (",username,")") as full_name, id'))->whereNull('deleted_at')->orderBy('last_name', 'asc')->orderBy('first_name', 'asc')->lists('full_name', 'id');
// Left join to get a list of assets and some other helpful info
$asset = DB::table('assets')
->leftJoin('users', 'users.id', '=', 'assets.assigned_to')
->leftJoin('models', 'assets.model_id', '=', 'models.id')
->select(
'assets.id',
'assets.name',
'first_name',
'last_name',
'asset_tag',
DB::raw('concat(first_name," ",last_name) as full_name, assets.id as id, models.name as modelname')
)
->whereNull('assets.deleted_at')
->get();
$asset_array = json_decode(json_encode($asset), true);
$asset_element[''] = 'Please select an asset';
// Build a list out of the data results
for ($x=0; $x<count($asset_array); $x++) {
if ($asset_array[$x]['full_name']!='') {
$full_name = ' ('.$asset_array[$x]['full_name'].') '.$asset_array[$x]['modelname'];
} else {
$full_name = ' (Unassigned) '.$asset_array[$x]['modelname'];
}
$asset_element[$asset_array[$x]['id']] = $asset_array[$x]['asset_tag'].' - '.$asset_array[$x]['name'].$full_name;
}
return View::make('licenses/checkout', compact('licenseseat'))->with('users_list', $users_list)->with('asset_list', $asset_element);
}
/**
* Check out the asset to a person
**/
public function postCheckout($seatId)
{
$licenseseat = LicenseSeat::find($seatId);
$assigned_to = e(Input::get('assigned_to'));
$asset_id = e(Input::get('asset_id'));
$user = Auth::user();
if (!Company::isCurrentUserHasAccess($licenseseat->license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
// Declare the rules for the form validation
$rules = array(
'note' => 'string',
'asset_id' => 'required_without:assigned_to',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
if ($assigned_to!='') {
// Check if the user exists
if (is_null($is_assigned_to = User::find($assigned_to))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.user_does_not_exist'));
}
}
if ($asset_id!='') {
if (is_null($is_asset_id = Asset::find($asset_id))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.asset_does_not_exist'));
}
if (($is_asset_id->assigned_to!=$assigned_to) && ($assigned_to!='')) {
//echo 'asset assigned to: '.$is_asset_id->assigned_to.'<br>license assigned to: '.$assigned_to;
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.owner_doesnt_match_asset'));
}
}
// Check if the asset exists
if (is_null($licenseseat)) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
}
if (Input::get('asset_id') == '') {
$licenseseat->asset_id = null;
} else {
$licenseseat->asset_id = e(Input::get('asset_id'));
}
// Update the asset data
if (e(Input::get('assigned_to')) == '') {
$licenseseat->assigned_to = null;
} else {
$licenseseat->assigned_to = e(Input::get('assigned_to'));
}
// Was the asset updated?
if ($licenseseat->save()) {
$logaction = new Actionlog();
//$logaction->location_id = $assigned_to->location_id;
$logaction->asset_type = 'software';
$logaction->user_id = Auth::user()->id;
$logaction->note = e(Input::get('note'));
$logaction->asset_id = $licenseseat->license_id;
$license = License::find($licenseseat->license_id);
$settings = Setting::getSettings();
// Update the asset data
if (e(Input::get('assigned_to')) == '') {
$logaction->checkedout_to = null;
$slack_msg = strtoupper($logaction->asset_type).' license <'.config('app.url').'/admin/licenses/'.$license->id.'/view'.'|'.$license->name.'> checked out to <'.config('app.url').'/hardware/'.$is_asset_id->id.'/view|'.$is_asset_id->showAssetName().'> by <'.config('app.url').'/admin/users/'.$user->id.'/view'.'|'.$user->fullName().'>.';
} else {
$logaction->checkedout_to = e(Input::get('assigned_to'));
$slack_msg = strtoupper($logaction->asset_type).' license <'.config('app.url').'/admin/licenses/'.$license->id.'/view'.'|'.$license->name.'> checked out to <'.config('app.url').'/admin/users/'.$is_assigned_to->id.'/view|'.$is_assigned_to->fullName().'> by <'.config('app.url').'/admin/users/'.$user->id.'/view'.'|'.$user->fullName().'>.';
}
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => $slack_msg
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('License Checked Out');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkout');
// Redirect to the new asset page
return Redirect::to("admin/licenses")->with('success', Lang::get('admin/licenses/message.checkout.success'));
}
// Redirect to the asset management page with error
return Redirect::to('admin/licenses/$assetId/checkout')->with('error', Lang::get('admin/licenses/message.create.error'))->with('license', new License);
}
/**
* Check the license back into inventory
**/
public function getCheckin($seatId = null, $backto = null)
{
// Check if the asset exists
if (is_null($licenseseat = LicenseSeat::find($seatId))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
} elseif (!Company::isCurrentUserHasAccess($licenseseat->license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
return View::make('licenses/checkin', compact('licenseseat'))->with('backto', $backto);
}
/**
* Check in the item so that it can be checked out again to someone else
**/
public function postCheckin($seatId = null, $backto = null)
{
// Check if the asset exists
if (is_null($licenseseat = LicenseSeat::find($seatId))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
}
$license = License::find($licenseseat->license_id);
if (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
if (!$license->reassignable) {
// Not allowed to checkin
Session::flash('error', 'License not reassignable.');
return Redirect::back()->withInput();
}
// Declare the rules for the form validation
$rules = array(
'note' => 'string',
'notes' => 'string',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails()) {
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
$return_to = $licenseseat->assigned_to;
$logaction = new Actionlog();
$logaction->checkedout_to = $licenseseat->assigned_to;
// Update the asset data
$licenseseat->assigned_to = null;
$licenseseat->asset_id = null;
$user = Auth::user();
// Was the asset updated?
if ($licenseseat->save()) {
$logaction->asset_id = $licenseseat->license_id;
$logaction->location_id = null;
$logaction->asset_type = 'software';
$logaction->note = e(Input::get('note'));
$logaction->user_id = $user->id;
$settings = Setting::getSettings();
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked In:',
'value' => strtoupper($logaction->asset_type).' <'.config('app.url').'/admin/licenses/'.$license->id.'/view'.'|'.$license->name.'> checked in by <'.config('app.url').'/admin/users/'.$user->id.'/view'.'|'.$user->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($logaction->note)
],
]
])->send('License Checked In');
} catch (Exception $e) {
}
}
$log = $logaction->logaction('checkin from');
if ($backto=='user') {
return Redirect::to("admin/users/".$return_to.'/view')->with('success', Lang::get('admin/licenses/message.checkin.success'));
} else {
return Redirect::to("admin/licenses/".$licenseseat->license_id."/view")->with('success', Lang::get('admin/licenses/message.checkin.success'));
}
}
// Redirect to the license page with error
return Redirect::to("admin/licenses")->with('error', Lang::get('admin/licenses/message.checkin.error'));
}
/**
* Get the asset information to present to the asset view page
*
* @param int $licenseId
* @return View
**/
public function getView($licenseId = null)
{
$license = License::find($licenseId);
if (isset($license->id)) {
if (!\App\Models\Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
return View::make('licenses/view', compact('license'));
} else {
// Prepare the error message
$error = Lang::get('admin/licenses/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('licenses')->with('error', $error);
}
}
public function getClone($licenseId = null)
{
// Check if the license exists
if (is_null($license_to_clone = License::find($licenseId))) {
// Redirect to the blogs management page
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($license_to_clone)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
// Show the page
$license_options = array('0' => 'Top Level') + License::pluck('name', 'id')->toArray();
$maintained_list = array('' => 'Maintained', '1' => 'Yes', '0' => 'No');
$company_list = Helper::companyList();
//clone the orig
$license = clone $license_to_clone;
$license->id = null;
$license->serial = null;
// Show the page
$depreciation_list = Helper::depreciationList();
$supplier_list = Helper::suppliersList();
return View::make('licenses/edit')
->with('license_options', $license_options)
->with('depreciation_list', $depreciation_list)
->with('supplier_list', $supplier_list)
->with('license', $license)
->with('maintained_list', $maintained_list)
->with('company_list', $company_list);
}
/**
* Upload the file to the server
*
* @param int $licenseId
* @return View
**/
public function postUpload($licenseId = null)
{
$license = License::find($licenseId);
// the license is valid
$destinationPath = storage_path().'/app/private_uploads';
if (isset($license->id)) {
if (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
if (Input::hasFile('licensefile')) {
foreach (Input::file('licensefile') as $file) {
$rules = array(
'licensefile' => 'required|mimes:png,gif,jpg,jpeg,doc,docx,pdf,txt,zip,rar|max:2000'
);
$validator = Validator::make(array('licensefile'=> $file), $rules);
if ($validator->passes()) {
$extension = $file->getClientOriginalExtension();
$filename = 'license-'.$license->id.'-'.str_random(8);
$filename .= '-'.str_slug($file->getClientOriginalName()).'.'.$extension;
$upload_success = $file->move($destinationPath, $filename);
//Log the deletion of seats to the log
$logaction = new Actionlog();
$logaction->asset_id = $license->id;
$logaction->asset_type = 'software';
$logaction->user_id = Auth::user()->id;
$logaction->note = e(Input::get('notes'));
$logaction->checkedout_to = null;
$logaction->created_at = date("Y-m-d h:i:s");
$logaction->filename = $filename;
$log = $logaction->logaction('uploaded');
} else {
return Redirect::back()->with('error', Lang::get('admin/licenses/message.upload.invalidfiles'));
}
}
if ($upload_success) {
return Redirect::back()->with('success', Lang::get('admin/licenses/message.upload.success'));
} else {
return Redirect::back()->with('success', Lang::get('admin/licenses/message.upload.error'));
}
} else {
return Redirect::back()->with('error', Lang::get('admin/licenses/message.upload.nofiles'));
}
} else {
// Prepare the error message
$error = Lang::get('admin/licenses/message.does_not_exist', compact('id'));
// Redirect to the licence management page
return Redirect::route('licenses')->with('error', $error);
}
}
/**
* Delete the associated file
*
* @param int $licenseId
* @param int $fileId
* @return View
**/
public function getDeleteFile($licenseId = null, $fileId = null)
{
$license = License::find($licenseId);
$destinationPath = storage_path().'/app/private_uploads';
// the license is valid
if (isset($license->id)) {
if (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
$log = Actionlog::find($fileId);
$full_filename = $destinationPath.'/'.$log->filename;
if (file_exists($full_filename)) {
unlink($destinationPath.'/'.$log->filename);
}
$log->delete();
return Redirect::back()->with('success', Lang::get('admin/licenses/message.deletefile.success'));
} else {
// Prepare the error message
$error = Lang::get('admin/licenses/message.does_not_exist', compact('id'));
// Redirect to the licence management page
return Redirect::route('licenses')->with('error', $error);
}
}
/**
* Display/download the uploaded file
*
* @param int $licenseId
* @param int $fileId
* @return View
**/
public function displayFile($licenseId = null, $fileId = null)
{
$license = License::find($licenseId);
// the license is valid
if (isset($license->id)) {
if (!Company::isCurrentUserHasAccess($license)) {
return Redirect::to('admin/licenses')->with('error', Lang::get('general.insufficient_permissions'));
}
$log = Actionlog::find($fileId);
$file = $log->get_src();
return Response::download($file);
} else {
// Prepare the error message
$error = Lang::get('admin/licenses/message.does_not_exist', compact('id'));
// Redirect to the licence management page
return Redirect::route('licenses')->with('error', $error);
}
}
public function getDatatable()
{
$licenses = License::with('company');
if (Input::has('search')) {
$licenses = $licenses->TextSearch(Input::get('search'));
}
$allowed_columns = ['id','name','purchase_cost','expiration_date','purchase_order','order_number','notes','purchase_date','serial'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$licenses = $licenses->orderBy($sort, $order);
$licenseCount = $licenses->count();
$licenses = $licenses->skip(Input::get('offset'))->take(Input::get('limit'))->get();
$rows = array();
foreach ($licenses as $license) {
$actions = '<span style="white-space: nowrap;"><a href="'.route('freecheckout/license', $license->id).'" class="btn btn-primary btn-sm" style="margin-right:5px;" '.(($license->remaincount() > 0) ? '' : 'disabled').'>'.Lang::get('general.checkout').'</a> <a href="'.route('clone/license', $license->id).'" class="btn btn-info btn-sm" style="margin-right:5px;" title="Clone asset"><i class="fa fa-files-o"></i></a><a href="'.route('update/license', $license->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/license', $license->id).'" data-content="'.Lang::get('admin/licenses/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($license->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></span>';
$rows[] = array(
'id' => $license->id,
'name' => (string) link_to('/admin/licenses/'.$license->id.'/view', $license->name),
'serial' => (string) link_to('/admin/licenses/'.$license->id.'/view', mb_strimwidth($license->serial, 0, 50, "...")),
'totalSeats' => $license->totalSeatsByLicenseID(),
'remaining' => $license->remaincount(),
'license_name' => $license->license_name,
'license_email' => $license->license_email,
'purchase_date' => ($license->purchase_date) ? $license->purchase_date : '',
'expiration_date' => ($license->expiration_date) ? $license->expiration_date : '',
'purchase_cost' => ($license->purchase_cost) ? $license->purchase_cost : '',
'purchase_order' => ($license->purchase_order) ? $license->purchase_order : '',
'order_number' => ($license->order_number) ? $license->order_number : '',
'notes' => ($license->notes) ? $license->notes : '',
'actions' => $actions,
'companyName' => is_null($license->company) ? '' : e($license->company->name)
);
}
$data = array('total' => $licenseCount, 'rows' => $rows);
return $data;
}
public function getFreeLicense($licenseId)
{
// Check if the asset exists
if (is_null($license = License::find($licenseId))) {
// Redirect to the asset management page with error
return Redirect::to('admin/licenses')->with('error', Lang::get('admin/licenses/message.not_found'));
}
$seatId = $license->freeSeat($licenseId);
return Redirect::to('admin/licenses/'.$seatId.'/checkout');
}
}

View file

@ -0,0 +1,379 @@
<?php
namespace App\Http\Controllers;
use Input;
use Lang;
use App\Models\Location;
use Redirect;
use App\Models\Setting;
use DB;
use Str;
use Validator;
use View;
use Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
class LocationsController extends Controller
{
/**
* Show a list of all the locations.
*
* @return View
*/
public function getIndex()
{
// Grab all the locations
$locations = \App\Models\Location::orderBy('created_at', 'DESC')->with('parent', 'assets', 'assignedassets')->get();
// Show the page
return View::make('locations/index', compact('locations'));
}
/**
* Location create.
*
* @return View
*/
public function getCreate()
{
$locations = \App\Models\Location::orderBy('name', 'ASC')->get();
$location_options_array = \App\Models\Location::getLocationHierarchy($locations);
$location_options = \App\Models\Location::flattenLocationsArray($location_options_array);
$location_options = array('' => 'Top Level') + $location_options;
return View::make('locations/edit')
->with('location_options', $location_options)
->with('location', new Location);
}
/**
* Location create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new location instance
$location = new \App\Models\Location();
// Save the location data
$location->name = e(Input::get('name'));
if (Input::get('parent_id')=='') {
$location->parent_id = null;
} else {
$location->parent_id = e(Input::get('parent_id'));
}
$location->currency = Input::get('currency', '$');
$location->address = e(Input::get('address'));
$location->address2 = e(Input::get('address2'));
$location->city = e(Input::get('city'));
$location->state = e(Input::get('state'));
$location->country = e(Input::get('country'));
$location->zip = e(Input::get('zip'));
$location->user_id = Auth::user()->id;
// Was the asset created?
if ($location->save()) {
// Redirect to the new location page
return Redirect::to("admin/settings/locations")->with('success', Lang::get('admin/locations/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($location->getErrors());
}
public function store()
{
$new['currency']=Setting::first()->default_currency;
// create a new location instance
$location = new Location();
// Save the location data
$location->name = e(Input::get('name'));
// if (Input::get('parent_id')=='') {
// $location->parent_id = null;
// } else {
// $location->parent_id = e(Input::get('parent_id'));
// }
$location->currency = Setting::first()->default_currency; //e(Input::get('currency'));
$location->address = ''; //e(Input::get('address'));
// $location->address2 = e(Input::get('address2'));
$location->city = e(Input::get('city'));
$location->state = '';//e(Input::get('state'));
$location->country = e(Input::get('country'));
// $location->zip = e(Input::get('zip'));
$location->user_id = Auth::user()->id;
// Was the location created?
if ($location->save()) {
return JsonResponse::create($location);
}
// failure
$errors = $location->errors();
return JsonResponse::create(["error" => "Failed validation: ".print_r($location->getErrors(), true)], 500);
}
/**
* Location update.
*
* @param int $locationId
* @return View
*/
public function getEdit($locationId = null)
{
// Check if the location exists
if (is_null($location = \App\Models\Location::find($locationId))) {
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.does_not_exist'));
}
// Show the page
$locations = \App\Models\Location::orderBy('name', 'ASC')->get();
$location_options_array = \App\Models\Location::getLocationHierarchy($locations);
$location_options = \App\Models\Location::flattenLocationsArray($location_options_array);
$location_options = array('' => 'Top Level') + $location_options;
return View::make('locations/edit', compact('location'))->with('location_options', $location_options);
}
/**
* Location update form processing page.
*
* @param int $locationId
* @return Redirect
*/
public function postEdit($locationId = null)
{
// Check if the location exists
if (is_null($location = \App\Models\Location::find($locationId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.does_not_exist'));
}
// Update the location data
$location->name = e(Input::get('name'));
if (Input::get('parent_id')=='') {
$location->parent_id = null;
} else {
$location->parent_id = e(Input::get('parent_id', ''));
}
$location->currency = Input::get('currency', '$');
$location->address = e(Input::get('address'));
$location->address2 = e(Input::get('address2'));
$location->city = e(Input::get('city'));
$location->state = e(Input::get('state'));
$location->country = e(Input::get('country'));
$location->zip = e(Input::get('zip'));
// Was the asset created?
if ($location->save()) {
// Redirect to the saved location page
return Redirect::to("admin/settings/locations/")->with('success', Lang::get('admin/locations/message.update.success'));
}
// Redirect to the location management page
return Redirect::back()->withInput()->withInput()->withErrors($location->getErrors());
}
/**
* Delete the given location.
*
* @param int $locationId
* @return Redirect
*/
public function getDelete($locationId)
{
// Check if the location exists
if (is_null($location = \App\Models\Location::find($locationId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.not_found'));
}
if ($location->users->count() > 0) {
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.assoc_users'));
} elseif ($location->childLocations->count() > 0) {
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.assoc_child_loc'));
} elseif ($location->assets->count() > 0) {
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.assoc_assets'));
} elseif ($location->assignedassets->count() > 0) {
return Redirect::to('admin/settings/locations')->with('error', Lang::get('admin/locations/message.assoc_assets'));
} else {
$location->delete();
return Redirect::to('admin/settings/locations')->with('success', Lang::get('admin/locations/message.delete.success'));
}
}
/**
* Get the location page detail page
*
* @param int $locationID
* @return View
**/
public function getView($locationId = null)
{
$location = \App\Models\Location::find($locationId);
if (isset($location->id)) {
return View::make('locations/view', compact('location'));
} else {
// Prepare the error message
$error = Lang::get('admin/locations/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('locations')->with('error', $error);
}
}
/**
* Get the locations API information to present to the location view page
*
* @param int $locationID
* @return JSON
**/
public function getDatatable()
{
$locations = \App\Models\Location::select(array('locations.id','locations.name','locations.address','locations.address2','locations.city','locations.state','locations.zip','locations.country','locations.parent_id','locations.currency'))->with('assets');
if (Input::has('search')) {
$locations = $locations->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
switch (Input::get('sort')) {
case 'parent':
$locations = $locations->OrderParent($order);
break;
default:
$allowed_columns = ['id','name','address','city','state','country','currency'];
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$locations = $locations->orderBy($sort, $order);
break;
}
$locationsCount = $locations->count();
$locations = $locations->skip($offset)->take($limit)->get();
$rows = array();
foreach ($locations as $location) {
$actions = '<nobr><a href="'.route('update/location', $location->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/location', $location->id).'" data-content="'.Lang::get('admin/locations/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($location->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></nobr>';
$rows[] = array(
'id' => $location->id,
'name' => (string)link_to('admin/settings/locations/'.$location->id.'/view', $location->name),
'parent' => ($location->parent) ? $location->parent->name : '',
// 'assets' => ($location->assets->count() + $location->assignedassets->count()),
'assets_default' => $location->assignedassets->count(),
'assets_checkedout' => $location->assets->count(),
'address' => ($location->address) ? $location->address: '',
'city' => $location->city,
'state' => $location->state,
'country' => $location->country,
'currency' => $location->currency,
'actions' => $actions
);
}
$data = array('total' => $locationsCount, 'rows' => $rows);
return $data;
}
/**
* Get the location user listing information to present to the location details page
*
* @param int $locationID
* @return JSON
**/
public function getDataViewUsers($locationID)
{
$location = \App\Models\Location::find($locationID);
$location_users = $location->users;
$count = $location_users->count();
$rows = array();
foreach ($location_users as $user) {
$rows[] = array(
'name' => (string)link_to('/admin/users/'.$user->id.'/view', $user->fullName())
);
}
$data = array('total' => $count, 'rows' => $rows);
return $data;
}
/**
* Get the location asset information to present to the location details page
*
* @param int $locationID
* @return JSON
**/
public function getDataViewAssets($locationID)
{
$location = \App\Models\Location::find($locationID);
$count = $location->assets->count();
$rows = array();
foreach ($location->assets as $asset) {
$rows[] = array(
'name' => (string)link_to('/hardware/'.$asset->id.'/view', $asset->showAssetName()),
'asset_tag' => $asset->asset_tag,
'serial' => $asset->serial,
'model' => $asset->model->name,
);
}
$data = array('total' => $count, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,288 @@
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use Input;
use Lang;
use App\Models\Manufacturer;
use Redirect;
use App\Models\Setting;
use Str;
use View;
use Auth;
class ManufacturersController extends Controller
{
/**
* Show a list of all manufacturers
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('manufacturers/index', compact('manufacturers'));
}
/**
* Manufacturer create.
*
* @return View
*/
public function getCreate()
{
return View::make('manufacturers/edit')->with('manufacturer', new Manufacturer);
}
/**
* Manufacturer create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// Create a new manufacturer
$manufacturer = new Manufacturer;
$manufacturer->name = e(Input::get('name'));
$manufacturer->user_id = Auth::user()->id;
// Was it created?
if ($manufacturer->save()) {
return Redirect::to("admin/settings/manufacturers")->with('success', Lang::get('admin/manufacturers/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($manufacturer->getErrors());
}
/**
* Manufacturer update.
*
* @param int $manufacturerId
* @return View
*/
public function getEdit($manufacturerId = null)
{
// Check if the manufacturer exists
if (is_null($manufacturer = Manufacturer::find($manufacturerId))) {
// Redirect to the manufacturer page
return Redirect::to('admin/settings/manufacturers')->with('error', Lang::get('admin/manufacturers/message.does_not_exist'));
}
// Show the page
return View::make('manufacturers/edit', compact('manufacturer'));
}
/**
* Manufacturer update form processing page.
*
* @param int $manufacturerId
* @return Redirect
*/
public function postEdit($manufacturerId = null)
{
// Check if the manufacturer exists
if (is_null($manufacturer = Manufacturer::find($manufacturerId))) {
// Redirect to the manufacturer page
return Redirect::to('admin/settings/manufacturers')->with('error', Lang::get('admin/manufacturers/message.does_not_exist'));
}
// Save the data
$manufacturer->name = e(Input::get('name'));
// Was it created?
if ($manufacturer->save()) {
// Redirect to the new manufacturer page
return Redirect::to("admin/settings/manufacturers")->with('success', Lang::get('admin/manufacturers/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($manufacturer->getErrors());
}
/**
* Delete the given manufacturer.
*
* @param int $manufacturerId
* @return Redirect
*/
public function getDelete($manufacturerId)
{
// Check if the manufacturer exists
if (is_null($manufacturer = Manufacturer::find($manufacturerId))) {
// Redirect to the manufacturers page
return Redirect::to('admin/settings/manufacturers')->with('error', Lang::get('admin/manufacturers/message.not_found'));
}
if ($manufacturer->has_models() > 0) {
// Redirect to the asset management page
return Redirect::to('admin/settings/manufacturers')->with('error', Lang::get('admin/manufacturers/message.assoc_users'));
} else {
// Delete the manufacturer
$manufacturer->delete();
// Redirect to the manufacturers management page
return Redirect::to('admin/settings/manufacturers')->with('success', Lang::get('admin/manufacturers/message.delete.success'));
}
}
/**
* Get the asset information to present to the category view page
*
* @param int $assetId
* @return View
**/
public function getView($manufacturerID = null)
{
$manufacturer = Manufacturer::find($manufacturerID);
if (isset($manufacturer->id)) {
return View::make('manufacturers/view', compact('manufacturer'));
} else {
// Prepare the error message
$error = Lang::get('admin/manufacturers/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('manufacturers')->with('error', $error);
}
}
public function getDatatable()
{
$manufacturers = Manufacturer::select(array('id','name'))->with('assets')
->whereNull('deleted_at');
if (Input::has('search')) {
$manufacturers = $manufacturers->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$manufacturers->orderBy($sort, $order);
$manufacturersCount = $manufacturers->count();
$manufacturers = $manufacturers->skip($offset)->take($limit)->get();
$rows = array();
foreach ($manufacturers as $manufacturer) {
$actions = '<a href="'.route('update/manufacturer', $manufacturer->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/manufacturer', $manufacturer->id).'" data-content="'.Lang::get('admin/manufacturers/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($manufacturer->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
$rows[] = array(
'id' => $manufacturer->id,
'name' => (string)link_to('admin/settings/manufacturers/'.$manufacturer->id.'/view', $manufacturer->name),
'assets' => $manufacturer->assets->count(),
'actions' => $actions
);
}
$data = array('total' => $manufacturersCount, 'rows' => $rows);
return $data;
}
public function getDataView($manufacturerID)
{
$manufacturer = Manufacturer::with('assets.company')->find($manufacturerID);
$manufacturer_assets = $manufacturer->assets;
if (Input::has('search')) {
$manufacturer_assets = $manufacturer_assets->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$allowed_columns = ['id','name','serial','asset_tag'];
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$count = $manufacturer_assets->count();
$rows = array();
foreach ($manufacturer_assets as $asset) {
$actions = '';
if ($asset->deleted_at=='') {
$actions = '<div style=" white-space: nowrap;"><a href="'.route('clone/hardware', $asset->id).'" class="btn btn-info btn-sm" title="Clone asset"><i class="fa fa-files-o"></i></a> <a href="'.route('update/hardware', $asset->id).'" class="btn btn-warning btn-sm"><i class="fa fa-pencil icon-white"></i></a> <a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/hardware', $asset->id).'" data-content="'.Lang::get('admin/hardware/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($asset->asset_tag).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a></div>';
} elseif ($asset->deleted_at!='') {
$actions = '<a href="'.route('restore/hardware', $asset->id).'" class="btn btn-warning btn-sm"><i class="fa fa-recycle icon-white"></i></a>';
}
if ($asset->assetstatus) {
if ($asset->assetstatus->deployable != 0) {
if (($asset->assigned_to !='') && ($asset->assigned_to > 0)) {
$inout = '<a href="'.route('checkin/hardware', $asset->id).'" class="btn btn-primary btn-sm">'.Lang::get('general.checkin').'</a>';
} else {
$inout = '<a href="'.route('checkout/hardware', $asset->id).'" class="btn btn-info btn-sm">'.Lang::get('general.checkout').'</a>';
}
}
}
$row = array(
'id' => $asset->id,
'name' => (string)link_to('/hardware/'.$asset->id.'/view', $asset->showAssetName()),
'model' => $asset->model->name,
'asset_tag' => $asset->asset_tag,
'serial' => $asset->serial,
'assigned_to' => ($asset->assigneduser) ? (string)link_to('/admin/users/'.$asset->assigneduser->id.'/view', $asset->assigneduser->fullName()): '',
'actions' => $actions,
'companyName' => Company::getName($asset),
);
if (isset($inout)) {
$row['change'] = $inout;
}
$rows[] = $row;
}
$data = array('total' => $count, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers;
use Image;
use Input;
use Redirect;
use App\Models\Location;
use View;
use Auth;
use App\Helpers\Helper;
class ProfileController extends Controller
{
/**
* User profile page.
*
* @return View
*/
public function getIndex()
{
// Get the user information
$user = Auth::user();
$location_list = Helper::locationsList();
return View::make('account/profile', compact('user'))->with('location_list', $location_list);
}
/**
* User profile form processing page.
*
* @return Redirect
*/
public function postIndex()
{
// Grab the user
$user = Auth::user();
// Update the user information
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->website = Input::get('website');
$user->location_id = Input::get('location_id');
$user->gravatar = Input::get('gravatar');
$user->locale = Input::get('locale');
if (Input::file('avatar')) {
$image = Input::file('avatar');
$file_name = $user->first_name."-".$user->last_name.".".$image->getClientOriginalExtension();
$path = public_path('uploads/avatars/'.$file_name);
Image::make($image->getRealPath())->resize(84, 84)->save($path);
$user->avatar = $file_name;
}
if (Input::get('avatar_delete') == 1 && Input::file('avatar') == "") {
$user->avatar = null;
}
if ($user->save()) {
return Redirect::route('profile')->with('success', 'Account successfully updated');
}
return Redirect::back()->withInput()->withErrors($user->getErrors());
}
}

View file

@ -0,0 +1,780 @@
<?php
namespace App\Http\Controllers;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\AssetMaintenance;
use Carbon\Carbon;
use Category;
use App\Models\Company;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Input;
use League\Csv\Reader;
use App\Models\License;
use App\Models\Location;
use App\Models\AssetModel;
use Redirect;
use App\Models\Setting;
use App\Models\User;
class ReportsController extends Controller
{
/**
* Show Report for Accessories
*
* @return View
*/
public function getAccessoryReport()
{
$accessories = Accessory::orderBy('created_at', 'DESC')->with('company')->get();
return View::make('reports/accessories', compact('accessories'));
}
/**
* Export Accessories Report as CSV
*
* @return file download
*/
public function exportAccessoryReport()
{
$accessories = Accessory::orderBy('created_at', 'DESC')->get();
$rows = array();
$header = array(
Lang::get('admin/accessories/table.title'),
Lang::get('admin/accessories/general.accessory_category'),
Lang::get('admin/accessories/general.total'),
Lang::get('admin/accessories/general.remaining')
);
$header = array_map('trim', $header);
$rows[] = implode($header, ', ');
// Row per accessory
foreach ($accessories as $accessory) {
$row = array();
$row[] = $accessory->accessory_name;
$row[] = $accessory->accessory_category;
$row[] = $accessory->total;
$row[] = $accessory->remaining;
$rows[] = implode($row, ',');
}
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
}
/**
* Show Asset Report
*
* @return View
*/
public function getAssetsReport()
{
// Grab all the assets
$assets = Asset::with(
'model',
'assigneduser.userLoc',
'assetstatus',
'defaultLoc',
'assetlog',
'supplier',
'model.manufacturer',
'company'
)
->orderBy('created_at', 'DESC')
->get();
return View::make('reports/asset', compact('assets'));
}
/**
* Export Asset Report as CSV
*
* @return file download
*/
public function exportAssetReport()
{
// Grab all the assets
$assets = Asset::orderBy('created_at', 'DESC')->get();
$rows = [ ];
// Create the header row
$header = [
Lang::get('admin/hardware/table.asset_tag'),
Lang::get('admin/hardware/form.manufacturer'),
Lang::get('admin/hardware/form.model'),
Lang::get('general.model_no'),
Lang::get('general.name'),
Lang::get('admin/hardware/table.serial'),
Lang::get('general.status'),
Lang::get('admin/hardware/table.purchase_date'),
Lang::get('admin/hardware/table.purchase_cost'),
Lang::get('admin/hardware/form.order'),
Lang::get('admin/hardware/form.supplier'),
Lang::get('admin/hardware/table.checkoutto'),
Lang::get('admin/hardware/table.location'),
Lang::get('general.notes'),
];
$header = array_map('trim', $header);
$rows[] = implode($header, ',');
// Create a row per asset
foreach ($assets as $asset) {
$row = [ ];
$row[] = $asset->asset_tag;
if ($asset->model->manufacturer) {
$row[] = $asset->model->manufacturer->name;
} else {
$row[] = '';
}
$row[] = '"' . $asset->model->name . '"';
$row[] = '"' . $asset->model->modelno . '"';
$row[] = $asset->name;
$row[] = $asset->serial;
if ($asset->assetstatus) {
$row[] = $asset->assetstatus->name;
} else {
$row[] = '';
}
$row[] = $asset->purchase_date;
$row[] = '"' . number_format($asset->purchase_cost) . '"';
if ($asset->order_number) {
$row[] = $asset->order_number;
} else {
$row[] = '';
}
if ($asset->supplier_id) {
$row[] = $asset->supplier->name;
} else {
$row[] = '';
}
if ($asset->assigned_to > 0) {
$user = User::find($asset->assigned_to);
$row[] = $user->fullName();
} else {
$row[] = ''; // Empty string if unassigned
}
if (( $asset->assigned_to > 0 ) && ( $asset->assigneduser->location_id > 0 )) {
$location = Location::find($asset->assigneduser->location_id);
if ($location) {
$row[] = $location->name;
} else {
$row[] = '';
}
} elseif ($asset->rtd_location_id) {
$location = Location::find($asset->rtd_location_id);
if ($location->name) {
$row[] = $location->name;
} else {
$row[] = '';
}
} else {
$row[] = ''; // Empty string if location is not set
}
if ($asset->notes) {
$row[] = '"' . $asset->notes . '"';
} else {
$row[] = '';
}
$rows[] = implode($row, ',');
}
// spit out a csv
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
}
/**
* Show Depreciation Report for Assets
*
* @return View
*/
public function getDeprecationReport()
{
// Grab all the assets
$assets = Asset::with('model', 'assigneduser', 'assetstatus', 'defaultLoc', 'assetlog', 'company')
->orderBy('created_at', 'DESC')->get();
return View::make('reports/depreciation', compact('assets'));
}
/**
* Export Depreciation Report as CSV
*
* @return file download
*/
public function exportDeprecationReport()
{
// Grab all the assets
$assets = Asset::with('model', 'assigneduser', 'assetstatus', 'defaultLoc', 'assetlog')
->orderBy('created_at', 'DESC')->get();
$csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());
$csv->setOutputBOM(Reader::BOM_UTF16_BE);
$rows = [ ];
// Create the header row
$header = [
Lang::get('admin/hardware/table.asset_tag'),
Lang::get('admin/hardware/table.title'),
Lang::get('admin/hardware/table.serial'),
Lang::get('admin/hardware/table.checkoutto'),
Lang::get('admin/hardware/table.location'),
Lang::get('admin/hardware/table.purchase_date'),
Lang::get('admin/hardware/table.purchase_cost'),
Lang::get('admin/hardware/table.book_value'),
Lang::get('admin/hardware/table.diff')
];
//we insert the CSV header
$csv->insertOne($header);
// Create a row per asset
foreach ($assets as $asset) {
$row = [ ];
$row[] = $asset->asset_tag;
$row[] = $asset->name;
$row[] = $asset->serial;
if ($asset->assigned_to > 0) {
$user = User::find($asset->assigned_to);
$row[] = $user->fullName();
} else {
$row[] = ''; // Empty string if unassigned
}
if (( $asset->assigned_to > 0 ) && ( $asset->assigneduser->location_id > 0 )) {
$location = Location::find($asset->assigneduser->location_id);
if ($location->city) {
$row[] = $location->city . ', ' . $location->state;
} elseif ($location->name) {
$row[] = $location->name;
} else {
$row[] = '';
}
} else {
$row[] = ''; // Empty string if location is not set
}
if ($asset->assetloc) {
$currency = $asset->assetloc->currency;
} else {
$currency = Setting::first()->default_currency;
}
$row[] = $asset->purchase_date;
$row[] = $currency . number_format($asset->purchase_cost);
$row[] = $currency . number_format($asset->getDepreciatedValue());
$row[] = $currency . number_format(( $asset->purchase_cost - $asset->getDepreciatedValue() ));
$csv->insertOne($row);
}
$csv->output('depreciation-report-' . date('Y-m-d') . '.csv');
die;
}
/**
* Show Report for Activity
*
* @return View
*/
public function getActivityReport()
{
$log_actions = Actionlog::orderBy('created_at', 'DESC')
->with('adminlog')
->with('accessorylog')
->with('assetlog')
->with('licenselog')
->with('userlog')
->orderBy('created_at', 'DESC')
->get();
return View::make('reports/activity', compact('log_actions'));
}
/**
* Show Report for Licenses
*
* @return View
*/
public function getLicenseReport()
{
$licenses = License::orderBy('created_at', 'DESC')
->with('company')
->get();
return View::make('reports/licenses', compact('licenses'));
}
/**
* Export License Report as CSV
*
* @return file download
*/
public function exportLicenseReport()
{
$licenses = License::orderBy('created_at', 'DESC')->get();
$rows = [ ];
$header = [
Lang::get('admin/licenses/table.title'),
Lang::get('admin/licenses/table.serial'),
Lang::get('admin/licenses/form.seats'),
Lang::get('admin/licenses/form.remaining_seats'),
Lang::get('admin/licenses/form.expiration'),
Lang::get('admin/licenses/form.date'),
Lang::get('admin/licenses/form.cost')
];
$header = array_map('trim', $header);
$rows[] = implode($header, ', ');
// Row per license
foreach ($licenses as $license) {
$row = [ ];
$row[] = $license->name;
$row[] = $license->serial;
$row[] = $license->seats;
$row[] = $license->remaincount();
$row[] = $license->expiration_date;
$row[] = $license->purchase_date;
$row[] = '"' . number_format($license->purchase_cost) . '"';
$rows[] = implode($row, ',');
}
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
}
public function getCustomReport()
{
return View::make('reports/custom');
}
public function postCustom()
{
$assets = Asset::orderBy('created_at', 'DESC')->get();
$rows = [ ];
$header = [ ];
if (e(Input::get('asset_name')) == '1') {
$header[] = 'Asset Name';
}
if (e(Input::get('asset_tag')) == '1') {
$header[] = 'Asset Tag';
}
if (e(Input::get('manufacturer')) == '1') {
$header[] = 'Manufacturer';
}
if (e(Input::get('model')) == '1') {
$header[] = 'Model';
$header[] = 'Model Number';
}
if (e(Input::get('category')) == '1') {
$header[] = 'Category';
}
if (e(Input::get('serial')) == '1') {
$header[] = 'Serial';
}
if (e(Input::get('purchase_date')) == '1') {
$header[] = 'Purchase Date';
}
if (( e(Input::get('purchase_cost')) == '1' ) && ( e(Input::get('depreciation')) != '1' )) {
$header[] = 'Purchase Cost';
}
if (e(Input::get('order')) == '1') {
$header[] = 'Order Number';
}
if (e(Input::get('supplier')) == '1') {
$header[] = 'Supplier';
}
if (e(Input::get('location')) == '1') {
$header[] = 'Location';
}
if (e(Input::get('assigned_to')) == '1') {
$header[] = 'Assigned To';
}
if (e(Input::get('status')) == '1') {
$header[] = 'Status';
}
if (e(Input::get('warranty')) == '1') {
$header[] = 'Warranty';
$header[] = 'Warranty Expires';
}
if (e(Input::get('depreciation')) == '1') {
$header[] = 'Purchase Cost';
$header[] = 'Value';
$header[] = 'Diff';
}
$header = array_map('trim', $header);
$rows[] = implode($header, ',');
foreach ($assets as $asset) {
$row = [ ];
if (e(Input::get('asset_name')) == '1') {
$row[] = '"' .$asset->name . '"';
}
if (e(Input::get('asset_tag')) == '1') {
$row[] = $asset->asset_tag;
}
if (e(Input::get('manufacturer')) == '1') {
if ($asset->model->manufacturer) {
$row[] = '"' .$asset->model->manufacturer->name . '"';
} else {
$row[] = '';
}
}
if (e(Input::get('model')) == '1') {
$row[] = '"' . $asset->model->name . '"';
$row[] = '"' . $asset->model->modelno . '"';
}
if (e(Input::get('category')) == '1') {
$row[] = '"' .$asset->model->category->name . '"';
}
if (e(Input::get('serial')) == '1') {
$row[] = $asset->serial;
}
if (e(Input::get('purchase_date')) == '1') {
$row[] = $asset->purchase_date;
}
if (e(Input::get('purchase_cost')) == '1' && ( e(Input::get('depreciation')) != '1' )) {
$row[] = '"' . number_format($asset->purchase_cost) . '"';
}
if (e(Input::get('order')) == '1') {
if ($asset->order_number) {
$row[] = $asset->order_number;
} else {
$row[] = '';
}
}
if (e(Input::get('supplier')) == '1') {
if ($asset->supplier_id) {
$row[] = '"' .$asset->supplier->name . '"';
} else {
$row[] = '';
}
}
if (e(Input::get('location')) == '1') {
$show_loc = '';
if (( $asset->assigned_to > 0 ) && ( $asset->assigneduser->location_id !='' )) {
$location = Location::find($asset->assigneduser->location_id);
if ($location) {
$show_loc .= '"' .$location->name. '"';
} else {
$show_loc .= 'User location '.$asset->assigneduser->location_id.' is invalid';
}
} elseif ($asset->rtd_location_id!='') {
$location = Location::find($asset->rtd_location_id);
if ($location) {
$show_loc .= '"' .$location->name. '"';
} else {
$show_loc .= 'Default location '.$asset->rtd_location_id.' is invalid';
}
}
$row[] = $show_loc;
}
if (e(Input::get('assigned_to')) == '1') {
if ($asset->assigned_to > 0) {
$user = User::find($asset->assigned_to);
$row[] = '"' .$user->fullName(). '"';
} else {
$row[] = ''; // Empty string if unassigned
}
}
if (e(Input::get('status')) == '1') {
if (( $asset->status_id == '0' ) && ( $asset->assigned_to == '0' )) {
$row[] = Lang::get('general.ready_to_deploy');
} elseif (( $asset->status_id == '' ) && ( $asset->assigned_to == '0' )) {
$row[] = Lang::get('general.pending');
} elseif ($asset->assetstatus) {
$row[] = '"' .$asset->assetstatus->name. '"';
} else {
$row[] = '';
}
}
if (e(Input::get('warranty')) == '1') {
if ($asset->warranty_months) {
$row[] = $asset->warranty_months;
$row[] = $asset->warrantee_expires();
} else {
$row[] = '';
$row[] = '';
}
}
if (e(Input::get('depreciation')) == '1') {
$depreciation = $asset->getDepreciatedValue();
$row[] = '"' . number_format($asset->purchase_cost) . '"';
$row[] = '"' . number_format($depreciation) . '"';
$row[] = '"' . number_format($asset->purchase_cost - $depreciation) . '"';
}
$rows[] = implode($row, ',');
}
// spit out a csv
if (array_filter($rows)) {
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
} else {
return Redirect::to("reports/custom")
->with('error', Lang::get('admin/reports/message.error'));
}
}
/**
* getImprovementsReport
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getAssetMaintenancesReport()
{
// Grab all the improvements
$assetMaintenances = \App\Models\AssetMaintenance::with('asset', 'supplier', 'asset.company')
->orderBy('created_at', 'DESC')
->get();
return View::make('reports/asset_maintenances', compact('assetMaintenances'));
}
/**
* exportImprovementsReport
*
* @return \Illuminate\Http\Response
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function exportAssetMaintenancesReport()
{
// Grab all the improvements
$assetMaintenances = AssetMaintenance::with('asset', 'supplier')
->orderBy('created_at', 'DESC')
->get();
$rows = [ ];
$header = [
Lang::get('admin/asset_maintenances/table.asset_name'),
Lang::get('admin/asset_maintenances/table.supplier_name'),
Lang::get('admin/asset_maintenances/form.asset_maintenance_type'),
Lang::get('admin/asset_maintenances/form.title'),
Lang::get('admin/asset_maintenances/form.start_date'),
Lang::get('admin/asset_maintenances/form.completion_date'),
Lang::get('admin/asset_maintenances/form.asset_maintenance_time'),
Lang::get('admin/asset_maintenances/form.cost')
];
$header = array_map('trim', $header);
$rows[] = implode($header, ',');
foreach ($assetMaintenances as $assetMaintenance) {
$row = [ ];
$row[] = str_replace(',', '', $assetMaintenance->asset->name);
$row[] = str_replace(',', '', $assetMaintenance->supplier->name);
$row[] = $assetMaintenance->improvement_type;
$row[] = $assetMaintenance->title;
$row[] = $assetMaintenance->start_date;
$row[] = $assetMaintenance->completion_date;
if (is_null($assetMaintenance->asset_maintenance_time)) {
$improvementTime = intval(Carbon::now()
->diffInDays(Carbon::parse($assetMaintenance->start_date)));
} else {
$improvementTime = intval($assetMaintenance->asset_maintenance_time);
}
$row[] = $improvementTime;
$row[] = Lang::get('general.currency') . number_format($assetMaintenance->cost, 2);
$rows[] = implode($row, ',');
}
// spit out a csv
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
}
/**
* getAssetAcceptanceReport
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getAssetAcceptanceReport()
{
$assetsForReport = Asset::notYetAccepted()->with('company')->get();
return View::make('reports/unaccepted_assets', compact('assetsForReport'));
}
/**
* exportAssetAcceptanceReport
*
* @return \Illuminate\Http\Response
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function exportAssetAcceptanceReport()
{
// Grab all the improvements
$assetsForReport = Actionlog::whereIn('id', $this->getAssetsNotAcceptedYet())
->get();
$rows = [ ];
$header = [
Lang::get('general.category'),
Lang::get('admin/hardware/form.model'),
Lang::get('admin/hardware/form.name'),
Lang::get('admin/hardware/table.asset_tag'),
Lang::get('admin/hardware/table.checkoutto'),
];
$header = array_map('trim', $header);
$rows[] = implode($header, ',');
foreach ($assetsForReport as $assetItem) {
$row = [ ];
$row[] = str_replace(',', '', $assetItem->assetlog->model->category->name);
$row[] = str_replace(',', '', $assetItem->assetlog->model->name);
$row[] = str_replace(',', '', $assetItem->assetlog->showAssetName());
$row[] = str_replace(',', '', $assetItem->assetlog->asset_tag);
$row[] = str_replace(',', '', $assetItem->assetlog->assigneduser->fullName());
$rows[] = implode($row, ',');
}
// spit out a csv
$csv = implode($rows, "\n");
$response = Response::make($csv, 200);
$response->header('Content-Type', 'text/csv');
$response->header('Content-disposition', 'attachment;filename=report.csv');
return $response;
}
/**
* getCheckedOutAssetsRequiringAcceptance
*
* @param $modelsInCategoriesThatRequireAcceptance
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
protected function getCheckedOutAssetsRequiringAcceptance($modelsInCategoriesThatRequireAcceptance)
{
$assets = Asset::deployed()
->inModelList($modelsInCategoriesThatRequireAcceptance)
->select('id')
->get()
->toArray();
return array_pluck($assets, 'id');
}
/**
* getModelsInCategoriesThatRequireAcceptance
*
* @param $assetCategoriesRequiringAcceptance
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
protected function getModelsInCategoriesThatRequireAcceptance($assetCategoriesRequiringAcceptance)
{
return array_pluck(Model::inCategory($assetCategoriesRequiringAcceptance)
->select('id')
->get()
->toArray(), 'id');
}
/**
* getCategoriesThatRequireAcceptance
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
protected function getCategoriesThatRequireAcceptance()
{
return array_pluck(Category::requiresAcceptance()
->select('id')
->get()
->toArray(), 'id');
}
/**
* getAssetsCheckedOutRequiringAcceptance
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
protected function getAssetsCheckedOutRequiringAcceptance()
{
return $this->getCheckedOutAssetsRequiringAcceptance(
$this->getModelsInCategoriesThatRequireAcceptance($this->getCategoriesThatRequireAcceptance())
);
}
/**
* getAssetsNotAcceptedYet
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
protected function getAssetsNotAcceptedYet()
{
return Asset::unaccepted();
}
}

View file

@ -0,0 +1,523 @@
<?php
/**
* This controller handles all actions related to Settings for
* the Snipe-IT Asset Management application.
*
* PHP version 5.5.9
* @package Snipe-IT
* @version v1.0
*/
namespace App\Http\Controllers;
use Input;
use Lang;
use App\Models\Setting;
use Redirect;
use DB;
use Str;
use View;
use Image;
use Config;
use Response;
use Artisan;
use Crypt;
use Mail;
use App\User;
use App\Http\Requests\SetupUserRequest;
use App\Http\Requests\SettingRequest;
/**
* This class controls all actions related to settings
*/
class SettingsController extends Controller
{
/**
* Checks to see whether or not the database has a migrations table
* and a user, otherwise display the setup view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return View
*/
public function getSetupIndex()
{
try {
$conn = DB::select('select 2 + 2');
$start_settings['db_conn'] = true;
$start_settings['db_name'] = DB::connection()->getDatabaseName();
$start_settings['db_error'] = null;
} catch (\PDOException $e) {
$start_settings['db_conn'] = false;
$start_settings['db_name'] = config('database.connections.mysql.database');
$start_settings['db_error'] = $e->getMessage();
}
$protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === true ? 'https://' : 'http://';
$pageURL = $protocol;
if ($_SERVER["SERVER_PORT"] != "80") {
$main_page = $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
$pageURL .= $main_page.$_SERVER["REQUEST_URI"];
} else {
$main_page = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$pageURL .= $main_page;
}
$start_settings['env_location'] = $pageURL.'../.env';
if (config('app.url').'/setup'!=$pageURL) {
$start_settings['url_valid']= false;
} else {
$start_settings['url_valid']= true;
}
$start_settings['url_config']= config('app.url');
$start_settings['real_url']= $pageURL;
$exposed_env = @file_get_contents($main_page.'/.env');
if ($exposed_env) {
$start_settings['env_exposed'] = true;
} else {
$start_settings['env_exposed'] = false;
}
if (\App::Environment('production') && (config('app.debug')==true)) {
$start_settings['debug_exposed'] = true;
} else {
$start_settings['debug_exposed'] = false;
}
$environment = app()->environment();
if ($environment!='production') {
$start_settings['env'] = $environment;
$start_settings['prod'] = false;
} else {
$start_settings['env'] = $environment;
$start_settings['prod'] = true;
}
$owner = posix_getpwuid(fileowner($_SERVER["SCRIPT_FILENAME"]));
$start_settings['owner'] = $owner['name'];
if (($start_settings['owner']=='root') || ($start_settings['owner']=='0') || ($start_settings['owner']=='root')) {
$start_settings['owner_is_admin'] = true;
} else {
$start_settings['owner_is_admin'] = false;
}
if ((is_writable(storage_path()))
&& (is_writable(storage_path().'/framework'))
&& (is_writable(storage_path().'/framework/cache'))
&& (is_writable(storage_path().'/framework/sessions'))
&& (is_writable(storage_path().'/framework/views'))
&& (is_writable(storage_path().'/logs'))
) {
$start_settings['writable'] = true;
} else {
$start_settings['writable'] = false;
}
$start_settings['gd'] = extension_loaded('gd');
return View::make('setup/index')
->with('step', 1)
->with('start_settings', $start_settings)
->with('section', 'Pre-Flight Check');
}
/**
* Test the email configuration
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return Redirect
*/
public function ajaxTestEmail()
{
try {
Mail::send('emails.test', [], function ($m) {
$m->to(config('mail.from.address'), config('mail.from.name'));
$m->subject('Test Email from Snipe-IT');
});
return 'success';
} catch (Exception $e) {
return 'error';
}
}
/**
* Save the first admin user from Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return Redirect
*/
public function postSaveFirstAdmin(SetupUserRequest $request)
{
$user = new \App\Models\User;
$user->first_name = $data['first_name']= e(Input::get('first_name'));
$user->last_name = e(Input::get('last_name'));
$user->email = $data['email'] = e(Input::get('email'));
$user->activated = 1;
$user->username = $data['username'] = e(Input::get('username'));
$user->password = bcrypt(Input::get('password'));
$data['password'] = Input::get('password');
$settings = new \App\Models\Setting;
$settings->site_name = e(Input::get('site_name'));
$settings->alert_email = e(Input::get('email'));
$settings->alerts_enabled = 1;
$settings->brand = 1;
$settings->default_currency = 'USD';
$settings->user_id = 1;
if ((!$user->isValid('initial')) && (!$settings->isValid('initial'))) {
return Redirect::back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());
} else {
$user->save();
$settings->save();
if (Input::get('email_creds')=='1') {
Mail::send(['text' => 'emails.firstadmin'], $data, function ($m) use ($data) {
$m->to($data['email'], $data['first_name']);
$m->subject('Your Snipe-IT credentials');
});
}
return redirect()->route('setup.done');
}
}
/**
* Return the admin user creation form in Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return View
*/
public function getSetupUser()
{
return View::make('setup/user')
->with('step', 3)
->with('section', 'Create a User');
}
/**
* Return the view that tells the user that the Setup is done.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return View
*/
public function getSetupDone()
{
return View::make('setup/done')
->with('step', 4)
->with('section', 'Done!');
}
/**
* Migrate the database tables, and return the output
* to a view for Setup
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v3.0]
* @return View
*/
public function getSetupMigrate()
{
Artisan::call('migrate', ['--force' => true]);
$output = Artisan::output();
return View::make('setup/migrate')
->with('output', $output)
->with('step', 2)
->with('section', 'Create Database Tables');
}
/**
* Return a view that shows some of the key settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return View
*/
public function getIndex()
{
// Grab all the settings
$settings = Setting::all();
// Show the page
return View::make('settings/index', compact('settings'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return View
*/
public function getEdit()
{
$setting = Setting::first();
$is_gd_installed = extension_loaded('gd');
return View::make('settings/edit', compact('setting'))->with('is_gd_installed', $is_gd_installed);
}
/**
* Validate and process settings edit form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.0]
* @return Redirect
*/
public function postEdit(SettingRequest $request)
{
// Check if the asset exists
if (is_null($setting = Setting::find(1))) {
// Redirect to the asset management page with error
return Redirect::to('admin')->with('error', Lang::get('admin/settings/message.update.error'));
}
if (Input::get('clear_logo')=='1') {
$setting->logo = null;
} elseif (Input::file('logo_img')) {
if (!config('app.lock_passwords')) {
$image = Input::file('logo_img');
$file_name = "logo.".$image->getClientOriginalExtension();
$path = public_path('uploads/'.$file_name);
Image::make($image->getRealPath())->resize(null, 40, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->save($path);
$setting->logo = $file_name;
}
}
$setting->id = '1';
if (config('app.lock_passwords')==false) {
$setting->site_name = e(Input::get('site_name'));
$setting->brand = e(Input::get('brand'));
$setting->custom_css = e(Input::get('custom_css'));
}
if (Input::get('per_page')!='') {
$setting->per_page = e(Input::get('per_page'));
} else {
$setting->per_page = 200;
}
$setting->locale = e(Input::get('locale', 'en'));
$setting->qr_code = e(Input::get('qr_code', '0'));
$setting->barcode_type = e(Input::get('barcode_type'));
$setting->load_remote = e(Input::get('load_remote', '0'));
$setting->default_currency = e(Input::get('default_currency', '$'));
$setting->qr_text = e(Input::get('qr_text'));
$setting->auto_increment_prefix = e(Input::get('auto_increment_prefix'));
$setting->auto_increment_assets = e(Input::get('auto_increment_assets', '0'));
$setting->labels_per_page = e(Input::get('labels_per_page'));
$setting->labels_width = e(Input::get('labels_width'));
$setting->labels_height = e(Input::get('labels_height'));
$setting->labels_pmargin_left = e(Input::get('labels_pmargin_left'));
$setting->labels_pmargin_right = e(Input::get('labels_pmargin_right'));
$setting->labels_pmargin_top = e(Input::get('labels_pmargin_top'));
$setting->labels_pmargin_bottom = e(Input::get('labels_pmargin_bottom'));
$setting->labels_display_bgutter = e(Input::get('labels_display_bgutter'));
$setting->labels_display_sgutter = e(Input::get('labels_display_sgutter'));
$setting->labels_fontsize = e(Input::get('labels_fontsize'));
$setting->labels_pagewidth = e(Input::get('labels_pagewidth'));
$setting->labels_pageheight = e(Input::get('labels_pageheight'));
if (Input::has('labels_display_name')) {
$setting->labels_display_name = 1;
} else {
$setting->labels_display_name = 0;
}
if (Input::has('labels_display_serial')) {
$setting->labels_display_serial = 1;
} else {
$setting->labels_display_serial = 0;
}
if (Input::has('labels_display_tag')) {
$setting->labels_display_tag = 1;
} else {
$setting->labels_display_tag = 0;
}
$alert_email = rtrim(Input::get('alert_email'), ',');
$alert_email = trim(Input::get('alert_email'));
$setting->alert_email = e($alert_email);
$setting->alerts_enabled = e(Input::get('alerts_enabled', '0'));
$setting->header_color = e(Input::get('header_color'));
$setting->default_eula_text = e(Input::get('default_eula_text'));
$setting->slack_endpoint = e(Input::get('slack_endpoint'));
$setting->slack_channel = e(Input::get('slack_channel'));
$setting->slack_botname = e(Input::get('slack_botname'));
$setting->ldap_enabled = Input::get('ldap_enabled', '0');
$setting->ldap_server = Input::get('ldap_server');
$setting->ldap_server_cert_ignore = e(Input::get('ldap_server_cert_ignore', false));
$setting->ldap_uname = Input::get('ldap_uname');
if (Input::has('ldap_pword')) {
$setting->ldap_pword = Crypt::encrypt(Input::get('ldap_pword'));
}
$setting->ldap_basedn = e(Input::get('ldap_basedn'));
$setting->ldap_filter = Input::get('ldap_filter');
$setting->ldap_username_field = Input::get('ldap_username_field');
$setting->ldap_lname_field = Input::get('ldap_lname_field');
$setting->ldap_fname_field = Input::get('ldap_fname_field');
$setting->ldap_auth_filter_query = Input::get('ldap_auth_filter_query');
$setting->ldap_version = Input::get('ldap_version');
$setting->ldap_active_flag = Input::get('ldap_active_flag');
$setting->ldap_emp_num = Input::get('ldap_emp_num');
$setting->ldap_email = Input::get('ldap_email');
// If validation fails, we'll exit the operation now.
if ($setting->save()) {
return Redirect::to("admin/settings/app")->with('success', Lang::get('admin/settings/message.update.success'));
} else {
return Redirect::back()->withInput()->withErrors($setting->getErrors());
}
// Redirect to the setting management page
return Redirect::to("admin/settings/app/edit")->with('error', Lang::get('admin/settings/message.update.error'));
}
/**
* Show the listing of backups
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.8]
* @return View
*/
public function getBackups()
{
$path = storage_path().'/app/'.config('laravel-backup.destination.path');
$files = array();
if ($handle = opendir($path)) {
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
clearstatcache();
if (substr(strrchr($entry, '.'), 1)=='zip') {
$files[] = array(
'filename' => $entry,
'filesize' => Setting::fileSizeConvert(filesize($path.'/'.$entry)),
'modified' => filemtime($path.'/'.$entry)
);
}
}
closedir($handle);
$files = array_reverse($files);
}
return View::make('settings/backups', compact('path', 'files'));
}
/**
* Process the backup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.8]
* @return Redirect
*/
public function postBackups()
{
if (!config('app.lock_passwords')) {
Artisan::call('backup:run');
return Redirect::to("admin/settings/backups")->with('success', Lang::get('admin/settings/message.backup.generated'));
} else {
return Redirect::to("admin/settings/backups")->with('error', Lang::get('general.feature_disabled'));
}
}
/**
* Download the backup file
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.8]
* @return Redirect
*/
public function downloadFile($filename = null)
{
if (!config('app.lock_passwords')) {
$path = storage_path().'/app/'.config('laravel-backup.destination.path');
$file = $path.'/'.$filename;
if (file_exists($file)) {
return Response::download($file);
} else {
// Redirect to the backup page
return Redirect::route('settings/backups')->with('error', Lang::get('admin/settings/message.backup.file_not_found'));
}
} else {
// Redirect to the backup page
return Redirect::route('settings/backups')->with('error', Lang::get('general.feature_disabled'));
}
}
/**
* Delete the backup file
*
* @author [A. Gianotto] [<snipe@snipe.net>]
* @since [v1.8]
* @return View
*/
public function deleteFile($filename = null)
{
if (!config('app.lock_passwords')) {
$file = config('backup::path').'/'.$filename;
if (file_exists($file)) {
unlink($file);
return Redirect::route('settings/backups')->with('success', Lang::get('admin/settings/message.backup.file_deleted'));
} else {
return Redirect::route('settings/backups')->with('error', Lang::get('admin/settings/message.backup.file_not_found'));
}
} else {
return Redirect::route('settings/backups')->with('error', Lang::get('general.feature_disabled'));
}
}
}

View file

@ -0,0 +1,263 @@
<?php
namespace App\Http\Controllers;
use Input;
use Lang;
use App\Models\Statuslabel;
use Redirect;
use DB;
use App\Models\Setting;
use Str;
use View;
use App\Helpers\Helper;
use Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
class StatuslabelsController extends Controller
{
/**
* Show a list of all the statuslabels.
*
* @return View
*/
public function getIndex()
{
// Show the page
return View::make('statuslabels/index', compact('statuslabels'));
}
/**
* Statuslabel create.
*
* @return View
*/
public function getCreate()
{
// Show the page
$statuslabel = new Statuslabel;
$use_statuslabel_type = $statuslabel->getStatuslabelType();
$statuslabel_types = Helper::statusTypeList();
return View::make('statuslabels/edit', compact('statuslabel_types', 'statuslabel'))->with('use_statuslabel_type', $use_statuslabel_type);
}
/**
* Statuslabel create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// create a new model instance
$statuslabel = new Statuslabel();
$statustype = Statuslabel::getStatuslabelTypesForDB(Input::get('statuslabel_types'));
// Save the Statuslabel data
$statuslabel->name = e(Input::get('name'));
$statuslabel->user_id = Auth::user()->id;
$statuslabel->notes = e(Input::get('notes'));
$statuslabel->deployable = $statustype['deployable'];
$statuslabel->pending = $statustype['pending'];
$statuslabel->archived = $statustype['archived'];
// Was the asset created?
if ($statuslabel->save()) {
// Redirect to the new Statuslabel page
return Redirect::to("admin/settings/statuslabels")->with('success', Lang::get('admin/statuslabels/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($statuslabel->getErrors());
}
public function store()
{
// create a new model instance
$statuslabel = new Statuslabel();
$statustype = Statuslabel::getStatuslabelTypesForDB(Input::get('modal-statuslabel_types'));
// attempt validation
if ($statuslabel->validate($new)) {
// Save the Statuslabel data
$statuslabel->name = e(Input::get('name'));
$statuslabel->user_id = Auth::user()->id;
$statuslabel->notes = '';
$statuslabel->deployable = $statustype['deployable'];
$statuslabel->pending = $statustype['pending'];
$statuslabel->archived = $statustype['archived'];
// Was the asset created?
if ($statuslabel->save()) {
// Redirect to the new Statuslabel page
return JsonResponse::create($statuslabel);
} else {
return JsonResponse::create(["error" => "Couldn't save Statuslabel"], 500);
}
} else {
// failure
$errors = $statuslabel->getErrors();
return JsonResponse::create(["error" => "Failed validation: ".print_r($errors->all('<li>:message</li>'), true)], 500);
}
}
/**
* Statuslabel update.
*
* @param int $statuslabelId
* @return View
*/
public function getEdit($statuslabelId = null)
{
// Check if the Statuslabel exists
if (is_null($statuslabel = Statuslabel::find($statuslabelId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/statuslabels')->with('error', Lang::get('admin/statuslabels/message.does_not_exist'));
}
$use_statuslabel_type = $statuslabel->getStatuslabelType();
$statuslabel_types = array('' => Lang::get('admin/hardware/form.select_statustype')) + array('undeployable' => Lang::get('admin/hardware/general.undeployable')) + array('pending' => Lang::get('admin/hardware/general.pending')) + array('archived' => Lang::get('admin/hardware/general.archived')) + array('deployable' => Lang::get('admin/hardware/general.deployable'));
return View::make('statuslabels/edit', compact('statuslabel', 'statuslabel_types'))->with('use_statuslabel_type', $use_statuslabel_type);
}
/**
* Statuslabel update form processing page.
*
* @param int $statuslabelId
* @return Redirect
*/
public function postEdit($statuslabelId = null)
{
// Check if the Statuslabel exists
if (is_null($statuslabel = Statuslabel::find($statuslabelId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/statuslabels')->with('error', Lang::get('admin/statuslabels/message.does_not_exist'));
}
// Update the Statuslabel data
$statustype = Statuslabel::getStatuslabelTypesForDB(Input::get('statuslabel_types'));
$statuslabel->name = e(Input::get('name'));
$statuslabel->notes = e(Input::get('notes'));
$statuslabel->deployable = $statustype['deployable'];
$statuslabel->pending = $statustype['pending'];
$statuslabel->archived = $statustype['archived'];
// Was the asset created?
if ($statuslabel->save()) {
// Redirect to the saved Statuslabel page
return Redirect::to("admin/settings/statuslabels/")->with('success', Lang::get('admin/statuslabels/message.update.success'));
} else {
return Redirect::back()->withInput()->withErrors($statuslabel->getErrors());
}
// Redirect to the Statuslabel management page
return Redirect::to("admin/settings/statuslabels/$statuslabelId/edit")->with('error', Lang::get('admin/statuslabels/message.update.error'));
}
/**
* Delete the given Statuslabel.
*
* @param int $statuslabelId
* @return Redirect
*/
public function getDelete($statuslabelId)
{
// Check if the Statuslabel exists
if (is_null($statuslabel = Statuslabel::find($statuslabelId))) {
// Redirect to the blogs management page
return Redirect::to('admin/settings/statuslabels')->with('error', Lang::get('admin/statuslabels/message.not_found'));
}
if ($statuslabel->has_assets() > 0) {
// Redirect to the asset management page
return Redirect::to('admin/settings/statuslabels')->with('error', Lang::get('admin/statuslabels/message.assoc_users'));
} else {
$statuslabel->delete();
// Redirect to the statuslabels management page
return Redirect::to('admin/settings/statuslabels')->with('success', Lang::get('admin/statuslabels/message.delete.success'));
}
}
public function getDatatable()
{
$statuslabels = Statuslabel::select(array('id','name','deployable','pending','archived'))
->whereNull('deleted_at');
if (Input::has('search')) {
$statuslabels = $statuslabels->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$statuslabels->orderBy($sort, $order);
$statuslabelsCount = $statuslabels->count();
$statuslabels = $statuslabels->skip($offset)->take($limit)->get();
$rows = array();
foreach ($statuslabels as $statuslabel) {
if ($statuslabel->deployable == 1) {
$label_type = Lang::get('admin/statuslabels/table.deployable');
} elseif ($statuslabel->pending == 1) {
$label_type = Lang::get('admin/statuslabels/table.pending');
} elseif ($statuslabel->archived == 1) {
$label_type = Lang::get('admin/statuslabels/table.archived');
} else {
$label_type = Lang::get('admin/statuslabels/table.undeployable');
}
$actions = '<a href="'.route('update/statuslabel', $statuslabel->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/statuslabel', $statuslabel->id).'" data-content="'.Lang::get('admin/statuslabels/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($statuslabel->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
$rows[] = array(
'id' => $statuslabel->id,
'type' => $label_type,
'name' => e($statuslabel->name),
'actions' => $actions
);
}
$data = array('total' => $statuslabelsCount, 'rows' => $rows);
return $data;
}
}

View file

@ -0,0 +1,290 @@
<?php
namespace App\Http\Controllers;
use Image;
use App\Models\AssetMaintenance;
use Input;
use Lang;
use App\Models\Supplier;
use Redirect;
use App\Models\Setting;
use Str;
use View;
use Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
class SuppliersController extends Controller
{
/**
* Show a list of all suppliers
*
* @return View
*/
public function getIndex()
{
// Grab all the suppliers
$suppliers = Supplier::orderBy('created_at', 'DESC')->get();
// Show the page
return View::make('suppliers/index', compact('suppliers'));
}
/**
* Supplier create.
*
* @return View
*/
public function getCreate()
{
return View::make('suppliers/edit')->with('supplier', new Supplier);
}
/**
* Supplier create form processing.
*
* @return Redirect
*/
public function postCreate()
{
// get the POST data
$new = Input::all();
// Create a new supplier
$supplier = new Supplier;
// Save the location data
$supplier->name = e(Input::get('name'));
$supplier->address = e(Input::get('address'));
$supplier->address2 = e(Input::get('address2'));
$supplier->city = e(Input::get('city'));
$supplier->state = e(Input::get('state'));
$supplier->country = e(Input::get('country'));
$supplier->zip = e(Input::get('zip'));
$supplier->contact = e(Input::get('contact'));
$supplier->phone = e(Input::get('phone'));
$supplier->fax = e(Input::get('fax'));
$supplier->email = e(Input::get('email'));
$supplier->notes = e(Input::get('notes'));
$supplier->url = $supplier->addhttp(e(Input::get('url')));
$supplier->user_id = Auth::user()->id;
if (Input::file('image')) {
$image = Input::file('image');
$file_name = str_random(25).".".$image->getClientOriginalExtension();
$path = public_path('uploads/suppliers/'.$file_name);
Image::make($image->getRealPath())->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->save($path);
$supplier->image = $file_name;
}
// Was it created?
if ($supplier->save()) {
// Redirect to the new supplier page
return Redirect::to("admin/settings/suppliers")->with('success', Lang::get('admin/suppliers/message.create.success'));
}
return Redirect::back()->withInput()->withErrors($supplier->getErrors());
}
public function store()
{
$supplier=new Supplier;
$supplier->name=$new['name'];
$supplier->user_id = Auth::user()->id;
if ($supplier->save()) {
return JsonResponse::create($supplier);
}
return JsonResponse::create(["error" => "Failed validation: ".print_r($supplier->getErrors(), true)], 500);
return JsonResponse::create(["error" => "Couldn't save Supplier"]);
}
/**
* Supplier update.
*
* @param int $supplierId
* @return View
*/
public function getEdit($supplierId = null)
{
// Check if the supplier exists
if (is_null($supplier = Supplier::find($supplierId))) {
// Redirect to the supplier page
return Redirect::to('admin/settings/suppliers')->with('error', Lang::get('admin/suppliers/message.does_not_exist'));
}
// Show the page
return View::make('suppliers/edit', compact('supplier'));
}
/**
* Supplier update form processing page.
*
* @param int $supplierId
* @return Redirect
*/
public function postEdit($supplierId = null)
{
// Check if the supplier exists
if (is_null($supplier = Supplier::find($supplierId))) {
// Redirect to the supplier page
return Redirect::to('admin/settings/suppliers')->with('error', Lang::get('admin/suppliers/message.does_not_exist'));
}
// Save the data
$supplier->name = e(Input::get('name'));
$supplier->address = e(Input::get('address'));
$supplier->address2 = e(Input::get('address2'));
$supplier->city = e(Input::get('city'));
$supplier->state = e(Input::get('state'));
$supplier->country = e(Input::get('country'));
$supplier->zip = e(Input::get('zip'));
$supplier->contact = e(Input::get('contact'));
$supplier->phone = e(Input::get('phone'));
$supplier->fax = e(Input::get('fax'));
$supplier->email = e(Input::get('email'));
$supplier->url = $supplier->addhttp(e(Input::get('url')));
$supplier->notes = e(Input::get('notes'));
if (Input::file('image')) {
$image = Input::file('image');
$file_name = str_random(25).".".$image->getClientOriginalExtension();
$path = public_path('uploads/suppliers/'.$file_name);
Image::make($image->getRealPath())->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->save($path);
$supplier->image = $file_name;
}
if (Input::get('image_delete') == 1 && Input::file('image') == "") {
$supplier->image = null;
}
if ($supplier->save()) {
return Redirect::to("admin/settings/suppliers")->with('success', Lang::get('admin/suppliers/message.update.success'));
}
return Redirect::back()->withInput()->withErrors($supplier->getErrors());
}
/**
* Delete the given supplier.
*
* @param int $supplierId
* @return Redirect
*/
public function getDelete($supplierId)
{
// Check if the supplier exists
if (is_null($supplier = Supplier::find($supplierId))) {
// Redirect to the suppliers page
return Redirect::to('admin/settings/suppliers')->with('error', Lang::get('admin/suppliers/message.not_found'));
}
if ($supplier->num_assets() > 0) {
// Redirect to the asset management page
return Redirect::to('admin/settings/suppliers')->with('error', Lang::get('admin/suppliers/message.assoc_users'));
} else {
// Delete the supplier
$supplier->delete();
// Redirect to the suppliers management page
return Redirect::to('admin/settings/suppliers')->with('success', Lang::get('admin/suppliers/message.delete.success'));
}
}
/**
* Get the asset information to present to the supplier view page
*
* @param int $assetId
* @return View
**/
public function getView($supplierId = null)
{
$supplier = Supplier::find($supplierId);
if (isset($supplier->id)) {
return View::make('suppliers/view', compact('supplier'));
} else {
// Prepare the error message
$error = Lang::get('admin/suppliers/message.does_not_exist', compact('id'));
// Redirect to the user management page
return Redirect::route('suppliers')->with('error', $error);
}
}
public function getDatatable()
{
$suppliers = Supplier::select(array('id','name','address','address2','city','state','country','fax', 'phone','email','contact'))
->whereNull('deleted_at');
if (Input::has('search')) {
$suppliers = $suppliers->TextSearch(e(Input::get('search')));
}
if (Input::has('offset')) {
$offset = e(Input::get('offset'));
} else {
$offset = 0;
}
if (Input::has('limit')) {
$limit = e(Input::get('limit'));
} else {
$limit = 50;
}
$allowed_columns = ['id','name','address','phone','contact','fax','email'];
$order = Input::get('order') === 'asc' ? 'asc' : 'desc';
$sort = in_array(Input::get('sort'), $allowed_columns) ? Input::get('sort') : 'created_at';
$suppliers->orderBy($sort, $order);
$suppliersCount = $suppliers->count();
$suppliers = $suppliers->skip($offset)->take($limit)->get();
$rows = array();
foreach ($suppliers as $supplier) {
$actions = '<a href="'.route('update/supplier', $supplier->id).'" class="btn btn-warning btn-sm" style="margin-right:5px;"><i class="fa fa-pencil icon-white"></i></a><a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="'.route('delete/supplier', $supplier->id).'" data-content="'.Lang::get('admin/suppliers/message.delete.confirm').'" data-title="'.Lang::get('general.delete').' '.htmlspecialchars($supplier->name).'?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a>';
$rows[] = array(
'id' => $supplier->id,
'name' => (string)link_to('admin/settings/suppliers/'.$supplier->id.'/view', $supplier->name),
'contact' => $supplier->contact,
'address' => $supplier->address.' '.$supplier->address2.' '.$supplier->city.' '.$supplier->state.' '.$supplier->country,
'phone' => $supplier->phone,
'fax' => $supplier->fax,
'email' => ($supplier->email!='') ? '<a href="mailto:'.$supplier->email.'">'.$supplier->email.'</a>' : '',
'assets' => $supplier->num_assets(),
'licenses' => $supplier->num_licenses(),
'actions' => $actions
);
}
$data = array('total' => $suppliersCount, 'rows' => $rows);
return $data;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,264 @@
<?php
namespace App\Http\Controllers;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\Company;
use App\Models\Consumable;
use App\Models\Location;
use App\Models\Setting;
use App\Models\User;
use Auth;
use Config;
use DB;
use Input;
use Lang;
use Mail;
use Redirect;
use Slack;
use Validator;
use View;
class ViewAssetsController extends Controller
{
/**
* Redirect to the profile page.
*
* @return Redirect
*/
public function getIndex()
{
$user = User::with('assets', 'assets.model', 'consumables', 'accessories', 'licenses', 'userloc')->withTrashed()->find(Auth::user()->id);
$userlog = $user->userlog->load('assetlog', 'consumablelog', 'assetlog.model', 'licenselog', 'accessorylog', 'userlog', 'adminlog');
if (isset($user->id)) {
return View::make('account/view-assets', compact('user', 'userlog'));
} else {
// Prepare the error message
$error = Lang::get('admin/users/message.user_not_found', compact('id'));
// Redirect to the user management page
return Redirect::route('users')->with('error', $error);
}
}
public function getRequestableIndex()
{
$assets = Asset::with('model', 'defaultLoc')->Hardware()->RequestableAssets()->get();
return View::make('account/requestable-assets', compact('user', 'assets'));
}
public function getRequestAsset($assetId = null)
{
$user = Auth::user();
// Check if the asset exists and is requestable
if (is_null($asset = Asset::RequestableAssets()->find($assetId))) {
// Redirect to the asset management page
return Redirect::route('requestable-assets')->with('error', Lang::get('admin/hardware/message.does_not_exist_or_not_requestable'));
} elseif (!Company::isCurrentUserHasAccess($asset)) {
return Redirect::route('requestable-assets')->with('error', Lang::get('general.insufficient_permissions'));
} else {
$logaction = new Actionlog();
$logaction->asset_id = $data['asset_id'] = $asset->id;
$logaction->asset_type = $data['asset_type'] = 'hardware';
$logaction->created_at = $data['requested_date'] = date("Y-m-d h:i:s");
if ($user->location_id) {
$logaction->location_id = $user->location_id;
}
$logaction->user_id = $data['user_id'] = Auth::user()->id;
$log = $logaction->logaction('requested');
$data['requested_by'] = $user->fullName();
$data['asset_name'] = $asset->showAssetName();
$settings = Setting::getSettings();
if (($settings->alert_email!='') && ($settings->alerts_enabled=='1') && (!config('app.lock_passwords'))) {
Mail::send('emails.asset-requested', $data, function ($m) use ($user, $settings) {
$m->to(explode(',', $settings->alert_email), $settings->site_name);
$m->subject('Asset Requested');
});
}
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'REQUESTED:',
'value' => strtoupper($logaction->asset_type).' asset <'.config('app.url').'/hardware/'.$asset->id.'/view'.'|'.$asset->showAssetName().'> requested by <'.config('app.url').'/hardware/'.$asset->id.'/view'.'|'.Auth::user()->fullName().'>.'
]
]
])->send('Asset Requested');
} catch (Exception $e) {
}
}
return Redirect::route('requestable-assets')->with('success')->with('success', Lang::get('admin/hardware/message.requests.success'));
}
}
// Get the acceptance screen
public function getAcceptAsset($logID = null)
{
if (is_null($findlog = Actionlog::find($logID))) {
// Redirect to the asset management page
return Redirect::to('account')->with('error', Lang::get('admin/hardware/message.does_not_exist'));
}
$user = Auth::user();
if ($user->id != $findlog->checkedout_to) {
return Redirect::to('account/view-assets')->with('error', Lang::get('admin/users/message.error.incorrect_user_accepted'));
}
// Asset
if (($findlog->asset_id!='') && ($findlog->asset_type=='hardware')) {
$item = Asset::find($findlog->asset_id);
// software
} elseif (($findlog->asset_id!='') && ($findlog->asset_type=='software')) {
$item = License::find($findlog->asset_id);
// accessories
} elseif ($findlog->accessory_id!='') {
$item = Accessory::find($findlog->accessory_id);
}
// Check if the asset exists
if (is_null($item)) {
// Redirect to the asset management page
return Redirect::to('account')->with('error', Lang::get('admin/hardware/message.does_not_exist'));
} elseif (!Company::isCurrentUserHasAccess($item)) {
return Redirect::route('requestable-assets')->with('error', Lang::get('general.insufficient_permissions'));
} else {
return View::make('account/accept-asset', compact('item'))->with('findlog', $findlog);
}
}
// Save the acceptance
public function postAcceptAsset($logID = null)
{
// Check if the asset exists
if (is_null($findlog = Actionlog::find($logID))) {
// Redirect to the asset management page
return Redirect::to('account/view-assets')->with('error', Lang::get('admin/hardware/message.does_not_exist'));
}
// NOTE: make sure the global scope is applied
$is_unauthorized = is_null(Actionlog::where('id', '=', $logID)->first());
if ($is_unauthorized) {
return Redirect::route('requestable-assets')->with('error', Lang::get('general.insufficient_permissions'));
}
if ($findlog->accepted_id!='') {
// Redirect to the asset management page
return Redirect::to('account/view-assets')->with('error', Lang::get('admin/users/message.error.asset_already_accepted'));
}
if (!Input::has('asset_acceptance')) {
return Redirect::to('account/view-assets')->with('error', Lang::get('admin/users/message.error.accept_or_decline'));
}
$user = Auth::user();
if ($user->id != $findlog->checkedout_to) {
return Redirect::to('account/view-assets')->with('error', Lang::get('admin/users/message.error.incorrect_user_accepted'));
}
$logaction = new Actionlog();
if (Input::get('asset_acceptance')=='accepted') {
$logaction_msg = 'accepted';
$accepted="accepted";
$return_msg = Lang::get('admin/users/message.accepted');
} else {
$logaction_msg = 'declined';
$accepted="rejected";
$return_msg = Lang::get('admin/users/message.declined');
}
// Asset
if (($findlog->asset_id!='') && ($findlog->asset_type=='hardware')) {
$logaction->asset_id = $findlog->asset_id;
$logaction->accessory_id = null;
$logaction->asset_type = 'hardware';
if (Input::get('asset_acceptance')!='accepted') {
DB::table('assets')
->where('id', $findlog->asset_id)
->update(array('assigned_to' => null));
}
// software
} elseif (($findlog->asset_id!='') && ($findlog->asset_type=='software')) {
$logaction->asset_id = $findlog->asset_id;
$logaction->accessory_id = null;
$logaction->asset_type = 'software';
// accessories
} elseif ($findlog->accessory_id!='') {
$logaction->asset_id = null;
$logaction->accessory_id = $findlog->accessory_id;
$logaction->asset_type = 'accessory';
}
$logaction->checkedout_to = $findlog->checkedout_to;
$logaction->note = e(Input::get('note'));
$logaction->user_id = $user->id;
$logaction->accepted_at = date("Y-m-d h:i:s");
$log = $logaction->logaction($logaction_msg);
$update_checkout = DB::table('asset_logs')
->where('id', $findlog->id)
->update(array('accepted_id' => $logaction->id));
$affected_asset=$logaction->assetlog;
$affected_asset->accepted=$accepted;
$affected_asset->save();
if ($update_checkout) {
return Redirect::to('account/view-assets')->with('success', $return_msg);
} else {
return Redirect::to('account/view-assets')->with('error', 'Something went wrong ');
}
}
}

59
app/Http/Kernel.php Normal file
View file

@ -0,0 +1,59 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\FrameGuard::class,
\App\Http\Middleware\XssProtectHeader::class,
\App\Http\Middleware\NosniffGuard::class,
\App\Http\Middleware\CheckForSetup::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\CheckLocale::class,
\App\Http\Middleware\CheckForSetup::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'authorize' => \App\Http\Middleware\CheckPermissions::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View file

@ -0,0 +1,47 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Config;
use Route;
class CheckForSetup
{
public function handle($request, Closure $next, $guard = null)
{
try {
$usercount = \App\Models\User::withTrashed()->count();
if (($usercount > 0) && (Route::is('setup*'))) {
return redirect(config('app.url'));
} else {
return $next($request);
}
} catch (\Exception $e) {
return $next($request);
}
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Config;
use Route;
class CheckLocale
{
/**
* Handle the locale for the user, default to settings otherwise
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
// User's preference
if (($request->user()) && ($request->user()->locale)) {
\App::setLocale($request->user()->locale);
// App setting preference
} elseif (\App\Models\Setting::getSettings()->locale!='') {
\App::setLocale(\App\Models\Setting::getSettings()->locale);
// Default app setting
} else {
\App::setLocale(config('app.locale'));
}
return $next($request);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Config;
use Route;
class CheckPermissions
{
/**
* Handle the ACLs for permissions.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $section = null, $guard = null)
{
if (($request->user()->hasAccess($section)) || ($request->user()->isSuperUser())) {
return $next($request);
}
return response()->view('layouts/basic', [
'content' => view('errors/403')
]);
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Closure;
class FrameGuard
{
/**
* Handle the given request and get the response.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);
return $response;
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Closure;
class NosniffGuard
{
/**
* Handle the given request and get the response.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff', false);
return $response;
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
];
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Closure;
class XssProtectHeader
{
/**
* Handle the given request and get the response.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-XSS-Protection', '1');
return $response;
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class AssetCheckinRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
];
}
public function response(array $errors)
{
return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class AssetCheckoutRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"assigned_to" => 'required',
];
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class AssetFileRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'file.*' => 'required|mimes:png,gif,jpg,jpeg,doc,docx,pdf,txt,zip,rar|max:2000'
];
}
public function response(array $errors)
{
return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag);
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class AssetRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
'name' => 'min:2|max:255',
'model_id' => 'required|integer',
'status_id' => 'required|integer',
'company_id' => 'integer',
'warranty_months' => 'integer|min:0|max:240',
'physical' => 'integer',
'checkout_date' => 'date|max:10|min:10',
'checkin_date' => 'date|max:10|min:10',
'supplier_id' => 'integer',
'asset_tag' => 'required|min:2|max:255|unique:assets,asset_tag,NULL,deleted_at',
'status' => 'integer',
];
$model = \App\Models\AssetModel::find($this->request->get('model_id'));
if ($model->fieldset)
{
$rules += $model->fieldset->validation_rules();
}
return $rules;
}
public function response(array $errors)
{
return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ComponentCheckoutRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"asset_id" => 'required',
"assigned_qty" => 'required|numeric|min:1',
];
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
protected $rules = [];
public function rules()
{
return $this->rules;
}
public function response(array $errors)
{
$this->session->flash('errorMessages', $errors);
return $this->redirector->back()->withErrors($errors)->withInput();
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class SettingRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"brand" => 'required|min:1|numeric',
"qr_text" => 'min:1|max:31',
"logo_img" => 'mimes:jpeg,bmp,png,gif',
"custom_css" => 'string',
"alert_email" => 'email_array',
"slack_endpoint" => 'url',
"default_currency" => 'required',
"locale" => 'required',
"slack_channel" => 'regex:/(?<!\w)#\w+/',
"slack_botname" => 'string',
'labels_per_page' => 'numeric',
'labels_width' => 'numeric',
'labels_height' => 'numeric',
'labels_pmargin_left' => 'numeric',
'labels_pmargin_right' => 'numeric',
'labels_pmargin_top' => 'numeric',
'labels_pmargin_bottom' => 'numeric',
'labels_display_bgutter' => 'numeric',
'labels_display_sgutter' => 'numeric',
'labels_fontsize' => 'numeric|min:5',
'labels_pagewidth' => 'numeric',
'labels_pageheight' => 'numeric',
"ldap_server" => 'sometimes|required_if:ldap_enabled,1|url',
"ldap_uname" => 'sometimes|required_if:ldap_enabled,1',
"ldap_basedn" => 'sometimes|required_if:ldap_enabled,1',
"ldap_filter" => 'sometimes|required_if:ldap_enabled,1',
"ldap_username_field" => 'sometimes|required_if:ldap_enabled,1',
"ldap_lname_field" => 'sometimes|required_if:ldap_enabled,1',
"ldap_auth_filter_query" => 'sometimes|required_if:ldap_enabled,1',
"ldap_version" => 'sometimes|required_if:ldap_enabled,1',
];
}
public function response(array $errors)
{
return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag);
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class SetupUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'first_name' => 'required|string|min:1',
'last_name' => 'required|string|min:1',
'location_id' => 'numeric',
'username' => 'required|string|min:2|unique:users,username,NULL,deleted_at',
'email' => 'email|unique:users,email',
'password' => 'required|min:6',
'password_confirm' => 'required|min:6|same:password',
'company_id' => 'integer',
];
}
public function response(array $errors)
{
return $this->redirector->back()->withInput()->withErrors($errors, $this->errorBag);
}
}

849
app/Http/routes.php Executable file
View file

@ -0,0 +1,849 @@
<?php
/*
|--------------------------------------------------------------------------
| Admin API Routes
|--------------------------------------------------------------------------
*/
Route::group([ 'prefix' => 'api', 'middleware' => 'auth' ], function () {
/*---Hardware API---*/
Route::group([ 'prefix' => 'hardware','middleware' => ['web','auth','authorize:hardware']], function () {
Route::get('list/{status?}', [ 'as' => 'api.hardware.list', 'uses' => 'AssetsController@getDatatable' ]);
Route::post('import', 'AssetsController@postAPIImportUpload');
});
/*---Status Label API---*/
Route::group([ 'prefix' => 'statuslabels' ,'middleware' => ['web','auth','authorize:admin']], function () {
Route::resource('/', 'StatuslabelsController');
Route::get('{statuslabelId}/deployable', function ($statuslabelId) {
$statuslabel = \App\Models\Statuslabel::find($statuslabelId);
if (( $statuslabel->deployable == '1' ) && ( $statuslabel->pending != '1' )
&& ( $statuslabel->archived != '1' )
) {
return '1';
} else {
return '0';
}
});
Route::get('list', [ 'as' => 'api.statuslabels.list', 'uses' => 'StatuslabelsController@getDatatable' ]);
});
/*---Accessories API---*/
Route::group([ 'prefix' => 'accessories' ], function () {
Route::get('list', [ 'as' => 'api.accessories.list', 'uses' => 'AccessoriesController@getDatatable' ]);
Route::get(
'{accessoryID}/view',
[ 'as' => 'api.accessories.view', 'uses' => 'AccessoriesController@getDataView' ]
);
});
/*---Consumables API---*/
Route::group(array('prefix'=>'consumables'), function () {
Route::get('list', array('as'=>'api.consumables.list', 'uses'=>'ConsumablesController@getDatatable'));
Route::get('{consumableID}/view', array('as'=>'api.consumables.view', 'uses'=>'ConsumablesController@getDataView'));
});
/*---Components API---*/
Route::group(array('prefix'=>'components'), function () {
Route::get('list', array('as'=>'api.components.list', 'uses'=>'ComponentsController@getDatatable'));
Route::get('{componentID}/view', array('as'=>'api.components.view', 'uses'=>'ComponentsController@getDataView'));
});
/*---Locations API---*/
Route::group(array('prefix'=>'locations'), function () {
Route::get('list', array('as'=>'api.locations.list', 'uses'=>'LocationsController@getDatatable'));
Route::get('{locationID}/view', array('as'=>'api.locations.view', 'uses'=>'LocationsController@getDataView'));
Route::get('{locationID}/users', array('as'=>'api.locations.viewusers', 'uses'=>'LocationsController@getDataViewUsers'));
Route::get('{locationID}/assets', array('as'=>'api.locations.viewassets', 'uses'=>'LocationsController@getDataViewAssets'));
});
/*---Depreciations API---*/
Route::group(array('prefix'=>'depreciations'), function () {
Route::get('list', array('as'=>'api.depreciations.list', 'uses'=>'DepreciationsController@getDatatable'));
Route::get('{$depreciationID}/view', array('as'=>'api.depreciations.view', 'uses'=>'DepreciationsController@getDataView'));
});
/*---Manufacturers API---*/
Route::group(array('prefix'=>'manufacturers'), function () {
Route::get('list', array('as'=>'api.manufacturers.list', 'uses'=>'ManufacturersController@getDatatable'));
Route::get('{manufacturerID}/view', array('as'=>'api.manufacturers.view', 'uses'=>'ManufacturersController@getDataView'));
});
/*---Suppliers API---*/
Route::group(array('prefix'=>'suppliers'), function () {
Route::get('list', array('as'=>'api.suppliers.list', 'uses'=>'SuppliersController@getDatatable'));
});
/*---Users API---*/
Route::group([ 'prefix' => 'users' ], function () {
Route::post('/', [ 'as' => 'api.users.store', 'uses' => 'UsersController@store' ]);
Route::get('list/{status?}', [ 'as' => 'api.users.list', 'uses' => 'UsersController@getDatatable' ]);
Route::get('{userId}/assets', [ 'as' => 'api.users.assetlist', 'uses' => 'UsersController@getAssetList' ]);
Route::post('{userId}/upload', [ 'as' => 'upload/user', 'uses' => 'UsersController@postUpload' ]);
});
/*---Groups API---*/
Route::group([ 'prefix' => 'groups' ], function () {
Route::get('list', [ 'as' => 'api.groups.list', 'uses' => 'GroupsController@getDatatable' ]);
});
/*---Licenses API---*/
Route::group([ 'prefix' => 'licenses' ], function () {
Route::get('list', [ 'as' => 'api.licenses.list', 'uses' => 'LicensesController@getDatatable' ]);
});
/*---Locations API---*/
Route::group([ 'prefix' => 'locations' ], function () {
Route::resource('/', 'LocationsController');
Route::get('{locationID}/check', function ($locationID) {
$location = \App\Models\Location::find($locationID);
return $location;
});
});
/*---Improvements API---*/
Route::group([ 'prefix' => 'asset_maintenances' ], function () {
Route::get(
'list',
[ 'as' => 'api.asset_maintenances.list', 'uses' => 'AssetMaintenancesController@getDatatable' ]
);
});
/*---Models API---*/
Route::group([ 'prefix' => 'models' ], function () {
Route::resource('/', 'AssetModelsController');
Route::get('list/{status?}', [ 'as' => 'api.models.list', 'uses' => 'AssetModelsController@getDatatable' ]);
Route::get('{modelID}/view', [ 'as' => 'api.models.view', 'uses' => 'AssetModelsController@getDataView' ]);
});
/*--- Categories API---*/
Route::group([ 'prefix' => 'categories' ], function () {
Route::get('list', [ 'as' => 'api.categories.list', 'uses' => 'CategoriesController@getDatatable' ]);
Route::get(
'{categoryID}/view',
[ 'as' => 'api.categories.view', 'uses' => 'CategoriesController@getDataView' ]
);
});
/*-- Suppliers API (mostly for creating new ones in-line while creating an asset) --*/
Route::group([ 'prefix' => 'suppliers' ], function () {
Route::resource('/', 'SuppliersController');
});
});
/*
|--------------------------------------------------------------------------
| Asset Routes
|--------------------------------------------------------------------------
|
| Register all the asset routes.
|
*/
Route::group(
[ 'prefix' => 'hardware',
'middleware' => ['web',
'auth',
'authorize:hardware']],
function () {
Route::get('create/{model?}', [
'as' => 'create/hardware',
'uses' => 'AssetsController@getCreate'
]);
Route::post('create', [
'as' => 'savenew/hardware',
'uses' => 'AssetsController@postCreate'
]);
Route::get('{assetId}/edit', [
'as' => 'update/hardware',
'uses' => 'AssetsController@getEdit'
]);
Route::get('{assetId}/clone', [ 'as' => 'clone/hardware', 'uses' => 'AssetsController@getClone' ]);
Route::post('{assetId}/clone', 'AssetsController@postCreate');
Route::get('{assetId}/delete', [ 'as' => 'delete/hardware', 'uses' => 'AssetsController@getDelete' ]);
Route::get(
'{assetId}/checkout',
[ 'as' => 'checkout/hardware', 'uses' => 'AssetsController@getCheckout' ]
);
Route::post('{assetId}/checkout', 'AssetsController@postCheckout');
Route::get(
'{assetId}/checkin/{backto?}',
[ 'as' => 'checkin/hardware', 'uses' => 'AssetsController@getCheckin' ]
);
Route::post('{assetId}/checkin/{backto?}', 'AssetsController@postCheckin');
Route::get('{assetId}/view', [ 'as' => 'view/hardware', 'uses' => 'AssetsController@getView' ]);
Route::get('{assetId}/qr-view', [ 'as' => 'qr-view/hardware', 'uses' => 'AssetsController@getView' ]);
Route::get('{assetId}/qr_code', [ 'as' => 'qr_code/hardware', 'uses' => 'AssetsController@getQrCode' ]);
Route::get('{assetId}/restore', [ 'as' => 'restore/hardware', 'uses' => 'AssetsController@getRestore' ]);
Route::post('{assetId}/upload', [ 'as' => 'upload/asset', 'uses' => 'AssetsController@postUpload' ]);
Route::get(
'{assetId}/deletefile/{fileId}',
[ 'as' => 'delete/assetfile', 'uses' => 'AssetsController@getDeleteFile' ]
);
Route::get(
'{assetId}/showfile/{fileId}',
[ 'as' => 'show/assetfile', 'uses' => 'AssetsController@displayFile' ]
);
Route::get(
'import/delete-import/{filename}',
[ 'as' => 'assets/import/delete-file', 'uses' => 'AssetsController@getDeleteImportFile' ]
);
Route::get(
'import/process/{filename}',
[ 'as' => 'assets/import/process-file', 'uses' => 'AssetsController@getProcessImportFile' ]
);
Route::get(
'import',
[ 'as' => 'assets/import', 'uses' => 'AssetsController@getImportUpload' ]
);
Route::post('{assetId}/edit', 'AssetsController@postEdit');
Route::post(
'bulkedit',
[
'as' => 'hardware/bulkedit',
'uses' => 'AssetsController@postBulkEdit'
]
);
Route::post(
'bulkdelete',
[
'as' => 'hardware/bulkdelete',
'uses' => 'AssetsController@postBulkDelete'
]
);
Route::post(
'bulksave',
[
'as' => 'hardware/bulksave',
'uses' => 'AssetsController@postBulkSave'
]
);
# Asset Model Management
Route::group([ 'prefix' => 'models', 'middleware' => 'auth' ], function () {
Route::get('/', [ 'as' => 'models', 'uses' => 'AssetModelsController@getIndex' ]);
Route::get('create', [ 'as' => 'create/model', 'uses' => 'AssetModelsController@getCreate' ]);
Route::post('create', 'AssetModelsController@postCreate');
Route::get('{modelId}/edit', [ 'as' => 'update/model', 'uses' => 'AssetModelsController@getEdit' ]);
Route::post('{modelId}/edit', 'AssetModelsController@postEdit');
Route::get('{modelId}/clone', [ 'as' => 'clone/model', 'uses' => 'AssetModelsController@getClone' ]);
Route::post('{modelId}/clone', 'AssetModelsController@postCreate');
Route::get('{modelId}/delete', [ 'as' => 'delete/model', 'uses' => 'AssetModelsController@getDelete' ]);
Route::get('{modelId}/view', [ 'as' => 'view/model', 'uses' => 'AssetModelsController@getView' ]);
Route::get('{modelID}/restore', [ 'as' => 'restore/model', 'uses' => 'AssetModelsController@getRestore' ]);
Route::get('{modelId}/custom_fields', ['as' => 'custom_fields/model','uses' => 'AssetModelsController@getCustomFields']);
});
Route::get('/', [
'as' => 'hardware',
'uses' => 'AssetsController@getIndex'
]);
}
);
/*
|--------------------------------------------------------------------------
| Admin Routes
|--------------------------------------------------------------------------
|
| Register all the admin routes.
|
*/
Route::group([ 'prefix' => 'admin','middleware' => ['web','auth','authorize:admin']], function () {
# Licenses
Route::group([ 'prefix' => 'licenses' ], function () {
Route::get('create', [ 'as' => 'create/licenses', 'uses' => 'LicensesController@getCreate' ]);
Route::post('create', 'LicensesController@postCreate');
Route::get('{licenseId}/edit', [ 'as' => 'update/license', 'uses' => 'LicensesController@getEdit' ]);
Route::post('{licenseId}/edit', 'LicensesController@postEdit');
Route::get('{licenseId}/clone', [ 'as' => 'clone/license', 'uses' => 'LicensesController@getClone' ]);
Route::post('{licenseId}/clone', 'LicensesController@postCreate');
Route::get('{licenseId}/delete', [ 'as' => 'delete/license', 'uses' => 'LicensesController@getDelete' ]);
Route::get(
'{licenseId}/freecheckout',
[ 'as' => 'freecheckout/license', 'uses' => 'LicensesController@getFreeLicense' ]
);
Route::get(
'{licenseId}/checkout',
[ 'as' => 'checkout/license', 'uses' => 'LicensesController@getCheckout' ]
);
Route::post('{licenseId}/checkout', 'LicensesController@postCheckout');
Route::get(
'{licenseId}/checkin/{backto?}',
[ 'as' => 'checkin/license', 'uses' => 'LicensesController@getCheckin' ]
);
Route::post('{licenseId}/checkin/{backto?}', 'LicensesController@postCheckin');
Route::get('{licenseId}/view', [ 'as' => 'view/license', 'uses' => 'LicensesController@getView' ]);
Route::post(
'{licenseId}/upload',
[ 'as' => 'upload/license', 'uses' => 'LicensesController@postUpload' ]
);
Route::get(
'{licenseId}/deletefile/{fileId}',
[ 'as' => 'delete/licensefile', 'uses' => 'LicensesController@getDeleteFile' ]
);
Route::get(
'{licenseId}/showfile/{fileId}',
[ 'as' => 'show/licensefile', 'uses' => 'LicensesController@displayFile' ]
);
Route::get('/', [ 'as' => 'licenses', 'uses' => 'LicensesController@getIndex' ]);
});
# Asset Maintenances
Route::group([ 'prefix' => 'asset_maintenances' ], function () {
Route::get(
'create/{assetId?}',
[ 'as' => 'create/asset_maintenances', 'uses' => 'AssetMaintenancesController@getCreate' ]
);
Route::post('create/{assetId?}', 'AssetMaintenancesController@postCreate');
Route::get('/', [ 'as' => 'asset_maintenances', 'uses' => 'AssetMaintenancesController@getIndex' ]);
Route::get(
'{assetMaintenanceId}/edit',
[ 'as' => 'update/asset_maintenance', 'uses' => 'AssetMaintenancesController@getEdit' ]
);
Route::post('{assetMaintenanceId}/edit', 'AssetMaintenancesController@postEdit');
Route::get(
'{assetMaintenanceId}/delete',
[ 'as' => 'delete/asset_maintenance', 'uses' => 'AssetMaintenancesController@getDelete' ]
);
Route::get(
'{assetMaintenanceId}/view',
[ 'as' => 'view/asset_maintenance', 'uses' => 'AssetMaintenancesController@getView' ]
);
});
# Accessories
Route::group([ 'prefix' => 'accessories' ], function () {
Route::get('create', [ 'as' => 'create/accessory', 'uses' => 'AccessoriesController@getCreate' ]);
Route::post('create', 'AccessoriesController@postCreate');
Route::get(
'{accessoryID}/edit',
[ 'as' => 'update/accessory', 'uses' => 'AccessoriesController@getEdit' ]
);
Route::post('{accessoryID}/edit', 'AccessoriesController@postEdit');
Route::get(
'{accessoryID}/delete',
[ 'as' => 'delete/accessory', 'uses' => 'AccessoriesController@getDelete' ]
);
Route::get('{accessoryID}/view', [ 'as' => 'view/accessory', 'uses' => 'AccessoriesController@getView' ]);
Route::get(
'{accessoryID}/checkout',
[ 'as' => 'checkout/accessory', 'uses' => 'AccessoriesController@getCheckout' ]
);
Route::post('{accessoryID}/checkout', 'AccessoriesController@postCheckout');
Route::get(
'{accessoryID}/checkin/{backto?}',
[ 'as' => 'checkin/accessory', 'uses' => 'AccessoriesController@getCheckin' ]
);
Route::post('{accessoryID}/checkin/{backto?}', 'AccessoriesController@postCheckin');
Route::get('/', [ 'as' => 'accessories', 'uses' => 'AccessoriesController@getIndex' ]);
});
# Consumables
Route::group([ 'prefix' => 'consumables' ], function () {
Route::get('create', [ 'as' => 'create/consumable', 'uses' => 'ConsumablesController@getCreate' ]);
Route::post('create', 'ConsumablesController@postCreate');
Route::get(
'{consumableID}/edit',
[ 'as' => 'update/consumable', 'uses' => 'ConsumablesController@getEdit' ]
);
Route::post('{consumableID}/edit', 'ConsumablesController@postEdit');
Route::get(
'{consumableID}/delete',
[ 'as' => 'delete/consumable', 'uses' => 'ConsumablesController@getDelete' ]
);
Route::get(
'{consumableID}/view',
[ 'as' => 'view/consumable', 'uses' => 'ConsumablesController@getView' ]
);
Route::get(
'{consumableID}/checkout',
[ 'as' => 'checkout/consumable', 'uses' => 'ConsumablesController@getCheckout' ]
);
Route::post('{consumableID}/checkout', 'ConsumablesController@postCheckout');
Route::get('/', [ 'as' => 'consumables', 'uses' => 'ConsumablesController@getIndex' ]);
});
# Components
Route::group([ 'prefix' => 'components' ], function () {
Route::get('create', [ 'as' => 'create/component', 'uses' => 'ComponentsController@getCreate' ]);
Route::post('create', 'ComponentsController@postCreate');
Route::get(
'{componentID}/edit',
[ 'as' => 'update/component', 'uses' => 'ComponentsController@getEdit' ]
);
Route::post('{componentID}/edit', 'ComponentsController@postEdit');
Route::get(
'{componentID}/delete',
[ 'as' => 'delete/component', 'uses' => 'ComponentsController@getDelete' ]
);
Route::get(
'{componentID}/view',
[ 'as' => 'view/component', 'uses' => 'ComponentsController@getView' ]
);
Route::get(
'{componentID}/checkout',
[ 'as' => 'checkout/component', 'uses' => 'ComponentsController@getCheckout' ]
);
Route::post('{componentID}/checkout', 'ComponentsController@postCheckout');
Route::post('bulk', [ 'as' => 'component/bulk-form', 'uses' => 'ComponentsController@postBulk' ]);
Route::post('bulksave', [ 'as' => 'component/bulk-save', 'uses' => 'ComponentsController@postBulkSave' ]);
Route::get('/', [ 'as' => 'components', 'uses' => 'ComponentsController@getIndex' ]);
});
# Admin Settings Routes (for categories, maufactureres, etc)
Route::group([ 'prefix' => 'settings'], function () {
# Settings
Route::group([ 'prefix' => 'app' ], function () {
Route::get('/', [ 'as' => 'app', 'uses' => 'SettingsController@getIndex' ]);
Route::get('edit', [ 'as' => 'edit/settings', 'uses' => 'SettingsController@getEdit' ]);
Route::post('edit', 'SettingsController@postEdit');
});
# Settings
Route::group([ 'prefix' => 'backups', 'middleware' => 'auth' ], function () {
Route::get('download/{filename}', [
'as' => 'settings/download-file',
'uses' => 'SettingsController@downloadFile' ]);
Route::get('delete/{filename}', [
'as' => 'settings/delete-file',
'uses' => 'SettingsController@deleteFile' ]);
Route::post('/', [
'as' => 'settings/backups',
'uses' => 'SettingsController@postBackups'
]);
Route::get('/', [ 'as' => 'settings/backups', 'uses' => 'SettingsController@getBackups' ]);
});
# Companies
Route::group([ 'prefix' => 'companies' ], function () {
Route::get('{companyId}/edit', ['as' => 'update/company', 'uses' => 'CompaniesController@getEdit']);
Route::get('create', ['as' => 'create/company', 'uses' => 'CompaniesController@getCreate']);
Route::get('/', ['as' => 'companies', 'uses' => 'CompaniesController@getIndex']);
Route::post('{companyId}/delete', ['as' => 'delete/company', 'uses' => 'CompaniesController@postDelete']);
Route::post('{companyId}/edit', 'CompaniesController@postEdit');
Route::post('create', 'CompaniesController@postCreate');
});
# Manufacturers
Route::group([ 'prefix' => 'manufacturers' ], function () {
Route::get('/', [ 'as' => 'manufacturers', 'uses' => 'ManufacturersController@getIndex' ]);
Route::get(
'create',
[ 'as' => 'create/manufacturer', 'uses' => 'ManufacturersController@getCreate' ]
);
Route::post('create', 'ManufacturersController@postCreate');
Route::get(
'{manufacturerId}/edit',
[ 'as' => 'update/manufacturer', 'uses' => 'ManufacturersController@getEdit' ]
);
Route::post('{manufacturerId}/edit', 'ManufacturersController@postEdit');
Route::get(
'{manufacturerId}/delete',
[ 'as' => 'delete/manufacturer', 'uses' => 'ManufacturersController@getDelete' ]
);
Route::get(
'{manufacturerId}/view',
[ 'as' => 'view/manufacturer', 'uses' => 'ManufacturersController@getView' ]
);
});
# Suppliers
Route::group([ 'prefix' => 'suppliers' ], function () {
Route::get('/', [ 'as' => 'suppliers', 'uses' => 'SuppliersController@getIndex' ]);
Route::get('create', [ 'as' => 'create/supplier', 'uses' => 'SuppliersController@getCreate' ]);
Route::post('create', 'SuppliersController@postCreate');
Route::get(
'{supplierId}/edit',
[ 'as' => 'update/supplier', 'uses' => 'SuppliersController@getEdit' ]
);
Route::post('{supplierId}/edit', 'SuppliersController@postEdit');
Route::get(
'{supplierId}/delete',
[ 'as' => 'delete/supplier', 'uses' => 'SuppliersController@getDelete' ]
);
Route::get('{supplierId}/view', [ 'as' => 'view/supplier', 'uses' => 'SuppliersController@getView' ]);
});
# Categories
Route::group([ 'prefix' => 'categories' ], function () {
Route::get('create', [ 'as' => 'create/category', 'uses' => 'CategoriesController@getCreate' ]);
Route::post('create', 'CategoriesController@postCreate');
Route::get(
'{categoryId}/edit',
[ 'as' => 'update/category', 'uses' => 'CategoriesController@getEdit' ]
);
Route::post('{categoryId}/edit', 'CategoriesController@postEdit');
Route::get(
'{categoryId}/delete',
[ 'as' => 'delete/category', 'uses' => 'CategoriesController@getDelete' ]
);
Route::get(
'{categoryId}/view',
[ 'as' => 'view/category', 'uses' => 'CategoriesController@getView' ]
);
Route::get('/', [ 'as' => 'categories', 'uses' => 'CategoriesController@getIndex' ]);
});
# Depreciations
Route::group([ 'prefix' => 'depreciations' ], function () {
Route::get('/', [ 'as' => 'depreciations', 'uses' => 'DepreciationsController@getIndex' ]);
Route::get(
'create',
[ 'as' => 'create/depreciations', 'uses' => 'DepreciationsController@getCreate' ]
);
Route::post('create', 'DepreciationsController@postCreate');
Route::get(
'{depreciationId}/edit',
[ 'as' => 'update/depreciations', 'uses' => 'DepreciationsController@getEdit' ]
);
Route::post('{depreciationId}/edit', 'DepreciationsController@postEdit');
Route::get(
'{depreciationId}/delete',
[ 'as' => 'delete/depreciations', 'uses' => 'DepreciationsController@getDelete' ]
);
});
# Locations
Route::group([ 'prefix' => 'locations' ], function () {
Route::get('/', [ 'as' => 'locations', 'uses' => 'LocationsController@getIndex' ]);
Route::get('create', [ 'as' => 'create/location', 'uses' => 'LocationsController@getCreate' ]);
Route::post('create', 'LocationsController@postCreate');
Route::get(
'{locationId}/edit',
[ 'as' => 'update/location', 'uses' => 'LocationsController@getEdit' ]
);
Route::post('{locationId}/edit', 'LocationsController@postEdit');
Route::get('{locationId}/view', 'LocationsController@getView');
Route::get(
'{locationId}/delete',
[ 'as' => 'delete/location', 'uses' => 'LocationsController@getDelete' ]
);
});
# Status Labels
Route::group([ 'prefix' => 'statuslabels' ], function () {
Route::get('/', [ 'as' => 'statuslabels', 'uses' => 'StatuslabelsController@getIndex' ]);
Route::get('create', [ 'as' => 'create/statuslabel', 'uses' => 'StatuslabelsController@getCreate' ]);
Route::post('create', 'StatuslabelsController@postCreate');
Route::get(
'{statuslabelId}/edit',
[ 'as' => 'update/statuslabel', 'uses' => 'StatuslabelsController@getEdit' ]
);
Route::post('{statuslabelId}/edit', 'StatuslabelsController@postEdit');
Route::get(
'{statuslabelId}/delete',
[ 'as' => 'delete/statuslabel', 'uses' => 'StatuslabelsController@getDelete' ]
);
});
});
# Custom fields support
Route::get('custom_fields/create-field', ['uses' =>'CustomFieldsController@createField','as' => 'admin.custom_fields.create-field']);
Route::post('custom_fields/create-field', ['uses' => 'CustomFieldsController@storeField','as' => 'admin.custom_fields.store-field']);
Route::post('custom_fields/{id}/associate', ['uses' => 'CustomFieldsController@associate','as' => 'admin.custom_fields.associate']);
Route::match(['DELETE'], 'custom_fields/delete-field/{id}', ['uses' => 'CustomFieldsController@deleteField','as' => 'admin.custom_fields.delete-field']);
Route::resource('custom_fields', 'CustomFieldsController');
# User Management
Route::group([ 'prefix' => 'users' ], function () {
Route::get('ldap', ['as' => 'ldap/user', 'uses' => 'UsersController@getLDAP' ]);
Route::post('ldap', 'UsersController@postLDAP');
Route::get('create', [ 'as' => 'create/user', 'uses' => 'UsersController@getCreate' ]);
Route::post('create', 'UsersController@postCreate');
Route::get('import', [ 'as' => 'import/user', 'uses' => 'UsersController@getImport' ]);
Route::post('import', 'UsersController@postImport');
Route::get('{userId}/edit', [ 'as' => 'update/user', 'uses' => 'UsersController@getEdit' ]);
Route::post('{userId}/edit', 'UsersController@postEdit');
Route::get('{userId}/clone', [ 'as' => 'clone/user', 'uses' => 'UsersController@getClone' ]);
Route::post('{userId}/clone', 'UsersController@postCreate');
Route::get('{userId}/delete', [ 'as' => 'delete/user', 'uses' => 'UsersController@getDelete' ]);
Route::get('{userId}/restore', [ 'as' => 'restore/user', 'uses' => 'UsersController@getRestore' ]);
Route::get('{userId}/view', [ 'as' => 'view/user', 'uses' => 'UsersController@getView' ]);
Route::get('{userId}/unsuspend', [ 'as' => 'unsuspend/user', 'uses' => 'UsersController@getUnsuspend' ]);
Route::get(
'{userId}/deletefile/{fileId}',
[ 'as' => 'delete/userfile', 'uses' => 'UsersController@getDeleteFile' ]
);
Route::get(
'{userId}/showfile/{fileId}',
[ 'as' => 'show/userfile', 'uses' => 'UsersController@displayFile' ]
);
Route::post(
'bulkedit',
[
'as' => 'users/bulkedit',
'uses' => 'UsersController@postBulkEdit'
]
);
Route::post(
'bulksave',
[
'as' => 'users/bulksave',
'uses' => 'UsersController@postBulkSave'
]
);
Route::get('/', [ 'as' => 'users', 'uses' => 'UsersController@getIndex' ]);
});
# Group Management
Route::group([ 'prefix' => 'groups' ], function () {
Route::get('/', [ 'as' => 'groups', 'uses' => 'GroupsController@getIndex' ]);
Route::get('create', [ 'as' => 'create/group', 'uses' => 'GroupsController@getCreate' ]);
Route::post('create', 'GroupsController@postCreate');
Route::get('{groupId}/edit', [ 'as' => 'update/group', 'uses' => 'GroupsController@getEdit' ]);
Route::post('{groupId}/edit', 'GroupsController@postEdit');
Route::get('{groupId}/delete', [ 'as' => 'delete/group', 'uses' => 'GroupsController@getDelete' ]);
Route::get('{groupId}/restore', [ 'as' => 'restore/group', 'uses' => 'GroupsController@getRestore' ]);
Route::get('{groupId}/view', [ 'as' => 'view/group', 'uses' => 'GroupsController@getView' ]);
});
# Dashboard
Route::get('/', [ 'as' => 'admin', 'uses' => 'DashboardController@getIndex' ]);
});
/*
|--------------------------------------------------------------------------
| Account Routes
|--------------------------------------------------------------------------
|
|
|
*/
Route::group([ 'prefix' => 'account', 'middleware' => 'auth' ], function () {
# Profile
Route::get('profile', [ 'as' => 'profile', 'uses' => 'ProfileController@getIndex' ]);
Route::post('profile', 'ProfileController@postIndex');
# Change Password
Route::get('change-password', [ 'as' => 'change-password', 'uses' => 'ChangePasswordController@getIndex' ]);
Route::post('change-password', 'ChangePasswordController@postIndex');
# View Assets
Route::get('view-assets', [ 'as' => 'view-assets', 'uses' => 'ViewAssetsController@getIndex' ]);
# Change Email
Route::get('change-email', [ 'as' => 'change-email', 'uses' => 'ChangeEmailController@getIndex' ]);
Route::post('change-email', 'ChangeEmailController@postIndex');
# Accept Asset
Route::get(
'accept-asset/{logID}',
[ 'as' => 'account/accept-assets', 'uses' => 'ViewAssetsController@getAcceptAsset' ]
);
Route::post(
'accept-asset/{logID}',
[ 'as' => 'account/asset-accepted', 'uses' => 'ViewAssetsController@postAcceptAsset' ]
);
# Profile
Route::get(
'requestable-assets',
[ 'as' => 'requestable-assets', 'uses' => 'ViewAssetsController@getRequestableIndex' ]
);
Route::get(
'request-asset/{assetId}',
[ 'as' => 'account/request-asset', 'uses' => 'ViewAssetsController@getRequestAsset' ]
);
# Account Dashboard
Route::get('/', [ 'as' => 'account', 'uses' => 'ProfileController@getDashboard' ]);
});
Route::group(['middleware' => ['web','auth','authorize:reports']], function () {
Route::get(
'reports/depreciation',
[ 'as' => 'reports/depreciation', 'uses' => 'ReportsController@getDeprecationReport' ]
);
Route::get(
'reports/export/depreciation',
[ 'as' => 'reports/export/depreciation', 'uses' => 'ReportsController@exportDeprecationReport' ]
);
Route::get(
'reports/asset_maintenances',
[ 'as' => 'reports/asset_maintenances', 'uses' => 'ReportsController@getAssetMaintenancesReport' ]
);
Route::get(
'reports/export/asset_maintenances',
[
'as' => 'reports/export/asset_maintenances',
'uses' => 'ReportsController@exportAssetMaintenancesReport'
]
);
Route::get(
'reports/licenses',
[ 'as' => 'reports/licenses', 'uses' => 'ReportsController@getLicenseReport' ]
);
Route::get(
'reports/export/licenses',
[ 'as' => 'reports/export/licenses', 'uses' => 'ReportsController@exportLicenseReport' ]
);
Route::get('reports/assets', [ 'as' => 'reports/assets', 'uses' => 'ReportsController@getAssetsReport' ]);
Route::get(
'reports/export/assets',
[ 'as' => 'reports/export/assets', 'uses' => 'ReportsController@exportAssetReport' ]
);
Route::get('reports/accessories', [ 'as' => 'reports/accessories', 'uses' => 'ReportsController@getAccessoryReport' ]);
Route::get(
'reports/export/accessories',
[ 'as' => 'reports/export/accessories', 'uses' => 'ReportsController@exportAccessoryReport' ]
);
Route::get('reports/custom', [ 'as' => 'reports/custom', 'uses' => 'ReportsController@getCustomReport' ]);
Route::post('reports/custom', 'ReportsController@postCustom');
Route::get(
'reports/activity',
[ 'as' => 'reports/activity', 'uses' => 'ReportsController@getActivityReport' ]
);
Route::get(
'reports/unaccepted_assets',
[ 'as' => 'reports/unaccepted_assets', 'uses' => 'ReportsController@getAssetAcceptanceReport' ]
);
Route::get(
'reports/export/unaccepted_assets',
[ 'as' => 'reports/export/unaccepted_assets', 'uses' => 'ReportsController@exportAssetAcceptanceReport' ]
);
});
/*
|--------------------------------------------------------------------------
| Setup Routes
|--------------------------------------------------------------------------
|
|
|
*/
Route::group([ 'prefix' => 'setup' ], function () {
Route::get(
'user',
[
'middleware' => 'web',
'as' => 'setup.user',
'uses' => 'SettingsController@getSetupUser' ]
);
Route::post(
'user',
[
'middleware' => 'web',
'as' => 'setup.user.save',
'uses' => 'SettingsController@postSaveFirstAdmin' ]
);
Route::get(
'migrate',
[
'middleware' => 'web',
'as' => 'setup.migrate',
'uses' => 'SettingsController@getSetupMigrate' ]
);
Route::get(
'done',
[
'middleware' => 'web',
'as' => 'setup.done',
'uses' => 'SettingsController@getSetupDone' ]
);
Route::get(
'mailtest',
[
'middleware' => 'web',
'as' => 'setup.mailtest',
'uses' => 'SettingsController@ajaxTestEmail' ]
);
Route::get(
'/',
[
'middleware' => 'web',
'as' => 'setup',
'uses' => 'SettingsController@getSetupIndex' ]
);
});
Route::get(
'/',
[
'as' => 'home',
'middleware' => 'auth',
'uses' => 'DashboardController@getIndex' ]
);
Route::group(['middleware' => 'web'], function () {
Route::auth();
});
Route::get('home', function () {
return redirect('/');
});

21
app/Jobs/Job.php Normal file
View file

@ -0,0 +1,21 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
abstract class Job
{
/*
|--------------------------------------------------------------------------
| Queueable Jobs
|--------------------------------------------------------------------------
|
| This job base class provides a central location to place any logic that
| is shared across all of your jobs. The trait included with the class
| provides access to the "onQueue" and "delay" queue helper methods.
|
*/
use Queueable;
}

0
app/Listeners/.gitkeep Normal file
View file

188
app/Models/Accessory.php Executable file
View file

@ -0,0 +1,188 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Accessory extends Model
{
use SoftDeletes;
use CompanyableTrait;
protected $dates = ['deleted_at'];
protected $table = 'accessories';
/**
* Accessory validation rules
*/
public $rules = array(
'name' => 'required|min:3|max:255',
'qty' => 'required|integer|min:1',
'category_id' => 'required|integer',
'company_id' => 'integer',
'min_amt' => 'integer|min:1',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','qty','category_id'];
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
public function location()
{
return $this->belongsTo('\App\Models\Location', 'location_id');
}
public function category()
{
return $this->belongsTo('\App\Models\Category', 'category_id')->where('category_type', '=', 'accessory');
}
/**
* Get action logs for this accessory
*/
public function assetlog()
{
return $this->hasMany('\App\Models\Actionlog', 'accessory_id')->where('asset_type', '=', 'accessory')->orderBy('created_at', 'desc')->withTrashed();
}
public function users()
{
return $this->belongsToMany('\App\Models\User', 'accessories_users', 'accessory_id', 'assigned_to')->withPivot('id')->withTrashed();
}
public function hasUsers()
{
return $this->belongsToMany('\App\Models\User', 'accessories_users', 'accessory_id', 'assigned_to')->count();
}
public function checkin_email()
{
return $this->category->checkin_email;
}
public function requireAcceptance()
{
return $this->category->require_acceptance;
}
public function getEula()
{
$Parsedown = new \Parsedown();
if ($this->category->eula_text) {
return $Parsedown->text(e($this->category->eula_text));
} elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula=='1')) {
return $Parsedown->text(e(Setting::getSettings()->default_eula_text));
} else {
return null;
}
}
public function numRemaining()
{
$checkedout = $this->users->count();
$total = $this->qty;
$remaining = $total - $checkedout;
return $remaining;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
$search = explode('+', $search);
return $query->where(function ($query) use ($search) {
foreach ($search as $search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%');
})->orWhere(function ($query) use ($search) {
$query->whereHas('company', function ($query) use ($search) {
$query->where('companies.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('assetlog', function ($query) use ($search) {
$query->where('action_type', '=', 'checkout')
->where('created_at', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('location', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
})->orWhere('accessories.name', 'LIKE', '%'.$search.'%')
->orWhere('accessories.order_number', 'LIKE', '%'.$search.'%')
->orWhere('accessories.purchase_cost', 'LIKE', '%'.$search.'%')
->orWhere('accessories.purchase_date', 'LIKE', '%'.$search.'%');
}
});
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCompany($query, $order)
{
return $query->leftJoin('companies', 'accessories.company_id', '=', 'companies.id')->orderBy('companies.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCategory($query, $order)
{
return $query->leftJoin('categories', 'accessories.category_id', '=', 'categories.id')->orderBy('categories.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderLocation($query, $order)
{
return $query->leftJoin('locations', 'consumables.location_id', '=', 'locations.id')->orderBy('locations.name', $order);
}
}

164
app/Models/Actionlog.php Executable file
View file

@ -0,0 +1,164 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\SoftDeletes;
class Actionlog extends Model implements ICompanyableChild
{
use SoftDeletes;
use CompanyableChildTrait;
protected $dates = [ 'deleted_at' ];
protected $table = 'asset_logs';
public $timestamps = true;
protected $fillable = [ 'created_at', 'asset_type' ];
public function getCompanyableParents()
{
return [ 'accessorylog', 'assetlog', 'licenselog', 'consumablelog' ];
}
public function assetlog()
{
return $this->belongsTo('\App\Models\Asset', 'asset_id')
->withTrashed();
}
public function uploads()
{
return $this->belongsTo('\App\Models\Asset', 'asset_id')
->where('action_type', '=', 'uploaded')
->withTrashed();
}
public function licenselog()
{
return $this->belongsTo('\App\Models\License', 'asset_id')
->withTrashed();
}
public function accessorylog()
{
return $this->belongsTo('\App\Models\Accessory', 'accessory_id')
->withTrashed();
}
public function consumablelog()
{
return $this->belongsTo('\App\Models\Consumable', 'consumable_id')
->withTrashed();
}
public function adminlog()
{
return $this->belongsTo('\App\Models\User', 'user_id')
->withTrashed();
}
public function userlog()
{
return $this->belongsTo('\App\Models\User', 'checkedout_to')
->withTrashed();
}
public function childlogs()
{
return $this->hasMany('\App\Models\ActionLog', 'thread_id');
}
public function parentlog()
{
return $this->belongsTo('\App\Models\ActionLog', 'thread_id');
}
/**
* Check if the file exists, and if it does, force a download
**/
public function get_src()
{
$file = storage_path() . '/app/private_uploads/' . $this->filename;
return $file;
}
/**
* Get the parent category name
*/
public function logaction($actiontype)
{
$this->action_type = $actiontype;
if ($this->save()) {
return true;
} else {
return false;
}
}
/**
* getListingOfActionLogsChronologicalOrder
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getListingOfActionLogsChronologicalOrder()
{
return DB::table('asset_logs')
->select('*')
->where('action_type', '!=', 'uploaded')
->orderBy('asset_id', 'asc')
->orderBy('created_at', 'asc')
->get();
}
/**
* getLatestCheckoutActionForAssets
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function getLatestCheckoutActionForAssets()
{
return DB::table('asset_logs')
->select(DB::raw('asset_id, MAX(created_at) as last_created'))
->where('action_type', '=', 'checkout')
->groupBy('asset_id')
->get();
}
/**
* scopeCheckoutWithoutAcceptance
*
* @param $query
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function scopeCheckoutWithoutAcceptance($query)
{
return $query->where('action_type', '=', 'checkout')
->where('accepted_id', '=', null);
}
}

811
app/Models/Asset.php Normal file
View file

@ -0,0 +1,811 @@
<?php
namespace App\Models;
use App\Models\Assetlog;
use App\Models\Company;
use App\Models\Location;
use Config;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Log;
use Parsedown;
use Watson\Validating\ValidatingTrait;
use DateTime;
use App\Models\Setting;
class Asset extends Depreciable
{
use SoftDeletes;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'assets';
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
protected $rules = [
'name' => 'min:2|max:255',
'model_id' => 'required|integer',
'status_id' => 'required|integer',
'company_id' => 'integer',
'warranty_months' => 'integer|min:0|max:240',
'physical' => 'integer',
'checkout_date' => 'date|max:10|min:10',
'checkin_date' => 'date|max:10|min:10',
'supplier_id' => 'integer',
'asset_tag' => 'required|min:2|max:255|unique:assets,asset_tag,NULL,deleted_at',
'status' => 'integer',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','model_id','status_id','asset_tag'];
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
/**
* Checkout asset
*/
public function checkOutToUser($user, $admin, $checkout_at = null, $expected_checkin = null, $note = null, $name = null)
{
if ($expected_checkin) {
$this->expected_checkin = $expected_checkin ;
}
$this->last_checkout = $checkout_at;
$this->assigneduser()->associate($user);
$this->name = $name;
$settings = Setting::getSettings();
if ($this->requireAcceptance()) {
$this->accepted="pending";
}
if (!$user) {
return false;
}
if ($this->save()) {
$log_id = $this->createCheckoutLog($checkout_at, $admin, $user, $expected_checkin, $note);
if ((($this->requireAcceptance()=='1') || ($this->getEula())) && ($user->email!='')) {
$this->checkOutNotifyMail($log_id, $user, $checkout_at, $expected_checkin, $note);
}
if ($settings->slack_endpoint) {
$this->checkOutNotifySlack($settings, $admin, $note);
}
return true;
}
return false;
}
public function checkOutNotifyMail($log_id, $user, $checkout_at, $expected_checkin, $note)
{
$data['log_id'] = $log_id;
$data['eula'] = $this->getEula();
$data['first_name'] = $user->first_name;
$data['item_name'] = $this->showAssetName();
$data['checkout_date'] = $checkout_at;
$data['expected_checkin'] = $expected_checkin;
$data['item_tag'] = $this->asset_tag;
$data['note'] = $note;
$data['item_serial'] = $this->serial;
$data['require_acceptance'] = $this->requireAcceptance();
if ((($this->requireAcceptance()=='1') || ($this->getEula())) && (!config('app.lock_passwords'))) {
\Mail::send('emails.accept-asset', $data, function ($m) use ($user) {
$m->to($user->email, $user->first_name . ' ' . $user->last_name);
$m->subject('Confirm asset delivery');
});
}
}
public function checkOutNotifySlack($settings, $admin, $note = null)
{
if ($settings->slack_endpoint) {
$slack_settings = [
'username' => $settings->botname,
'channel' => $settings->slack_channel,
'link_names' => true
];
$client = new \Maknz\Slack\Client($settings->slack_endpoint, $slack_settings);
try {
$client->attach([
'color' => 'good',
'fields' => [
[
'title' => 'Checked Out:',
'value' => 'HARDWARE asset <'.config('app.url').'/hardware/'.$this->id.'/view'.'|'.$this->showAssetName().'> checked out to <'.config('app.url').'/admin/users/'.$this->assigned_to.'/view|'.$this->assigneduser->fullName().'> by <'.config('app.url').'/hardware/'.$this->id.'/view'.'|'.$admin->fullName().'>.'
],
[
'title' => 'Note:',
'value' => e($note)
],
]
])->send('Asset Checked Out');
} catch (Exception $e) {
print_r($e);
}
}
}
public function validationRules($id = '0')
{
return $this->rules;
}
public function createCheckoutLog($checkout_at = null, $admin, $user, $expected_checkin = null, $note = null)
{
$logaction = new \App\Models\Actionlog();
$logaction->asset_id = $this->id;
$logaction->checkedout_to = $this->assigned_to;
$logaction->asset_type = 'hardware';
if ($user) {
$logaction->location_id = $user->location_id;
}
$logaction->adminlog()->associate($admin);
$logaction->note = $note;
if ($checkout_at) {
$logaction->created_at = $checkout_at;
}
$log = $logaction->logaction('checkout');
return $logaction->id;
}
/**
* Set depreciation relationship
*/
public function depreciation()
{
return $this->model->belongsTo('\App\Models\Depreciation', 'depreciation_id');
}
/**
* Get depreciation attribute from associated asset model
*/
public function get_depreciation()
{
return $this->model->depreciation;
}
/**
* Get uploads for this asset
*/
public function uploads()
{
return $this->hasMany('\App\Models\Actionlog', 'asset_id')
->where('asset_type', '=', 'hardware')
->where('action_type', '=', 'uploaded')
->whereNotNull('filename')
->orderBy('created_at', 'desc');
}
public static function checkUploadIsImage($file)
{
// Check if the file is an image, so we can show a preview
$finfo = @finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$filetype = @finfo_file($finfo, $file);
finfo_close($finfo);
if (($filetype=="image/jpeg") || ($filetype=="image/jpg") || ($filetype=="image/gif")) {
return true;
}
return false;
}
public function assigneduser()
{
return $this->belongsTo('\App\Models\User', 'assigned_to')
->withTrashed();
}
/**
* Get the asset's location based on the assigned user
**/
public function assetloc()
{
if ($this->assigneduser) {
return $this->assigneduser->userloc();
} else {
return $this->belongsTo('\App\Models\Location', 'rtd_location_id');
}
}
/**
* Get the asset's location based on default RTD location
**/
public function defaultLoc()
{
return $this->belongsTo('\App\Models\Location', 'rtd_location_id');
}
/**
* Get action logs for this asset
*/
public function assetlog()
{
return $this->hasMany('\App\Models\Actionlog', 'asset_id')
->where('asset_type', '=', 'hardware')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* assetmaintenances
* Get improvements for this asset
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function assetmaintenances()
{
return $this->hasMany('\App\Models\AssetMaintenance', 'asset_id')
->orderBy('created_at', 'desc')
->withTrashed();
}
/**
* Get action logs for this asset
*/
public function adminuser()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
/**
* Get total assets
*/
public static function assetcount()
{
return Asset::where('physical', '=', '1')
->whereNull('deleted_at', 'and')
->count();
}
/**
* Get total assets not checked out
*/
public static function availassetcount()
{
return Asset::RTD()
->whereNull('deleted_at')
->count();
}
/**
* Get requestable assets
*/
public static function getRequestable()
{
return Asset::Requestable()
->whereNull('deleted_at')
->count();
}
/**
* Get total assets
*/
public function assetstatus()
{
return $this->belongsTo('\App\Models\Statuslabel', 'status_id');
}
/**
* Get name for EULA
**/
public function showAssetName()
{
if ($this->name == '') {
return $this->model->name;
} else {
return $this->name;
}
}
public function warrantee_expires()
{
$date = date_create($this->purchase_date);
date_add($date, date_interval_create_from_date_string($this->warranty_months . ' months'));
return date_format($date, 'Y-m-d');
}
public function model()
{
return $this->belongsTo('\App\Models\AssetModel', 'model_id')->withTrashed();
}
public static function getExpiringWarrantee($days = 30)
{
return Asset::where('archived', '=', '0')
->whereNotNull('warranty_months')
->whereNotNull('purchase_date')
->whereNull('deleted_at')
->whereRaw(\DB::raw('DATE_ADD(`purchase_date`,INTERVAL `warranty_months` MONTH) <= DATE(NOW() + INTERVAL '
. $days
. ' DAY) AND DATE_ADD(`purchase_date`,INTERVAL `warranty_months` MONTH) > NOW()'))
->orderBy('purchase_date', 'ASC')
->get();
}
/**
* Get the license seat information
**/
public function licenses()
{
return $this->belongsToMany('\App\Models\License', 'license_seats', 'asset_id', 'license_id');
}
public function licenseseats()
{
return $this->hasMany('\App\Models\LicenseSeat', 'asset_id');
}
public function supplier()
{
return $this->belongsTo('\App\Models\Supplier', 'supplier_id');
}
public function months_until_eol()
{
$today = date("Y-m-d");
$d1 = new DateTime($today);
$d2 = new DateTime($this->eol_date());
if ($this->eol_date() > $today) {
$interval = $d2->diff($d1);
} else {
$interval = null;
}
return $interval;
}
public function eol_date()
{
if (( $this->purchase_date ) && ( $this->model )) {
$date = date_create($this->purchase_date);
date_add($date, date_interval_create_from_date_string($this->model->eol . ' months'));
return date_format($date, 'Y-m-d');
}
}
/**
* Get auto-increment
*/
public static function autoincrement_asset()
{
$settings = \App\Models\Setting::getSettings();
if ($settings->auto_increment_assets == '1') {
$asset_tag = \DB::table('assets')
->where('physical', '=', '1')
->max('id');
return $settings->auto_increment_prefix.($asset_tag + 1);
} else {
return false;
}
}
public function checkin_email()
{
return $this->model->category->checkin_email;
}
public function requireAcceptance()
{
return $this->model->category->require_acceptance;
}
public function getEula()
{
$Parsedown = new \Parsedown();
if ($this->model->category->eula_text) {
return $Parsedown->text(e($this->model->category->eula_text));
} elseif ($this->model->category->use_default_eula == '1') {
return $Parsedown->text(e(Setting::getSettings()->default_eula_text));
} else {
return null;
}
}
/**
* -----------------------------------------------
* BEGIN QUERY SCOPES
* -----------------------------------------------
**/
/**
* Query builder scope for hardware
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeHardware($query)
{
return $query->where('physical', '=', '1');
}
/**
* Query builder scope for pending assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopePending($query)
{
return $query->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 0)
->where('pending', '=', 1)
->where('archived', '=', 0);
});
}
/**
* Query builder scope for RTD assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeRTD($query)
{
return $query->whereNULL('assigned_to')
->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 1)
->where('pending', '=', 0)
->where('archived', '=', 0);
});
}
/**
* Query builder scope for Undeployable assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeUndeployable($query)
{
return $query->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 0)
->where('pending', '=', 0)
->where('archived', '=', 0);
});
}
/**
* Query builder scope for Archived assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeArchived($query)
{
return $query->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 0)
->where('pending', '=', 0)
->where('archived', '=', 1);
});
}
/**
* Query builder scope for Deployed assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeployed($query)
{
return $query->where('assigned_to', '>', '0');
}
/**
* Query builder scope for Requestable assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeRequestableAssets($query)
{
return $query->where('requestable', '=', 1)
->whereHas('assetstatus', function ($query) {
$query->where('deployable', '=', 1)
->where('pending', '=', 0)
->where('archived', '=', 0);
});
}
/**
* Query builder scope for Deleted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
/**
* scopeInModelList
* Get all assets in the provided listing of model ids
*
* @param $query
* @param array $modelIdListing
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function scopeInModelList($query, array $modelIdListing)
{
return $query->whereIn('model_id', $modelIdListing);
}
/**
* Query builder scope to get not-yet-accepted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeNotYetAccepted($query)
{
return $query->where("accepted", "=", "pending");
}
/**
* Query builder scope to get rejected assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeRejected($query)
{
return $query->where("accepted", "=", "rejected");
}
/**
* Query builder scope to get accepted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeAccepted($query)
{
return $uery->where("accepted", "=", "accepted");
}
/**
* Query builder scope to search on text for complex Bootstrap Tables API
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
$search = explode(' OR ', $search);
return $query->where(function ($query) use ($search) {
foreach ($search as $search) {
$query->whereHas('model', function ($query) use ($search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%')
->orWhere('models.name', 'LIKE', '%'.$search.'%');
});
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('assetstatus', function ($query) use ($search) {
$query->where('status_labels.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('company', function ($query) use ($search) {
$query->where('companies.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('defaultLoc', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('assigneduser', function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->where('users.first_name', 'LIKE', '%'.$search.'%')
->orWhere('users.last_name', 'LIKE', '%'.$search.'%')
->orWhere(function ($query) use ($search) {
$query->whereHas('userloc', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
});
});
});
})->orWhere('assets.name', 'LIKE', '%'.$search.'%')
->orWhere('assets.asset_tag', 'LIKE', '%'.$search.'%')
->orWhere('assets.serial', 'LIKE', '%'.$search.'%')
->orWhere('assets.order_number', 'LIKE', '%'.$search.'%')
->orWhere('assets.notes', 'LIKE', '%'.$search.'%');
}
foreach (CustomField::all() as $field) {
$query->orWhere($field->db_column_name(), 'LIKE', "%$search%");
}
});
}
/**
* Query builder scope to order on model
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderModels($query, $order)
{
return $query->join('models', 'assets.model_id', '=', 'models.id')->orderBy('models.name', $order);
}
/**
* Query builder scope to order on assigned user
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderAssigned($query, $order)
{
return $query->join('users', 'assets.assigned_to', '=', 'users.id')->orderBy('users.first_name', $order)->orderBy('users.last_name', $order);
}
/**
* Query builder scope to order on status
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderStatus($query, $order)
{
return $query->join('status_labels', 'assets.status_id', '=', 'status_labels.id')->orderBy('status_labels.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCompany($query, $order)
{
return $query->leftJoin('companies', 'assets.company_id', '=', 'companies.id')->orderBy('companies.name', $order);
}
/**
* Query builder scope to order on category
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCategory($query, $order)
{
return $query->join('models', 'assets.model_id', '=', 'models.id')
->join('categories', 'models.category_id', '=', 'categories.id')
->orderBy('categories.name', $order);
}
/**
* Query builder scope to order on model
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
* TODO: Extend this method out for checked out assets as well. Right now it
* only checks the location name related to rtd_location_id
*/
public function scopeOrderLocation($query, $order)
{
return $query->join('locations', 'locations.id', '=', 'assets.rtd_location_id')->orderBy('locations.name', $order);
}
}

View file

@ -0,0 +1,116 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Lang;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class AssetMaintenance extends Model implements ICompanyableChild
{
use SoftDeletes;
use CompanyableChildTrait;
protected $dates = [ 'deleted_at' ];
protected $table = 'asset_maintenances';
// Declaring rules for form validation
protected $rules = [
'asset_id' => 'required|integer',
'supplier_id' => 'required|integer',
'asset_maintenance_type' => 'required',
'title' => 'required|max:100',
'is_warranty' => 'boolean',
'start_date' => 'required|date_format:Y-m-d',
'completion_date' => 'date_format:Y-m-d',
'notes' => 'string',
'cost' => 'numeric'
];
public function getCompanyableParents()
{
return [ 'asset' ];
}
/**
* getImprovementOptions
*
* @return array
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public static function getImprovementOptions()
{
return [
Lang::get('admin/asset_maintenances/general.maintenance') => Lang::get('admin/asset_maintenances/general.maintenance'),
Lang::get('admin/asset_maintenances/general.repair') => Lang::get('admin/asset_maintenances/general.repair'),
Lang::get('admin/asset_maintenances/general.upgrade') => Lang::get('admin/asset_maintenances/general.upgrade')
];
}
/**
* asset
* Get asset for this improvement
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function asset()
{
return $this->belongsTo('\App\Models\Asset', 'asset_id')
->withTrashed();
}
public function supplier()
{
return $this->belongsTo('\App\Models\Supplier', 'supplier_id')
->withTrashed();
}
/**
* -----------------------------------------------
* BEGIN QUERY SCOPES
* -----------------------------------------------
**/
/**
* Query builder scope for Deleted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('title', 'LIKE', '%'.$search.'%')
->orWhere('notes', 'LIKE', '%'.$search.'%')
->orWhere('asset_maintenance_type', 'LIKE', '%'.$search.'%')
->orWhere('cost', 'LIKE', '%'.$search.'%')
->orWhere('start_date', 'LIKE', '%'.$search.'%')
->orWhere('completion_date', 'LIKE', '%'.$search.'%');
});
}
}

149
app/Models/AssetModel.php Executable file
View file

@ -0,0 +1,149 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class AssetModel extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'models';
// Declare the rules for the model validation
protected $rules = array(
'name' => 'required|min:2|max:255',
'modelno' => 'min:1|max:255',
'category_id' => 'required|integer',
'manufacturer_id' => 'required|integer',
'eol' => 'integer:min:0|max:240',
'user_id' => 'integer',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','manufacturer_id','category_id','eol'];
public function assets()
{
return $this->hasMany('\App\Models\Asset', 'model_id');
}
public function category()
{
return $this->belongsTo('\App\Models\Category', 'category_id');
}
public function depreciation()
{
return $this->belongsTo('\App\Models\Depreciation', 'depreciation_id');
}
public function adminuser()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
public function manufacturer()
{
return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id');
}
public function fieldset()
{
return $this->belongsTo('\App\Models\CustomFieldset', 'fieldset_id');
}
public function getNote()
{
$Parsedown = new \Parsedown();
if ($this->note) {
return $Parsedown->text(e($this->note));
}
}
/**
* -----------------------------------------------
* BEGIN QUERY SCOPES
* -----------------------------------------------
**/
/**
* Query builder scope for Deleted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
/**
* scopeInCategory
* Get all models that are in the array of category ids
*
* @param $query
* @param array $categoryIdListing
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function scopeInCategory($query, array $categoryIdListing)
{
return $query->whereIn('category_id', $categoryIdListing);
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where('name', 'LIKE', "%$search%")
->orWhere('modelno', 'LIKE', "%$search%")
->orWhere(function ($query) use ($search) {
$query->whereHas('depreciation', function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
})
->orWhere(function ($query) use ($search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
})
->orWhere(function ($query) use ($search) {
$query->whereHas('manufacturer', function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
});
}
}

135
app/Models/Category.php Executable file
View file

@ -0,0 +1,135 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Category extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'categories';
/**
* Category validation rules
*/
public $rules = array(
'user_id' => 'numeric',
'name' => 'required|min:3|max:255|unique:categories,name,NULL,deleted_at',
'category_type' => 'required',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','category_type'];
public function has_models()
{
return $this->hasMany('\App\Models\AssetModel', 'category_id')->count();
}
public function accessories()
{
return $this->hasMany('\App\Models\Accessory');
}
public function consumables()
{
return $this->hasMany('\App\Models\Consumable');
}
public function components()
{
return $this->hasMany('\App\Models\Component');
}
public function itemCount()
{
switch ($this->category_type) {
case 'asset':
return $this->assets->count();
case 'accessory':
return $this->accessories->count();
case 'component':
return $this->components->count();
case 'consumable':
return $this->consumables->count();
}
return '0';
}
public function assets()
{
return $this->hasManyThrough('\App\Models\Asset', '\App\Models\AssetModel', 'category_id', 'model_id');
}
public function models()
{
return $this->hasMany('\App\Models\AssetModel', 'category_id');
}
public function getEula()
{
$Parsedown = new \Parsedown();
if ($this->eula_text) {
return $Parsedown->text(e($this->eula_text));
} elseif ((Setting::getSettings()->default_eula_text) && ($this->use_default_eula=='1')) {
return $Parsedown->text(e(Setting::getSettings()->default_eula_text));
} else {
return null;
}
}
/**
* scopeRequiresAcceptance
*
* @param $query
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function scopeRequiresAcceptance($query)
{
return $query->where('require_acceptance', '=', true);
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%')
->orWhere('category_type', 'LIKE', '%'.$search.'%');
});
}
}

167
app/Models/Company.php Normal file
View file

@ -0,0 +1,167 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
final class Company extends Model
{
protected $table = 'companies';
// Declare the rules for the model validation
protected $rules = ['name' => 'required|min:2|max:255|unique:companies,name'];
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name'];
private static function isFullMultipleCompanySupportEnabled()
{
$settings = Setting::getSettings();
// NOTE: this can happen when seeding the database
if (is_null($settings)) {
return false;
} else {
return $settings->full_multiple_companies_support == 1;
}
}
private static function scopeCompanyablesDirectly($query, $column = 'company_id')
{
if (Auth::user()) {
$company_id = Auth::user()->company_id;
} else {
$company_id = null;
}
if ($company_id == null) {
return $query;
} else {
return $query->where($column, '=', $company_id);
}
}
public static function getSelectList()
{
$select_company = Lang::get('general.select_company');
return ['0' => $select_company] + DB::table('companies')->orderBy('name', 'ASC')->lists('name', 'id');
}
public static function getIdFromInput($unescaped_input)
{
$escaped_input = e($unescaped_input);
if ($escaped_input == '0') {
return null;
} else {
return $escaped_input;
}
}
public static function getIdForCurrentUser($unescaped_input)
{
if (!static::isFullMultipleCompanySupportEnabled()) {
return static::getIdFromInput($unescaped_input);
} else {
$current_user = Auth::user();
if ($current_user->company_id != null) {
return $current_user->company_id;
} else {
return static::getIdFromInput($unescaped_input);
}
}
}
public static function isCurrentUserHasAccess($companyable)
{
if (is_null($companyable)) {
return false;
} elseif (!static::isFullMultipleCompanySupportEnabled()) {
return true;
} else {
$current_user_company_id = Auth::user()->company_id;
$companyable_company_id = $companyable->company_id;
return ($current_user_company_id == null || $current_user_company_id == $companyable_company_id);
}
}
public static function isCurrentUserAuthorized()
{
return (!static::isFullMultipleCompanySupportEnabled() || Auth::user()->company_id == null);
}
public static function canManageUsersCompanies()
{
return (!static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser() ||
Auth::user()->company_id == null);
}
public static function getIdForUser($unescaped_input)
{
if (!static::isFullMultipleCompanySupportEnabled() || Auth::user()->isSuperUser()) {
return static::getIdFromInput($unescaped_input);
} else {
return static::getIdForCurrentUser($unescaped_input);
}
}
public static function scopeCompanyables($query, $column = 'company_id')
{
if (!static::isFullMultipleCompanySupportEnabled()) {
return $query;
} else {
return static::scopeCompanyablesDirectly($query, $column);
}
}
public static function scopeCompanyableChildren(array $companyable_names, $query)
{
if (count($companyable_names) == 0) {
throw new Exception('No Companyable Children to scope');
} elseif (!static::isFullMultipleCompanySupportEnabled()) {
return $query;
} else {
$f = function ($q) {
static::scopeCompanyablesDirectly($q);
};
$q = $query->where(function ($q) use ($companyable_names, $f) {
$q2 = $q->whereHas($companyable_names[0], $f);
for ($i = 1; $i < count($companyable_names); $i++) {
$q2 = $q2->orWhereHas($companyable_names[$i], $f);
}
});
return $q;
}
}
public static function getName($companyable)
{
$company = $companyable->company;
if (is_null($company)) {
return '';
} else {
return e($company->name);
}
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
use \Illuminate\Database\Eloquent\Scope;
final class CompanyableChildScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$model = $builder->getModel();
return Company::scopeCompanyableChildren($model->getCompanyableParents(), $builder);
}
/**
* @todo IMPLEMENT
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function remove(Builder $builder)
{
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Models;
trait CompanyableChildTrait
{
/**
* Boot the companyable trait for a model.
*
* @return void
*/
public static function bootCompanyableChildTrait()
{
static::addGlobalScope(new CompanyableChildScope);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
use \Illuminate\Database\Eloquent\Scope;
final class CompanyableScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function apply(Builder $builder, Model $model)
{
return Company::scopeCompanyables($builder);
}
/**
* @todo IMPLEMENT
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function remove(Builder $builder)
{
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Models;
trait CompanyableTrait
{
/**
* Boot the companyable trait for a model.
*
* @return void
*/
public static function bootCompanyableTrait()
{
static::addGlobalScope(new CompanyableScope);
}
}

178
app/Models/Component.php Normal file
View file

@ -0,0 +1,178 @@
<?php
namespace App\Models;
use App\Models\User;
use App\Models\ConsumableAssignment;
use App\Models\Company;
use App\Models\Location;
use App\Models\Category;
use App\Models\ActionLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Component extends Model
{
use SoftDeletes;
use CompanyableTrait;
protected $dates = ['deleted_at'];
protected $table = 'components';
/**
* Category validation rules
*/
public $rules = array(
'name' => 'required|min:3|max:255',
'min_amt' => 'integer|min:1',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','company_id','category_id'];
public function location()
{
return $this->belongsTo('\App\Models\Location', 'location_id');
}
public function assets()
{
return $this->belongsToMany('\App\Models\Asset', 'components_assets')->withPivot('assigned_qty', 'created_at', 'user_id');
}
public function admin()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
public function category()
{
return $this->belongsTo('\App\Models\Category', 'category_id');
}
/**
* Get action logs for this consumable
*/
public function assetlog()
{
return $this->hasMany('\App\Models\Actionlog', 'component_id')->where('asset_type', '=', 'component')->orderBy('created_at', 'desc')->withTrashed();
}
public function numRemaining()
{
$checkedout = 0;
foreach ($this->assets as $checkout) {
$checkedout += $checkout->pivot->assigned_qty;
}
$total = $this->total_qty;
$remaining = $total - $checkedout;
return $remaining;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
$search = explode(' ', $search);
return $query->where(function ($query) use ($search) {
foreach ($search as $search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%');
})->orWhere(function ($query) use ($search) {
$query->whereHas('company', function ($query) use ($search) {
$query->where('companies.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('location', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
})->orWhere('components.name', 'LIKE', '%'.$search.'%')
->orWhere('components.order_number', 'LIKE', '%'.$search.'%')
->orWhere('components.purchase_cost', 'LIKE', '%'.$search.'%')
->orWhere('components.purchase_date', 'LIKE', '%'.$search.'%');
}
});
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCategory($query, $order)
{
return $query->join('categories', 'components.category_id', '=', 'categories.id')->orderBy('categories.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderLocation($query, $order)
{
return $query->leftJoin('locations', 'components.location_id', '=', 'locations.id')->orderBy('locations.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCompany($query, $order)
{
return $query->leftJoin('companies', 'components.company_id', '=', 'companies.id')->orderBy('companies.name', $order);
}
}

205
app/Models/Consumable.php Normal file
View file

@ -0,0 +1,205 @@
<?php
namespace App\Models;
use App\Models\User;
use App\Models\ConsumableAssignment;
use App\Models\Company;
use App\Models\Location;
use App\Models\Category;
use App\Models\ActionLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Consumable extends Model
{
use SoftDeletes;
use CompanyableTrait;
protected $dates = ['deleted_at'];
protected $table = 'consumables';
/**
* Category validation rules
*/
public $rules = array(
'name' => 'required|min:3|max:255',
'qty' => 'required|integer|min:0',
'category_id' => 'required|integer',
'company_id' => 'integer',
'min_amt' => 'integer|min:1',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','qty','company_id','category_id'];
public function admin()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
public function consumableAssigments()
{
return $this->hasMany('\App\Models\ConsumableAssignment');
}
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
public function location()
{
return $this->belongsTo('\App\Models\Location', 'location_id');
}
public function category()
{
return $this->belongsTo('\App\Models\Category', 'category_id');
}
/**
* Get action logs for this consumable
*/
public function assetlog()
{
return $this->hasMany('\App\Models\Actionlog', 'consumable_id')->where('asset_type', '=', 'consumable')->orderBy('created_at', 'desc')->withTrashed();
}
public function users()
{
return $this->belongsToMany('\App\Models\User', 'consumables_users', 'consumable_id', 'assigned_to')->withPivot('user_id')->withTrashed()->withTimestamps();
}
public function hasUsers()
{
return $this->belongsToMany('\App\Models\User', 'consumables_users', 'consumable_id', 'assigned_to')->count();
}
public function requireAcceptance()
{
return $this->category->require_acceptance;
}
public function getEula()
{
$Parsedown = new \Parsedown();
if ($this->category->eula_text) {
return $Parsedown->text(e($this->category->eula_text));
} elseif ((Setting::getSettings()->default_eula_text) && ($this->category->use_default_eula=='1')) {
return $Parsedown->text(e(Setting::getSettings()->default_eula_text));
} else {
return null;
}
}
public function numRemaining()
{
$checkedout = $this->users->count();
$total = $this->qty;
$remaining = $total - $checkedout;
return $remaining;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
$search = explode(' ', $search);
return $query->where(function ($query) use ($search) {
foreach ($search as $search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%');
})->orWhere(function ($query) use ($search) {
$query->whereHas('company', function ($query) use ($search) {
$query->where('companies.name', 'LIKE', '%'.$search.'%');
});
})->orWhere(function ($query) use ($search) {
$query->whereHas('location', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
})->orWhere('consumables.name', 'LIKE', '%'.$search.'%')
->orWhere('consumables.order_number', 'LIKE', '%'.$search.'%')
->orWhere('consumables.purchase_cost', 'LIKE', '%'.$search.'%')
->orWhere('consumables.purchase_date', 'LIKE', '%'.$search.'%');
}
});
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCategory($query, $order)
{
return $query->join('categories', 'consumables.category_id', '=', 'categories.id')->orderBy('categories.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderLocation($query, $order)
{
return $query->leftJoin('locations', 'consumables.location_id', '=', 'locations.id')->orderBy('locations.name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCompany($query, $order)
{
return $query->leftJoin('companies', 'consumables.company_id', '=', 'companies.id')->orderBy('companies.name', $order);
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ConsumableAssignment extends Model
{
use CompanyableTrait;
protected $dates = ['deleted_at'];
protected $table = 'consumables_users';
public function consumable()
{
return $this->belongsTo('\App\Models\Consumable');
}
public function user()
{
return $this->belongsTo('\App\Models\User', 'assigned_to');
}
public function admin()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
}

112
app/Models/CustomField.php Normal file
View file

@ -0,0 +1,112 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CustomField extends Model
{
public $guarded=["id"];
/**
*/
public static $PredefinedFormats=[
"ANY" => "",
"ALPHA" => "alpha",
"EMAIL" => "email",
"DATE" => "date",
"URL" => "url",
"NUMERIC" => "numeric",
"MAC" => "regex:/^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$/",
"IP" => "ip"
];
public $rules=[
"name" => "required|unique:custom_fields"
];
public static $table_name="assets";
public static function name_to_db_name($name)
{
return "_snipeit_".preg_replace("/[^a-zA-Z0-9]/", "_", strtolower($name));
}
public static function boot()
{
self::creating(function ($custom_field) {
if (in_array($custom_field->db_column_name(), \Schema::getColumnListing(\DB::getTablePrefix().CustomField::$table_name))) {
//field already exists when making a new custom field; fail.
return false;
}
\Schema::table(\DB::getTablePrefix().\App\Models\CustomField::$table_name, function ($table) use ($custom_field) {
$table->text($custom_field->db_column_name())->nullable();
});
});
self::updating(function ($custom_field) {
if ($custom_field->isDirty("name")) {
if (in_array($custom_field->db_column_name(), \Schema::getColumnListing(CustomField::$table_name))) {
//field already exists when renaming a custom field
return false;
}
return \DB::statement("UPDATE ".CustomField::$table_name." RENAME ".self::name_to_db_name($custom_field->get_original("name"))." TO ".$custom_field->db_column_name());
}
return true;
});
self::deleting(function ($custom_field) {
return \DB::statement("ALTER TABLE ".CustomField::$table_name." DROP COLUMN ".$custom_field->db_column_name());
});
}
public function fieldset()
{
return $this->belongsToMany('\App\Models\CustomFieldset'); //?!?!?!?!?!?
}
public function user()
{
return $this->belongsTo('\App\Models\User');
}
//public function
//need helper to go from regex->English
//need helper to go from English->regex
//need helper for save() stuff - basically to alter table for the fields in question
public function check_format($value)
{
return preg_match('/^'.$this->attributes['format'].'$/', $value)===1;
}
public function db_column_name()
{
return self::name_to_db_name($this->name);
}
//mutators for 'format' attribute
public function getFormatAttribute($value)
{
foreach (self::$PredefinedFormats as $name => $pattern) {
if ($pattern===$value) {
return $name;
}
}
return $value;
}
public function setFormatAttribute($value)
{
if (isset(self::$PredefinedFormats[$value])) {
$this->attributes['format']=self::$PredefinedFormats[$value];
} else {
$this->attributes['format']=$value;
}
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CustomFieldset extends Model
{
protected $guarded=["id"];
public $rules=[
"name" => "required|unique:custom_fieldsets"
];
public function fields()
{
return $this->belongsToMany('\App\Models\CustomField')->withPivot(["required","order"])->orderBy("pivot_order");
}
public function models()
{
return $this->hasMany('\App\Models\AssetModel', "fieldset_id");
}
public function user()
{
return $this->belongsTo('\App\Models\User'); //WARNING - not all CustomFieldsets have a User!!
}
public function validation_rules()
{
$rules=[];
foreach ($this->fields as $field) {
$rule=[];
if ($field->pivot->required) {
$rule[]="required";
}
array_push($rule, $field->attributes['format']);
$rules[$field->db_column_name()]=$rule;
}
return $rules;
}
//requiredness goes *here*
//sequence goes here?
}

View file

@ -0,0 +1,83 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Depreciation;
class Depreciable extends Model
{
/**
* Depreciation Relation, and associated helper methods
*/
//REQUIRES a purchase_date field
// and a purchase_cost field
//REQUIRES a get_depreciation method,
//which will return the deprecation.
//this is needed because assets get
//their depreciation from a model,
//whereas licenses have deprecations
//directly associated with them.
//assets will override the following
//two methods in order to inherit from
//their model instead of directly (like
//here)
public function depreciation()
{
return $this->belongsTo('\App\Models\Depreciation', 'depreciation_id');
}
public function get_depreciation()
{
return $this->depreciation;
}
/**
* @return float|int
*/
public function getDepreciatedValue()
{
if (!$this->get_depreciation()) { // will never happen
return $this->purchase_cost;
}
if ($this->get_depreciation()->months <= 0) {
return $this->purchase_cost;
}
// fraction of value left
$months_remaining = $this->time_until_depreciated()->m + 12*$this->time_until_depreciated()->y; //UGlY
$current_value = round(($months_remaining/ $this->get_depreciation()->months) * $this->purchase_cost, 2);
if ($current_value < 0) {
$current_value = 0;
}
return $current_value;
}
public function time_until_depreciated()
{
// @link http://www.php.net/manual/en/class.datetime.php
$d1 = new \DateTime();
$d2 = $this->depreciated_date();
// @link http://www.php.net/manual/en/class.dateinterval.php
$interval = $d1->diff($d2);
if (!$interval->invert) {
return $interval;
} else {
return new \DateInterval("PT0S"); //null interval (zero seconds from now)
}
}
public function depreciated_date()
{
$date = date_create($this->purchase_date);
date_add($date, date_interval_create_from_date_string($this->get_depreciation()->months . ' months'));
return $date; //date_format($date, 'Y-m-d'); //don't bake-in format, for internationalization
}
}

61
app/Models/Depreciation.php Executable file
View file

@ -0,0 +1,61 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
class Depreciation extends Model
{
// Declare the rules for the form validation
protected $rules = array(
'name' => 'required|min:3|max:255|unique:depreciations,name',
'months' => 'required|min:1|max:240|integer',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','months'];
public function has_models()
{
return $this->hasMany('\App\Models\AssetModel', 'depreciation_id')->count();
}
public function has_licenses()
{
return $this->hasMany('\App\Models\License', 'depreciation_id')->count();
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%')
->orWhere('months', 'LIKE', '%'.$search.'%');
});
}
}

34
app/Models/Group.php Executable file
View file

@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Watson\Validating\ValidatingTrait;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $table = 'groups';
public $rules = array(
'name' => 'required|min:3|max:255',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* Get user groups
*/
public function users()
{
return $this->belongsToMany('\App\Models\User', 'users_groups');
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Models;
interface ICompanyableChild
{
public function getCompanyableParents();
}

215
app/Models/License.php Executable file
View file

@ -0,0 +1,215 @@
<?php
namespace App\Models;
use App\Models\Company;
use DB;
use Watson\Validating\ValidatingTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
class License extends Depreciable
{
use SoftDeletes;
use CompanyableTrait;
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
protected $dates = ['deleted_at'];
public $timestamps = true;
protected $guarded = 'id';
protected $table = 'licenses';
protected $rules = array(
'name' => 'required|string|min:3|max:255',
'serial' => 'required|min:5',
'seats' => 'required|min:1|max:10000|integer',
'license_email' => 'email|min:0|max:120',
'license_name' => 'string|min:0|max:100',
'note' => 'string',
'notes' => 'string|min:0',
'company_id' => 'integer',
);
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
/**
* Get the assigned user
*/
public function assignedusers()
{
return $this->belongsToMany('\App\Models\User', 'license_seats', 'assigned_to', 'license_id');
}
/**
* Get asset logs for this asset
*/
public function assetlog()
{
return $this->hasMany('\App\Models\Actionlog', 'asset_id')
->where('asset_type', '=', 'software')
->orderBy('created_at', 'desc');
}
/**
* Get uploads for this asset
*/
public function uploads()
{
return $this->hasMany('\App\Models\Actionlog', 'asset_id')
->where('asset_type', '=', 'software')
->where('action_type', '=', 'uploaded')
->whereNotNull('filename')
->orderBy('created_at', 'desc');
}
/**
* Get admin user for this asset
*/
public function adminuser()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
/**
* Get total licenses
*/
public static function assetcount()
{
return LicenseSeat::whereNull('deleted_at')
->count();
}
/**
* Get total licenses
*/
public function totalSeatsByLicenseID()
{
return LicenseSeat::where('license_id', '=', $this->id)
->whereNull('deleted_at')
->count();
}
/**
* Get total licenses not checked out
*/
public static function availassetcount()
{
return LicenseSeat::whereNull('assigned_to')
->whereNull('asset_id')
->whereNull('deleted_at')
->count();
}
/**
* Get the number of available seats
*/
public function availcount()
{
return LicenseSeat::whereNull('assigned_to')
->whereNull('asset_id')
->where('license_id', '=', $this->id)
->whereNull('deleted_at')
->count();
}
/**
* Get the number of assigned seats
*
*/
public function assignedcount()
{
return \App\Models\LicenseSeat::where('license_id', '=', $this->id)
->where(function ($query) {
$query->whereNotNull('assigned_to')
->orWhereNotNull('asset_id');
})
->count();
}
public function remaincount()
{
$total = $this->totalSeatsByLicenseID();
$taken = $this->assignedcount();
$diff = ($total - $taken);
return $diff;
}
/**
* Get the total number of seats
*/
public function totalcount()
{
$avail = $this->availcount();
$taken = $this->assignedcount();
$diff = ($avail + $taken);
return $diff;
}
/**
* Get license seat data
*/
public function licenseseats()
{
return $this->hasMany('\App\Models\LicenseSeat');
}
public function supplier()
{
return $this->belongsTo('\App\Models\Supplier', 'supplier_id');
}
public function freeSeat()
{
$seat = LicenseSeat::where('license_id', '=', $this->id)
->whereNull('deleted_at')
->whereNull('assigned_to')
->whereNull('asset_id')
->first();
return $seat->id;
}
public static function getExpiringLicenses($days = 60)
{
return License::whereNotNull('expiration_date')
->whereNull('deleted_at')
->whereRaw(DB::raw('DATE_SUB(`expiration_date`,INTERVAL '.$days.' DAY) <= DATE(NOW()) '))
->where('expiration_date', '>', date("Y-m-d"))
->orderBy('expiration_date', 'ASC')
->get();
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%')
->orWhere('serial', 'LIKE', '%'.$search.'%')
->orWhere('notes', 'LIKE', '%'.$search.'%')
->orWhere('order_number', 'LIKE', '%'.$search.'%')
->orWhere('purchase_date', 'LIKE', '%'.$search.'%')
->orWhere('purchase_cost', 'LIKE', '%'.$search.'%');
});
}
}

35
app/Models/LicenseSeat.php Executable file
View file

@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class LicenseSeat extends Model implements ICompanyableChild
{
use CompanyableChildTrait;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $guarded = 'id';
protected $table = 'license_seats';
public function getCompanyableParents()
{
return ['asset', 'license'];
}
public function license()
{
return $this->belongsTo('\App\Models\License', 'license_id');
}
public function user()
{
return $this->belongsTo('\App\Models\User', 'assigned_to')->withTrashed();
}
public function asset()
{
return $this->belongsTo('\App\Models\Asset', 'asset_id')->withTrashed();
}
}

168
app/Models/Location.php Executable file
View file

@ -0,0 +1,168 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\User;
use App\Models\Asset;
use Watson\Validating\ValidatingTrait;
class Location extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'locations';
protected $rules = array(
'name' => 'required|min:3|max:255|unique:locations,name,NULL,deleted_at',
'city' => 'min:3|max:255',
'state' => 'min:2|max:32',
'country' => 'min:2|max:2|max:2',
'address' => 'min:5|max:80',
'address2' => 'min:2|max:80',
'zip' => 'min:3|max:10',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name'];
public function users()
{
return $this->hasMany('\App\Models\User', 'location_id');
}
public function assets()
{
return $this->hasManyThrough('\App\Models\Asset', '\App\Models\Actionlog', 'location_id', 'id');
}
public function assignedassets()
{
return $this->hasMany('\App\Models\Asset', 'rtd_location_id');
}
public function parent()
{
return $this->belongsTo('\App\Models\Location', 'parent_id');
}
public function childLocations()
{
return $this->hasMany('\App\Models\Location', 'parent_id');
}
public static function getLocationHierarchy($locations, $parent_id = null)
{
$op = array();
foreach ($locations as $location) {
if ($location['parent_id'] == $parent_id) {
$op[$location['id']] =
array(
'name' => $location['name'],
'parent_id' => $location['parent_id']
);
// Using recursion
$children = Location::getLocationHierarchy($locations, $location['id']);
if ($children) {
$op[$location['id']]['children'] = $children;
}
}
}
return $op;
}
public static function flattenLocationsArray($location_options_array = null)
{
$location_options = array();
foreach ($location_options_array as $id => $value) {
// get the top level key value
$location_options[$id] = $value['name'];
// If there is a key named children, it has child locations and we have to walk it
if (array_key_exists('children', $value)) {
foreach ($value['children'] as $child_id => $child_location_array) {
$child_location_options = Location::flattenLocationsArray($value['children']);
foreach ($child_location_options as $child_id => $child_name) {
$location_options[$child_id] = '--'.$child_name;
}
}
}
}
return $location_options;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextsearch($query, $search)
{
return $query->where('name', 'LIKE', "%$search%")
->orWhere('address', 'LIKE', "%$search%")
->orWhere('city', 'LIKE', "%$search%")
->orWhere('state', 'LIKE', "%$search%")
->orWhere('zip', 'LIKE', "%$search%")
// This doesn't actually work - need to use a table alias maybe?
->orWhere(function ($query) use ($search) {
$query->whereHas('parent', function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
})
// Ugly, ugly code because Laravel sucks at self-joins
->orWhere(function ($query) use ($search) {
$query->whereRaw("parent_id IN (select id from locations where name LIKE '%".$search."%') ");
});
});
}
/**
* Query builder scope to order on parent
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderParent($query, $order)
{
// Left join here, or it will only return results with parents
return $query->leftJoin('locations as parent_loc', 'locations.parent_id', '=', 'parent_loc.id')->orderBy('parent_loc.name', $order);
}
}

65
app/Models/Manufacturer.php Executable file
View file

@ -0,0 +1,65 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Manufacturer extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $table = 'manufacturers';
// Declare the rules for the form validation
protected $rules = array(
'name' => 'required|min:2|max:255|unique:manufacturers,name,NULL,deleted_at',
'user_id' => 'integer',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name'];
public function has_models()
{
return $this->hasMany('\App\Models\AssetModel', 'manufacturer_id')->count();
}
public function assets()
{
return $this->hasManyThrough('\App\Models\Asset', '\App\Models\AssetModel', 'manufacturer_id', 'model_id');
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
}
}

113
app/Models/Setting.php Executable file
View file

@ -0,0 +1,113 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
class Setting extends Model
{
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
protected $rules = [
"brand" => 'required|min:1|numeric',
"qr_text" => 'min:1|max:31',
"custom_css" => 'string',
"slack_endpoint" => 'url',
"default_currency" => 'required',
"slack_channel" => 'regex:/(?<!\w)#\w+/',
"slack_botname" => 'string',
"ldap_server" => 'sometimes|required_if:ldap_enabled,1|url',
"ldap_uname" => 'sometimes|required_if:ldap_enabled,1',
"ldap_pword" => 'sometimes|required_if:ldap_enabled,1',
"ldap_basedn" => 'sometimes|required_if:ldap_enabled,1',
"ldap_filter" => 'sometimes|required_if:ldap_enabled,1',
"ldap_username_field" => 'sometimes|required_if:ldap_enabled,1',
"ldap_lname_field" => 'sometimes|required_if:ldap_enabled,1',
"ldap_auth_filter_query" => 'sometimes|required_if:ldap_enabled,1',
"ldap_version" => 'sometimes|required_if:ldap_enabled,1',
];
protected $fillable = ['site_name'];
public static function getSettings()
{
static $static_cache = null;
if (!$static_cache) {
$static_cache = Setting::first();
}
return $static_cache;
}
public function lar_ver()
{
$app = \App::getFacadeApplication();
return $app::VERSION;
}
public static function getDefaultEula()
{
$Parsedown = new \Parsedown();
if (Setting::getSettings()->default_eula_text) {
return $Parsedown->text(e(Setting::getSettings()->default_eula_text));
} else {
return null;
}
}
public function show_custom_css()
{
$custom_css = Setting::getSettings()->custom_css;
$custom_css = e($custom_css);
// Needed for modifying the bootstrap nav :(
$custom_css = str_ireplace('script', 'SCRIPTS-NOT-ALLOWED-HERE', $custom_css);
$custom_css = str_replace('&gt;', '>', $custom_css);
return $custom_css;
}
/**
* Converts bytes into human readable file size.
*
* @param string $bytes
* @return string human readable file size (2,87 Мб)
* @author Mogilev Arseny
*/
public static function fileSizeConvert($bytes)
{
$bytes = floatval($bytes);
$arBytes = array(
0 => array(
"UNIT" => "TB",
"VALUE" => pow(1024, 4)
),
1 => array(
"UNIT" => "GB",
"VALUE" => pow(1024, 3)
),
2 => array(
"UNIT" => "MB",
"VALUE" => pow(1024, 2)
),
3 => array(
"UNIT" => "KB",
"VALUE" => 1024
),
4 => array(
"UNIT" => "B",
"VALUE" => 1
),
);
foreach ($arBytes as $arItem) {
if ($bytes >= $arItem["VALUE"]) {
$result = $bytes / $arItem["VALUE"];
$result = round($result, 2) .$arItem["UNIT"];
break;
}
}
return $result;
}
}

87
app/Models/Statuslabel.php Executable file
View file

@ -0,0 +1,87 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Statuslabel extends Model
{
use SoftDeletes;
use ValidatingTrait;
protected $injectUniqueIdentifier = true;
protected $dates = ['deleted_at'];
protected $table = 'status_labels';
protected $rules = array(
'name' => 'required|string|unique:status_labels,name,NULL,deleted_at',
//'statuslabel_types' => 'required|in:deployable,pending,archived,undeployable',
'notes' => 'string',
);
protected $fillable = ['name'];
public function has_assets()
{
return $this->hasMany('\App\Models\Asset', 'status_id')->count();
}
public function getStatuslabelType()
{
if ($this->pending == 1) {
return 'pending';
} elseif ($this->archived == 1) {
return 'archived';
} elseif (($this->archived == 0) && ($this->deployable == 0) && ($this->deployable == 0)) {
return 'undeployable';
} else {
return 'deployable';
}
}
public static function getStatuslabelTypesForDB($type)
{
if ($type == 'pending') {
$statustype['pending'] = 1;
$statustype['deployable'] = 0;
$statustype['archived'] = 0;
} elseif ($type == 'deployable') {
$statustype['pending'] = 0;
$statustype['deployable'] = 1;
$statustype['archived'] = 0;
} elseif ($type == 'archived') {
$statustype['pending'] = 0;
$statustype['deployable'] = 0;
$statustype['archived'] = 1;
} elseif ($type == 'undeployable') {
$statustype['pending'] = 0;
$statustype['deployable'] = 0;
$statustype['archived'] = 0;
}
return $statustype;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
}
}

96
app/Models/Supplier.php Executable file
View file

@ -0,0 +1,96 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
class Supplier extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $rules = array(
'name' => 'required|min:3|max:255|unique:suppliers,name,NULL,deleted_at',
'address' => 'min:3|max:255',
'address2' => 'min:2|max:255',
'city' => 'min:3|max:255',
'state' => 'min:0|max:32',
'country' => 'min:0|max:2',
'fax' => 'min:7|max:20',
'phone' => 'min:7|max:20',
'contact' => 'min:0|max:255',
'notes' => 'min:0|max:255',
'email' => 'email|min:5|max:150',
'zip' => 'min:0|max:10',
'url' => 'min:3|max:250',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name'];
public function assets()
{
return $this->hasMany('\App\Models\Asset', 'supplier_id');
}
public function asset_maintenances()
{
return $this->hasMany('\App\Models\AssetMaintenance', 'supplier_id');
}
public function num_assets()
{
return $this->hasMany('\App\Models\Asset', 'supplier_id')->count();
}
public function licenses()
{
return $this->hasMany('\App\Models\License', 'supplier_id');
}
public function num_licenses()
{
return $this->hasMany('\App\Models\License', 'supplier_id')->count();
}
public function addhttp($url)
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
}
}

14
app/Models/Throttle.php Normal file
View file

@ -0,0 +1,14 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Throttle extends Model
{
protected $table = 'throttle';
public function user()
{
return $this->belongsTo('User', 'user_id');
}
}

383
app/Models/User.php Executable file
View file

@ -0,0 +1,383 @@
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Watson\Validating\ValidatingTrait;
use App\Models\Company;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use SoftDeletes;
use ValidatingTrait;
use Authenticatable;
use CanResetPassword;
protected $dates = ['deleted_at'];
protected $table = 'users';
protected $injectUniqueIdentifier = true;
protected $fillable = ['first_name', 'last_name', 'email','password','username'];
/**
* Model validation rules
*
* @var array
*/
protected $rules = [
'first_name' => 'required|string|min:1',
'last_name' => 'required|string|min:1',
'username' => 'required|string|min:2|unique:users,username,NULL,deleted_at',
'email' => 'email',
'password' => 'required|min:6',
];
// This is very coarse and should be changed
public function hasAccess($section)
{
$user_permissions = json_decode($this->permissions, true);
$user_groups = $this->groups();
if (((array_key_exists($section, $user_permissions)) && ($user_permissions[$section]=='1')) ||
((array_key_exists('admin', $user_permissions)) && ($user_permissions['admin']=='1'))) {
return true;
}
foreach ($user_groups as $user_group) {
$group_permissions = json_decode($user_group->permissions, true);
if (((array_key_exists($section, $group_permissions)) && ($group_permissions[$section]=='1')) ||
((array_key_exists('admin', $group_permissions)) && ($group_permissions['admin']=='1'))) {
return true;
}
}
return false;
}
public function isSuperUser() {
$user_permissions = json_decode($this->permissions, true);
$user_groups = $this->groups();
if ((array_key_exists('superuser', $user_permissions)) && ($user_permissions['superuser']=='1')) {
return true;
} else {
return false;
}
}
public function company()
{
return $this->belongsTo('\App\Models\Company', 'company_id');
}
public function isActivated()
{
if ($this->activated == 1) {
return true;
} else {
return false;
}
}
/**
* Returns the user full name, it simply concatenates
* the user first and last name.
*
* @return string
*/
public function fullName()
{
return "{$this->first_name} {$this->last_name}";
}
/**
* Returns the user Gravatar image url.
*
* @return string
*/
public function gravatar()
{
if ($this->avatar) {
return config('app.url').'/uploads/avatars/'.$this->avatar;
}
if ($this->email) {
// Generate the Gravatar hash
$gravatar = md5(strtolower(trim($this->email)));
// Return the Gravatar url
return "//gravatar.com/avatar/".$gravatar;
}
return false;
}
/**
* Get assets assigned to this user
*/
public function assets()
{
return $this->hasMany('\App\Models\Asset', 'assigned_to')->withTrashed();
}
/**
* Get accessories assigned to this user
*/
public function accessories()
{
return $this->belongsToMany('\App\Models\Accessory', 'accessories_users', 'assigned_to', 'accessory_id')->withPivot('id')->withTrashed();
}
/**
* Get consumables assigned to this user
*/
public function consumables()
{
return $this->belongsToMany('\App\Models\Consumable', 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id')->withTrashed();
}
/**
* Get licenses assigned to this user
*/
public function licenses()
{
return $this->belongsToMany('\App\Models\License', 'license_seats', 'assigned_to', 'license_id')->withPivot('id');
}
/**
* Get action logs for this user
*/
public function userlog()
{
return $this->hasMany('\App\Models\Actionlog', 'checkedout_to')->orderBy('created_at', 'DESC')->withTrashed();
}
/**
* Get the asset's location based on the assigned user
**/
public function userloc()
{
return $this->belongsTo('\App\Models\Location', 'location_id')->withTrashed();
}
/**
* Get the user's manager based on the assigned user
**/
public function manager()
{
return $this->belongsTo('\App\Models\User', 'manager_id')->withTrashed();
}
/**
* Get user groups
*/
public function groups()
{
return $this->belongsToMany('\App\Models\Group', 'users_groups');
}
public function accountStatus()
{
if ($this->sentryThrottle) {
if ($this->sentryThrottle->suspended==1) {
return 'suspended';
} elseif ($this->sentryThrottle->banned==1) {
return 'banned';
} else {
return false;
}
} else {
return false;
}
}
public function assetlog()
{
return $this->hasMany('\App\Models\Asset', 'id')->withTrashed();
}
/**
* Get uploads for this asset
*/
public function uploads()
{
return $this->hasMany('\App\Models\Actionlog', 'asset_id')
->where('asset_type', '=', 'user')
->where('action_type', '=', 'uploaded')
->whereNotNull('filename')
->orderBy('created_at', 'desc');
}
public function sentryThrottle()
{
return $this->hasOne('\App\Models\Throttle');
}
public function scopeGetDeleted($query)
{
return $query->withTrashed()->whereNotNull('deleted_at');
}
public function scopeGetNotDeleted($query)
{
return $query->whereNull('deleted_at');
}
/**
* Override the SentryUser getPersistCode method for
* multiple logins at one time
**/
public function getPersistCode()
{
if (!config('session.multi_login') || (!$this->persist_code)) {
$this->persist_code = $this->getRandomString();
// Our code got hashed
$persistCode = $this->persist_code;
$this->save();
return $persistCode;
}
return $this->persist_code;
}
public function scopeMatchEmailOrUsername($query, $user_username, $user_email)
{
return $query->where('email', '=', $user_email)
->orWhere('username', '=', $user_username)
->orWhere('username', '=', $user_email);
}
public static function generateFormattedNameFromFullName($format = 'filastname', $users_name)
{
$name = explode(" ", $users_name);
$name = str_replace("'", '', $name);
$first_name = $name[0];
$email_last_name = '';
$email_prefix = $first_name;
// If there is no last name given
if (!array_key_exists(1, $name)) {
$last_name='';
$email_last_name = $last_name;
$user_username = $first_name;
// There is a last name given
} else {
$last_name = str_replace($first_name, '', $users_name);
if ($format=='filastname') {
$email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_name[0].$email_last_name;
} elseif ($format=='firstname.lastname') {
$email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_name.'.'.$email_last_name;
} elseif ($format=='firstname') {
$email_last_name.=str_replace(' ', '', $last_name);
$email_prefix = $first_name;
}
}
$user_username = $email_prefix;
$user['first_name'] = $first_name;
$user['last_name'] = $last_name;
$user['username'] = strtolower($user_username);
return $user;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextsearch($query, $search)
{
return $query->where(function ($query) use ($search) {
$query->where('users.first_name', 'LIKE', "%$search%")
->orWhere('users.last_name', 'LIKE', "%$search%")
->orWhere('users.email', 'LIKE', "%$search%")
->orWhere('users.username', 'LIKE', "%$search%")
->orWhere('users.notes', 'LIKE', "%$search%")
->orWhere('users.employee_num', 'LIKE', "%$search%")
->orWhere(function ($query) use ($search) {
$query->whereHas('userloc', function ($query) use ($search) {
$query->where('locations.name', 'LIKE', '%'.$search.'%');
});
})
// Ugly, ugly code because Laravel sucks at self-joins
->orWhere(function ($query) use ($search) {
$query->whereRaw("users.manager_id IN (select id from users where first_name LIKE '%".$search."%' OR last_name LIKE '%".$search."%') ");
});
});
}
/**
* Query builder scope for Deleted users
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
/**
* Query builder scope to order on manager
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderManager($query, $order)
{
// Left join here, or it will only return results with parents
return $query->leftJoin('users as manager', 'users.manager_id', '=', 'manager.id')->orderBy('manager.first_name', $order)->orderBy('manager.last_name', $order);
}
/**
* Query builder scope to order on company
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderLocation($query, $order)
{
return $query->leftJoin('locations', 'users.location_id', '=', 'locations.id')->orderBy('locations.name', $order);
}
}

0
app/Policies/.gitkeep Normal file
View file

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