Kaynağa Gözat

repo init

master
Dukai Károly 3 yıl önce
işleme
f7d9dbf047
100 değiştirilmiş dosya ile 56122 ekleme ve 0 silme
  1. +13
    -0
      .gitignore
  2. +143
    -0
      README.txt
  3. +42
    -0
      modules/README.txt
  4. +339
    -0
      modules/contrib/fontawesome/LICENSE.txt
  5. +104
    -0
      modules/contrib/fontawesome/README.txt
  6. +15
    -0
      modules/contrib/fontawesome/composer.json
  7. +12
    -0
      modules/contrib/fontawesome/config/install/fontawesome.settings.yml
  8. +43
    -0
      modules/contrib/fontawesome/config/schema/fontawesome.schema.yml
  9. +9
    -0
      modules/contrib/fontawesome/drush.services.yml
  10. +12
    -0
      modules/contrib/fontawesome/fontawesome.info.yml
  11. +104
    -0
      modules/contrib/fontawesome/fontawesome.install
  12. +143
    -0
      modules/contrib/fontawesome/fontawesome.libraries.yml
  13. +5
    -0
      modules/contrib/fontawesome/fontawesome.links.menu.yml
  14. +572
    -0
      modules/contrib/fontawesome/fontawesome.module
  15. +21
    -0
      modules/contrib/fontawesome/fontawesome.routing.yml
  16. BIN
      modules/contrib/fontawesome/js/plugins/drupalfontawesome/icons/drupalfontawesome.png
  17. BIN
      modules/contrib/fontawesome/js/plugins/drupalfontawesome/icons/hidpi/drupalfontawesome.png
  18. +139
    -0
      modules/contrib/fontawesome/js/plugins/drupalfontawesome/plugin.es6.js
  19. +105
    -0
      modules/contrib/fontawesome/js/plugins/drupalfontawesome/plugin.js
  20. +40944
    -0
      modules/contrib/fontawesome/metadata/icons.yml
  21. +14
    -0
      modules/contrib/fontawesome/modules/fontawesome_media/fontawesome_media.info.yml
  22. +100
    -0
      modules/contrib/fontawesome/modules/fontawesome_media/src/Plugin/media/Source/FontAwesomeIconMedia.php
  23. +123
    -0
      modules/contrib/fontawesome/src/Commands/FontawesomeCommands.php
  24. +80
    -0
      modules/contrib/fontawesome/src/Controller/AutocompleteController.php
  25. +467
    -0
      modules/contrib/fontawesome/src/Form/EditorIconDialog.php
  26. +285
    -0
      modules/contrib/fontawesome/src/Form/SettingsForm.php
  27. +64
    -0
      modules/contrib/fontawesome/src/Plugin/CKEditorPlugin/DrupalFontAwesome.php
  28. +197
    -0
      modules/contrib/fontawesome/src/Plugin/Field/FieldFormatter/FontAwesomeIconFormatter.php
  29. +80
    -0
      modules/contrib/fontawesome/src/Plugin/Field/FieldType/FontAwesomeIcon.php
  30. +538
    -0
      modules/contrib/fontawesome/src/Plugin/Field/FieldWidget/FontAwesomeIconWidget.php
  31. +20
    -0
      modules/contrib/fontawesome/templates/fontawesomeicon.html.twig
  32. +19
    -0
      modules/contrib/fontawesome/templates/fontawesomeicons.html.twig
  33. +6
    -0
      modules/custom/arlista/arlista.info.yml
  34. +319
    -0
      modules/custom/arlista/arlista.install
  35. +13
    -0
      modules/custom/arlista/arlista.libraries.yml
  36. +37
    -0
      modules/custom/arlista/arlista.links.menu.yml
  37. +126
    -0
      modules/custom/arlista/arlista.module
  38. +4
    -0
      modules/custom/arlista/arlista.permissions.yml
  39. +294
    -0
      modules/custom/arlista/arlista.routing.yml
  40. +39
    -0
      modules/custom/arlista/arlista.services.yml
  41. +84
    -0
      modules/custom/arlista/css/arlista.css
  42. +542
    -0
      modules/custom/arlista/js/arlista.js
  43. BIN
      modules/custom/arlista/regi_kategoriak.xlsx
  44. +15
    -0
      modules/custom/arlista/src/BaseEntityNotFoundException.php
  45. +13
    -0
      modules/custom/arlista/src/BaseException.php
  46. +134
    -0
      modules/custom/arlista/src/Controller/ArlistaAbstractController.php
  47. +76
    -0
      modules/custom/arlista/src/Controller/AxicoIdController.php
  48. +101
    -0
      modules/custom/arlista/src/Controller/CategoryController.php
  49. +90
    -0
      modules/custom/arlista/src/Controller/ComponentController.php
  50. +140
    -0
      modules/custom/arlista/src/Controller/ProductController.php
  51. +79
    -0
      modules/custom/arlista/src/Controller/UploadedFileController.php
  52. +103
    -0
      modules/custom/arlista/src/Entity/AbstractEntity.php
  53. +89
    -0
      modules/custom/arlista/src/Entity/AxicoId.php
  54. +172
    -0
      modules/custom/arlista/src/Entity/Calculation.php
  55. +41
    -0
      modules/custom/arlista/src/Entity/Category.php
  56. +39
    -0
      modules/custom/arlista/src/Entity/Component.php
  57. +23
    -0
      modules/custom/arlista/src/Entity/Currency.php
  58. +43
    -0
      modules/custom/arlista/src/Entity/EnabledGroup.php
  59. +196
    -0
      modules/custom/arlista/src/Entity/Install.php
  60. +60
    -0
      modules/custom/arlista/src/Entity/Manufacturer.php
  61. +21
    -0
      modules/custom/arlista/src/Entity/MeasureUnit.php
  62. +21
    -0
      modules/custom/arlista/src/Entity/PackingMaterial.php
  63. +668
    -0
      modules/custom/arlista/src/Entity/Product.php
  64. +73
    -0
      modules/custom/arlista/src/Entity/ResponseBody.php
  65. +280
    -0
      modules/custom/arlista/src/Entity/SheetSetting.php
  66. +54
    -0
      modules/custom/arlista/src/Entity/Status.php
  67. +63
    -0
      modules/custom/arlista/src/Entity/UploadedFile.php
  68. +25
    -0
      modules/custom/arlista/src/Entity/WorkFlow.php
  69. +201
    -0
      modules/custom/arlista/src/Factory/AbstractFactory.php
  70. +56
    -0
      modules/custom/arlista/src/Factory/AbstractSpreadSheetFactory.php
  71. +546
    -0
      modules/custom/arlista/src/Factory/AxicoIdFactory.php
  72. +223
    -0
      modules/custom/arlista/src/Factory/CalculationFactory.php
  73. +145
    -0
      modules/custom/arlista/src/Factory/CategoryFactory.php
  74. +230
    -0
      modules/custom/arlista/src/Factory/ComponentFactory.php
  75. +152
    -0
      modules/custom/arlista/src/Factory/EnabledGroupFactory.php
  76. +128
    -0
      modules/custom/arlista/src/Factory/FileFactory.php
  77. +747
    -0
      modules/custom/arlista/src/Factory/InstallFactory.php
  78. +216
    -0
      modules/custom/arlista/src/Factory/ManufacturerFactory.php
  79. +1400
    -0
      modules/custom/arlista/src/Factory/ProductFactory.php
  80. +196
    -0
      modules/custom/arlista/src/Factory/SheetSettingFactory.php
  81. +464
    -0
      modules/custom/arlista/src/Factory/SpreadSheetFactory.php
  82. +107
    -0
      modules/custom/arlista/src/Form/AbstractConfirmForm.php
  83. +268
    -0
      modules/custom/arlista/src/Form/ArlistaAbstractForm.php
  84. +487
    -0
      modules/custom/arlista/src/Form/Calculation/CalculationEdit.php
  85. +83
    -0
      modules/custom/arlista/src/Form/Calculation/CalculationList.php
  86. +133
    -0
      modules/custom/arlista/src/Form/Category/CategoryEdit.php
  87. +91
    -0
      modules/custom/arlista/src/Form/Category/CategoryList.php
  88. +76
    -0
      modules/custom/arlista/src/Form/Category/ConfirmCategoryDelete.php
  89. +149
    -0
      modules/custom/arlista/src/Form/Component/ComponentEdit.php
  90. +120
    -0
      modules/custom/arlista/src/Form/Component/ComponentList.php
  91. +75
    -0
      modules/custom/arlista/src/Form/Component/ConfirmComponentDelete.php
  92. +185
    -0
      modules/custom/arlista/src/Form/Config/ArlistaSetupForm.php
  93. +54
    -0
      modules/custom/arlista/src/Form/Config/ConfirmFixAxicoId.php
  94. +49
    -0
      modules/custom/arlista/src/Form/Config/ConfirmProductReImport.php
  95. +236
    -0
      modules/custom/arlista/src/Form/EnabledGroup/EnabledGroupListForm.php
  96. +67
    -0
      modules/custom/arlista/src/Form/File/ConfirmUploadedFileDelete.php
  97. +162
    -0
      modules/custom/arlista/src/Form/File/FileUpload.php
  98. +61
    -0
      modules/custom/arlista/src/Form/Manufacturer/ConfirmManufacturerDelete.php
  99. +180
    -0
      modules/custom/arlista/src/Form/Manufacturer/ManufacturerEdit.php
  100. +0
    -0
      modules/custom/arlista/src/Form/Manufacturer/ManufacturerList.php

+ 13
- 0
.gitignore Dosyayı Görüntüle

@@ -0,0 +1,13 @@

nbproject
vendor
core
profiles
sites
themes
.editorconfig
.gitattributes
/*
!README.txt
!.gitignore
!/modules

+ 143
- 0
README.txt Dosyayı Görüntüle

@@ -0,0 +1,143 @@

CONTENTS OF THIS FILE
---------------------

* About Drupal
* Configuration and features
* Installation profiles
* Appearance
* Developing for Drupal
* More information


ABOUT DRUPAL
------------

Drupal is an open source content management platform supporting a variety of
websites ranging from personal weblogs to large community-driven websites. For
more information, see the Drupal website at https://www.drupal.org, and join
the Drupal community at https://www.drupal.org/community.

Legal information about Drupal:
* Know your rights when using Drupal:
See LICENSE.txt in the "core" directory.
* Learn about the Drupal trademark and logo policy:
https://www.drupal.com/trademark


CONFIGURATION AND FEATURES
--------------------------

Drupal core (what you get when you download and extract a drupal-x.y.tar.gz or
drupal-x.y.zip file from https://www.drupal.org/project/drupal) has what you
need to get started with your website. It includes several modules (extensions
that add functionality) for common website features, such as managing content,
user accounts, image uploading, and search. Core comes with many options that
allow site-specific configuration. In addition to the core modules, there are
thousands of contributed modules (for functionality not included with Drupal
core) available for download.

More about configuration:
* Install, update, and maintain Drupal:
See INSTALL.txt and UPDATE.txt in the "core" directory.
* Learn about how to use Drupal to create your site:
https://www.drupal.org/documentation
* Follow best practices:
https://www.drupal.org/best-practices
* Download contributed modules to /modules to extend Drupal's functionality:
https://www.drupal.org/project/project_module
* See also: "Developing for Drupal" for writing your own modules, below.


INSTALLATION PROFILES
---------------------

Installation profiles define additional steps (such as enabling modules,
defining content types, etc.) that run after the base installation provided
by core when Drupal is first installed. There are two basic installation
profiles provided with Drupal core.

Installation profiles from the Drupal community modify the installation process
to provide a website for a specific use case, such as a CMS for media
publishers, a web-based project tracking tool, or a full-fledged CRM for
non-profit organizations raising money and accepting donations. They can be
distributed as bare installation profiles or as "distributions". Distributions
include Drupal core, the installation profile, and all other required
extensions, such as contributed and custom modules, themes, and third-party
libraries. Bare installation profiles require you to download Drupal Core and
the required extensions separately; place the downloaded profile in the
/profiles directory before you start the installation process.

More about installation profiles and distributions:
* Read about the difference between installation profiles and distributions:
https://www.drupal.org/docs/distributions/creating-distributions
* Download contributed installation profiles and distributions:
https://www.drupal.org/project/project_distribution
* Develop your own installation profile or distribution:
https://www.drupal.org/docs/distributions/creating-distributions


APPEARANCE
----------

In Drupal, the appearance of your site is set by the theme (themes are
extensions that set fonts, colors, and layout). Drupal core comes with several
themes. More themes are available for download, and you can also create your own
custom theme.

More about themes:
* Download contributed themes to /themes to modify Drupal's appearance:
https://www.drupal.org/project/project_theme
* Develop your own theme:
https://www.drupal.org/docs/theming-drupal


DEVELOPING FOR DRUPAL
---------------------

Drupal contains an extensive API that allows you to add to and modify the
functionality of your site. The API consists of "hooks", which allow modules to
react to system events and customize Drupal's behavior, and functions that
standardize common operations such as database queries and form generation. The
flexible hook architecture means that you should never need to directly modify
the files that come with Drupal core to achieve the functionality you want;
instead, functionality modifications take the form of modules.

When you need new functionality for your Drupal site, search for existing
contributed modules. If you find a module that matches except for a bug or an
additional needed feature, change the module and contribute your improvements
back to the project in the form of a "patch". Create new custom modules only
when nothing existing comes close to what you need.

More about developing:
* Search for existing contributed modules:
https://www.drupal.org/project/project_module
* Contribute a patch:
https://www.drupal.org/patch/submit
* Develop your own module:
https://www.drupal.org/developing/modules
* Follow programming best practices:
https://www.drupal.org/docs/develop/standards
* Refer to the API documentation:
https://api.drupal.org/api/drupal/9
* Learn from documented Drupal API examples:
https://www.drupal.org/project/examples


MORE INFORMATION
----------------

* See the Drupal.org online documentation:
https://www.drupal.org/documentation

* For a list of security announcements, see the "Security advisories" page at
https://www.drupal.org/security (available as an RSS feed). This page also
describes how to subscribe to these announcements via email.

* For information about the Drupal security process, or to find out how to
report a potential security issue to the Drupal security team, see the
"Security team" page at https://www.drupal.org/drupal-security-team

* For information about the wide range of available support options, visit
https://www.drupal.org and click on Community and Support in the top or
bottom navigation.

+ 42
- 0
modules/README.txt Dosyayı Görüntüle

@@ -0,0 +1,42 @@
Modules extend your site functionality beyond Drupal core.

WHAT TO PLACE IN THIS DIRECTORY?
--------------------------------

Placing downloaded and custom modules in this directory separates downloaded and
custom modules from Drupal core's modules. This allows Drupal core to be updated
without overwriting these files.

DOWNLOAD ADDITIONAL MODULES
---------------------------

Contributed modules from the Drupal community may be downloaded at
https://www.drupal.org/project/project_module.

ORGANIZING MODULES IN THIS DIRECTORY
------------------------------------

You may create subdirectories in this directory, to organize your added modules,
without breaking the site. Some common subdirectories include "contrib" for
contributed modules, and "custom" for custom modules. Note that if you move a
module to a subdirectory after it has been enabled, you may need to clear the
Drupal cache so it can be found.

There are number of directories that are ignored when looking for modules. These
are 'src', 'lib', 'vendor', 'assets', 'css', 'files', 'images', 'js', 'misc',
'templates', 'includes', 'fixtures' and 'Drupal'.

MULTISITE CONFIGURATION
-----------------------

In multisite configurations, modules found in this directory are available to
all sites. You may also put modules in the sites/all/modules directory, and the
versions in sites/all/modules will take precedence over versions of the same
module that are here. Alternatively, the sites/your_site_name/modules directory
pattern may be used to restrict modules to a specific site instance.

MORE INFORMATION
----------------

Refer to the “Developing for Drupal” section of the README.txt in the Drupal
root directory for further information on extending Drupal with custom modules.

+ 339
- 0
modules/contrib/fontawesome/LICENSE.txt Dosyayı Görüntüle

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.

We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and
modification follow.

GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.

b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.

c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,

b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,

c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

NO WARRANTY

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.

<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

+ 104
- 0
modules/contrib/fontawesome/README.txt Dosyayı Görüntüle

@@ -0,0 +1,104 @@

CONTENTS OF THIS FILE
---------------------

* Introduction
* Installation
* Usage
* Credits


INTRODUCTION 8.2.x version
------------
Font Awesome (http://fontawesome.com) is the web's most popular icon set and
toolkit. This release of the Font Awesome Icons module supports Font Awesome
versions higher than 5.0. For older versions of Font Awesome, you should
download and install Font Awesome Icons 8.1.x. See the Font Awesome Icons
page on Drupal.org for more information.

"fontawesome" provides integration of "Font Awesome" with Drupal. Once enabled
"Font Awesome" icon fonts could be used as:

1. Directly inside of any HTML (node/block/view/panel). Inside HTML you can
place Font Awesome icons just about anywhere with an <i> tag.

Example for an info icon: <i class="fas fa-camera-retro"></i>

See more examples of using "Font Awesome" within HTML at:
https://fontawesome.com/how-to-use/on-the-web/referencing-icons/basic-use


INSTALLATION
------------

1. Using Drush (https://github.com/drush-ops/drush#readme)

$ drush en fontawesome

Upon enabling, this will also attempt to download and install the library
in `/libraries/fontawesome`. If, for whatever reason, this process
fails, you can re-run the library install manually by first clearing Drush
caches:

$ drush cc drush

and then using another drush command:-

(Drush 8)
$ drush fa-download
(Drush 9)
$ drush fa:download

2. Manually

a. Install the "Font Awesome" library following one of these 2 options:
- run "drush fa-download" (recommended, it will download the right
package and extract it at the right place for you.)
- manual install: Download & extract "Font Awesome"
(http://fontawesome.com) and place inside
"/libraries/fontawesome" directory. The JS file should
be at /libraries/fontawesome/js/all.js
Direct link for downloading latest version (current is v5.13.1) is:
https://use.fontawesome.com/releases/v5.13.1/fontawesome-free-5.13.1-web.zip
b. Enable the module at Administer >> Site building >> Modules.


USAGE
_____
Font Awesome can be used in many ways - you can manually insert Font Awesome
tags wherever you see fit after enabling the module, but there are other ways
as well. See
https://fontawesome.com/how-to-use/on-the-web/referencing-icons/basic-use
for information on basic usage.

CSS Pseudo-elements - if you are using the older version of Font Awesome, CSS
with webfonts, you can use CSS Pseudo-elements for inserting your icons rather
than the default method. See
https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements
for more information on how to add the icons through CSS.

Font Awesome icon field - this module includes the option to add a Font Awesome
icon field to any of your content types without the need for coding.

Font Awesome CKEditor plugin - this module includes a CKEditor plugin which
will allow you to insert Font Awesome icons into any CKEditor text field with
the plugin enabled. It can be enabled under
Configuration -> Content authoring -> Text formats and editors
From here, simply add the icon to your active toolbar (it looks like a flag).
Please note that in order to use SVG with JS version of Font Awesome, you will
need to either disable the "Correct faulty and chopped off HTML" filter, or you
will have to add the required SVG tags to the exception list. A list of SVG
tags can be found here:
https://www.w3.org/TR/SVG11/eltindex.html
or
https://developer.mozilla.org/en-US/docs/Web/SVG/Element


CREDITS
-------
* Rob Loach (RobLoach) http://robloach.net
* Inder Singh (inders) http://indersingh.com | https://www.drupal.org/u/inders
* Mark Carver https://www.drupal.org/u/mark-carver
* Brian Gilbert https://drupal.org/u/realityloop
* Daniel Moberly https://drupal.org/u/danielmoberly
* Truls S. Yggeseth https://drupal.org/u/truls1502

+ 15
- 0
modules/contrib/fontawesome/composer.json Dosyayı Görüntüle

@@ -0,0 +1,15 @@
{
"name": "drupal/fontawesome",
"description": "The web's most popular icon set and toolkit.",
"type": "drupal-module",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/fontawesome",
"minimum-stability": "dev",
"extra": {
"drush": {
"services": {
"drush.services.yml": "^9"
}
}
}
}

+ 12
- 0
modules/contrib/fontawesome/config/install/fontawesome.settings.yml Dosyayı Görüntüle

@@ -0,0 +1,12 @@
tag: 'i'
method: 'svg'
use_cdn: true
external_svg_location: 'https://use.fontawesome.com/releases/v5.13.1/js/all.js'
use_shim: true
external_shim_location: 'https://use.fontawesome.com/releases/v5.13.1/js/v4-shims.js'
use_solid_file: true
use_regular_file: true
use_light_file: true
use_brands_file: true
use_duotone_file: true
external_svg_integrity: null

+ 43
- 0
modules/contrib/fontawesome/config/schema/fontawesome.schema.yml Dosyayı Görüntüle

@@ -0,0 +1,43 @@
fontawesome.settings:
type: config_object
label: 'Font Awesome settings'
mapping:
tag:
type: string
label: 'Tag used for Font Awesome elements'
method:
type: string
label: 'Method used for delivering Font Awesome'
use_cdn:
type: boolean
label: 'Use CDN to serve Font Awesome'
external_svg_location:
type: string
label: 'Location of the external CDN for Font Awesome'
use_shim:
type: boolean
label: 'Use Shim File for v4 compatibility'
external_shim_location:
type: string
label: 'Location of the external CDN for Font Awesome shim file'
allow_pseudo_elements:
type: boolean
label: 'Allow CSS pseudo elements with webfonts'
use_solid_file:
type: boolean
label: 'Use the Font Awesome solid icons file'
use_regular_file:
type: boolean
label: 'Use the Font Awesome regular icons file'
use_light_file:
type: boolean
label: 'Use the Font Awesome light icons file'
use_brands_file:
type: boolean
label: 'Use the Font Awesome brands icons file'
use_duotone_file:
type: boolean
label: 'Use the Font Awesome duotone icons file'
external_svg_integrity:
type: string
label: 'Integrity value of the external CDN for Font Awesome'

+ 9
- 0
modules/contrib/fontawesome/drush.services.yml Dosyayı Görüntüle

@@ -0,0 +1,9 @@
services:
fontawesome.commands:
class: \Drupal\fontawesome\Commands\FontawesomeCommands
arguments:
- '@library.discovery'
- '@file_system'
- '@plugin.manager.archiver'
tags:
- { name: drush.command }

+ 12
- 0
modules/contrib/fontawesome/fontawesome.info.yml Dosyayı Görüntüle

@@ -0,0 +1,12 @@
name: 'Font Awesome'
type: module
description: 'The most popular icon set and toolkit on the web.'

core: 8.x
core_version_requirement: ^8 || ^9
configure: fontawesome.admin_settings

# Information added by Drupal.org packaging script on 2020-07-02
version: '8.x-2.17'
project: 'fontawesome'
datestamp: 1593708091

+ 104
- 0
modules/contrib/fontawesome/fontawesome.install Dosyayı Görüntüle

@@ -0,0 +1,104 @@
<?php

/**
* @file
* Requirements page for Font Awesome.
*/

use Drupal\Core\Link;

/**
* Implements hook_requirements().
*/
function fontawesome_requirements($phase) {
$requirements = [];

// Report the version of Font Awesome.
if ($phase == 'runtime') {
$requirements['fontawesome'] = [
'title' => t('Font Awesome 5'),
];

// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Check if Font Awesome is installed.
if (fontawesome_check_installed()) {
// Get the version.
if ($configuration_settings->get('method') == 'webfonts') {
$version = t('Webfonts with CSS');
}
elseif ($configuration_settings->get('use_cdn')) {
$version = t('CDN SVG with JS');
}
else {
$version = t('SVG with JS');
}

// First check if we're using everything.
if (is_null($configuration_settings->get('use_solid_file')) === TRUE || ($configuration_settings->get('use_solid_file') && $configuration_settings->get('use_regular_file') && $configuration_settings->get('use_light_file') && $configuration_settings->get('use_brands_file'))) {
// Attach the main library.
$loadedMessages = [
t('All icons loaded'),
];
}
// Else we attach the libraries piecemeal.
else {
$loadedMessages = [];
if ($configuration_settings->get('use_solid_file')) {
$loadedMessages[] = t('Solid icons loaded');
}
if ($configuration_settings->get('use_regular_file')) {
$loadedMessages[] = t('Regular icons loaded');
}
if ($configuration_settings->get('use_light_file')) {
$loadedMessages[] = t('Light icons loaded');
}
if ($configuration_settings->get('use_brands_file')) {
$loadedMessages[] = t('Brands icons loaded');
}
}

$requirements['fontawesome']['severity'] = REQUIREMENT_OK;
$requirements['fontawesome']['value'] = t('Font Awesome 5 library is installed. Using %version version. (@moreInfoLink)', [
'%version' => $version,
'@moreInfoLink' => Link::createFromRoute(t('more information'), 'fontawesome.admin_settings')->toString(),
]);
$requirements['fontawesome']['description'] = [
'#theme' => 'item_list',
'#items' => $loadedMessages,
'#title' => '',
'#list_type' => 'ul',
'#attributes' => [],
];
}
else {
$requirements['fontawesome']['severity'] = REQUIREMENT_ERROR;
$requirements['fontawesome']['value'] = t('Not installed');
$requirements['fontawesome']['description'] = t('The Font Awesome 5 library could not be found. Please verify Font Awesome 5 is installed correctly or that the CDN has been activated and properly configured. Please see the @adminPage and the Font Awesome module README file for more details.', [
'@adminPage' => Link::createFromRoute(t('admin page'), 'fontawesome.admin_settings')->toString(),
]);
}
}

return $requirements;
}

/**
* Implements hook_uninstall().
*/
function fontawesome_uninstall() {
// Delete set variables.
$query = \Drupal::database()->delete('config');
$query->condition('name', 'fontawesome.settings');
$query->execute();
$query = \Drupal::database()->delete('key_value');
$query->condition('name', 'fontawesome');
$query->execute();

// Icon API module : Delete fontawesome icon bundle & clear cache.
if (\Drupal::moduleHandler()->moduleExists('icon') && ($cache = \Drupal::cache()->get('icon_bundles')) && !empty($cache->data)) {
$fa_icon_bundle = isset($cache->data['fontawesome']) ? $cache->data['fontawesome'] : [];
$fa_icon_bundle['path'] = isset($fa_icon_bundle['path']) ? $fa_icon_bundle['path'] : 'fontawesome';
}
}

+ 143
- 0
modules/contrib/fontawesome/fontawesome.libraries.yml Dosyayı Görüntüle

@@ -0,0 +1,143 @@
fontawesome.svg:
remote: &fontawesome_remote https://use.fontawesome.com/releases/v5.13.1/fontawesome-free-5.13.1-web.zip
license: &fontawesome_svg_license
name: CC BY 4.0
url: https://fontawesome.com/license
gpl-compatible: true
version: &fontawesome_version "5.13.1"
header: true
js:
/libraries/fontawesome/js/all.min.js: { minified: true, attributes: { defer: true } }

fontawesome.svg.shim:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/v4-shims.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg

fontawesome.svg.base:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/fontawesome.min.js: { minified: true, attributes: { defer: true } }

fontawesome.svg.solid:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/solid.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg.base

fontawesome.svg.regular:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/regular.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg.base

fontawesome.svg.light:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/light.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg.base

fontawesome.svg.brands:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/brands.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg.base

fontawesome.svg.duotone:
version: *fontawesome_version
license: *fontawesome_svg_license
header: true
js:
/libraries/fontawesome/js/duotone.min.js: { minified: true, attributes: { defer: true } }
dependencies:
- fontawesome/fontawesome.svg.base

fontawesome.webfonts:
remote: *fontawesome_remote
license: &fontawesome_webfonts_license
name: SIL OFL 1.1
url: https://fontawesome.com/license
gpl-compatible: true
version: *fontawesome_version
css:
theme:
/libraries/fontawesome/css/all.min.css: { minified: true }

fontawesome.webfonts.base:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/fontawesome.min.css: { minified: true }

fontawesome.webfonts.solid:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/solid.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts.base

fontawesome.webfonts.regular:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/regular.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts.base

fontawesome.webfonts.light:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/light.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts.base

fontawesome.webfonts.brands:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/brands.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts.base

fontawesome.webfonts.duotone:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/duotone.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts.base

fontawesome.webfonts.shim:
version: *fontawesome_version
license: *fontawesome_webfonts_license
css:
theme:
/libraries/fontawesome/css/v4-shims.min.css: { minified: true }
dependencies:
- fontawesome/fontawesome.webfonts

+ 5
- 0
modules/contrib/fontawesome/fontawesome.links.menu.yml Dosyayı Görüntüle

@@ -0,0 +1,5 @@
fontawesome.admin_settings:
title: 'Font Awesome Settings'
description: 'Global settings for the display of Font Awesome icons.'
route_name: fontawesome.admin_settings
parent: 'system.admin_config_content'

+ 572
- 0
modules/contrib/fontawesome/fontawesome.module Dosyayı Görüntüle

@@ -0,0 +1,572 @@
<?php

/**
* @file
* Drupal integration with Font Awesome, the iconic font for use with Bootstrap.
*/

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Link;
use Symfony\Component\Yaml\Yaml;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\TypedData\Plugin\DataType\ItemList;

/**
* Implements hook_help().
*/
function fontawesome_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.fontawesome':
return '<p><i class="far fa-font-awesome fa-2x"></i> ' . t('<a href=":fontawesome_url">Font Awesome</a> is an iconic font and CSS toolkit. Font Awesome gives you scalable vector icons that can instantly be customized — size, color, drop shadow, and anything that can be done with the power of CSS. For more information on how to use Font Awesome, see the <a href=":fontawesome_examples_page">Font Awesome Examples page</a>.', [
':fontawesome_url' => 'https://fontawesome.com',
':fontawesome_examples_page' => 'https://fontawesome.com/how-to-use/on-the-web/referencing-icons/basic-use',
]) . '</p>';
}
}

/**
* Implements hook_library_info_alter().
*/
function fontawesome_library_info_alter(&$libraries, $extension) {
// Modify the Font Awesome library to use external file if user chose.
if ($extension == 'fontawesome') {
// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Have to modify the library if the user is using a CDN.
if ($configuration_settings->get('use_cdn')) {

// First check if we're using everything.
if (isset($libraries['fontawesome.' . $configuration_settings->get('method')])) {
_fontawesome_modify_library($libraries, NULL, $configuration_settings->get('method'), $configuration_settings->get('external_svg_location'));
}

// Determine the base for the CDN.
$cdnComponents = parse_url($configuration_settings->get('external_svg_location'));
$cdnComponents['path'] = explode('/', $cdnComponents['path']);
unset($cdnComponents['path'][count($cdnComponents['path']) - 1]);
$cdnComponents['path'] = implode('/', $cdnComponents['path']) . '/';

if (isset($libraries['fontawesome.' . $configuration_settings->get('method') . '.base'])) {
// Modify settings for the base file.
$cdnBase = $cdnComponents;
$cdnBase['path'] .= 'fontawesome.' . ($configuration_settings->get('method') == 'webfonts' ? 'css' : 'js');
_fontawesome_modify_library($libraries, 'base', $configuration_settings->get('method'), _fontawesome_unparse_url($cdnBase));
}

// Modify settings for individual included files.
foreach (['solid', 'regular', 'light', 'brands'] as $libraryType) {
if (isset($libraries['fontawesome.' . $configuration_settings->get('method') . '.' . $libraryType])) {
$cdnBase = $cdnComponents;
$cdnBase['path'] .= $libraryType . '.' . ($configuration_settings->get('method') == 'webfonts' ? 'css' : 'js');
_fontawesome_modify_library($libraries, $libraryType, $configuration_settings->get('method'), _fontawesome_unparse_url($cdnBase));
}
}

// Modify the shim as well.
if (isset($libraries['fontawesome.' . $configuration_settings->get('method') . '.shim'])) {
_fontawesome_modify_library($libraries, 'shim', $configuration_settings->get('method'), $configuration_settings->get('external_shim_location'));
}
}

// Allow pseudo-elements in JS if selected.
if ($configuration_settings->get('allow_pseudo_elements') && $configuration_settings->get('method') == 'svg') {
// Modify the libraries to add pseudo elements tag.
foreach ($libraries as $key => &$values) {
if (substr($key, 0, 15) == 'fontawesome.svg') {
$librarySettings = reset($values['js']);
$librarySource = key($values['js']);
// Font Awesome requires this script tag to enable pseudo elements.
$librarySettings['attributes'] = [
'data-search-pseudo-elements' => TRUE,
];
$values['js'][$librarySource] = $librarySettings;
}
}
}
}
}

/**
* Modifies library inclusions to use CDN files when necessary.
*
* @param array $libraries
* The libraries inclusion array.
* @param string $librarySuffix
* The suffix of the library being modified.
* @param string $type
* The type of library we are modifying.
* @param string $cdnLocation
* The location of the CDN file being used.
*/
function _fontawesome_modify_library(array &$libraries, $librarySuffix, $type, $cdnLocation) {
// Determine the name of the library.
$libraryName = 'fontawesome.' . $type;
if (!empty($librarySuffix)) {
$libraryName .= '.' . $librarySuffix;
}

// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Handle SVG method.
if ($type == 'svg') {
$librarySettings = array_shift($libraries[$libraryName]['js']);
$librarySettings['type'] = 'external';
$librarySettings['attributes']['crossorigin'] = 'anonymous';
// Add the integrity check if set.
if (!empty($configuration_settings->get('external_svg_integrity'))) {
$librarySettings['attributes']['integrity'] = $configuration_settings->get('external_svg_integrity');
}
$libraries[$libraryName]['js'] = [
$cdnLocation => $librarySettings,
];
}
// Handle WebFonts method.
elseif ($type == 'webfonts') {
$librarySettings = array_shift($libraries[$libraryName]['css']['theme']);
$librarySettings['type'] = 'external';
// TODO: add integrity and crossorigin to CSS.
// See https://www.drupal.org/project/drupal/issues/2716115.
$libraries[$libraryName]['css']['theme'] = [
$cdnLocation => $librarySettings,
];
}
}

/**
* Unparses a CDN URL for use with individual Font Awesome file inclusions.
*
* @param array $parsed
* Array containing URL parsed data.
*
* @return string
* The unparsed URL for the CDN.
*/
function _fontawesome_unparse_url(array $parsed) {
$get = function ($key) use ($parsed) {
return isset($parsed[$key]) ? $parsed[$key] : NULL;
};

$pass = $get('pass');
$user = $get('user');
$userinfo = $pass !== NULL ? "$user:$pass" : $user;
$port = $get('port');
$scheme = $get('scheme');
$query = $get('query');
$fragment = $get('fragment');
$authority = ($userinfo !== NULL ? "$userinfo@" : '') . $get('host') . ($port ? ":$port" : '');

return (strlen($scheme) ? "$scheme:" : '') . (strlen($authority) ? "//$authority" : '') . $get('path') . (strlen($query) ? "?$query" : '') . (strlen($fragment) ? "#$fragment" : '');
}

/**
* Implements hook_ckeditor_css_alter().
*
* This function allows for the proper functionality of the icons inside the
* CKEditor when using Webfonts with CSS as the Font Awesome display method.
*
* See fontawesome_editor_js_settings_alter() for allowing the use of the icons
* inside CKEditor when using the SVG with JS display method.
*/
function fontawesome_ckeditor_css_alter(&$css, $editor) {
// Attach the main library if we're using the CSS webfonts method..
if (\Drupal::config('fontawesome.settings')->get('method') == 'webfonts') {
// Load the library.
$fontawesome_library = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.webfonts');
// Attach it's CSS.
$css[] = $fontawesome_library['css'][0]['data'];

// Attach the shim CSS if needed.
if (Drupal::config('fontawesome.settings')->get('use_shim')) {
// Load the library.
$fontawesome_library_shim = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.webfonts.shim');
// Attach it's CSS.
$css[] = $fontawesome_library_shim['css'][0]['data'];
}
}
}

/**
* Check to make sure that Font Awesome is installed.
*
* @return bool
* Flag indicating if the library is properly installed.
*/
function fontawesome_check_installed() {
// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Throw error if library file not found.
if ($configuration_settings->get('use_cdn')) {
return !empty($configuration_settings->get('external_svg_location'));
}
elseif ($configuration_settings->get('method') == 'webfonts') {
// Webfonts method.
$fontawesome_library = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.webfonts');
return file_exists(DRUPAL_ROOT . '/' . $fontawesome_library['css'][0]['data']);
}
else {
// SVG method.
$fontawesome_library = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.svg');
return file_exists(DRUPAL_ROOT . '/' . $fontawesome_library['js'][0]['data']);
}
}

/**
* Implements hook_page_attachments().
*
* Purposefully only load on page requests and not hook_init(). This is
* required so it does not increase the bootstrap time of Drupal when it isn't
* necessary.
*/
function fontawesome_page_attachments(array &$page) {
// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Throw error if library file not found.
if (!fontawesome_check_installed()) {
\Drupal::messenger()->addWarning(t('The Font Awesome library could not be found. Please verify Font Awesome is installed correctly or that the CDN has been activated and properly configured. Please see the @adminPage and the Font Awesome module README file for more details.', [
'@adminPage' => Link::createFromRoute(t('admin page'), 'fontawesome.admin_settings')->toString(),
]));
return;
}

// Determine which files we are using.
$activeFiles = [
'use_solid_file' => is_null($configuration_settings->get('use_solid_file')) === TRUE ? TRUE : $configuration_settings->get('use_solid_file'),
'use_regular_file' => is_null($configuration_settings->get('use_regular_file')) === TRUE ? TRUE : $configuration_settings->get('use_regular_file'),
'use_light_file' => is_null($configuration_settings->get('use_light_file')) === TRUE ? TRUE : $configuration_settings->get('use_light_file'),
'use_brands_file' => is_null($configuration_settings->get('use_brands_file')) === TRUE ? TRUE : $configuration_settings->get('use_brands_file'),
'use_duotone_file' => is_null($configuration_settings->get('use_duotone_file')) === TRUE ? TRUE : $configuration_settings->get('use_duotone_file'),
];

// First check if we're using everything.
if (count(array_unique($activeFiles)) == 1) {
// Attach the main library.
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method');
}
// Else we attach the libraries piecemeal.
else {
if ($activeFiles['use_solid_file']) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.solid';
}
if ($activeFiles['use_regular_file']) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.regular';
}
if ($activeFiles['use_light_file']) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.light';
}
if ($activeFiles['use_brands_file']) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.brands';
}
if ($activeFiles['use_duotone_file']) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.duotone';
}
}

// Attach the shim file if needed.
if ($configuration_settings->get('use_shim')) {
$page['#attached']['library'][] = 'fontawesome/fontawesome.' . $configuration_settings->get('method') . '.shim';
}
}

/**
* Helper function returns the prefix for an icon based on icon type.
*
* @param array $styles
* An array of valid styles for the icon.
* @param string $default
* The value to assign here if it's not a brand icon.
*
* @return string
* A valid prefix for this icon.
*/
function fontawesome_determine_prefix(array $styles, $default = 'fas') {
// Determine the icon style - brands behave differently.
foreach ($styles as $style) {
if ($style == 'brands') {
return 'fab';
}
}
return $default;
}

/**
* Implements hook_theme().
*/
function fontawesome_theme($existing, $type, $theme, $path) {
return [
'fontawesomeicons' => [
'variables' => [
'icons' => NULL,
'layers' => FALSE,
],
],
'fontawesomeicon' => [
'variables' => [
'tag' => 'i',
'name' => NULL,
'style' => NULL,
'settings' => NULL,
'transforms' => NULL,
'mask' => NULL,
'css' => NULL,
],
],
];
}

/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function fontawesome_theme_suggestions_fontawesomeicon(array $variables) {
// Suggest a template with the icon name if it exists.
$suggestions = [];
if (!empty($variables['name'])) {
$suggestions[] = $variables['theme_hook_original'] . '__' . $variables['name'];
}
return $suggestions;
}

/**
* Implements hook_theme_registry_alter().
*/
function fontawesome_theme_registry_alter(&$theme_registry) {
/*
* By default, Drupal 8 does not include theme suggestions from inside the
* module in which they were created, so we must add them manually here.
*/
$path = drupal_get_path('module', 'fontawesome');
$fontawesome_templates = drupal_find_theme_templates($theme_registry, '.html.twig', $path);
foreach ($fontawesome_templates as &$fontawesome_template) {
$fontawesome_template['type'] = 'module';
}
$theme_registry += $fontawesome_templates;
}

/**
* Implements hook_icon_providers().
*/
function fontawesome_icon_providers() {
$providers['fontawesome'] = [
'title' => 'Font Awesome',
'url' => 'http://fontawesome.io',
];
return $providers;
}

/**
* Implements hook_icon_bundle_configure().
*/
function fontawesome_icon_bundle_configure(&$settings, &$form_state, &$complete_form) {
$bundle = $form_state['bundle'];
if ($bundle['provider'] === 'fontawesome') {
$settings['tag'] = [
'#type' => 'select',
'#title' => t('HTML Markup'),
'#description' => t('Choose the HTML markup tag that Font Awesome icons should be created with. Typically, this is a %tag tag, however it can be changed to suite the theme requirements.', [
'%tag' => '<' . $bundle['settings']['tag'] . '>',
]),
'#options' => array_combine(
['i', 'span'],
['i', 'span']
),
'#default_value' => $bundle['settings']['tag'],
];
}
}

/**
* Implements hook_preprocess_icon_RENDER_HOOK().
*/
function fontawesome_preprocess_icon_sprite(&$variables) {
$bundle = &$variables['bundle'];
if ($bundle['provider'] === 'fontawesome') {
// Remove the default "icon" class.
$key = array_search('icon', $variables['attributes']['class']);
if ($key !== FALSE) {
unset($variables['attributes']['class'][$key]);
}

// TODO: need to add the correct class depending on icon type.
// Add the necessary FA identifier class.
$variables['attributes']['class'][] = 'fas';

// Prepend the icon with the FA prefix (which will be used as the class).
$variables['icon'] = 'fa-' . $variables['icon'];
}
}

/**
* Implements hook_icon_bundles().
*
* TODO: this is waiting on an 8.x release of Icon API.
*/
function fontawesome_icon_bundles() {
$bundles['fontawesome'] = [
'title' => 'Font Awesome',
'provider' => 'fontawesome',
'render' => 'sprite',
'settings' => [
'tag' => 'i',
],
'icons' => fontawesome_extract_icons(),
];
return $bundles;
}

/**
* Loads the Font Awesome metadata file.
*
* @return string
* The filepath of the metadata file.
*/
function fontawesome_get_metadata_filepath() {
// Attempt to load the icons from the local library's metadata if possible.
$metadataFile = \Drupal::service('file_system')->realpath(DRUPAL_ROOT . '/libraries/fontawesome/metadata/icons.yml');
// If we can't load the local file, use the included module icons file.
if (!file_exists($metadataFile)) {
$metadataFile = drupal_get_path('module', 'fontawesome') . '/metadata/icons.yml';
}
return $metadataFile;
}

/**
* Provides a list of all available Font Awesome icons from metadata.
*
* @return array
* Array containing icons.
*/
function fontawesome_extract_icons() {
// Check for cached icons.
if (!$icons = \Drupal::cache('data')->get('fontawesome.iconlist')) {

// Parse the metadata file and use it to generate the icon list.
$icons = [];
foreach (Yaml::parse(file_get_contents(fontawesome_get_metadata_filepath())) as $name => $icon) {
// Determine the icon type - brands behave differently.
$type = 'solid';
foreach ($icon['styles'] as $style) {
if ($style == 'brands') {
$type = 'brands';
break;
}
}
$icons[$name] = [
'name' => $name,
'type' => $type,
'label' => $icon['label'],
'styles' => $icon['styles'],
];
}

// Cache the icons array.
\Drupal::cache('data')->set('fontawesome.iconlist', $icons, strtotime('+1 week'), ['fontawesome', 'iconlist']);
}
else {
$icons = $icons->data;
}

return (array) $icons;
}

/**
* Extract metadata for a specific icon.
*
* @param string $findIcon
* The icon for which we want metadata.
*
* @return array|bool
* Array containing icons.
*/
function fontawesome_extract_icon_metadata($findIcon) {
// Parse the metadata file and use it to generate the icon list.
foreach (Yaml::parse(file_get_contents(fontawesome_get_metadata_filepath())) as $name => $icon) {
if ($name == $findIcon) {
// Determine the icon type - brands behave differently.
$type = 'solid';
foreach ($icon['styles'] as $style) {
if ($style == 'brands') {
$type = 'brands';
break;
}
}
return [
'name' => $name,
'type' => $type,
'label' => $icon['label'],
'styles' => $icon['styles'],
];
}
}

return FALSE;
}

/**
* Implements hook_entity_presave().
*/
function fontawesome_entity_presave(EntityInterface $entity) {
if ($entity instanceof ContentEntityInterface) {
// Loop over the fields.
foreach ($entity->getFields() as $fields) {
if ($fields instanceof ItemList) {
// If this is a text field (uses an editor).
if (in_array($fields->getFieldDefinition()->getType(), [
'text',
'text_long',
'text_with_summary',
])) {
foreach ($fields as $field) {
// Find and replace SVG strings with original icon HTML.
$fieldValue = $field->getValue();
$fieldValue['value'] = preg_replace('%<svg .*?class="svg-inline--fa.*?<\/svg><!--\s?(.*?)\s?-->%', '$1', $fieldValue['value']);
$field->setValue($fieldValue);
}
}
}
}
}
}

/**
* Implements hook_editor_js_settings_alter().
*
* This function allows for the proper functionality of the icons inside the
* CKEditor when using SVG with JS as the Font Awesome display method. This
* function also provides for the use of empty tags inside the CKEditor. These
* tags are normally stripped, which makes the traditional method of using
* Font Awesome unworkable. Allowing those tags here lets users use the methods
* of including icons described in all of the Font Awesome guides and docs.
*
* See fontawesome_ckeditor_css_alter() for allowing the use of the icons
* inside CKEditor when using the Webfonts with CSS display method.
*/
function fontawesome_editor_js_settings_alter(array &$settings) {
// Load the configuration settings.
$configuration_settings = \Drupal::config('fontawesome.settings');

// Attach our JS libraries as needed for loading inside the editor.
if ($configuration_settings->get('method') == 'svg') {
// SVG mode requires loading javascript.
$fontawesome_library = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.svg');
if (!$configuration_settings->get('use_cdn')) {
$fontawesome_library['js'][0]['data'] = '/' . $fontawesome_library['js'][0]['data'];
}
$settings['editor']['fontawesome']['fontawesomeLibraries']['primary'] = $fontawesome_library['js'][0]['data'];

// Load the shim file as well if needed.
if ($configuration_settings->get('use_shim')) {
$fontawesome_library = \Drupal::service('library.discovery')->getLibraryByName('fontawesome', 'fontawesome.svg.shim');
if (!$configuration_settings->get('use_cdn')) {
$fontawesome_library['js'][0]['data'] = '/' . $fontawesome_library['js'][0]['data'];
}
$settings['editor']['fontawesome']['fontawesomeLibraries']['shim'] = $fontawesome_library['js'][0]['data'];
}
}

// Attach the list of allowed empty tags.
$settings['editor']['fontawesome']['allowedEmptyTags'] = ['i', 'span'];
}

+ 21
- 0
modules/contrib/fontawesome/fontawesome.routing.yml Dosyayı Görüntüle

@@ -0,0 +1,21 @@
fontawesome.admin_settings:
path: '/admin/config/content/fontawesome'
defaults:
_form: '\Drupal\fontawesome\Form\SettingsForm'
_title: 'Font Awesome settings'
requirements:
_permission: 'administer site configuration'
fontawesome.icon_dialog:
path: '/fontawesome/dialog/icon/{editor}'
defaults:
_form: '\Drupal\fontawesome\Form\EditorIconDialog'
_title: 'Add Font Awesome Icon'
requirements:
_entity_access: 'editor.use'
fontawesome.autocomplete:
path: '/fontawesome-autocomplete'
defaults:
_controller: '\Drupal\fontawesome\Controller\AutocompleteController::handleAutocomplete'
_format: json
requirements:
_access: 'TRUE'

BIN
modules/contrib/fontawesome/js/plugins/drupalfontawesome/icons/drupalfontawesome.png Dosyayı Görüntüle

Önce Sonra
Genişlik: 16  |  Yükseklik: 16  |  Boyut: 457B

BIN
modules/contrib/fontawesome/js/plugins/drupalfontawesome/icons/hidpi/drupalfontawesome.png Dosyayı Görüntüle

Önce Sonra
Genişlik: 32  |  Yükseklik: 32  |  Boyut: 637B

+ 139
- 0
modules/contrib/fontawesome/js/plugins/drupalfontawesome/plugin.es6.js Dosyayı Görüntüle

@@ -0,0 +1,139 @@
/**
* @file
* Drupal Font Awesome plugin.
*
* @ignore
*/

(($, Drupal, drupalSettings, CKEDITOR) => {
'use strict';

CKEDITOR.plugins.add('drupalfontawesome', {
icons: 'drupalfontawesome',
hidpi: true,

init(editor) {
// Add the command for inserting Font Awesome icons.
editor.addCommand('drupalfontawesome', {
modes: { wysiwyg: 1 },
canUndo: true,
exec(execEditor) {
// Prepare a save callback to be used upon saving the dialog.
const saveCallback = (returnValues) => {
execEditor.fire('saveSnapshot');

// Create a new icon element if needed.
const selection = execEditor.getSelection();
const range = selection.getRanges(1)[0];

// Create the container span for the icon.
var container = new CKEDITOR.dom.element('span', execEditor.document);
container.addClass('fontawesome-icon-inline');
// Create the icon element from the editor.
var icon = new CKEDITOR.dom.element(returnValues.tag, execEditor.document);
icon.setAttributes(returnValues.attributes);
// Add the icon to the container.
container.append(icon);
// CKEditor doesn't play well with SVG - this allows editing.
container.appendHtml('&nbsp;');

// Add the container to the range.
range.insertNode(container);
range.select();

// Save snapshot for undo support.
execEditor.fire('saveSnapshot');

// Fire custom event so we can reload SVGs.
execEditor.fire('insertedIcon');
};

// Drupal.t() will not work inside CKEditor plugins because CKEditor
// loads the JavaScript file instead of Drupal. Pull translated
// strings from the plugin settings that are translated server-side.
const dialogSettings = {
title: execEditor.config.drupalFontAwesome_dialogTitleAdd,
dialogClass: 'fontawesome-icon-dialog',
};

// Open the dialog for the edit form.
Drupal.ckeditor.openDialog(execEditor, Drupal.url(`fontawesome/dialog/icon/${execEditor.config.drupal.format}`), {}, saveCallback, dialogSettings);
},
});

// Add button for icons.
if (editor.ui.addButton) {
editor.ui.addButton('DrupalFontAwesome', {
label: Drupal.t('Font Awesome'),
command: 'drupalfontawesome',
});
}
},
});

// Allow empty tags in the CKEditor since Font Awesome requires them.
if ('editor' in drupalSettings && 'fontawesome' in drupalSettings.editor) {
$.each(drupalSettings.editor.fontawesome.allowedEmptyTags, (_, tag) => {
CKEDITOR.dtd.$removeEmpty[tag] = 0;
});
}

// Define FontAwesome conversion functions.
Drupal.FontAwesome = {};

// Converts HTML tags to SVG by loading the attached libraries.
Drupal.FontAwesome.tagsToSvg = (drupalSettings, thisEditor) => {
if ('editor' in drupalSettings && 'fontawesome' in drupalSettings.editor) {
// Loop over each SVG library and include them. These convert the tags.
$.each(drupalSettings.editor.fontawesome.fontawesomeLibraries, (_, library) => {
// Create a script.
const $script = document.createElement('script');
const $editorInstance = CKEDITOR.instances[thisEditor.editor.name];
// Point the script at our library.
$script.src = library;

$editorInstance.document.getHead().$.appendChild($script);
});
}
};

// Converts the resulting SVG tags back to their original HTML tags.
Drupal.FontAwesome.svgToTags = (thisEditor) => {
// Get the current body of text.
let htmlBody = thisEditor.editor.getData();
// Turn the SVGs back into their original icons.
htmlBody = htmlBody.replace(/<svg .*?class="svg-inline--fa.*?<\/svg><!--\s?(.*?)\s?-->/g, '$1');
// Set the body to the new value.
thisEditor.editor.setData(htmlBody);
};

// After CKEditor is ready.
CKEDITOR.on(
'instanceReady',
(ev) => {
// On initial load, convert icons to SVGs.
Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);

// On mode change, deal with the changes on the fly.
ev.editor.on('mode', () => {
if (ev.editor.mode === 'source') {
// If we are showing source, turn SVG back to original tags.
Drupal.FontAwesome.svgToTags(ev);
}
else if (ev.editor.mode === 'wysiwyg') {
// If switching back to the display mode, have to load SVGs again.
Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);
}
});

// Listen to the event for inserting icons from the plugin.
ev.editor.on('insertedIcon', () => {
// todo: For some reason this throws an 'Uncaught TypeError'.
// Force an update to the content.
ev.editor.setData(ev.editor.getData());
// Then reload the SVGs.
Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);
});
},
);
})(jQuery, Drupal, drupalSettings, CKEDITOR);

+ 105
- 0
modules/contrib/fontawesome/js/plugins/drupalfontawesome/plugin.js Dosyayı Görüntüle

@@ -0,0 +1,105 @@
/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/

(function ($, Drupal, drupalSettings, CKEDITOR) {
'use strict';

CKEDITOR.plugins.add('drupalfontawesome', {
icons: 'drupalfontawesome',
hidpi: true,

init: function init(editor) {
editor.addCommand('drupalfontawesome', {
modes: { wysiwyg: 1 },
canUndo: true,
exec: function exec(execEditor) {
var saveCallback = function saveCallback(returnValues) {
execEditor.fire('saveSnapshot');

var selection = execEditor.getSelection();
var range = selection.getRanges(1)[0];

var container = new CKEDITOR.dom.element('span', execEditor.document);
container.addClass('fontawesome-icon-inline');
var icon = new CKEDITOR.dom.element(returnValues.tag, execEditor.document);
icon.setAttributes(returnValues.attributes);
container.append(icon);
container.appendHtml('&nbsp;');

range.insertNode(container);
range.select();

execEditor.fire('saveSnapshot');

execEditor.fire('insertedIcon');
};

var dialogSettings = {
title: execEditor.config.drupalFontAwesome_dialogTitleAdd,
dialogClass: 'fontawesome-icon-dialog'
};

Drupal.ckeditor.openDialog(execEditor, Drupal.url('fontawesome/dialog/icon/' + execEditor.config.drupal.format), {}, saveCallback, dialogSettings);
}
});

if (editor.ui.addButton) {
editor.ui.addButton('DrupalFontAwesome', {
label: Drupal.t('Font Awesome'),
command: 'drupalfontawesome'
});
}
}
});

if ('editor' in drupalSettings && 'fontawesome' in drupalSettings.editor) {
$.each(drupalSettings.editor.fontawesome.allowedEmptyTags, function (_, tag) {
CKEDITOR.dtd.$removeEmpty[tag] = 0;
});
}

Drupal.FontAwesome = {};

Drupal.FontAwesome.tagsToSvg = function (drupalSettings, thisEditor) {
if ('editor' in drupalSettings && 'fontawesome' in drupalSettings.editor) {
$.each(drupalSettings.editor.fontawesome.fontawesomeLibraries, function (_, library) {
var $script = document.createElement('script');
var $editorInstance = CKEDITOR.instances[thisEditor.editor.name];

$script.src = library;

$editorInstance.document.getHead().$.appendChild($script);
});
}
};

Drupal.FontAwesome.svgToTags = function (thisEditor) {
var htmlBody = thisEditor.editor.getData();

htmlBody = htmlBody.replace(/<svg .*?class="svg-inline--fa.*?<\/svg><!--\s?(.*?)\s?-->/g, '$1');

thisEditor.editor.setData(htmlBody);
};

CKEDITOR.on('instanceReady', function (ev) {
Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);

ev.editor.on('mode', function () {
if (ev.editor.mode === 'source') {
Drupal.FontAwesome.svgToTags(ev);
} else if (ev.editor.mode === 'wysiwyg') {
Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);
}
});

ev.editor.on('insertedIcon', function () {
ev.editor.setData(ev.editor.getData());

Drupal.FontAwesome.tagsToSvg(drupalSettings, ev);
});
});
})(jQuery, Drupal, drupalSettings, CKEDITOR);

+ 40944
- 0
modules/contrib/fontawesome/metadata/icons.yml
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle


+ 14
- 0
modules/contrib/fontawesome/modules/fontawesome_media/fontawesome_media.info.yml Dosyayı Görüntüle

@@ -0,0 +1,14 @@
name: 'Font Awesome Media Entity'
type: module
description: 'Adds a Font Awesome Media Entity Type.'

core: 8.x
core_version_requirement: ^8 || ^9
dependencies:
- fontawesome:fontawesome
- drupal:svg_image

# Information added by Drupal.org packaging script on 2020-07-02
version: '8.x-2.17'
project: 'fontawesome'
datestamp: 1593708091

+ 100
- 0
modules/contrib/fontawesome/modules/fontawesome_media/src/Plugin/media/Source/FontAwesomeIconMedia.php Dosyayı Görüntüle

@@ -0,0 +1,100 @@
<?php

namespace Drupal\fontawesome_media\Plugin\media\Source;

use Drupal\media\MediaInterface;
use Drupal\media\MediaSourceBase;
use Drupal\fontawesome\Plugin\Field\FieldType\FontAwesomeIcon;

/**
* Media source wrapping around a Font Awesome icon field.
*
* @see \Drupal\fontawesome\Plugin\Field\FieldType\FontAwesomeIcon
*
* @MediaSource(
* id = "font_awesome_icon",
* label = @Translation("Font Awesome Icon"),
* description = @Translation("Use a Font Awesome Icon for reusable media."),
* allowed_field_types = {"fontawesome_icon"},
* default_thumbnail_filename = "generic.png"
* )
*/
class FontAwesomeIconMedia extends MediaSourceBase {

/**
* {@inheritdoc}
*/
public function getMetadataAttributes() {
return [
'title' => $this->t('Title'),
];
}

/**
* {@inheritdoc}
*/
public function getMetadata(MediaInterface $media, $attribute_name) {
/** @var \Drupal\fontawesome\Plugin\Field\FieldType\FontAwesomeIcon $icon */
$icon = $media
->get($this->configuration['source_field'])
->first();

// If the source field is not required, it may be empty.
if (!$icon->isEmpty()) {
return parent::getMetadata($media, $attribute_name);
}
switch ($attribute_name) {
case 'default_name':
return $icon
->get('icon_name')
->getValue();

case 'thumbnail_uri':
return $this->getThumbnail($icon);

default:
return parent::getMetadata($media, $attribute_name);
}
}

/**
* Gets the thumbnail image URI based on an icon entity.
*
* @param \Drupal\fontawesome\Plugin\Field\FieldType\FontAwesomeIcon $icon
* A Font Awesome Iocn entity.
*
* @return string
* File URI of the thumbnail image or NULL if there is no specific icon.
*/
protected function getThumbnail(FontAwesomeIcon $icon) {

// Determine the source folder.
switch ($icon->get('style')->getValue()) {
case 'fab':
$srcFolder = 'brands';
break;

case 'fal':
$srcFolder = 'light';
break;

case 'fas':
$srcFolder = 'solid';
break;

case 'far':
default:
$srcFolder = 'regular';
break;

case 'fad':
$srcFolder = 'duotone';
break;
}

return 'libraries/fontawesome/svgs/' . $srcFolder . '/' . $icon
->get('icon_name')
->getValue() . '.svg';
}

}

+ 123
- 0
modules/contrib/fontawesome/src/Commands/FontawesomeCommands.php Dosyayı Görüntüle

@@ -0,0 +1,123 @@
<?php

namespace Drupal\fontawesome\Commands;

use Drush\Commands\DrushCommands;
use Drupal\Core\Asset\LibraryDiscovery;
use Drupal\Core\File\FileSystem;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Archiver\ArchiverManager;

/**
* A Drush commandfile for Font Awesome module.
*/
class FontawesomeCommands extends DrushCommands {

/**
* Library discovery service.
*
* @var \Drupal\Core\Asset\LibraryDiscovery
*/
protected $libraryDiscovery;

/**
* File system service.
*
* @var \Drupal\Core\File\FileSystem
*/
protected $fileSystem;

/**
* Archive manager service.
*
* @var \Drupal\Core\Archiver\ArchiverManager
*/
protected $archiverManager;

/**
* {@inheritdoc}
*/
public function __construct(LibraryDiscovery $library_discovery, FileSystem $file_system, ArchiverManager $archiver_manager) {
parent::__construct();

$this->libraryDiscovery = $library_discovery;
$this->fileSystem = $file_system;
$this->archiverManager = $archiver_manager;
}

/**
* Downloads the required Fontawesome library.
*
* @param string $path
* Optional path to module. If omitted Drush will use the default location.
*
* @command fa:download
* @aliases fadl,fa-download
*/
public function download($path = '') {

if (empty($path)) {
// We have dependencies on libraries module so no need to check for that
// TODO: any way to get path for libraries directory?
// Just in case if it is site specific? e.g. sites/domain.com/libraries ?
$path = DRUPAL_ROOT . '/libraries/fontawesome';
}

// Create the path if it does not exist yet. Added substr check for
// preventing any wrong attempts or hacks !
if (substr($path, -11) == 'fontawesome' && !is_dir($path)) {
$this->fileSystem->mkdir($path);
}
if (is_dir($path . '/css')) {
$this->logger()->notice(dt('Font Awesome already present at @path. No download required.', ['@path' => $path]));
return;
}

// Load the Font Awesome defined library.
if ($fontawesome_library = $this->libraryDiscovery->getLibraryByName('fontawesome', 'fontawesome.svg')) {

// Download the file.
$destination = tempnam(sys_get_temp_dir(), 'file.') . "tar.gz";
system_retrieve_file($fontawesome_library['remote'], $destination);
if (!file_exists($destination)) {
// Remove the directory.
$this->fileSystem->rmdir($path);
$this->logger()->error(dt('Drush was unable to download the Font Awesome library from @remote.', [
'@remote' => $fontawesome_library['remote'],
]));
return;
}
$this->fileSystem->move($destination, $path . '/fontawesome.zip');
if (!file_exists($path . '/fontawesome.zip')) {
// Remove the directory where we tried to install.
$this->fileSystem->rmdir($path);
$this->logger()->error(dt('Error: unable to download Fontawesome library from @remote', [
'@remote' => $fontawesome_library['remote'],
]));
return;
}

// Unzip the file.
/** @var \Drupal\Core\Archiver\ArchiverInterface $zipFile */
$zipFile = $this->archiverManager->getInstance(['filepath' => $path . '/fontawesome.zip']);
$zipFile->extract($path);

// Remove the downloaded zip file.
$this->fileSystem->unlink($path . '/fontawesome.zip');

// Move the file.
$this->fileSystem->move($path . '/fontawesome-free-' . $fontawesome_library['version'] . '-web', $this->fileSystem->getTempDirectory() . '/temp_fontawesome', FileSystemInterface::EXISTS_REPLACE);
$this->fileSystem->rmdir($path);
$this->fileSystem->move($this->fileSystem->getTempDirectory() . '/temp_fontawesome', $path, FileSystemInterface::EXISTS_REPLACE);

// Success.
$this->logger()->notice(dt('Fontawesome library has been successfully downloaded to @path.', [
'@path' => $path,
]));
}
else {
$this->logger()->error(dt('Drush was unable to load the Font Awesome library'));
}
}

}

+ 80
- 0
modules/contrib/fontawesome/src/Controller/AutocompleteController.php Dosyayı Görüntüle

@@ -0,0 +1,80 @@
<?php

namespace Drupal\fontawesome\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Render\FormattableMarkup;

/**
* Defines a route controller for entity autocomplete form elements.
*/
class AutocompleteController extends ControllerBase {

/**
* Handler for autocomplete request.
*/
public function handleAutocomplete(Request $request) {
$results = [];

// Get the typed string from the URL, if it exists.
if ($input = $request->query->get('q')) {
$typed_string = Tags::explode($input);
$typed_string = mb_strtolower(array_pop($typed_string));

// Load the icon data so we can check for a valid icon.
$iconData = fontawesome_extract_icons();

// Check each icon to see if it starts with the typed string.
foreach ($iconData as $icon => $data) {
// If the string is found.
if (strpos($icon, $typed_string) === 0) {
$iconRenders = [];
// Loop over each style.
foreach ($iconData[$icon]['styles'] as $style) {

// Determine the prefix.
switch ($style) {

case 'brands':
$iconPrefix = 'fab';
break;

case 'light':
$iconPrefix = 'fal';
break;

case 'regular':
$iconPrefix = 'far';
break;

case 'duotone':
$iconPrefix = 'fad';
break;

default:
case 'solid':
$iconPrefix = 'fas';
break;
}
// Render the icon.
$iconRenders[] = new FormattableMarkup('<i class=":prefix fa-:icon fa-fw fa-2x"></i> ', [
':prefix' => $iconPrefix,
':icon' => $icon,
]);
}

$results[] = [
'value' => $icon,
'label' => implode('', $iconRenders) . $icon,
];
}
}
}

return new JsonResponse($results);
}

}

+ 467
- 0
modules/contrib/fontawesome/src/Form/EditorIconDialog.php Dosyayı Görüntüle

@@ -0,0 +1,467 @@
<?php

namespace Drupal\fontawesome\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\editor\Ajax\EditorDialogSave;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Config\ConfigFactory;

/**
* Provides a Font Awesome icon dialog for text editors.
*/
class EditorIconDialog extends FormBase {
/**
* Drupal configuration service container.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;

/**
* {@inheritdoc}
*/
public function __construct(ConfigFactory $config_factory) {
$this->configFactory = $config_factory;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory')
);
}

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'fontawesome_icon_dialog';
}

/**
* {@inheritdoc}
*
* @param array $form
* Form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
* @param \Drupal\editor\Entity\Editor $editor
* The text editor to which this dialog corresponds.
*/
public function buildForm(array $form, FormStateInterface $form_state, Editor $editor = NULL) {
// Load the configuration settings.
$configuration_settings = $this->configFactory->get('fontawesome.settings');

$form['#tree'] = TRUE;
$form['#attached']['library'][] = 'editor/drupal.editor.dialog';

$form['#prefix'] = '<div id="fontawesome-icon-dialog-form">';
$form['#suffix'] = '</div>';

$form['information'] = [
'#type' => 'container',
'#attributes' => [],
'#children' => $this->t('For more information on icon selection, see @iconLink. If an icon below is displayed with a question mark, it is likely a Font Awesome Pro icon, unavailable with the free version of Font Awesome.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
];

$form['icon_name'] = [
'#type' => 'textfield',
'#title' => $this->t('Icon Name'),
'#size' => 50,
'#field_prefix' => 'fa-',
'#default_value' => '',
'#description' => $this->t('Name of the Font Awesome Icon. See @iconsLink for valid icon names, or begin typing for an autocomplete list.', [
'@iconsLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#autocomplete_route_name' => 'fontawesome.autocomplete',
'#element_validate' => [
[static::class, 'validateIconName'],
],
];

// Build additional settings.
$form['settings'] = [
'#type' => 'details',
'#open' => FALSE,
'#title' => $this->t('Additional Font Awesome Settings'),
];
// Allow user to determine size.
$form['settings']['style'] = [
'#type' => 'select',
'#title' => $this->t('Style'),
'#description' => $this->t('This changes the style of the icon. Please note that this is not available for all icons, and for some of the icons this is only available in the pro version. If the icon does not render properly in the preview above, the icon does not support that style. Notably, brands do not support any styles. See @iconLink for more information.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#options' => [
'fas' => $this->t('Solid'),
'far' => $this->t('Regular'),
'fal' => $this->t('Light'),
'fad' => $this->t('Duotone'),
],
'#default_value' => 'fas',
];
// Allow user to determine size.
$form['settings']['size'] = [
'#type' => 'select',
'#title' => $this->t('Size'),
'#description' => $this->t('This increases icon sizes relative to their container'),
'#options' => [
'' => $this->t('Default'),
'fa-xs' => $this->t('Extra Small'),
'fa-sm' => $this->t('Small'),
'fa-lg' => $this->t('Large'),
'fa-2x' => $this->t('2x'),
'fa-3x' => $this->t('3x'),
'fa-4x' => $this->t('4x'),
'fa-5x' => $this->t('5x'),
'fa-6x' => $this->t('6x'),
'fa-7x' => $this->t('7x'),
'fa-8x' => $this->t('8x'),
'fa-9x' => $this->t('9x'),
'fa-10x' => $this->t('10x'),
],
'#default_value' => '',
];
// Set icon to fixed width.
$form['settings']['fixed-width'] = [
'#type' => 'checkbox',
'#title' => $this->t('Fixed Width?'),
'#description' => $this->t('Use to set icons at a fixed width. Great to use when different icon widths throw off vertical alignment. Especially useful in things like nav lists and list groups.'),
'#default_value' => FALSE,
'#return_value' => 'fa-fw',
];
// Add border.
$form['settings']['border'] = [
'#type' => 'checkbox',
'#title' => $this->t('Border?'),
'#description' => $this->t('Adds a border to the icon.'),
'#default_value' => FALSE,
'#return_value' => 'fa-border',
];
// Invert color.
$form['settings']['invert'] = [
'#type' => 'checkbox',
'#title' => $this->t('Invert color?'),
'#description' => $this->t('Inverts the color of the icon (black becomes white, etc.)'),
'#default_value' => FALSE,
'#return_value' => 'fa-inverse',
];
// Animated the icon.
$form['settings']['animation'] = [
'#type' => 'select',
'#title' => $this->t('Animation'),
'#description' => $this->t('Use spin to get any icon to rotate, and pulse to have it rotate with 8 steps. Works especially well with fa-spinner & everything in the @iconLink.', [
'@iconLink' => Link::fromTextAndUrl($this->t('spinner icons category'), Url::fromUri('https://fontawesome.com/icons?d=gallery&c=spinners'))->toString(),
]),
'#options' => [
'' => $this->t('None'),
'fa-spin' => $this->t('Spin'),
'fa-pulse' => $this->t('Pulse'),
],
'#default_value' => '',
];

// Pull the icons.
$form['settings']['pull'] = [
'#type' => 'select',
'#title' => $this->t('Pull'),
'#description' => $this->t('This setting will pull the icon (float) to one side or the other in relation to its nearby content'),
'#options' => [
'' => $this->t('None'),
'fa-pull-left' => $this->t('Left'),
'fa-pull-right' => $this->t('Right'),
],
'#default_value' => '',
];

// Build new power-transforms.
$form['settings']['power_transforms'] = [
'#type' => 'details',
'#open' => FALSE,
'#disabled' => $configuration_settings->get('method') == 'webfonts',
'#title' => $this->t('Power Transforms'),
'#description' => $this->t('See @iconLink for additional information on Power Transforms. Note that these transforms only work with the SVG with JS version of Font Awesome and are disabled for Webfonts. See the @adminLink to set your version of Font Awesome.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome `Power Transforms` guide'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/power-transforms'))->toString(),
'@adminLink' => Link::createFromRoute($this->t('admin page'), 'fontawesome.admin_settings')->toString(),
]),
];
// Rotate the icon.
$form['settings']['power_transforms']['rotate']['value'] = [
'#type' => 'number',
'#title' => $this->t('Rotate'),
'#field_suffix' => '&deg;',
'#default_value' => '',
'#description' => $this->t('Power Transform rotating effects icon angle without changing or moving the container. To rotate icons use any arbitrary value. Units are degrees with negative numbers allowed.'),
];
// Flip the icon.
$form['settings']['power_transforms']['flip-h']['value'] = [
'#type' => 'checkbox',
'#title' => $this->t('Flip Horizontal?'),
'#default_value' => FALSE,
'#description' => $this->t('Power Transform flipping effects icon reflection without changing or moving the container.'),
'#return_value' => 'h',
];
$form['settings']['power_transforms']['flip-v']['value'] = [
'#type' => 'checkbox',
'#title' => $this->t('Flip Vertical?'),
'#default_value' => FALSE,
'#description' => $this->t('Power Transform flipping effects icon reflection without changing or moving the container.'),
'#return_value' => 'v',
];
// Scale the icon.
$form['settings']['power_transforms']['scale'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Scale'),
'#description' => $this->t('Power Transform scaling effects icon size without changing or moving the container. This field will scale icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
];
$form['settings']['power_transforms']['scale']['type'] = [
'#type' => 'select',
'#title' => $this->t('Scale Type'),
'#options' => [
'' => $this->t('None'),
'shrink' => $this->t('Shrink'),
'grow' => $this->t('Grow'),
],
'#default_value' => '',
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$form['settings']['power_transforms']['scale']['value'] = [
'#type' => 'number',
'#title' => $this->t('Scale Value'),
'#min' => 0,
'#default_value' => '',
'#states' => [
'disabled' => [
':input[name="settings[power_transforms][scale][type]"]' => ['value' => ''],
],
],
];
// Position the icon.
$form['settings']['power_transforms']['position_y'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Position (Y Axis)'),
'#description' => $this->t('Power Transform positioning effects icon location without changing or moving the container. This field will move icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
];
$form['settings']['power_transforms']['position_y']['type'] = [
'#type' => 'select',
'#title' => $this->t('Position Type'),
'#options' => [
'' => $this->t('None'),
'up' => $this->t('Up'),
'down' => $this->t('Down'),
],
'#default_value' => '',
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$form['settings']['power_transforms']['position_y']['value'] = [
'#type' => 'number',
'#title' => $this->t('Position Value'),
'#min' => 0,
'#default_value' => '',
'#states' => [
'disabled' => [
':input[name="settings[power_transforms][position_y][type]"]' => ['value' => ''],
],
],
];
$form['settings']['power_transforms']['position_x'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Position (X Axis)'),
'#description' => $this->t('Power Transform positioning effects icon location without changing or moving the container. This field will move icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
];
$form['settings']['power_transforms']['position_x']['type'] = [
'#type' => 'select',
'#title' => $this->t('Position Type'),
'#options' => [
'' => $this->t('None'),
'left' => $this->t('Left'),
'right' => $this->t('Right'),
],
'#default_value' => '',
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$form['settings']['power_transforms']['position_x']['value'] = [
'#type' => 'number',
'#title' => $this->t('Position Value'),
'#min' => 0,
'#default_value' => '',
'#states' => [
'disabled' => [
':input[name="settings[power_transforms][position_x][type]"]' => ['value' => ''],
],
],
];

$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['save_modal'] = [
'#type' => 'submit',
'#value' => $this->t('Insert Icon'),
// No regular submit-handler. This form only works via JavaScript.
'#submit' => [],
'#ajax' => [
'callback' => '::submitForm',
'event' => 'click',
],
];

return $form;
}

/**
* Validate the Font Awesome power transforms.
*/
public static function validatePowerTransforms($element, FormStateInterface $form_state) {
$value = $element['#value'];
if (strlen($value) == 0) {
$form_state->setValueForElement($element, '');
return;
}

// Check the value of the power transform.
$transformSettings = $form_state->getValues();
foreach (array_slice($element['#parents'], 0, 3) as $key) {
$transformSettings = $transformSettings[$key];
}

if (!is_numeric($transformSettings['value'])) {
$form_state->setError($element, t("Invalid value for Font Awesome Power Transform %value. Please see @iconLink for information on correct values.", [
'%value' => $value,
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome guide to Power Transforms'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/power-transforms'))->toString(),
]));
}
}

/**
* Validate the Font Awesome icon name.
*/
public static function validateIconName($element, FormStateInterface $form_state) {
$value = $element['#value'];
if (strlen($value) == 0) {
$form_state->setValueForElement($element, '');
return;
}

// Remove the prefix if the user accidentally added it.
if (substr($value, 0, 3) == 'fa-') {
$value = substr($value, 3);
}

// Load the icon data so we can check for a valid icon.
$iconData = fontawesome_extract_icon_metadata($value);

if (!isset($iconData['name'])) {
$form_state->setError($element, t("Invalid icon name %value. Please see @iconLink for correct icon names.", [
'%value' => $value,
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]));
}
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();

if ($form_state->getErrors()) {
unset($form['#prefix'], $form['#suffix']);
$form['status_messages'] = [
'#type' => 'status_messages',
'#weight' => -10,
];
$response->addCommand(new HtmlCommand('#fontawesome-icon-dialog-form', $form));
}
else {
$item = $form_state->getValues();

// Remove the prefix if the user accidentally added it.
if (substr($item['icon_name'], 0, 3) == 'fa-') {
$item['icon_name'] = substr($item['icon_name'], 3);
}

// Massage rotate and flip values to make them format properly.
if (is_numeric($item['settings']['power_transforms']['rotate']['value'])) {
$item['settings']['power_transforms']['rotate']['type'] = 'rotate';
}
else {
unset($item['settings']['power_transforms']['rotate']);
}
if (!empty($item['settings']['power_transforms']['flip-h']['value'])) {
$item['settings']['power_transforms']['flip-h']['type'] = 'flip';
}
else {
unset($item['settings']['power_transforms']['flip-h']);
}
if (!empty($item['settings']['power_transforms']['flip-v']['value'])) {
$item['settings']['power_transforms']['flip-v']['type'] = 'flip';
}
else {
unset($item['settings']['power_transforms']['flip-v']);
}
// Determine the icon style - brands don't allow style.
$metadata = fontawesome_extract_icon_metadata($item['icon_name']);
$item['style'] = fontawesome_determine_prefix($metadata['styles'], $item['settings']['style']);
unset($item['settings']['style']);

// Remove blank data.
$item['settings'] = array_filter($item['settings']);

// Get power transforms.
$item['power_transforms'] = [];
foreach ($item['settings']['power_transforms'] as $transform) {
if (!empty($transform['type'])) {
$item['power_transforms'][] = $transform['type'] . '-' . $transform['value'];
}
}
unset($item['settings']['power_transforms']);

// Set the icon attributes.
$icon_attributes = [
'attributes' => [
'class' => [
trim($item['style'] . ' fa-' . $item['icon_name'] . ' ' . implode(' ', $item['settings'])),
],
],
];
// If there are power transforms, add them.
if (count($item['power_transforms']) > 0) {
$icon_attributes['attributes']['data-fa-transform'] = [implode(' ', $item['power_transforms'])];
}

// Load the configuration settings.
$configuration_settings = $this->configFactory->get('fontawesome.settings');

// Set the user-selected tag type being used.
$icon_attributes['tag'] = empty($configuration_settings->get('tag')) ? 'i' : $configuration_settings->get('tag');

$response->addCommand(new EditorDialogSave($icon_attributes));
$response->addCommand(new CloseModalDialogCommand());
}

return $response;
}

}

+ 285
- 0
modules/contrib/fontawesome/src/Form/SettingsForm.php Dosyayı Görüntüle

@@ -0,0 +1,285 @@
<?php

namespace Drupal\fontawesome\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Asset\LibraryDiscovery;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
* Defines a form that configures fontawesome settings.
*/
class SettingsForm extends ConfigFormBase {

/**
* Drupal LibraryDiscovery service container.
*
* @var \Drupal\Core\Asset\LibraryDiscovery
*/
protected $libraryDiscovery;

/**
* {@inheritdoc}
*/
public function __construct(ConfigFactoryInterface $config_factory, LibraryDiscovery $library_discovery) {
parent::__construct($config_factory);

$this->libraryDiscovery = $library_discovery;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
$container->get('library.discovery')
);
}

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'fontawesome_admin_settings_form';
}

/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'fontawesome.settings',
];
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Get current settings.
$fontawesome_config = $this->config('fontawesome.settings');

// Load the fontawesome libraries so we can use its definitions here.
$fontawesome_library = $this->libraryDiscovery->getLibraryByName('fontawesome', 'fontawesome.svg');

$form['tag'] = [
'#type' => 'select',
'#title' => $this->t('Font Awesome Tag'),
'#options' => [
'i' => $this->t('&lt;i&gt;'),
'span' => $this->t('&lt;span&gt;'),
],
'#default_value' => empty($fontawesome_config->get('tag')) ? 'i' : $fontawesome_config->get('tag'),
'#description' => $this->t('Font Awesome works with any consistent HTML element. By default, Font Awesome uses the &lt;i&gt; tag for its icons. However, in some cases you may want to use a different tag for your Font Awesome icons, such as a &lt;span&gt; tag. Changing the value here will change the way the tags are inserted into your site. Manually created Font Awesome tags can use any HTML element you like. Note that changing this setting will require clearing the site cache.'),
];

$form['method'] = [
'#type' => 'select',
'#title' => $this->t('Font Awesome Method'),
'#options' => [
'svg' => $this->t('SVG with JS'),
'webfonts' => $this->t('Web Fonts with CSS'),
],
'#default_value' => $fontawesome_config->get('method'),
'#description' => $this->t('This setting controls the way Font Awesome works. SVG with JS is the modern, easy, and powerful version with the most backwards compatibility. Web Fonts with CSS is the classic Font Awesome icon method that you have seen in earlier versions of Font Awesome. We recommend SVG with JS. Please note that the Webfonts with CSS version does not allow backwards compatibility with Font Awesome 4. That means you will need to check your code base to be certain that the icons are all updated to work with version 5. See @gettingStartedLink for more information.', [
'@gettingStartedLink' => Link::fromTextAndUrl($this->t('the Font Awesome guide'), Url::fromUri('https://fontawesome.com/start'))->toString(),
]),
];

$form['allow_pseudo_elements'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow CSS pseudo-elements?'),
'#description' => $this->t('If you do not want to add icons directly in code, you can add them through CSS pseudo-elements. Font Awesome has leveraged the ::before pseudo-element to add icons to a page since the very beginning. For more information on how to use pseudo-elements, see the @pseudoElementsLink. Note that this feature is always available with the Webfonts version of Font Awesome. If you turn this feature on for SVG with JS, it will slow your site down noticeably.', [
'@pseudoElementsLink' => Link::fromTextAndUrl($this->t('Font Awesome guide to pseudo-elements'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements'))->toString(),
]),
'#default_value' => $fontawesome_config->get('allow_pseudo_elements'),
];

$form['external'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('External file configuration'),
'#description' => $this->t('These settings control the method by which the Font Awesome library is loaded. You can choose to use an external (full URL) or local (relative path) library by selecting a URL / path below, or you can use a local version of the file by leaving the box unchecked and downloading the library <a href=":remoteurl">:remoteurl</a> and installing locally at %installpath. See the README for more information.', [
':remoteurl' => $fontawesome_library['remote'],
'%installpath' => '/libraries',
]),
'use_cdn' => [
'#type' => 'checkbox',
'#title' => $this->t('Use external file (CDN) / local file?'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to be loaded from the given source rather than from the local library file.'),
'#default_value' => $fontawesome_config->get('use_cdn'),
],
'external_svg_location' => [
'#type' => 'textfield',
'#title' => $this->t('External File Location'),
'#default_value' => $fontawesome_config->get('external_svg_location'),
'#size' => 80,
'#description' => $this->t('Enter a source URL for the external Font Awesome library file you wish to use. Note that this is designed for use with the <strong>SVG with JS</strong> method. Use for the Webfonts method at your own risk. This URL should point to the Font Awesome JS svg file when using <strong>SVG with JS</strong> or it should point to the Font Awesome CSS file when using <strong>Web Fonts with CSS</strong>. Leave blank to use the default Font Awesome CDN.'),
'#states' => [
'disabled' => [
':input[name="use_cdn"]' => ['checked' => FALSE],
],
'visible' => [
':input[name="use_cdn"]' => ['checked' => TRUE],
],
],
],
'external_svg_integrity' => [
'#type' => 'textfield',
'#title' => $this->t('External File Integrity Value'),
'#default_value' => $fontawesome_config->get('external_svg_integrity'),
'#size' => 80,
'#description' => $this->t('Enter an (optional) integrity value for checking the CDN. This value should be provided by Font Awesome alongside the CDN source. This will force the browser to confirm the integrity of the CDN to prevent unexpected content from being loaded.'),
'#states' => [
'disabled' => [
':input[name="use_cdn"]' => ['checked' => FALSE],
],
'visible' => [
':input[name="use_cdn"]' => ['checked' => TRUE],
],
],
],
];

$form['partial'] = [
'#type' => 'details',
'#open' => FALSE,
'#title' => $this->t('Partial file configuration'),
'#description' => $this->t('By default, Font Awesome loads all of the icons. However, you can choose to load only some of the icon files if you only want a subset of the available icons. This method can result in reduced file size. These files will be assumed to exist in the same directory as the parent <i>all.js/all.css</i> file.'),
'use_solid_file' => [
'#type' => 'checkbox',
'#title' => $this->t('Load solid icons'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to load the file containing the solid icon declarations (<i>solid.js/solid.css</i>)'),
'#default_value' => is_null($fontawesome_config->get('use_solid_file')) === TRUE ? TRUE : $fontawesome_config->get('use_solid_file'),
],
'use_regular_file' => [
'#type' => 'checkbox',
'#title' => $this->t('Load regular icons'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to load the file containing the regular icon declarations (<i>regular.js/regular.css</i>)'),
'#default_value' => is_null($fontawesome_config->get('use_regular_file')) === TRUE ? TRUE : $fontawesome_config->get('use_regular_file'),
],
'use_light_file' => [
'#type' => 'checkbox',
'#title' => $this->t('Load light icons'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to load the file containing the light icon declarations (<i>light.js/light.css</i>). Note that this a Pro-only feature.'),
'#default_value' => is_null($fontawesome_config->get('use_light_file')) === TRUE ? TRUE : $fontawesome_config->get('use_light_file'),
],
'use_brands_file' => [
'#type' => 'checkbox',
'#title' => $this->t('Load brand icons'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to load the file containing the brands icon declarations (<i>brands.js/brands.css</i>)'),
'#default_value' => is_null($fontawesome_config->get('use_brands_file')) === TRUE ? TRUE : $fontawesome_config->get('use_brands_file'),
],
'use_duotone_file' => [
'#type' => 'checkbox',
'#title' => $this->t('Load duotone icons'),
'#description' => $this->t('Checking this box will cause the Font Awesome library to load the file containing the duotone icon declarations (<i>duotone.js/duotone.css</i>)'),
'#default_value' => is_null($fontawesome_config->get('use_duotone_file')) === TRUE ? TRUE : $fontawesome_config->get('use_duotone_file'),
],
];

$form['shim'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Version 4 Backwards Compatibility'),
'#description' => $this->t('Version 5 of Font Awesome has some changes which require modifications to the way you declare many of your icons. The settings below are designed to ease that transition. See @upgradingLink for more information.', [
'@upgradingLink' => Link::fromTextAndUrl($this->t('the Font Awesome guide to upgrading version 4 to version 5'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4'))->toString(),
]),
'use_shim' => [
'#type' => 'checkbox',
'#title' => $this->t('Use version 4 shim file?'),
'#description' => $this->t('Rather than editing all of your Font Awesome declarations to use the new Font Awesome syntax, you can choose to include a shim file above. This file will allow you to use Font Awesome version 5 with Font Awesome version 4 syntax. This prevents you from needing to modify your existing code and syntax.'),
'#default_value' => $fontawesome_config->get('use_shim'),
],
'external_shim_location' => [
'#type' => 'textfield',
'#title' => $this->t('External / local Library Location'),
'#default_value' => $fontawesome_config->get('external_shim_location'),
'#size' => 80,
'#description' => $this->t('Enter a source URL for the external / local (relative path) Font Awesome v4 shim file you wish to use. This URL should point to the Font Awesome JS shim file. Leave blank to use the default Font Awesome CDN.'),
'#states' => [
'disabled' => [
':input[name="use_cdn"]' => ['checked' => FALSE],
':input[name="use_shim"]' => ['checked' => FALSE],
],
'visible' => [
':input[name="use_cdn"]' => ['checked' => TRUE],
':input[name="use_shim"]' => ['checked' => TRUE],
],
],
],
];

return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

// Validate URL.
if (!empty($values['fontawesome_external_location']) && !UrlHelper::isValid($values['fontawesome_external_location'])) {
$form_state->setErrorByName('fontawesome_external_location', $this->t('Invalid external library location.'));
}
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();

// Load the fontawesome libraries so we can use its definitions here.
$fontawesome_library = $this->libraryDiscovery->getLibraryByName('fontawesome', 'fontawesome.svg');

// Clear the library cache so we use the updated information.
$this->libraryDiscovery->clearCachedDefinitions();

// Set external file defaults.
$default_location = 'https://use.fontawesome.com/releases/v' . $fontawesome_library['version'] . '/';
$default_svg_location = $default_location . 'js/all.js';
$default_webfonts_location = $default_location . 'css/all.css';
$default_svg_shimfile_location = $default_location . 'js/v4-shims.js';
$default_webfonts_shimfile_location = $default_location . 'css/v4-shims.css';

// Use default values if CDN is checked and the locations are blank.
if ($values['use_cdn']) {
if (empty($values['external_svg_location']) || $values['external_svg_location'] == $default_webfonts_location || $values['external_svg_location'] == $default_svg_location) {
// Choose the default depending on method.
$values['external_svg_location'] = ($values['method'] == 'webfonts') ? $default_webfonts_location : $default_svg_location;
}
if ($values['use_shim'] && (empty($values['external_shim_location']) || $values['external_shim_location'] == $default_webfonts_shimfile_location || $values['external_shim_location'] == $default_svg_shimfile_location)) {
// Choose the default depending on method.
$values['external_shim_location'] = ($values['method'] == 'webfonts') ? $default_webfonts_shimfile_location : $default_svg_shimfile_location;
}
}

// Save the updated settings.
$this->config('fontawesome.settings')
->set('tag', $values['tag'])
->set('method', $values['method'])
->set('use_cdn', $values['use_cdn'])
->set('external_svg_location', (string) $values['external_svg_location'])
->set('external_svg_integrity', (string) $values['external_svg_integrity'])
->set('use_shim', $values['use_shim'])
->set('external_shim_location', (string) $values['external_shim_location'])
->set('allow_pseudo_elements', $values['allow_pseudo_elements'])
->set('use_solid_file', $values['use_solid_file'])
->set('use_regular_file', $values['use_regular_file'])
->set('use_light_file', $values['use_light_file'])
->set('use_brands_file', $values['use_brands_file'])
->set('use_duotone_file', $values['use_duotone_file'])
->save();

parent::submitForm($form, $form_state);
}

}

+ 64
- 0
modules/contrib/fontawesome/src/Plugin/CKEditorPlugin/DrupalFontAwesome.php Dosyayı Görüntüle

@@ -0,0 +1,64 @@
<?php

namespace Drupal\fontawesome\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\editor\Entity\Editor;

/**
* Defines the "drupalfontawesome" plugin.
*
* @CKEditorPlugin(
* id = "drupalfontawesome",
* label = @Translation("Drupal Font Awesome"),
* module = "fontawesome"
* )
*/
class DrupalFontAwesome extends CKEditorPluginBase {

/**
* {@inheritdoc}
*/
public function getFile() {
return drupal_get_path('module', 'fontawesome') . '/js/plugins/drupalfontawesome/plugin.js';
}

/**
* {@inheritdoc}
*/
public function getLibraries(Editor $editor) {
return [
'core/drupal.ajax',
];
}

/**
* {@inheritdoc}
*/
public function getConfig(Editor $editor) {
return [
'drupalFontAwesome_dialogTitleAdd' => $this->t('Insert Font Awesome Icon'),
];
}

/**
* {@inheritdoc}
*/
public function getButtons() {
return [
'DrupalFontAwesome' => [
'label' => $this->t('Font Awesome'),
'image' => drupal_get_path('module', 'fontawesome') . '/js/plugins/drupalfontawesome/icons/drupalfontawesome.png',
],
];
}

/**
* {@inheritdoc}
*/
public function isEnabled(Editor $editor) {
// Assume that someone installing this module probably wants the help.
return TRUE;
}

}

+ 197
- 0
modules/contrib/fontawesome/src/Plugin/Field/FieldFormatter/FontAwesomeIconFormatter.php Dosyayı Görüntüle

@@ -0,0 +1,197 @@
<?php

namespace Drupal\fontawesome\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;

/**
* Implementation of Font Awesome icon formatter.
*
* @FieldFormatter(
* id = "fontawesome_icon_formatter",
* label = @Translation("Font Awesome Icon"),
* field_types = {
* "fontawesome_icon"
* }
* )
*/
class FontAwesomeIconFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* Drupal configuration service container.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;

/**
* {@inheritdoc}
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, ConfigFactory $config_factory) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);

$this->configFactory = $config_factory;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('config.factory')
);
}

/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
// Load the configuration settings.
$configuration_settings = $this->configFactory->get('fontawesome.settings');

// Setting for optional download link.
$elements['layers'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display multi-value fields as layers?'),
'#default_value' => $this->getSetting('layers'),
'#description' => $this->t('Layers are the new way to place icons and text visually on top of each other, replacing the Font Awesome classic icons stacks. With this new approach you can use more than 2 icons. Layers are awesome when you don’t want your page’s background to show through, or when you do want to use multiple colors, layer several icons, layer text, or layer counters onto an icon. Note that layers only work with the SVG version of Font Awesome. For more information, see @layersLink.', [
'@layersLink' => Link::fromTextAndUrl($this->t('the Font Awesome guide to layers'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/layering'))->toString(),
]),
// Disable power transforms for webfonts.
'#disabled' => $configuration_settings->get('method') == 'webfonts',
];

return $elements;
}

/**
* {@inheritdoc}
*/
public function settingsSummary() {
$settings = $this->getSettings();

$summary = [];

// Load the configuration settings.
$configuration_settings = $this->configFactory->get('fontawesome.settings');

// Show whether or not we are layering the icons.
$summary[] = $this->t('Display multi-value fields as layers: <strong>@layersSetting</strong>', [
'@layersSetting' => (($settings['layers'] && $configuration_settings->get('method') != 'webfonts') ? 'Yes' : 'No'),
]);

return $summary;
}

/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'layers' => FALSE,
] + parent::defaultSettings();
}

/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
// Early opt-out if the field is empty.
if (count($items) <= 0) {
return [];
}

// Load the configuration settings.
$configurationSettings = $this->configFactory->get('fontawesome.settings');

// Loop over each icon and build data.
$icons = [];
foreach ($items as $item) {
// Get the icon settings.
$iconSettings = unserialize($item->get('settings')->getValue());
$cssStyles = [];

// Format mask.
$iconMask = '';
if (!empty($iconSettings['masking']['mask'])) {
$iconMask = $iconSettings['masking']['style'] . ' fa-' . $iconSettings['masking']['mask'];
}
unset($iconSettings['masking']);

// Format power transforms.
$iconTransforms = [];
$powerTransforms = $iconSettings['power_transforms'];
foreach ($powerTransforms as $transform) {
if (!empty($transform['type'])) {
$iconTransforms[] = $transform['type'] . '-' . $transform['value'];
}
}
unset($iconSettings['power_transforms']);

// Move duotone settings into the render.
if (isset($iconSettings['duotone'])) {
// Handle swap opacity flag.
if (!empty($iconSettings['duotone']['swap-opacity'])) {
$iconSettings['swap-opacity'] = $iconSettings['duotone']['swap-opacity'];
}
// Handle custom CSS styles.
if (!empty($iconSettings['duotone']['opacity']['primary'])) {
$cssStyles[] = '--fa-primary-opacity: ' . $iconSettings['duotone']['opacity']['primary'] . ';';
}
if (!empty($iconSettings['duotone']['opacity']['secondary'])) {
$cssStyles[] = '--fa-secondary-opacity: ' . $iconSettings['duotone']['opacity']['secondary'] . ';';
}
if (!empty($iconSettings['duotone']['color']['primary'])) {
$cssStyles[] = '--fa-primary-color: ' . $iconSettings['duotone']['color']['primary'] . ';';
}
if (!empty($iconSettings['duotone']['color']['secondary'])) {
$cssStyles[] = '--fa-secondary-color: ' . $iconSettings['duotone']['color']['secondary'] . ';';
}

unset($iconSettings['duotone']);
}

// Add additional CSS styles if needed.
if (isset($iconSettings['additional_classes'])) {
$cssStyles[] = $iconSettings['additional_classes'];
}

$icons[] = [
'#theme' => 'fontawesomeicon',
'#tag' => $configurationSettings->get('tag'),
'#name' => 'fa-' . $item->get('icon_name')->getValue(),
'#style' => $item->get('style')->getValue(),
'#settings' => implode(' ', array_filter($iconSettings)),
'#transforms' => implode(' ', $iconTransforms),
'#mask' => $iconMask,
'#css' => implode(' ', $cssStyles),
];
}

// Get the icon settings.
$settings = $this->getSettings();

return [
[
'#theme' => 'fontawesomeicons',
'#icons' => $icons,
'#layers' => $settings['layers'],
],
];
}

}

+ 80
- 0
modules/contrib/fontawesome/src/Plugin/Field/FieldType/FontAwesomeIcon.php Dosyayı Görüntüle

@@ -0,0 +1,80 @@
<?php

namespace Drupal\fontawesome\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
* Provides a field type of Font Awesome Icon.
*
* @FieldType(
* id = "fontawesome_icon",
* label = @Translation("Font Awesome Icon"),
* module = "fontawesome",
* category = @Translation("Icons"),
* description = @Translation("A Font Awesome icon"),
* default_formatter = "fontawesome_icon_formatter",
* default_widget = "fontawesome_icon_widget",
* serialized_property_names = {
* "settings"
* }
* )
*/
class FontAwesomeIcon extends FieldItemBase implements FieldItemInterface {

/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
// Columns contains the values that the field will store.
'columns' => [
'icon_name' => [
'type' => 'text',
'size' => 'normal',
'not null' => TRUE,
],
'style' => [
'type' => 'text',
'size' => 'tiny',
'not null' => TRUE,
],
'settings' => [
'type' => 'text',
'size' => 'normal',
'not null' => FALSE,
],
],
];
}

/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = [];
$properties['icon_name'] = DataDefinition::create('string')
->setLabel(t('Icon Name'))
->setDescription(t('The name of the icon'));
$properties['style'] = DataDefinition::create('string')
->setLabel(t('Icon Style'))
->setDescription(t('The style of the icon'));
$properties['settings'] = DataDefinition::create('string')
->setLabel(t('Icon Settings'))
->setDescription(t('The additional class settings for the icon'));

return $properties;
}

/**
* {@inheritdoc}
*/
public function isEmpty() {
$icon_name = $this->get('icon_name')->getValue();
return $icon_name === NULL || $icon_name === '';
}

}

+ 538
- 0
modules/contrib/fontawesome/src/Plugin/Field/FieldWidget/FontAwesomeIconWidget.php Dosyayı Görüntüle

@@ -0,0 +1,538 @@
<?php

namespace Drupal\fontawesome\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Config\ConfigFactory;

/**
* Plugin implementation of the 'fontawesome_icon' widget.
*
* @FieldWidget(
* id = "fontawesome_icon_widget",
* module = "fontawesome",
* label = @Translation("Font Awesome Icon"),
* field_types = {
* "fontawesome_icon"
* }
* )
*/
class FontAwesomeIconWidget extends WidgetBase implements ContainerFactoryPluginInterface {
/**
* Drupal configuration service container.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;

/**
* {@inheritdoc}
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ConfigFactory $config_factory) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

$this->configFactory = $config_factory;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['third_party_settings'],
$container->get('config.factory')
);
}

/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition->getName();

// Load the configuration settings.
$configuration_settings = $this->configFactory->get('fontawesome.settings');

$cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
$element['icon_name'] = [
'#type' => 'textfield',
'#title' => $cardinality == 1 ? $this->fieldDefinition->getLabel() : $this->t('Icon Name'),
'#required' => $element['#required'],
'#size' => 50,
'#field_prefix' => 'fa-',
'#default_value' => $items[$delta]->get('icon_name')->getValue(),
'#description' => $this->t('Name of the Font Awesome Icon. See @iconsLink for valid icon names, or begin typing for an autocomplete list. Note that all four versions of the icon will be shown - Light, Regular, Solid, and Duotone respectively. If the icon shows a question mark, that icon version is not supported in your version of Fontawesome.', [
'@iconsLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#autocomplete_route_name' => 'fontawesome.autocomplete',
'#element_validate' => [
[static::class, 'validateIconName'],
],
];

// Get current settings.
$iconSettings = unserialize($items[$delta]->get('settings')->getValue());
// Build additional settings.
$element['settings'] = [
'#type' => 'details',
'#open' => FALSE,
'#title' => $this->t('Additional Font Awesome Settings'),
];

// Allow user to determine style.
$element['settings']['style'] = [
'#type' => 'select',
'#title' => $this->t('Style'),
'#description' => $this->t('This changes the style of the icon. Please note that this is not available for all icons, and for some of the icons this is only available in the pro version. If the icon does not render properly in the , the icon does not support that style. Notably, brands do not support any styles. See @iconLink for more information.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#options' => [
'fas' => $this->t('Solid'),
'far' => $this->t('Regular'),
'fal' => $this->t('Light'),
'fad' => $this->t('Duotone'),
],
'#default_value' => $items[$delta]->get('style')->getValue(),
];
// Remove style options if they aren't being loaded.
if (is_bool($configuration_settings->get('use_solid_file')) && !$configuration_settings->get('use_solid_file')) {
unset($element['settings']['style']['#options']['fas']);
}
if (is_bool($configuration_settings->get('use_regular_file')) && !$configuration_settings->get('use_regular_file')) {
unset($element['settings']['style']['#options']['far']);
}
if (is_bool($configuration_settings->get('use_light_file')) && !$configuration_settings->get('use_light_file')) {
unset($element['settings']['style']['#options']['fal']);
}
if (is_bool($configuration_settings->get('use_duotone_file')) && !$configuration_settings->get('use_duotone_file')) {
unset($element['settings']['style']['#options']['fad']);
}

// Allow user to determine size.
$element['settings']['size'] = [
'#type' => 'select',
'#title' => $this->t('Size'),
'#description' => $this->t('This increases icon sizes relative to their container'),
'#options' => [
'' => $this->t('Default'),
'fa-xs' => $this->t('Extra Small'),
'fa-sm' => $this->t('Small'),
'fa-lg' => $this->t('Large'),
'fa-2x' => $this->t('2x'),
'fa-3x' => $this->t('3x'),
'fa-4x' => $this->t('4x'),
'fa-5x' => $this->t('5x'),
'fa-6x' => $this->t('6x'),
'fa-7x' => $this->t('7x'),
'fa-8x' => $this->t('8x'),
'fa-9x' => $this->t('9x'),
'fa-10x' => $this->t('10x'),
],
'#default_value' => isset($iconSettings['size']) ? $iconSettings['size'] : '',
];
// Set icon to fixed width.
$element['settings']['fixed-width'] = [
'#type' => 'checkbox',
'#title' => $this->t('Fixed Width?'),
'#description' => $this->t('Use to set icons at a fixed width. Great to use when different icon widths throw off vertical alignment. Especially useful in things like nav lists and list groups.'),
'#default_value' => isset($iconSettings['fixed-width']) ? $iconSettings['fixed-width'] : FALSE,
'#return_value' => 'fa-fw',
];
// Add border.
$element['settings']['border'] = [
'#type' => 'checkbox',
'#title' => $this->t('Border?'),
'#description' => $this->t('Adds a border to the icon.'),
'#default_value' => isset($iconSettings['border']) ? $iconSettings['border'] : FALSE,
'#return_value' => 'fa-border',
];
// Invert color.
$element['settings']['invert'] = [
'#type' => 'checkbox',
'#title' => $this->t('Invert color?'),
'#description' => $this->t('Inverts the color of the icon (black becomes white, etc.)'),
'#default_value' => isset($iconSettings['invert']) ? $iconSettings['invert'] : FALSE,
'#return_value' => 'fa-inverse',
];
// Animated the icon.
$element['settings']['animation'] = [
'#type' => 'select',
'#title' => $this->t('Animation'),
'#description' => $this->t('Use spin to get any icon to rotate, and pulse to have it rotate with 8 steps. Works especially well with fa-spinner & everything in the @iconLink.', [
'@iconLink' => Link::fromTextAndUrl($this->t('spinner icons category'), Url::fromUri('https://fontawesome.com/icons?c=spinner-icons'))->toString(),
]),
'#options' => [
'' => $this->t('None'),
'fa-spin' => $this->t('Spin'),
'fa-pulse' => $this->t('Pulse'),
],
'#default_value' => isset($iconSettings['animation']) ? $iconSettings['animation'] : '',
];

// Pull the icons.
$element['settings']['pull'] = [
'#type' => 'select',
'#title' => $this->t('Pull'),
'#description' => $this->t('This setting will pull the icon (float) to one side or the other in relation to its nearby content'),
'#options' => [
'' => $this->t('None'),
'fa-pull-left' => $this->t('Left'),
'fa-pull-right' => $this->t('Right'),
],
'#default_value' => isset($iconSettings['pull']) ? $iconSettings['pull'] : '',
];

// Allow to use CSS Classes for any purpose eg background color.
$element['settings']['additional_classes'] = [
'#type' => 'textfield',
'#title' => $this->t('Additional Classes'),
'#default_value' => isset($iconSettings['additional_classes']) ? $iconSettings['additional_classes'] : '',
'#description' => $this->t('Use space separated classes for additional manual icon tagging / settings.'),
];

// Allow user to edit duotone.
$element['settings']['duotone'] = [
'#type' => 'details',
'#open' => FALSE,
// Disable power transforms for webfonts.
'#title' => $this->t('Duotone Settings'),
'#description' => $this->t('Duotone provides a version of every icon in Font Awesome that has two distinct shades of color. They’re great for adding more of your brand or an illustrative quality to the icons in your project. See @duotoneLink for more information. Note that duotone only works with the Pro version of Font Awesome.', [
'@duotoneLink' => Link::fromTextAndUrl($this->t('the Font Awesome guide to duotone'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/duotone-icons'))->toString(),
]),
];
$element['settings']['duotone']['swap-opacity'] = [
'#type' => 'checkbox',
'#title' => $this->t('Swap Opacity?'),
'#description' => $this->t('Use to swap the default opacity of each duotone icon’s layers. This will make an icon’s primary layer have the default opacity of 40% rather than its secondary layer.'),
'#default_value' => isset($iconSettings['duotone']['swap-opacity']) ? $iconSettings['duotone']['swap-opacity'] : '',
'#return_value' => 'fa-swap-opacity',
];
// Manual opacity.
$element['settings']['duotone']['opacity'] = [
'#type' => 'details',
'#open' => TRUE,
// Disable power transforms for webfonts.
'#title' => $this->t('Layer Opacity'),
'#description' => $this->t('By default the secondary layer in a duotone icon is set to 40% opacity (via an opacity 0.4; rule in Font Awesome’s support CSS). You can explicitly set the opacity of a duotone icon’s layer by using CSS custom properties either in your style sheets or by setting them manually below. New to custom properties? Here are some @cssLink.', [
'@cssLink' => Link::fromTextAndUrl($this->t('places to set them'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/duotone-icons#using-in-a-project'))->toString(),
]),
];
$element['settings']['duotone']['opacity']['primary'] = [
'#type' => 'number',
'#title' => $this->t('Primary Layer Opacity'),
'#step' => 0.01,
'#default_value' => isset($iconSettings['duotone']['opacity']['primary']) ? $iconSettings['duotone']['opacity']['primary'] : '',
'#description' => $this->t('Opacity of the primary duotone layer.'),
];
$element['settings']['duotone']['opacity']['secondary'] = [
'#type' => 'number',
'#title' => $this->t('Secondary Layer Opacity'),
'#step' => 0.01,
'#default_value' => isset($iconSettings['duotone']['opacity']['secondary']) ? $iconSettings['duotone']['opacity']['secondary'] : '',
'#description' => $this->t('Opacity of the secondary duotone layer.'),
];
// Manual opacity.
$element['settings']['duotone']['color'] = [
'#type' => 'details',
'#open' => TRUE,
// Disable power transforms for webfonts.
'#title' => $this->t('Layer Color'),
'#description' => $this->t('Like all other Font Awesome icons, duotone icons automatically inherit CSS size and color. A duotone icon consists of a primary and secondary layer. By default, The secondary layer is given an opacity of 40% so that it appears as a lighter shade of the icon’s inherited or directly set color. Using CSS custom properties, we’ve also added some color hooks to a duotone icon’s primary and secondary layers. New to custom properties? Here are some @cssLink.', [
'@cssLink' => Link::fromTextAndUrl($this->t('places to set them'), Url::fromUri('https://fontawesome.com/how-to-use/on-the-web/styling/duotone-icons#using-in-a-project'))->toString(),
]),
];
$element['settings']['duotone']['color']['primary'] = [
'#type' => 'color',
'#title' => $this->t('Primary Layer Color'),
'#step' => 0.01,
'#default_value' => isset($iconSettings['duotone']['color']['primary']) ? $iconSettings['duotone']['color']['primary'] : '',
'#description' => $this->t('Opacity of the primary duotone layer.'),
];
$element['settings']['duotone']['color']['secondary'] = [
'#type' => 'color',
'#title' => $this->t('Secondary Layer Color'),
'#step' => 0.01,
'#default_value' => isset($iconSettings['duotone']['color']['secondary']) ? $iconSettings['duotone']['color']['secondary'] : '',
'#description' => $this->t('Opacity of the secondary duotone layer.'),
];

// Allow user to add masking.
$element['settings']['masking'] = [
'#type' => 'details',
'#open' => FALSE,
// Disable power transforms for webfonts.
'#disabled' => $configuration_settings->get('method') == 'webfonts',
'#title' => $this->t('Icon Mask'),
'#description' => $this->t('Masking is used to combine two icons to create one single-color shape. Use it with Power Transforms for some really awesome effects. Masks are great when you do want your background color to show through. See @maskingLink for more information. Note that masking only works with the SVG version of Font Awesome.', [
'@maskingLink' => Link::fromTextAndUrl($this->t('the Font Awesome guide to masking'), Url::fromUri('https://fontawesome.com/how-to-use/svg-with-js#masking'))->toString(),
]),
];
$element['settings']['masking']['mask'] = [
'#type' => 'textfield',
'#title' => $this->t('Icon Name'),
'#size' => 50,
'#field_prefix' => 'fa-',
'#default_value' => isset($iconSettings['masking']['mask']) ? $iconSettings['masking']['mask'] : '',
'#description' => $this->t('Name of the Font Awesome Icon. See @iconsLink for valid icon names, or begin typing for an autocomplete list.', [
'@iconsLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#autocomplete_route_name' => 'fontawesome.autocomplete',
'#element_validate' => [
[static::class, 'validateIconName'],
],
];
$element['settings']['masking']['style'] = [
'#type' => 'select',
'#title' => $this->t('Style'),
'#description' => $this->t('This changes the style of the masking icon. Please note that this is not available for all icons, and for some of the icons this is only available in the pro version. If the icon does not render properly in the preview above, the icon does not support that style. Notably, brands do not support any styles. See @iconLink for more information.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]),
'#options' => [
'fas' => $this->t('Solid'),
'far' => $this->t('Regular'),
'fal' => $this->t('Light'),
'fad' => $this->t('Duotone'),
],
'#default_value' => isset($iconSettings['masking']['style']) ? $iconSettings['masking']['style'] : '',
];

// Build new power-transforms.
$element['settings']['power_transforms'] = [
'#type' => 'details',
'#open' => FALSE,
// Disable power transforms for webfonts.
'#disabled' => $configuration_settings->get('method') == 'webfonts',
'#title' => $this->t('Power Transforms'),
'#description' => $this->t('See @iconLink for additional information on Power Transforms. Note that these transforms only work with the SVG with JS version of Font Awesome and are disabled for Webfonts. See the @adminLink to set your version of Font Awesome.', [
'@iconLink' => Link::fromTextAndUrl($this->t('the Font Awesome `How to use` guide'), Url::fromUri('https://fontawesome.com/how-to-use/svg-with-js'))->toString(),
'@adminLink' => Link::createFromRoute($this->t('admin page'), 'fontawesome.admin_settings')->toString(),
]),
];
// Rotate the icon.
$element['settings']['power_transforms']['rotate']['value'] = [
'#type' => 'number',
'#title' => $this->t('Rotate'),
'#step' => 0.01,
'#field_suffix' => '&deg;',
'#default_value' => isset($iconSettings['power_transforms']['rotate']['value']) ? $iconSettings['power_transforms']['rotate']['value'] : '',
'#description' => $this->t('Power Transform rotating effects icon angle without changing or moving the container. To rotate icons use any arbitrary value. Units are degrees with negative numbers allowed.'),
];
// Flip the icon.
$element['settings']['power_transforms']['flip-h']['value'] = [
'#type' => 'checkbox',
'#title' => $this->t('Flip Horizontal?'),
'#default_value' => isset($iconSettings['power_transforms']['flip-h']['value']) ? $iconSettings['power_transforms']['flip-h']['value'] : FALSE,
'#description' => $this->t('Power Transform flipping effects icon reflection without changing or moving the container.'),
'#return_value' => 'h',
];
$element['settings']['power_transforms']['flip-v']['value'] = [
'#type' => 'checkbox',
'#title' => $this->t('Flip Vertical?'),
'#default_value' => isset($iconSettings['power_transforms']['flip-v']['value']) ? $iconSettings['power_transforms']['flip-v']['value'] : FALSE,
'#description' => $this->t('Power Transform flipping effects icon reflection without changing or moving the container.'),
'#return_value' => 'v',
];
// Scale the icon.
$element['settings']['power_transforms']['scale'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Scale'),
'#description' => $this->t('Power Transform scaling effects icon size without changing or moving the container. This field will scale icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$element['settings']['power_transforms']['scale']['type'] = [
'#type' => 'select',
'#title' => $this->t('Scale Type'),
'#options' => [
'' => $this->t('None'),
'shrink' => $this->t('Shrink'),
'grow' => $this->t('Grow'),
],
'#default_value' => isset($iconSettings['power_transforms']['scale']['type']) ? $iconSettings['power_transforms']['scale']['type'] : '',
];
$element['settings']['power_transforms']['scale']['value'] = [
'#type' => 'number',
'#title' => $this->t('Scale Value'),
'#min' => 0,
'#step' => 0.01,
'#default_value' => isset($iconSettings['power_transforms']['scale']['value']) ? $iconSettings['power_transforms']['scale']['value'] : '',
'#states' => [
'disabled' => [
':input[name="' . $field_name . '[' . $delta . '][settings][power_transforms][scale][type]"]' => ['value' => ''],
],
],
];
// Position the icon.
$element['settings']['power_transforms']['position_y'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Position (Y Axis)'),
'#description' => $this->t('Power Transform positioning effects icon location without changing or moving the container. This field will move icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$element['settings']['power_transforms']['position_y']['type'] = [
'#type' => 'select',
'#title' => $this->t('Position Type'),
'#options' => [
'' => $this->t('None'),
'up' => $this->t('Up'),
'down' => $this->t('Down'),
],
'#default_value' => isset($iconSettings['power_transforms']['position_y']['type']) ? $iconSettings['power_transforms']['position_y']['type'] : '',
];
$element['settings']['power_transforms']['position_y']['value'] = [
'#type' => 'number',
'#title' => $this->t('Position Value'),
'#min' => 0,
'#step' => 0.01,
'#default_value' => isset($iconSettings['power_transforms']['position_y']['value']) ? $iconSettings['power_transforms']['position_y']['value'] : '',
'#states' => [
'disabled' => [
':input[name="' . $field_name . '[' . $delta . '][settings][power_transforms][position_y][type]"]' => ['value' => ''],
],
],
];
$element['settings']['power_transforms']['position_x'] = [
'#type' => 'details',
'#open' => TRUE,
'#title' => $this->t('Position (X Axis)'),
'#description' => $this->t('Power Transform positioning effects icon location without changing or moving the container. This field will move icons up or down with any arbitrary value, including decimals. Units are 1/16em.'),
'#element_validate' => [
[static::class, 'validatePowerTransforms'],
],
];
$element['settings']['power_transforms']['position_x']['type'] = [
'#type' => 'select',
'#title' => $this->t('Position Type'),
'#options' => [
'' => $this->t('None'),
'left' => $this->t('Left'),
'right' => $this->t('Right'),
],
'#default_value' => isset($iconSettings['power_transforms']['position_x']['type']) ? $iconSettings['power_transforms']['position_x']['type'] : '',
];
$element['settings']['power_transforms']['position_x']['value'] = [
'#type' => 'number',
'#title' => $this->t('Position Value'),
'#min' => 0,
'#step' => 0.01,
'#default_value' => isset($iconSettings['power_transforms']['position_x']['value']) ? $iconSettings['power_transforms']['position_x']['value'] : '',
'#states' => [
'disabled' => [
':input[name="' . $field_name . '[' . $delta . '][settings][power_transforms][position_x][type]"]' => ['value' => ''],
],
],
];

return $element;
}

/**
* Validate the Font Awesome power transforms.
*/
public static function validatePowerTransforms($element, FormStateInterface $form_state) {
$values = $form_state->getValue($element['#parents']);

if (!empty($values['type']) && empty($values['value'])) {
$form_state->setError($element, t('Missing value for Font Awesome Power Transform %value. Please see @iconLink for information on correct values.', [
'%value' => $values['type'],
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/how-to-use/svg-with-js'))->toString(),
]));
}
elseif (empty($values['type']) && !empty($values['value'])) {
$form_state->setError($element, t('Missing type value for Font Awesome Power Transform. Please see @iconLink for information on correct values.', [
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/how-to-use/svg-with-js'))->toString(),
]));
}
if (!empty($values['value']) && !is_numeric($values['value'])) {
$form_state->setError($element, t("Invalid value for Font Awesome Power Transform %value. Please see @iconLink for information on correct values.", [
'%value' => $values['type'],
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/how-to-use/svg-with-js'))->toString(),
]));
}
}

/**
* Validate the Font Awesome icon name.
*/
public static function validateIconName($element, FormStateInterface $form_state) {
$value = $element['#value'];
if (strlen($value) == 0) {
$form_state->setValueForElement($element, '');
return;
}

// Load the icon data so we can check for a valid icon.
$iconData = fontawesome_extract_icon_metadata($value);

if (!isset($iconData['name'])) {
$form_state->setError($element, t("Invalid icon name %value. Please see @iconLink for correct icon names.", [
'%value' => $value,
'@iconLink' => Link::fromTextAndUrl(t('the Font Awesome icon list'), Url::fromUri('https://fontawesome.com/icons'))->toString(),
]));
}
}

/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
// Load the icon data so we can determine the icon type.
$metadata = fontawesome_extract_icons();

// Loop over each item and set the data properly.
foreach ($values as &$item) {
// Remove the prefix if the user accidentally added it.
if (substr($item['icon_name'], 0, 3) == 'fa-') {
$item['icon_name'] = substr($item['icon_name'], 3);
}

if (!empty($item['settings']['masking']['style'])) {
$item['settings']['masking']['style'] = isset($metadata[$item['icon_name']]['styles']) ? fontawesome_determine_prefix($metadata[$item['icon_name']]['styles'], $item['settings']['masking']['style']) : 'fas';
}

// Massage rotate and flip values to make them format properly.
if (is_numeric($item['settings']['power_transforms']['rotate']['value'])) {
$item['settings']['power_transforms']['rotate']['type'] = 'rotate';
}
else {
unset($item['settings']['power_transforms']['rotate']);
}
if (!empty($item['settings']['power_transforms']['flip-h']['value'])) {
$item['settings']['power_transforms']['flip-h']['type'] = 'flip';
}
else {
unset($item['settings']['power_transforms']['flip-h']);
}
if (!empty($item['settings']['power_transforms']['flip-v']['value'])) {
$item['settings']['power_transforms']['flip-v']['type'] = 'flip';
}
else {
unset($item['settings']['power_transforms']['flip-v']);
}
// Determine the icon style - brands don't allow style.
$item['style'] = isset($metadata[$item['icon_name']]['styles']) ? fontawesome_determine_prefix($metadata[$item['icon_name']]['styles'], $item['settings']['style']) : 'fas';
unset($item['settings']['style']);

$item['settings'] = serialize(array_filter($item['settings']));
}

return $values;
}

}

+ 20
- 0
modules/contrib/fontawesome/templates/fontawesomeicon.html.twig Dosyayı Görüntüle

@@ -0,0 +1,20 @@
{#
/**
* @file
* Default implementation for Font Awesome Icon field.
*
* Available variables:
* - tag: the HTML tag being used to create the icon.
* - icon: the name of the icon being used for templating.
* - style: the Font Awesome style for the icon.
* - settings: the additional Font Awesome style settings.
* - transforms: Font Awesome power transforms.
* - mask: Font Awesome mask.
* - css: Additional inline CSS styles (for duotone, etc).
*
* @ingroup themeable
*/
#}
<div class="fontawesome-icon">
<{{tag }} class="{{ style }} {{ name }} {{ settings }}" data-fa-transform="{{ transforms }}" data-fa-mask="{{ mask }}" style="{{ css }}"></{{ tag }}>
</div>

+ 19
- 0
modules/contrib/fontawesome/templates/fontawesomeicons.html.twig Dosyayı Görüntüle

@@ -0,0 +1,19 @@
{#
/**
* @file
* Default implementation for Font Awesome icons.
*
* Available variables:
* - icons: a list of Font Awesome icons to be rendered.
* - layers: flag indicating if icons are printing as layers.
*
* @ingroup themeable
*/
#}
<div class="fontawesome-icons">
{% if layers == '1' %}
<span class="fa-layers fa-fw">{{ icons }}</span>
{% else %}
{{ icons }}
{% endif %}
</div>

+ 6
- 0
modules/custom/arlista/arlista.info.yml Dosyayı Görüntüle

@@ -0,0 +1,6 @@
name: 'Pricelist Manager'
type: module
description: 'AXICO - Komponens árlista kezelő'
dependencies:
package: 'ITC Web Custom'
core_version_requirement: ^8 || ^9

+ 319
- 0
modules/custom/arlista/arlista.install Dosyayı Görüntüle

@@ -0,0 +1,319 @@
<?php

use Drupal\Core\Database\Database;
use Drupal\arlista\Factory\InstallFactory;

/**
* Implements hook_schema().o
*/
function arlista_schema() {
$schema[getPrefix() . 'axico_id'] = getAxicoIdSchema();
$schema[getPrefix() . 'active_product'] = getActiveProductSchema();
$schema[getPrefix() . 'calculation'] = getCalculationSchema();
$schema[getPrefix() . 'category'] = getCategorySchema();
$schema[getPrefix() . 'component'] = getComponentSchema();
$schema[getPrefix() . 'enabled_group'] = getEnabledGroupSchema();
$schema[getPrefix() . 'manufacturer'] = getManufacturerSchema();
$schema[getPrefix() . 'sheet_setting'] = getSheetSettingSchema();
$schema[getPrefix() . 'uploaded_file'] = getArlistaUploadedFileSchema();
$schema[getPrefix() . 'uploaded_product'] = getUploadedProductSchema();

return $schema;
}

function getPrefix() {
return 'arlista_manager_';
}

function getManufacturerSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
$fields['fields']['axico_id_name'] = ['type' => 'varchar', 'length' => 3];
$fields['fields']['component_based'] = ['type' => 'int'];

return $fields;
}

function getSheetSettingSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
unset($fields['fields']['sif']);

$fields['fields']['manufacturer_id'] = ['type' => 'int', 'not null' => true];
$fields['fields']['index'] = ['type' => 'int', 'not null' => true];

$default_field = ['type' => 'varchar', 'length' => 2, 'not null' => true, 'default' => ''];

$fields['fields']['product_name'] = $default_field;
$fields['fields']['product_fabric_name'] = $default_field;
$fields['fields']['product_axico_name'] = ['type' => 'varchar', 'length' => 5, 'not null' => true, 'default' => ''];
$fields['fields']['product_fabric_id'] = $default_field;
$fields['fields']['product_ean'] = $default_field;
$fields['fields']['product_warranty'] = $default_field;
$fields['fields']['product_eol'] = $default_field;
$fields['fields']['product_notes'] = $default_field;
$fields['fields']['product_description'] = $default_field;
$fields['fields']['product_category'] = $default_field;
$fields['fields']['product_price'] = $default_field;
$fields['fields']['currency'] = ['type' => 'varchar', 'length' => 3, 'not null' => true, 'default' => 'HUF'];
$fields['fields']['product_vtsz'] = $default_field;
$fields['fields']['product_width'] = $default_field;
$fields['fields']['product_length'] = $default_field;
$fields['fields']['product_height'] = $default_field;
$fields['fields']['product_weight'] = $default_field;
$fields['fields']['filterable'] = ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 0];
$fields['fields']['filterable_remarks'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['default_setting'] = ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1];

return $fields;
}

function getCategorySchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
$fields['fields']['axico_id_name'] = ['type' => 'varchar', 'length' => 3];

return $fields;
}

function getComponentSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
$fields['fields']['parent_manufacturer_id'] = ['type' => 'int'];
$fields['fields']['axico_id_name'] = ['type' => 'varchar', 'length' => 3];

return $fields;
}

function getCalculationSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
unset($fields['fields']['sif']);

$fields['fields']['parent_manufacturer_id'] = ['type' => 'int'];
$fields['fields']['parent_category_id'] = ['type' => 'int'];
$fields['fields']['parent_component_id'] = ['type' => 'int'];
$fields['fields']['list_price_factor'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_d_one'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_d_two'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_v_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_dev_d_one'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_dev_d_two'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_dev_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['price_factor_dev_v_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.00];
$fields['fields']['transport_expense'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 1.0000];
$fields['fields']['default_setting'] = ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1];

return $fields;
}

function getArlistaUploadedFileSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];

unset($fields['fields']['sif']);

$fields['fields']['parent_manufacturer_id'] = ['type' => 'int'];
$fields['fields']['component_based'] = ['type' => 'int'];
$fields['fields']['fid'] = ['type' => 'int'];
$fields['fields']['total_products'] = ['type' => 'int'];
$fields['fields']['work_flow'] = ['type' => 'varchar', 'length' => 128, 'not null' => true];



return $fields;
}

function getDefaultFields() {

return [
'created_at' => ['mysql_type' => 'datetime', 'not null' => true],
'created_by' => ['type' => 'int', 'not null' => true],
'deleted_at' => ['mysql_type' => 'datetime'],
'id' => ['type' => 'serial', 'not null' => true],
'modified_at' => ['mysql_type' => 'datetime'],
'modified_by' => ['type' => 'int'],
'name' => ['type' => 'varchar', 'length' => 128, 'not null' => true],
'status' => ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1],
'sif' => ['type' => 'varchar', 'length' => 32]
];
}

function getUploadedProductSchema() {

$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id'],
];

$fields['fields']['parent_category_id'] = ['type' => 'int'];
$fields['fields']['parent_manufacturer_id'] = ['type' => 'int'];
$fields['fields']['parent_component_id'] = ['type' => 'int'];
$fields['fields']['axico_id'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['axico_name'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['fabric_name'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['fabric_id'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['ean'] = ['type' => 'varchar', 'length' => 32];
$fields['fields']['warranty'] = ['type' => 'int'];
$fields['fields']['eol'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['notes'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['description'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['price'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['list_price'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['purchase_price'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_changed'] = ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 1];
$fields['fields']['price_d_one'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_d_two'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_v_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_dev_d_one'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_dev_d_two'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_dev_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['price_dev_v_spec'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];
$fields['fields']['currency'] = ['type' => 'varchar', 'length' => 3];
$fields['fields']['measure_unit'] = ['type' => 'varchar', 'length' => 16];
$fields['fields']['uploaded_file_id'] = ['type' => 'int'];
$fields['fields']['sheet_index'] = ['type' => 'int'];
$fields['fields']['correct_status'] = ['type' => 'varchar', 'length' => 32];
$fields['fields']['work_flow'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['vtsz'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['width'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0.00];
$fields['fields']['length'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0.00];
$fields['fields']['height'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0.00];
$fields['fields']['weight'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0.00];
$fields['fields']['packing_material'] = ['type' => 'varchar', 'length' => 32];
$fields['fields']['listed'] = ['type' => 'int', 'size' => 'tiny', 'not null' => true, 'default' => 0];

/**
* Update hook 9002
*/
$fields['fields']['previous_axico_name'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['previous_fabric_name'] = ['type' => 'varchar', 'length' => 128];
$fields['fields']['previous_warranty'] = ['type' => 'int'];
$fields['fields']['previous_eol'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['previous_notes'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['previous_description'] = ['type' => 'varchar', 'length' => 255];
$fields['fields']['previous_price'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];


return $fields;
}

function getActiveProductSchema() {

$fields = getUploadedProductSchema();

return $fields;
}

function getAxicoIdSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];

unset($fields['fields']['sif']);

$fields['fields']['parent_manufacturer_id'] = ['type' => 'int'];
$fields['fields']['parent_category_id'] = ['type' => 'int'];
$fields['fields']['parent_component_id'] = ['type' => 'int'];
$fields['fields']['product_id'] = ['type' => 'int'];
$fields['fields']['current_count'] = ['type' => 'int'];
$fields['fields']['next_count'] = ['type' => 'int'];



return $fields;
}

function getEnabledGroupSchema() {
$fields = [
'fields' => getDefaultFields(),
'primary key' => ['id']
];
unset($fields['fields']['sif']);

$fields['fields']['sheet_setting_id'] = ['type' => 'int'];
$fields['fields']['component_id'] = ['type' => 'int'];
$fields['fields']['category_id'] = ['type' => 'int'];

return $fields;
}

/**
* Implements hook_install().
*/
function arlista_install() {
openFolders();
/* @var $installFactory InstallFactory */
$installFactory = \Drupal::service('arlista.install.factory');
$installFactory->importPrimaryDataBases();
$installFactory->importSecondaryDataBases();
$installFactory->importDataFromExcelFile('termekek.xls', false);
}

function openFolders() {
$requiredFolders = [
'public://arlista',
'public://arlista/uploaded',
'public://arlista/downloaded',
];

foreach ($requiredFolders as $folder) {
if (!file_exists($folder)) {
Drupal::service('file_system')->mkdir($folder);
}
}
}

/*
*
* ***
*
* Update hooks
*
* ***
*/

function arlista_update_9001(&$sandbox) {
$column_data = [
'type' => 'numeric',
'precision' => 20,
'scale' => 6,
'default' => 1.0000,
'not null' => true,
'description' => '',
];
$schema = Database::getConnection()->schema();
$schema->changeField('arlista_manager_calculation', 'transport_expense', 'transport_expense', $column_data);
}

function arlista_update_9002(&$sandbox) {

$fields['prev_axico_name'] = ['type' => 'varchar', 'length' => 128];
$fields['prev_fabric_name'] = ['type' => 'varchar', 'length' => 128];
$fields['prev_warranty'] = ['type' => 'int'];
$fields['prev_eol'] = ['type' => 'varchar', 'length' => 255];
$fields['prev_notes'] = ['type' => 'varchar', 'length' => 255];
$fields['prev_description'] = ['type' => 'varchar', 'length' => 255];
$fields['prev_price'] = ['type' => 'numeric', 'precision' => 20, 'scale' => 6, 'not null' => true, 'default' => 0];

$schema = Database::getConnection()->schema();
foreach ($fields as $field_name => $field_specs) {
$schema->addField(getPrefix() . 'active_product', $field_name, $field_specs);
$schema->addField(getPrefix() . 'uploaded_product', $field_name, $field_specs);
}
}

+ 13
- 0
modules/custom/arlista/arlista.libraries.yml Dosyayı Görüntüle

@@ -0,0 +1,13 @@
arlista:
version: VERSION
header: true
css:
component:
css/arlista.css: {}
js:
js/arlista.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings
- core/jquery.once

+ 37
- 0
modules/custom/arlista/arlista.links.menu.yml Dosyayı Görüntüle

@@ -0,0 +1,37 @@
arlista.manufacturer.list:
title: "Gyártók"
description: "Gyártók szerkesztése"
parent: main
route_name: arlista.manufacturer.list
weight: 10
menu_name: main
arlista.category.list:
title: "Termékcsoportok"
description: "Termékcsoportok szerkesztése"
parent: main
route_name: arlista.category.list
weight: 30
menu_name: main
arlista.component.list:
title: "Komponensek"
description: "Komponensek szerkesztése"
parent: main
route_name: arlista.component.list
weight: 20
menu_name: main
route_parameters: { mid: '0' }
arlista.file.list:
title: "Fájlok"
description: "Fájlok feltöltése"
parent: main
route_name: arlista.file.list
weight: 40
menu_name: main
route_parameters: { mid: '0' }
arlista.config.setup:
title: "Beállítások"
description: "Árlista kezelő beállítások"
parent: main
route_name: arlista.config.setup
weight: 50
menu_name: main

+ 126
- 0
modules/custom/arlista/arlista.module Dosyayı Görüntüle

@@ -0,0 +1,126 @@
<?php

function arlista_theme($existing, $type, $theme, $path) {
return [
'arlista_category_list' => [
'variables' => [
'categories' => null,
'enabledList' => null,
'sheetSettingList' => null,
],
'template' => 'arlista-category-list',
'render element' => 'form',
],
'arlista_category_enable_calculations' => [
'variables' => [
'categories' => null,
'enabledList' => null,
],
'template' => 'arlista-category-enable-calculations',
'render element' => 'form',
],
'arlista_component_list' => [
'variables' => [
'components' => null,
'manufacturerNames' => null,
'enabledList' => null,
'sheetSettingList' => null,
],
'template' => 'arlista-component-list',
'render element' => 'form',
],
'arlista_component_enable_calculations' => [
'variables' => [
'components' => null,
'manufacturerNames' => null,
'enabledList' => null,
],
'template' => 'arlista-component-enable-calculations',
'render element' => 'form',
],
'arlista_file_list' => [
'variables' => [
'files' => null,
'manufacturers' => null,
'sheetSettings' => null,
'listed' => null,
],
'template' => 'arlista-file-list',
'render element' => 'form',
],
'arlista_manufacturer_list' => [
'variables' => [
'manufacturers' => null,
],
'template' => 'arlista-manufacturer-list',
'render element' => 'form',
],
'arlista_manufacturer_edit' => [
'variables' => [
'manufacturer' => null,
'sheet_index' => null,
'sheet_settings' => null,
],
'template' => 'arlista-manufacturer-edit',
'render element' => 'form',
],
'arlista_pager' => [
'variables' => [
'items' => null,
'pages' => null,
'page' => null,
'uri' => null,
'products' => null,
'sheetIndex' => null,
'componentBased' => null,
'filterable' => null,
'listed' => null,
'cikkszam' => null,
],
'template' => 'arlista-pager',
'render element' => 'form',
],
'arlista_filters' => [
'variables' => [
'fid' => null,
'mid' => null,
'activeSheet' => null,
'availableSheets' => null,
'sheetIndex' => null,
'keyWords' => null,
'correctStatus' => null,
'listed' => null,
'cikkszam' => null,
],
'template' => 'arlista-filters',
'render element' => 'form',
],
'arlista_product_uploaded_list' => [
'variables' => [
'manufacturer' => null,
'categories' => null,
'products' => null,
'correctStatus' => null,
'components' => null,
'componentManufacturers' => null,
'page' => null,
'file' => null,
'correctStatus' => null,
'keyWords' => null,
'listed' => null,
'cikkszam' => null,
'workFlows' => null,
'correctStatuses' => null,
'icons' => null,
],
'template' => 'arlista-product-uploaded-list',
'render element' => 'form',
],
];
}

function arlista_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'arlista/arlista';
$attachments['#attached']['drupalSettings']['arlista']['host'] = strtok($_SERVER["REQUEST_URI"], '?');
$attachments['#attached']['drupalSettings']['arlista']['basePath'] = str_replace("/index.php", "", $_SERVER["PHP_SELF"]);
}

+ 4
- 0
modules/custom/arlista/arlista.permissions.yml Dosyayı Görüntüle

@@ -0,0 +1,4 @@
arlista manage_pricelists:
title: "Árlista kezelés"
description: "Megtekintés, szerkesztés és törlés"
restrict access: false

+ 294
- 0
modules/custom/arlista/arlista.routing.yml Dosyayı Görüntüle

@@ -0,0 +1,294 @@
# CONFIGURATION
arlista.config.setup:
path: '/arlista/setup'
defaults:
_form: '\Drupal\arlista\Form\Config\ArlistaSetupForm'
_title: 'Árlista beállítások'
requirements:
_permission: 'arlista manage_pricelists'
arlista.config.reimport:
path: '/arlista/setup/reimport'
defaults:
_form: '\Drupal\arlista\Form\Config\ConfirmProductReImport'
_title: 'Termékek re-importálása'
requirements:
_permission: 'arlista manage_pricelists'
arlista.config.fix.axico.id:
path: '/arlista/setup/fix/axico/id'
defaults:
_form: '\Drupal\arlista\Form\Config\ConfirmFixAxicoId'
_title: 'Axico cikkszámok helyreállítása'
requirements:
_permission: 'arlista manage_pricelists'
# MANUFACTURER
arlista.manufacturer.list:
path: "/manufacturer/list"
defaults:
_form: '\Drupal\arlista\Form\Manufacturer\ManufacturerList'
_title: "Gyártók"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.manufacturer.edit:
path: "/manufacturer/{mid}/edit"
defaults:
_form: '\Drupal\arlista\Form\Manufacturer\ManufacturerEdit'
_title: "Gyártó szerkesztése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
arlista.manufacturer.delete:
path: "/manufacturer/{id}/delete"
defaults:
_form: '\Drupal\arlista\Form\Manufacturer\ConfirmManufacturerDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
# SHEET SETTING
arlista.manufacturer.sheet-setting.edit:
path: "/manufacturer/sheet-settings"
defaults:
_form: '\Drupal\arlista\Form\SheetSetting\SheetSettingEdit'
_title: "Munkalapok beállítása"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.sheet-setting.delete:
path: "/manufacturer/{mid}/{sheetIndex}/delete"
defaults:
_form: '\Drupal\arlista\Form\SheetSetting\ConfirmSheetSettingDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
sheetIndex: ^\d+$
arlista.manufacturer.sheet-setting.enable-groups:
path: "/manufacturer/{mid}/{sheetSettingId}/{componentBased}/enable-groups"
defaults:
_form: '\Drupal\arlista\Form\EnabledGroup\EnabledGroupListForm'
_title: "Munkalap termékcsoportok és komponensek engedélyezése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
sheetSettingId: ^\d+$
componentBased: ^\d+$
# CALCULATION
arlista.manufacturer.calculations.list:
path: "/manufacturer/{mid}/calculations/list"
defaults:
_form: '\Drupal\arlista\Form\Calculation\CalculationList'
_title: "Gyártó kalkulációk"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
arlista.manufacturer.calculation.edit:
path: "/manufacturer/{mid}/calculations/list/edit/{catId}/{cmpId}"
defaults:
_form: '\Drupal\arlista\Form\Calculation\CalculationEdit'
_title: "Kalkuláció szerkesztése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
catId: ^\d+$
cmpId: ^\d+$
# CATEGORY
arlista.category.list:
path: "/category/list"
defaults:
_form: '\Drupal\arlista\Form\Category\CategoryList'
_title: "Termékcsoportok"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.category.edit:
path: "/category"
defaults:
_form: '\Drupal\arlista\Form\Category\CategoryEdit'
_title: "Termékcsoport szerkesztése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.category.delete:
path: "/category/{id}/delete"
defaults:
_form: '\Drupal\arlista\Form\Category\ConfirmCategoryDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
# COMPONENT
arlista.component.list:
path: "/component/list"
defaults:
_form: '\Drupal\arlista\Form\Component\ComponentList'
_title: "Komponensnek"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.component.edit:
path: "/component"
defaults:
_form: '\Drupal\arlista\Form\Component\ComponentEdit'
_title: "Komponens szerkesztése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.component.delete:
path: "/component/{id}/delete"
defaults:
_form: '\Drupal\arlista\Form\Component\ConfirmComponentDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
# FILE
arlista.file.list:
path: "/files/{mid}/list"
defaults:
_form: '\Drupal\arlista\Form\File\FileUpload'
_title: "Fájlok kezelése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
arlista.file.delete:
path: "/files/{mid}/list/{id}/delete"
defaults:
_form: '\Drupal\arlista\Form\File\ConfirmUploadedFileDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
mid: ^\d+$
arlista.file.import:
path: "/files/{mid}/list/import"
defaults:
_controller: '\Drupal\arlista\Controller\UploadedFileController::importProducts'
_title: "Termék adatok importálása"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
arlista.file.actualise-product-data:
path: "/files/{mid}/list/actualise-product-data"
defaults:
_controller: '\Drupal\arlista\Controller\ProductController::actualiseProductData'
_title: "Termék adatok aktivizálása"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
# PRODUCT
arlista.product.list:
path: "product/list/file"
defaults:
_form: '\Drupal\arlista\Form\Product\ProductUploadedList'
_title: "Feltöltött termékek kezelése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.product.edit:
path: "product/edit/{id}/{page}/{correctStatus}/{keyWords}/{listed}/{cikkszam}/{source}/{mid}/{fid}"
defaults:
_form: '\Drupal\arlista\Form\Product\ProductUploadedEdit'
_title: "Termék szerkesztése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
page: ^\d+$
correctStatus: ^-?\d+$
keyWords: ^-?\d+$
listed: ^\d+$
cikkszam: (.*)?
source: (.*)?
mid: ^\d+$
fid: ^\d+$
arlista.product.add:
path: "product/add/{mid}/{fid}/{sheetIndex}"
defaults:
_form: '\Drupal\arlista\Form\Product\ProductAdd'
_title: "Termék hozzáadása a munkalaphoz"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
mid: ^\d+$
fid: ^\d+$
sheetIndex: ^\d+$
arlista.product.delete:
path: "product/delete/{id}/{page}/{correctStatus}/{keyWords}/{listed}/{cikkszam}/{source}/{mid}/{fid}"
defaults:
_form: '\Drupal\arlista\Form\Product\ConfirmProductDelete'
_title: "Törlés megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
page: ^\d+$
correctStatus: ^-?\d+$
keyWords: ^-?\d+$
listed: ^\d+$
cikkszam: (.*)?
source: (.*)?
mid: ^\d+$
fid: ^\d+$
arlista.product.deactivate:
path: "product/deactivate/{id}/{page}/{correctStatus}/{keyWords}/{listed}/{cikkszam}/live/{mid}/{fid}"
defaults:
_form: '\Drupal\arlista\Form\Product\ConfirmProductDeactivate'
_title: "Passziválás megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
page: ^\d+$
correctStatus: ^-?\d+$
keyWords: ^-?\d+$
listed: ^\d+$
cikkszam: (.*)?
source: (.*)?
mid: ^\d+$
fid: ^\d+$
arlista.product.reactivate:
path: "product/reactivate/{id}/{page}/{correctStatus}/{keyWords}/{listed}/{cikkszam}/{source}/{mid}/{fid}"
defaults:
_form: '\Drupal\arlista\Form\Product\ConfirmProductActivate'
_title: "Aktiválás megerősítése"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
id: ^\d+$
page: ^\d+$
correctStatus: ^-?\d+$
keyWords: ^-?\d+$
listed: ^\d+$
cikkszam: (.*)?
source: (.*)?
mid: ^\d+$
fid: ^\d+$
arlista.product.list.file.update.category:
path: "product/list/file/update/category"
defaults:
_controller: '\Drupal\arlista\Controller\CategoryController::updateProductCategory'
_title: "Termékcsoport update"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"
arlista.product.list.file.update.component:
path: "product/list/file/update/component"
defaults:
_controller: '\Drupal\arlista\Controller\ComponentController::updateProductComponent'
_title: "Komponens update"
requirements:
_permission: "arlista manage_pricelists"
_disable_route_normalizer: "TRUE"

+ 39
- 0
modules/custom/arlista/arlista.services.yml Dosyayı Görüntüle

@@ -0,0 +1,39 @@
services:
arlista.axico-id.factory:
class: Drupal\arlista\Factory\AxicoIdFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.cache-service:
class: Drupal\arlista\Service\CacheService
arlista.category.factory:
class: Drupal\arlista\Factory\CategoryFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.calculation.factory:
class: Drupal\arlista\Factory\CalculationFactory
arguments: ['@database', '@current_user', '@datetime.time','@config.factory']
arlista.component.factory:
class: Drupal\arlista\Factory\ComponentFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.install.factory:
class: Drupal\arlista\Factory\InstallFactory
arguments: ['@arlista.axico-id.factory', '@arlista.category.factory', '@arlista.component.factory', '@arlista.manufacturer.factory', '@arlista.product.factory', '@arlista.calculation.factory', '@arlista.file.factory', '@arlista.spread-sheet.factory']
arlista.enabled-group.factory:
class: Drupal\arlista\Factory\EnabledGroupFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.file.factory:
class: Drupal\arlista\Factory\FileFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.manufacturer.factory:
class: Drupal\arlista\Factory\ManufacturerFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.product.factory:
class: Drupal\arlista\Factory\ProductFactory
arguments: ['@database', '@current_user', '@datetime.time', '@arlista.axico-id.factory', '@arlista.category.factory', '@arlista.component.factory', '@arlista.manufacturer.factory', '@arlista.calculation.factory','@arlista.cache-service']
arlista.product.service:
class: Drupal\arlista\Service\ProductService
arguments: ['@arlista.product.factory','@arlista.file.factory']
arlista.sheet-setting.factory:
class: Drupal\arlista\Factory\SheetSettingFactory
arguments: ['@database', '@current_user', '@datetime.time']
arlista.spread-sheet.factory:
class: Drupal\arlista\Factory\SpreadSheetFactory
arguments: ['@arlista.component.factory','@arlista.manufacturer.factory','@arlista.category.factory']

+ 84
- 0
modules/custom/arlista/css/arlista.css Dosyayı Görüntüle

@@ -0,0 +1,84 @@
.custom-wrapper {
display: flex;
flex-direction: row;
}

.custom-wrapper .custom-items-wrapper {
margin-right: 0.5rem;
}

.operations-wrapper span {
display: block;
}

.operations-wrapper span:hover, .custom-items-wrapper a:hover {
cursor: pointer;
color: red;
}

.list-container {
overflow: scroll;
height: 32rem;
}

.pager-active-page {
font-weight: bold;
padding-bottom: 0.1rem;
}

.bold-text {
font-weight: bold;
}

.table tr:nth-child(even) {
background-color: #d2d2e0;
}

.table tr:hover {
background-color: #ffd9cc;
}

.arlista-green {
color: green;
padding: 0.2rem 0rem;
}

.price-changed {
color: red !important;
font-weight: bold !important;
}

.arlista-red {
color: red;
}

.product-changes:hover {
cursor: pointer;
}

.product-changes {
display: none;
flex-direction: column;
}

.previous-value {
color: blue;
text-decoration: line-through;
}

.new-value {
color: green;
}

.changed-data {
color: red;
margin-top: 1.0rem;
}

div.field__item:hover {
background-color: lightcoral;
}

button.button {
margin-right: 1rem;
}

+ 542
- 0
modules/custom/arlista/js/arlista.js Dosyayı Görüntüle

@@ -0,0 +1,542 @@
/**
* @file
* Arlista behaviors.
*/

(function ($, Drupal, drupalSettings) {
Drupal.behaviors.correct_files = {
attach: function attach(context, drupalSettings) {
$(document).ready(function () {

/*
* Mouse enter show/hide previous price
*/
$('.changed-data').on("mouseleave", function () {
$(this).closest('tr').find('.product-changes').css('display', 'none');
});
$('.changed-data').on("mouseenter", function () {
$(this).closest('tr').find('.product-changes').css('display', 'flex');
});

/*
* # uploaded_files_manufacturer_select
*/
$("#uploaded_files_manufacturer_select").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(document.URL.replace(/(?<=\/)(\d+)(?=\/)/, selected.val()));
});

/*
* # Manufacturer-edit-selected-sheet-index redirect
*/
$("#manufacturer-edit-selected-sheet-index").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('sheetIndex', selected.val(), 'page', 1));
});

/*
* # Components-manufacturer-selected redirect
*/
$("#components-manufacturer-select").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('mid', selected.val(), null, null));
});

/*
* # Correct status filter change redirect
*/
$("#filtered-product-correct-status").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('correctStatus', selected.val(), 'page', 1));
});

/*
* # Sheet-selected-sheet-index on change-redirect
*/
$("#selected-sheet-index").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('sheetIndex', selected.val(), 'page', 1));
});

/*
* # Filtered-product-by-keyWords-change redirect
*/
$("#filtered-product-by-key-words").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('keyWords', selected.val(), null, null));
});

/*
* # Filtered-product-number-of-listed-products redirect
*/
$("#filtered-number-of-listed-products").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
window.location.replace(replaceUrlParams('listed', selected.val(), 'page', 1));
});

/*
* # Manufacturer-category-calculation-select redirect
*/
$("#manufacturer-category-calculation-select").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled') || selected.val() === 0) {
return;
}
selected.prop('disabled', true);
let url = document.URL;
url = url + "/edit/" + selected.val() + "/0";
window.location.replace(url);
});

/*
* # Manufacturer-component-calculation-select redirect
*/
$("#manufacturer-component-calculation-select").change(function (e) {
e.preventDefault();
let selected = $(this);
if (selected.prop('disabled') || selected.val() === 0 || selected.val() === '0') {
return;
}
selected.prop('disabled', true);
let url = document.URL;
url = url + "/edit/0" + "/" + selected.val();
window.location.replace(url);
});

/*
* Filter by cikkszam input change
*/
$("#filtered-products-cikkszam").keyup(delay(function (e) {
let inputField = $(this);
if (inputField.val().length < 3 && inputField.val().length > 1) {
return;
}
window.location.replace(replaceUrlParams('cikkszam', inputField.val(), null, null));
}, 750));

function delay(callback, ms) {
let timer = 0;
return function () {
let context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}

/*
* Fabric id, enables group select if it is disabled
*/
$("#edit-fabricid").focusout(function () {
let input = $(this).val();
if (!input.length) {
return;
}
if ($("#category_select")) {
$("#category_select").closest('.form-disabled').removeClass('form-disabled');
$("#category_select").removeAttr('disabled');

$("#category_select").focus();
}
if ($("#component_select")) {
$("#component_select").closest('.form-disabled').removeClass('form-disabled');
$("#component_select").removeAttr('disabled');
$("#component_select").focus();
}
});

/*
* # delete uploaded file
*/
$(".file-operation-delete-file").click(function () {
let fid = $(this).closest("tr").attr("data-field-uploaded-file-id");
let url = drupalSettings.arlista.host + "/" + fid + "/delete";
window.location.replace(url);
});

/*
* # Import products from file
*/
$(".file-operation-import-product-data").click(function (e) {
e.preventDefault();
let buttonClicked = $(this);
if (buttonClicked.attr("data-field-request-status") === "loading") {
return;
}
buttonClicked.attr("data-field-request-status", "loading");

let fid = buttonClicked.closest("tr").attr("data-field-uploaded-file-id");
let url = drupalSettings.arlista.host + "/import";
postPackageToUrl({fid: fid}, url, true);
});

/*
* # Update listed products category on select change
*/
$(".product-list-category-select").change(function (e) {
e.preventDefault();
let selected = $(this);
let cid = selected.val();
if (cid === '-1' || cid === -1) {
return;
}
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
let revokeAxicoId = 0;
if (cid === '0-0-revokeAxicoId') {
revokeAxicoId = 1;
}
let mid = selected.closest("tr").attr("data-field-attr-mid");
let pid = selected.closest("tr").attr("data-field-product-id");
let fid = selected.closest("tr").attr("data-field-uploaded-file-id");
let package = {
fid: fid,
cid: cid,
mid: mid,
pid: pid,
revokeAxicoId: revokeAxicoId
};
let url = drupalSettings.arlista.host + "/update/category";
postPackageToUrl(package, url, false, selected);
});

/*
* # Update selected products category on select change
*/
$("#category_select").change(function (e) {
e.preventDefault();
let url = document.URL;
if (url.includes('/add')) {
return;
}
let selected = $(this);
let cid = selected.val();
if (cid < 1) {
return;
}
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
let pid = $('form').find('*').filter(':input[name=id]').attr('value');
let mid = $('form').find('*').filter(':input[name=file_mid]').attr('value');
let fid = $('form').find('*').filter(':input[name=file_fid]').attr('value');

let package = {
cid: cid,
pid: pid,
mid: mid,
fid: fid
};
let fullPath = drupalSettings.arlista.host;
let arr = fullPath.split("edit");
url = arr[0] + "list/file/update/category";
$('html,body').css('cursor', 'wait');
$.ajax({
url: url,
method: "POST",
data: package,
success: function (data, status, xhr) {
$('html,body').css('cursor', 'initial');
selected.prop('disabled', false);
$('#edit-axicoid').val(data.data.axicoId[pid]);
window.location.replace(document.URL);
},
error: function (request, ajaxOptions, thrownError) {
$('html,body').css('cursor', 'initial');
alert(request.status);
alert(thrownError);
}
});
});

/*
* # Update listed products component on select change
*/
$(".product-list-component-select").change(function (e) {
e.preventDefault();
let selected = $(this);
let cmpId = selected.val().split("-")[1];
if (cmpId === 'x') {
return;
}
let mid = selected.val().split("-")[0];
let revokeAxicoId = 0;
if (selected.val().split("-")[2]) {
revokeAxicoId = 1;
}
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
let pid = selected.closest("tr").attr("data-field-product-id");
let fid = selected.closest("tr").attr("data-field-uploaded-file-id");
let package = {
fid: fid,
cmpId: cmpId,
mid: mid,
pid: pid,
revokeAxicoId: revokeAxicoId
};

let url = drupalSettings.arlista.host + "/update/component";
postPackageToUrl(package, url, false, selected);
});

/*
* # Update selected products component on select change
*/
$("#component_select").change(function (e) {
e.preventDefault();
let url = document.URL;
if (url.includes('/add')) {
return;
}
let selected = $(this);
let cmpId = selected.val();
if (cmpId < 1) {
return;
}
if (selected.prop('disabled')) {
return;
}
selected.prop('disabled', true);
let pid = $('form').find('*').filter(':input:first').attr('value');
let mid = $('form').find('*').filter(':input[name=file_mid]').attr('value');
let fid = $('form').find('*').filter(':input[name=file_fid]').attr('value');

let package = {
cmpId: cmpId,
pid: pid,
mid: mid,
fid: fid
};
let fullPath = drupalSettings.arlista.host;
let arr = fullPath.split("edit");
url = arr[0] + "list/file/update/component";
$('html,body').css('cursor', 'wait');
$.ajax({
url: url,
method: "POST",
data: package,
success: function (data, status, xhr) {
$('html,body').css('cursor', 'initial');
selected.prop('disabled', false);
$('#edit-axicoid').val(data.data.axicoId[pid]);
window.location.replace(document.URL);
},
error: function (request, ajaxOptions, thrownError) {
$('html,body').css('cursor', 'initial');
alert(request.status);
alert(thrownError);
}
});
});

/*
* # Find axicoId of products
*/
$(".file-operation-find-axico-id").click(function (e) {
e.preventDefault();
let buttonClicked = $(this);
if (buttonClicked.attr("data-field-request-status") === "loading") {
return;
}
buttonClicked.attr("data-field-request-status", "loading");

let fid = buttonClicked.closest("tr").attr("data-field-uploaded-file-id");
let url = drupalSettings.arlista.host + "/find-axico-id";
postPackageToUrl({fid: fid}, url, true);
});

/*
* # Compare product data
*/
$(".file-operation-sync-product-data").click(function (e) {
e.preventDefault();
let buttonClicked = $(this);
if (buttonClicked.attr("data-field-request-status") === "loading") {
return;
}
buttonClicked.attr("data-field-request-status", "loading");

let fid = buttonClicked.closest("tr").attr("data-field-uploaded-file-id");
let url = drupalSettings.arlista.host + "/compare-product-data";
postPackageToUrl({fid: fid}, url, true);
});

/*
* # Actualise product data
*/
$(".file-operation-actualise-product-data").click(function (e) {
e.preventDefault();
let buttonClicked = $(this);
if (buttonClicked.attr("data-field-request-status") === "loading") {
return;
}
buttonClicked.attr("data-field-request-status", "loading");

let fid = buttonClicked.closest("tr").attr("data-field-uploaded-file-id");
let url = drupalSettings.arlista.host + "/actualise-product-data";
let currentUrl = document.URL;
if (!currentUrl.includes("/files")) {
let urlVars = getUrlVars(currentUrl);
fid = urlVars['fid'];
url = drupalSettings.arlista.basePath + "/files/" + urlVars['mid'] + "/list/actualise-product-data";
}
postPackageToUrl({fid: fid}, url, true);
});

/*
* # default_status_select
*/
$("#default_status_select").change(function (e) {
e.preventDefault();
let selected = $(this);
console.log(selected.val());
if (selected.val() === 2 || selected.val() === "2") {
$("#enable-group-calculation-list").show();
}
if (selected.val() === 1 || selected.val() === 0 || selected.val() === "1" || selected.val() === "0") {
$("#enable-group-calculation-list").hide();
}
});

/**
* HTTP post request with params
*
* @param {object} package
* @param {string} url
* @param {boolean} redirect
* @param {object} selected
* @returns {undefined}
*/
function postPackageToUrl(package, url, redirect, selected = null) {
$('html,body').css('cursor', 'wait');
$.ajax({
url: url,
method: "POST",
data: package,
success: function (data, status, xhr) {
console.log(data);
$('html,body').css('cursor', 'initial');
if(!data.success){
alert(data.message);

return;
}
if (redirect) {
let url = document.URL;
window.location.replace(document.URL);
}
if (selected) {
console.log('here');
let id = package.pid;
selected.closest('td').prev().text(data.data.axicoId[id]);
if (!data.data.axicoId[id]) {
// add option

}

if (package.cmpId) {
if (selected.closest(".product-list-component-select")) {
selected.closest(".product-list-component-select").val(data.data.optionValues[package.pid]);
}
} else {
if (selected.closest('.product-list-category-select')) {
selected.closest('.product-list-category-select').val(data.data.optionValues[package.pid]);
}
}
selected.prop('disabled', false);
selected.closest('.correct-files-uploaded-product').find('.downloadable').html('Igen');
}
},
error: function (request, ajaxOptions, thrownError) {
$('html,body').css('cursor', 'initial');
alert(request.status);
alert(thrownError);
}
});
}

/**
* Replace params found in active url and return it
*
* @param {string} paramNameOne
* @param {string} paramValueOne
* @param {string} paramNameTwo
* @param {string} paramValueTwo
* @returns {String}
*/
function replaceUrlParams(paramNameOne, paramValueOne, paramNameTwo, paramValueTwo) {
let urlVars = getUrlVars();
urlVars[paramNameOne] = paramValueOne;
if (paramNameTwo) {
urlVars[paramNameTwo] = paramValueTwo;
}
let url = document.URL;
urlParams = '';
urlVars.forEach(function (item) {
urlParams = urlParams + item + "=" + urlVars[item] + "&";
});

let arr = url.split("?");
url = arr[0] + "?" + urlParams;
return url.substring(0, url.length - 1);
}

function getUrlVars() {
let vars = [], hash;
let hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (let i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}


});
}};
})(jQuery, Drupal, drupalSettings);

BIN
modules/custom/arlista/regi_kategoriak.xlsx Dosyayı Görüntüle


+ 15
- 0
modules/custom/arlista/src/BaseEntityNotFoundException.php Dosyayı Görüntüle

@@ -0,0 +1,15 @@
<?php

namespace Drupal\arlista;

use Drupal\arlista\BaseException;

class BaseEntityNotFoundException extends BaseException {

public function __construct(string $message) {
parent::__construct($message);
}

}



+ 13
- 0
modules/custom/arlista/src/BaseException.php Dosyayı Görüntüle

@@ -0,0 +1,13 @@
<?php

namespace Drupal\arlista;

use Exception;

class BaseException extends Exception {

public function __construct(string $message) {
parent::__construct($message);
}

}

+ 134
- 0
modules/custom/arlista/src/Controller/ArlistaAbstractController.php Dosyayı Görüntüle

@@ -0,0 +1,134 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\arlista\Service\CacheService;
use Drupal\arlista\Factory\CategoryFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\arlista\Factory\FileFactory;
use Drupal\arlista\Factory\ManufacturerFactory;
use Drupal\arlista\Factory\SheetSettingFactory;
use Drupal\arlista\Factory\SpreadSheetFactory;
use Drupal\arlista\Factory\ProductFactory;
use Drupal\arlista\Factory\CalculationFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\arlista\Entity\ResponseBody;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\WorkFlow;

abstract class ArlistaAbstractController extends ControllerBase {

private $categoryFactory;
private $fileFactory;
private $manufacturerFactory;
private $sheetSettingFactory;
private $cacheService;
private $spreadSheetFactory;
private $productFactory;
private $calculationFactory;
private $response;
private $responseBody;
private $admin;

public function __construct(CategoryFactory $categoryFactory,
FileFactory $fileFactory, ManufacturerFactory $manufacturerFactory,
SheetSettingFactory $SheetSettingFactory, CacheService $cacheService,
SpreadSheetFactory $spreadSheetFactory, ProductFactory $productFactory,
CalculationFactory $calculationFactory) {
$this->categoryFactory = $categoryFactory;
$this->fileFactory = $fileFactory;
$this->manufacturerFactory = $manufacturerFactory;
$this->sheetSettingFactory = $SheetSettingFactory;
$this->cacheService = $cacheService;
$this->spreadSheetFactory = $spreadSheetFactory;
$this->productFactory = $productFactory;
$this->calculationFactory = $calculationFactory;
$this->response = new JsonResponse();
$this->response->headers->set('Content-Type', 'application/json');
$this->responseBody = new ResponseBody();
$this->responseBody->setTime(date("Y-m-d H:i:s"));
$this->admin = \Drupal\user\Entity\User::load($this->currentUser()->id())->hasRole('administrator');
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {

return new static(
$container->get('arlista.category.factory'),
$container->get('arlista.file.factory'),
$container->get('arlista.manufacturer.factory'),
$container->get('arlista.sheet-setting.factory'),
$container->get('arlista.cache-service'),
$container->get('arlista.spread-sheet.factory'),
$container->get('arlista.product.factory'),
$container->get('arlista.calculation.factory'),
);
}

public function getCategoryFactory(): CategoryFactory {
return $this->categoryFactory;
}

public function getFileFactory(): FileFactory {
return $this->fileFactory;
}

public function getManufacturerFactory(): ManufacturerFactory {
return $this->manufacturerFactory;
}

public function getSheetSettingFactory(): SheetSettingFactory {
return $this->sheetSettingFactory;
}

public function getCacheService(): CacheService {
return $this->cacheService;
}

public function getSpreadSheetFactory(): SpreadSheetFactory {
return $this->spreadSheetFactory;
}

public function getProductFactory(): ProductFactory {
return $this->productFactory;
}

public function getCalculationFactory(): CalculationFactory {
return $this->calculationFactory;
}

public function getResponse(): JsonResponse {
return $this->response;
}

public function getResponseBody(): ResponseBody {
return $this->responseBody;
}

public function isAdmin(): bool {
return $this->admin;
}

public function updateProductInOtherFiles(Product $product): void {
$sameUploadedProductsInDifferentFiles = $this->getProductFactory()->findSameUploadedProductInDifferentFilesByFabricId($product->getFabricId(), $product->getUploadedFileId());
/* @var $sameProductInOtherFiles Product */
foreach ($sameUploadedProductsInDifferentFiles as $sameProductInOtherFiles) {
$sameProductInOtherFiles->setParentComponentId($product->getParentComponentId());
$sameProductInOtherFiles->setParentManufacturerId($product->getParentManufacturerId());
$sameProductInOtherFiles->setParentCategoryId($product->getParentCategoryId());
$sameProductInOtherFiles->copyPrices($sameProductInOtherFiles);
$sameProductInOtherFiles->setAxicoId($product->getAxicoId());
$sameProductInOtherFiles->setWorkFlow(WorkFlow::ACTIVATED);
$sameProductInOtherFiles->setCorrectStatus(Status::CORRECT_IMPORTED);
$this->getProductFactory()->save($sameProductInOtherFiles);
$this->cacheService->resetCache(['arlista_product_edit_form', 'uploaded', $product->getId()]);
}
}

}

+ 76
- 0
modules/custom/arlista/src/Controller/AxicoIdController.php Dosyayı Görüntüle

@@ -0,0 +1,76 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\arlista\Controller\ArlistaAbstractController;
use Symfony\Component\HttpFoundation\Request;
use Drupal\arlista\Entity\WorkFlow;

class AxicoIdController extends ArlistaAbstractController {

public function setAxicoId(Request $request) {

$this->getResponseBody()->setFid($request->request->get('fid'));
$this->getResponseBody()->setMessage('Sikertelen cikkszámozás');

if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile = $this->getFileFactory()->find($request->request->get('fid'));

if (empty($uploadedFile) || empty($request->request->get('fid'))) {
$this->getResponseBody()->setMessage('Nincs ilyen fájl');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (empty($uploadedFile->getTotalProducts() < 1)) {
$this->getResponseBody()->setMessage('A feltöltött fájl nem tartalmaz termékeket');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$products = $this->getProductFactory()->findProductsByUploadedFileId($uploadedFile->getId());

if (empty($products)) {
$this->getResponseBody()->setMessage('A feltöltött fájlhoz kapcsolódó termékek nem találhatóak');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$result = [
'products' => $products,
'manufacturer' => $this->getManufacturerFactory()->find($uploadedFile->getParentManufacturerId()),
'totalNumbered' => 0,
'axicoId' => [],
'axicoIdContinued' => 0,
'axicoIdGenerated' => 0,
'axicoIdMissing' => 0,
'optionValues' => [],
'status' => false,
];

$result = $this->getProductFactory()->createOrFindAxicoIdForEachProduct($result);

if (!$result['status']) {
$this->getResponseBody()->setMessage('A fájl egyik munkalapja sem tartalmazott sorszámozható terméket - ellenőrizze a konfigurációkat');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile->setWorkFlow(WorkFlow::NUMBERED);
$this->getFileFactory()->save($uploadedFile);

unset($result['products'], $result['manufacturer']);

$this->getResponseBody()->setMessage('Sikeres sorszámozás');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());

return $this->getResponse();
}

}

+ 101
- 0
modules/custom/arlista/src/Controller/CategoryController.php Dosyayı Görüntüle

@@ -0,0 +1,101 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\arlista\Controller\ArlistaAbstractController;
use Symfony\Component\HttpFoundation\Request;
use Drupal\arlista\Entity\Product;

class CategoryController extends ArlistaAbstractController {

public function updateProductCategory(Request $request) {

$this->getResponseBody()->setFid($request->request->get('fid'));

if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile = $this->getFileFactory()->find($request->request->get('fid'));
if (empty($uploadedFile) || empty($request->request->get('fid'))) {
$this->getResponseBody()->setMessage('Nincs ilyen fájl');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (strpos($request->request->get('cid'), "-")) {
$array = explode("-", $request->request->get('cid'));
$cid = $array[1];
} else {
$cid = $request->request->get('cid');
}

/* @var $product Product */
$product = $this->getProductFactory()->find($request->request->get('pid'));

$revokeAxicoId = (int) $request->request->get('revokeAxicoId');

if (!$cid || $revokeAxicoId) {
$result = [
'products' => [$product],
'manufacturer' => null,
'totalNumbered' => 0,
'axicoIdCopied' => 0,
'axicoIdContinued' => 0,
'axicoIdGenerated' => 0,
'axicoId' => [],
'axicoIdMissing' => 0,
'status' => false,
'revokeAxicoId' => $revokeAxicoId,
'revokedProducts' => [],
'axicoIdRevoked' => 0,
];
$result = $this->getProductFactory()->createOrFindAxicoIdForEachProduct($result);
} else {
/* @var $category Category */
$category = $this->getProductFactory()->getCategoryFactory()->find($cid);
$product->setParentComponentId(null);
$product->setParentManufacturerId($request->request->get('mid'));
$product->setParentCategoryId($category->getId());
$product = $this->getProductFactory()->save($product);

$result = [
'products' => [$product],
'manufacturer' => $product->getParentManufacturerId(),
'totalNumbered' => 0,
'axicoIdCopied' => 0,
'axicoIdContinued' => 0,
'axicoIdGenerated' => 0,
'axicoId' => [],
'axicoIdMissing' => 0,
'status' => false,
'revokeAxicoId' => $revokeAxicoId,
'revokedProducts' => [],
'axicoIdRevoked' => 0,
];

$result = $this->getProductFactory()->createOrFindAxicoIdForEachProduct($result);
}

if (!$result['status']) {
$this->getResponseBody()->setMessage('Sikertelen termékcsoport frissítés');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (count($result['products']) === 1) {
$this->updateProductInOtherFiles($result['products'][0]);
}

unset($result['products'], $result['manufacturer'], $result['revokedProducts']);
$this->getResponseBody()->setMessage('Sikeres frissítés');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());

return $this->getResponse();
}

}

+ 90
- 0
modules/custom/arlista/src/Controller/ComponentController.php Dosyayı Görüntüle

@@ -0,0 +1,90 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\arlista\Controller\ArlistaAbstractController;
use Symfony\Component\HttpFoundation\Request;
use Drupal\arlista\Entity\Product;

class ComponentController extends ArlistaAbstractController {

public function updateProductComponent(Request $request) {

$this->getResponseBody()->setFid($request->request->get('fid'));

if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile = $this->getFileFactory()->find($request->request->get('fid'));
if (empty($uploadedFile) || empty($request->request->get('fid'))) {
$this->getResponseBody()->setMessage('Nincs ilyen fájl');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

/* @var $product Product */
$product = $this->getProductFactory()->find($request->request->get('pid'));

$revokeAxicoId = (int) $request->request->get('revokeAxicoId');
$cmpId = (int) $request->request->get('cmpId');
if (!$cmpId && $revokeAxicoId) {
$result = [
'products' => [$product],
'manufacturer' => null,
'totalNumbered' => 0,
'axicoIdContinued' => 0,
'axicoIdGenerated' => 0,
'axicoId' => [],
'axicoIdMissing' => 0,
'status' => false,
'axicoIdRevoked' => 0,
'revokeAxicoId' => $revokeAxicoId,
'revokedProducts' => [],
];
$result = $this->getProductFactory()->createOrFindAxicoIdForEachProduct($result);
} else {
$component = $this->getProductFactory()->getComponentFactory()->find($cmpId);
$product->setParentComponentId($component->getId());
$product->setParentManufacturerId($component->getParentManufacturerId());
$product = $this->getProductFactory()->save($product);
$result = [
'products' => [$product],
'manufacturer' => $this->getManufacturerFactory()->find($request->request->get('mid')),
'totalNumbered' => 0,
'axicoIdContinued' => 0,
'axicoIdGenerated' => 0,
'axicoId' => [],
'axicoIdMissing' => 0,
'status' => false,
'axicoIdRevoked' => 0,
'revokeAxicoId' => $revokeAxicoId,
'revokedProducts' => [],
];
$result = $this->getProductFactory()->createOrFindAxicoIdForEachProduct($result);
}

if (!$result['status']) {
$this->getResponseBody()->setMessage('Sikertelen kompononens csoport frissítés');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (count($result['products']) === 1) {
$this->updateProductInOtherFiles($result['products'][0]);
}

unset($result['products'], $result['manufacturer'], $result['revokedProducts']);

$this->getResponseBody()->setMessage('Sikeres frissítés');
$result['status'] = 1;
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());

return $this->getResponse();
}

}

+ 140
- 0
modules/custom/arlista/src/Controller/ProductController.php Dosyayı Görüntüle

@@ -0,0 +1,140 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\arlista\Controller\ArlistaAbstractController;
use Symfony\Component\HttpFoundation\Request;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\WorkFlow;

class ProductController extends ArlistaAbstractController {

public function compareProducts(Request $request) {

$fid = $request->request->get('fid');
$this->getResponseBody()->setFid($fid);
$this->getResponseBody()->setMessage('Sikertelen szinkronizáció');

if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}
$uploadedFile = $this->getFileFactory()->find($fid);
if (empty($uploadedFile) || empty($fid)) {
$this->getResponseBody()->setMessage('Nincs ilyen fájl');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (empty($uploadedFile->getTotalProducts() < 1)) {
$this->getResponseBody()->setMessage('A feltöltött fájl nem tartalmaz termékeket');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$products = $this->getProductFactory()->findProductsByUploadedFileId($uploadedFile->getId());
if (empty($products)) {
$this->getResponseBody()->setMessage('A feltöltött fájlhoz kapcsolódó termékek nem találhatóak');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$result = [
'products' => $products,
'manufacturer' => $this->getManufacturerFactory()->find($uploadedFile->getParentManufacturerId()),
'totalCompared' => 0,
'unchanged' => 0,
'changed' => 0,
'newProduct' => 0,
'status' => false,
];

$result = $this->getProductFactory()->compareProducts($result);
if ($result['total'] === 0 || !$result['status']) {
$this->getResponseBody()->setMessage('Nincs sorszámozott és szinkronizálható termék - ellenőrizze a konfigurációkat');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile->setWorkFlow(WorkFlow::COMPARED);
$this->getFileFactory()->save($uploadedFile);

unset($result['products'], $result['manufacturer']);

$this->getResponseBody()->setMessage('Sikeres szinkronizáció');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());

return $this->getResponse();
}

public function actualiseProductData(Request $request) {

$fid = $request->request->get('fid');
$this->getResponseBody()->setFid($fid);
$this->getResponseBody()->setMessage('Sikertelen aktualizáció');

if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile = $this->getFileFactory()->find($fid);
if (empty($uploadedFile) || empty($fid)) {
$this->getResponseBody()->setMessage('Nincs ilyen fájl');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

if (empty($uploadedFile->getTotalProducts() < 1)) {
$this->getResponseBody()->setMessage('A feltöltött fájl nem tartalmaz termékeket');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$products = $this->getProductFactory()->findProductsByUploadedFileId($uploadedFile->getId());
if (empty($products)) {
$this->getResponseBody()->setMessage('A feltöltött fájlhoz kapcsolódó termékek nem találhatóak');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}
$modifiedProducts = [];

/* @var $product Product */
foreach ($products as $product) {
if ($product->getModifiedAt() > $uploadedFile->getModifiedAt()) {
$modifiedProducts[] = $product;
}
}

$result = [
'products' => $modifiedProducts,
'manufacturer' => $this->getManufacturerFactory()->find($uploadedFile->getParentManufacturerId()),
'totalActualised' => 0,
'newProduct' => 0,
'updatedProduct' => 0,
'status' => false,
];

$result = $this->getProductFactory()->actualiseProducts($result);
if ($result['totalActualised'] === 0 || !$result['status']) {
$this->getResponseBody()->setMessage('Nincs aktualizálható termék - ellenőrizze a konfigurációkat');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

$uploadedFile->setWorkFlow(WorkFlow::ACTIVATED);
$this->getFileFactory()->save($uploadedFile);

unset($result['products'], $result['manufacturer']);

$this->getResponseBody()->setMessage('Sikeres aktualizáció');
$this->getResponseBody()->setData($result);
$this->getResponse()->setData($this->getResponseBody()->toArray());

return $this->getResponse();
}

}

+ 79
- 0
modules/custom/arlista/src/Controller/UploadedFileController.php Dosyayı Görüntüle

@@ -0,0 +1,79 @@
<?php

namespace Drupal\arlista\Controller;

use Drupal\arlista\Controller\ArlistaAbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\arlista\Entity\UploadedFile;
use Drupal\arlista\Entity\WorkFlow;

class UploadedFileController extends ArlistaAbstractController {

/**
* Import product data from uploaded excel file
*
* @param Request $request
* @return JsonResponse
*/
public function importProducts(Request $request): JsonResponse {

$this->getResponseBody()->setFid($request->request->get('fid'));
$this->getResponseBody()->setMessage('Sikertelen import');
if ($this->currentUser->isAnonymous() || !$this->isAdmin()) {
$this->getResponseBody()->setMessage('Sikertelen azonosítás');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}
/* @var $uploadedFile UploadedFile */
$uploadedFile = $this->getFileFactory()->find($request->request->get('fid'));
$spreadSheet = $this->getSpreadSheetFactory()->loadUploadedFile($uploadedFile);
if (empty($spreadSheet)) {
$this->getResponseBody()->setMessage('A feltöltött fájl nem tartalmaz excel adatokat');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($uploadedFile->getParentManufacturerId());
// Data extraction from file
$result = $this->getSpreadSheetFactory()->extractDataFromSpreadSheet($spreadSheet, $sheetSettings);

if (empty($result['totalProducts'])) {
$this->getResponseBody()->setMessage('A fájl egyik munkalapja sem tartalmaz terméket - ellenőrizze a konfigurációkat');
$this->getResponse()->setData($this->getResponseBody()->toArray());
return $this->getResponse();
}

foreach ($result['extracted'] as $workSheet) {
$this->getProductFactory()->saveAllExtractedFromUploadedFile($workSheet['products'], $uploadedFile->getComponentBased());
}

$uploadedFile->setWorkFlow(WorkFlow::IMPORTED);
$this->getFileFactory()->save($uploadedFile);

$this->getResponseBody()->setSuccess(1);
$this->getResponseBody()->setData($result['totalProducts']);
$this->getResponse()->setData($this->getResponseBody()->toArray());

$this->compare($uploadedFile);
$this->getResponseBody()->setMessage('Sikeres import, összehasonlítás éa sorszámozás. Ellenőrizze az adatokat');

return $this->getResponse();
}

private function compare(UploadedFile $uploadedFile): void {
$products = $this->getProductFactory()->findProductsByUploadedFileId($uploadedFile->getId());
$result = [
'products' => $products,
'manufacturer' => $this->getManufacturerFactory()->find($uploadedFile->getParentManufacturerId()),
'totalCompared' => 0,
'unchanged' => 0,
'changed' => 0,
'newProduct' => 0,
'status' => false,
];
$this->getProductFactory()->compareProducts($result);
$uploadedFile->setWorkFlow(WorkFlow::ACTIVATED);
$this->getFileFactory()->save($uploadedFile);
}

}

+ 103
- 0
modules/custom/arlista/src/Entity/AbstractEntity.php Dosyayı Görüntüle

@@ -0,0 +1,103 @@
<?php

namespace Drupal\arlista\Entity;

abstract class AbstractEntity {

private ?int $id = null;
private ?int $status = null;
private $createdAt;
private $createdBy;
private $modifiedAt;
private $modifiedBy;
private $deletedAt;
private ?string $name = null;
private ?string $sif = null;

public function __construct() {
$this->status = Status::ACTIVE;
}

public function isNew() {
return $this->id === null;
}

public function isVisible() {
return $this->status === 1;
}
public function getId(): ?int {
return $this->id;
}

public function getStatus(): ?int {
return $this->status;
}

public function getCreatedAt() {
return $this->createdAt;
}

public function getCreatedBy() {
return $this->createdBy;
}

public function getModifiedAt() {
return $this->modifiedAt;
}

public function getModifiedBy() {
return $this->modifiedBy;
}

public function getDeletedAt() {
return $this->deletedAt;
}

public function getName(): ?string {
return $this->name;
}

public function getSif(): ?string {
return $this->sif;
}

public function setId(?int $id): void {
$this->id = $id;
}

public function setStatus(?int $status): void {
$this->status = $status;
}

public function setCreatedAt($createdAt): void {
$this->createdAt = $createdAt;
}

public function setCreatedBy($createdBy): void {
$this->createdBy = $createdBy;
}

public function setModifiedAt($modifiedAt): void {
$this->modifiedAt = $modifiedAt;
}

public function setModifiedBy($modifiedBy): void {
$this->modifiedBy = $modifiedBy;
}

public function setDeletedAt($deletedAt): void {
$this->deletedAt = $deletedAt;
}

public function setName(?string $name): void {
$this->name = $name;
}

public function setSif(?string $sif): void {
$this->sif = $sif;
}



}

+ 89
- 0
modules/custom/arlista/src/Entity/AxicoId.php Dosyayı Görüntüle

@@ -0,0 +1,89 @@
<?php

namespace Drupal\arlista\Entity;

use Drupal\arlista\Entity\AbstractEntity;

class AxicoId extends AbstractEntity {

private ?int $parentManufacturerId = null;
private ?int $parentCategoryId = null;
private ?int $parentComponentId = null;
private ?int $currentCount = 1;
/*
* This tells if this axico id is next in the line
*
* @property int $nextCount
*/
private ?int $nextCount = 0;
private ?int $productId = null;

public function __construct() {
parent::__construct();
}

public function isComponentBased(): bool {
return !empty($this->parentComponentId);
}

public function close() {
$this->nextCount = 0;
}

public function addToCurrentCount($count) {
$this->currentCount = $this->currentCount + $count;
}

public function getNextAxicoIdName() {
return preg_replace('/[0-9]+/', '', $this->getName());
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function getParentCategoryId(): ?int {
return $this->parentCategoryId;
}

public function getParentComponentId(): ?int {
return $this->parentComponentId;
}

public function getCurrentCount(): ?int {
return $this->currentCount;
}

public function getNextCount(): ?int {
return $this->nextCount;
}

public function getProductId(): ?int {
return $this->productId;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}

public function setParentCategoryId(?int $parentCategoryId): void {
$this->parentCategoryId = $parentCategoryId;
}

public function setParentComponentId(?int $parentComponentId): void {
$this->parentComponentId = $parentComponentId;
}

public function setCurrentCount(?int $currentCount): void {
$this->currentCount = $currentCount;
}

public function setNextCount(?int $nextCount): void {
$this->nextCount = $nextCount;
}

public function setProductId(?int $productId): void {
$this->productId = $productId;
}

}

+ 172
- 0
modules/custom/arlista/src/Entity/Calculation.php Dosyayı Görüntüle

@@ -0,0 +1,172 @@
<?php

namespace Drupal\arlista\Entity;

class Calculation extends AbstractEntity {

private ?int $parentManufacturerId = null;
private ?int $parentComponentId = null;
private ?int $parentCategoryId = null;
private ?float $listPriceFactor;
private ?float $priceFactorDOne = null;
private ?float $priceFactorDTwo = null;
private ?float $priceFactorSpec = null;
private ?float $priceFactorVSpec = null;
private ?float $priceFactorDevDOne = null;
private ?float $priceFactorDevDTwo = null;
private ?float $priceFactorDevSpec = null;
private ?float $priceFactorDevVSpec = null;
private ?int $defaultCalculation = null;
private ?float $exchangeRate = null;
private ?float $transportExpense = null;

public function __construct() {
parent::__construct();
$this->listPriceFactor = 1.00;
$this->priceFactorDOne = 1.00;
$this->priceFactorDTwo = 1.00;
$this->priceFactorSpec = 1.00;
$this->priceFactorVSpec = 1.00;
$this->priceFactorDevDOne = 1.00;
$this->priceFactorDevDTwo = 1.00;
$this->priceFactorDevSpec = 1.00;
$this->priceFactorDevVSpec = 1.00;
$this->defaultCalculation = 0;
$this->exchangeRate = 1.00;
$this->transportExpense = 0.00;
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function getParentComponentId(): ?int {
return $this->parentComponentId;
}

public function getParentCategoryId(): ?int {
return $this->parentCategoryId;
}

public function getListPriceFactor(): ?float {
return $this->listPriceFactor;
}

public function getPriceFactorDOne(): ?float {
return $this->priceFactorDOne;
}

public function getPriceFactorDTwo(): ?float {
return $this->priceFactorDTwo;
}

public function getPriceFactorSpec(): ?float {
return $this->priceFactorSpec;
}

public function getPriceFactorVSpec(): ?float {
return $this->priceFactorVSpec;
}

public function getPriceFactorDevDOne(): ?float {
return $this->priceFactorDevDOne;
}

public function getPriceFactorDevDTwo(): ?float {
return $this->priceFactorDevDTwo;
}

public function getPriceFactorDevSpec(): ?float {
return $this->priceFactorDevSpec;
}

public function getPriceFactorDevVSpec(): ?float {
return $this->priceFactorDevVSpec;
}

public function getDefaultCalculation(): ?int {
return $this->defaultCalculation;
}

public function getExchangeRate(): ?float {
return $this->exchangeRate;
}

public function getTransportExpense(): ?float {
return $this->transportExpense;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}

public function setParentComponentId(?int $parentComponentId): void {
$this->parentComponentId = $parentComponentId;
}

public function setParentCategoryId(?int $parentCategoryId): void {
$this->parentCategoryId = $parentCategoryId;
}

public function setListPriceFactor(?float $listPriceFactor): void {
$this->listPriceFactor = $listPriceFactor;
}

public function setPriceFactorDOne(?float $priceFactorDOne): void {
$this->priceFactorDOne = $priceFactorDOne;
}

public function setPriceFactorDTwo(?float $priceFactorDTwo): void {
$this->priceFactorDTwo = $priceFactorDTwo;
}

public function setPriceFactorSpec(?float $priceFactorSpec): void {
$this->priceFactorSpec = $priceFactorSpec;
}

public function setPriceFactorVSpec(?float $priceFactorVSpec): void {
$this->priceFactorVSpec = $priceFactorVSpec;
}

public function setPriceFactorDevDOne(?float $priceFactorDevDOne): void {
$this->priceFactorDevDOne = $priceFactorDevDOne;
}

public function setPriceFactorDevDTwo(?float $priceFactorDevDTwo): void {
$this->priceFactorDevDTwo = $priceFactorDevDTwo;
}

public function setPriceFactorDevSpec(?float $priceFactorDevSpec): void {
$this->priceFactorDevSpec = $priceFactorDevSpec;
}

public function setPriceFactorDevVSpec(?float $priceFactorDevVSpec): void {
$this->priceFactorDevVSpec = $priceFactorDevVSpec;
}

public function setDefaultCalculation(?int $defaultCalculation): void {
$this->defaultCalculation = $defaultCalculation;
}

public function setExchangeRate(?float $exchangeRate): void {
$this->exchangeRate = $exchangeRate;
}

public function setTransportExpense(?float $transportExpense): void {
$this->transportExpense = $transportExpense;
}

public function copyProperties(Calculation $calculation): void {
$this->setListPriceFactor(floatval($calculation->getListPriceFactor()));
$this->setPriceFactorDOne(floatval($calculation->getPriceFactorDOne()));
$this->setPriceFactorDTwo(floatval($calculation->getPriceFactorDTwo()));
$this->setPriceFactorSpec(floatval($calculation->getPriceFactorSpec()));
$this->setPriceFactorVSpec(floatval($calculation->getPriceFactorVSpec()));
$this->setPriceFactorDevDOne($calculation->getPriceFactorDevDOne() ? $calculation->getPriceFactorDevDOne() : 0.000);
$this->setPriceFactorDevDTwo($calculation->getPriceFactorDevDTwo() ? $calculation->getPriceFactorDevDTwo() : 0.000);
$this->setPriceFactorDevSpec($calculation->getPriceFactorDevSpec() ? $calculation->getPriceFactorDevSpec() : 0.000);
$this->setPriceFactorDevVSpec($calculation->getPriceFactorDevVSpec() ? $calculation->getPriceFactorDevVSpec() : 0.000);
$this->setTransportExpense(floatval($calculation->getTransportExpense()));
}

}

+ 41
- 0
modules/custom/arlista/src/Entity/Category.php Dosyayı Görüntüle

@@ -0,0 +1,41 @@
<?php

namespace Drupal\arlista\Entity;

class Category extends AbstractEntity {

private ?string $axicoIdName = null;
private ?int $parentId = null;
private ?int $parentManufacturerId = null;

public function __construct() {
parent::__construct();
}
public function getAxicoIdName(): ?string {
return $this->axicoIdName;
}

public function getParentId(): ?int {
return $this->parentId;
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function setAxicoIdName(?string $axicoIdName): void {
$this->axicoIdName = $axicoIdName;
}

public function setParentId(?int $parentId): void {
$this->parentId = $parentId;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}



}

+ 39
- 0
modules/custom/arlista/src/Entity/Component.php Dosyayı Görüntüle

@@ -0,0 +1,39 @@
<?php

namespace Drupal\arlista\Entity;

class Component extends AbstractEntity {

private ?string $axicoIdName = null;
private ?int $parentManufacturerId = null;
private ?AxicoId $axicoId = null;

public function __construct() {
parent::__construct();
}
public function getAxicoIdName(): ?string {
return $this->axicoIdName;
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function setAxicoIdName(?string $axicoIdName): void {
$this->axicoIdName = $axicoIdName;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}
public function getAxicoId(): ?AxicoId {
return $this->axicoId;
}

public function setAxicoId(?AxicoId $axicoId): void {
$this->axicoId = $axicoId;
}
}

+ 23
- 0
modules/custom/arlista/src/Entity/Currency.php Dosyayı Görüntüle

@@ -0,0 +1,23 @@
<?php

namespace Drupal\arlista\Entity;

class Currency {

const HUF = 'HUF';
const EUR = 'EUR';
const USD = 'USD';

public static function findAll(): array {
return [
'HUF' => 'HUF',
'EUR' => 'EUR',
'USD' => 'USD'
];
}

public static function isSameCurrency(string $param0, string $param1) {
return strpos(strtolower($param0), strtolower($param1)) !== false;
}

}

+ 43
- 0
modules/custom/arlista/src/Entity/EnabledGroup.php Dosyayı Görüntüle

@@ -0,0 +1,43 @@
<?php

namespace Drupal\arlista\Entity;

class EnabledGroup extends AbstractEntity {

private ?int $sheetSettingId = null;
private ?int $componentId = null;
private ?int $categoryId = null;

public function __construct() {
parent::__construct();
}

public function getSheetSettingId(): ?int {
return $this->sheetSettingId;
}

public function getComponentId(): ?int {
return $this->componentId;
}

public function getCategoryId(): ?int {
return $this->categoryId;
}

public function setSheetSettingId(?int $sheetSettingId): void {
$this->sheetSettingId = $sheetSettingId;
}

public function setComponentId(?int $componentId): void {
$this->componentId = $componentId;
}

public function setCategoryId(?int $categoryId): void {
$this->categoryId = $categoryId;
}

public function isComponentBased(): bool {
return $this->componentId != null;
}

}

+ 196
- 0
modules/custom/arlista/src/Entity/Install.php Dosyayı Görüntüle

@@ -0,0 +1,196 @@
<?php

namespace Drupal\arlista\Entity;

class Install {

public static function getStaticComponentData() {
return [
'VIX' => 'Videokártyák',
'MEX' => 'RAM memóriák szerverhez, PC-hez',
'HAX' => 'Hálózati kártyák',
'HSW' => 'Switch-ek',
'MED' => 'SSD memóriák',
'MEF' => 'SATADOM (Flash Module)',
'SSG' => 'Szerver kiegészítők',
'HAB' => 'Hálózati berendezések',
'MEM' => 'SSD M.2',
'HDD' => '2,5" SATA HDD-k',
'HDF' => '2,5" SAS HDD-k',
'HDK' => '3,5" SATA HDD-k',
'HDM' => '3,5" SAS HDD-k',
];
}

public static function getComponentManufacturers() {
return [
'OCZ' => 'OCZ',
'SUP' => 'Supermicro',
'AMD' => 'AMD',
'INT' => 'Intel',
'HIT' => 'Hittachi',
'SAM' => 'Samsung',
'SAN' => 'Sandisk',
'SEA' => 'Seagate',
'HNX' => 'Hynix',
'KIN' => 'Kingston',
'MES' => 'MES',
'MIC' => 'Micron',
'WED' => 'WesternDigital',
'TOS' => 'Toshiba',
'CRS' => 'Corsair',
];
}

public static function getBaseCategories(): array {
return [
'ALA' => 'Több pr. szerver alaplapok Intel pr.',
'ALD' => 'Egy pr. szerver alaplapok Intel pr.',
'ALG' => 'Több pr. szerver alaplapok AMD pr.',
'ALH' => 'Egy pr. szerver alaplapok AMD pr.',
'ALP' => 'PC alaplapok',
'FWS' => 'SATA csatolókártyák',
'HAB' => 'Hálózati berendezések',
'HAX' => 'Hálózati kártyák',
'HSW' => 'Switch-ek',
'KAS' => 'SAS és SCSI kábelek',
'KSA' => 'RAID,SAN,NAS berendezések',
'RHX' => '19" és külső doboz tartalék alkatrészek',
'RSA' => '19" 1U szerver házak',
'RSB' => '19" 2U szerver házak',
'RSC' => '19" 3U szerver házak',
'RSD' => '19" 4U szerver házak',
'RSG' => '19" 7U szerver házak',
'SSA' => '19" 1U szerverek',
'SSB' => '19" 2U szerverek',
'SSC' => '19" 3U szerverek',
'SSD' => '19" 4U szerverek',
'SSE' => 'Álló szerverek',
'SSG' => 'Szerver kiegészítők',
'SSH' => '19" 5U szerverek',
'SSS' => 'SuperBlade szerverek',
'TAX' => 'PC-szerver tápegység',
'SBE' => 'SuperBlade Enclosure',
'SSI' => '19" 7U szerverek',
'SSF' => 'mini ITX Box PC/ioT'
];
}

public static function getTermekekFileColumnConfig(): array {
return [
'axicoId' => 'A',
'productName' => 'B',
'description' => 'C',
'fabricId' => 'D',
'price' => 'G',
'currency' => 'H',
'productGroupName' => 'F',
'manufacturerName' => 'J',
'status' => 'K'
];
}

public static function getIgnorableManufacturers(): array {
return [
'3CO',
'ATL',
'AXI',
'AVI',
'BLA',
'BTC',
'CAS',
'CID',
'COA',
'CRE',
'DAF',
'DEL',
'DRK',
'DRR',
'EXC',
'FJI',
'FUJ',
'GAL',
'GOR',
'GRE',
'HAM',
'HML',
'HIR',
'IMA',
'IOM',
'JOB',
'JVC',
'KOD',
'LOW',
'MAM',
'MAN',
'MAX',
'MCT',
'MIM',
'MIN',
'MIR',
'MIS',
'MXT',
'NAK',
'NEC',
'NER',
'NEW',
'NIG',
'NIK',
'NIX',
'NOM',
'NOV',
'OLI',
'OLY',
'OPT',
'ORT',
'PAN',
'PHI',
'PIN',
'PIO',
'PLE',
'PND',
'PNY',
'POC',
'PRI',
'QLO',
'QUA',
'RAP',
'RAR',
'RIC',
'ROD',
'ROL',
'ROX',
'SCM',
'SIG',
'SIL',
'SNY',
'SOC',
'SOG',
'SON',
'SUR',
'TDK',
'TEA',
'TRA',
'TTL',
'TYA',
'TWI',
'USR',
'VER',
'VRT',
'WAT',
'WBR',
'WRT',
'YAM'
];
}

public static function getSpecificGroupNames(): array {
return [
'VIX',
'HAX',
'SSG',
'HSW'
];
}

}

+ 60
- 0
modules/custom/arlista/src/Entity/Manufacturer.php Dosyayı Görüntüle

@@ -0,0 +1,60 @@
<?php

namespace Drupal\arlista\Entity;

class Manufacturer extends AbstractEntity {

private ?string $axicoIdName = null;
private ?Calculation $calculation = null;
private ?array $sheetSettings = null;
private ?int $componentBased = null;

public function __construct() {
parent::__construct();
}

public function isEnabled(): bool {
return $this->getStatus() === 1;
}

public function getAxicoIdName(): ?string {
return $this->axicoIdName;
}

public function getCalculation(): ?Calculation {
return $this->calculation;
}

public function getSheetSettings(): ?array {
return $this->sheetSettings;
}

public function getComponentBased(): ?int {
return $this->componentBased;
}

public function setAxicoIdName(?string $axicoIdName): void {
$this->axicoIdName = $axicoIdName;
}

public function setCalculation(?Calculation $calculation): void {
$this->calculation = $calculation;
}

public function setSheetSettings(?array $sheetSettings): void {
$this->sheetSettings = $sheetSettings;
}

public function setComponentBased(?int $componentBased): void {
$this->componentBased = $componentBased;
}

public function isComponentBased(): bool {
return $this->componentBased === 1;
}

public function isAxicoIdNameSameAs(string $axicoIdName) {
return strpos(strtolower($this->getAxicoIdName()), strtolower($axicoIdName)) !== false;
}

}

+ 21
- 0
modules/custom/arlista/src/Entity/MeasureUnit.php Dosyayı Görüntüle

@@ -0,0 +1,21 @@
<?php

namespace Drupal\arlista\Entity;

class MeasureUnit {

const UNDEFINED = 'Kérem válasszon';
const KILO = 'kg';
const PIECE = 'db';
const METER = 'm';

public static function findAll() {
return [
'UNDEFINED' => 'Kérem válasszon',
'KILO' => 'kg',
'PIECE' => 'db',
'METER' => 'm',
];
}

}

+ 21
- 0
modules/custom/arlista/src/Entity/PackingMaterial.php Dosyayı Görüntüle

@@ -0,0 +1,21 @@
<?php

namespace Drupal\arlista\Entity;

class PackingMaterial {

const UNKNOWN = 'Ismeretlen';
const PLASTIC = 'Műanyag';
const PAPER = 'Papir';
const WOOD = 'Fa';

public static function findAll() {
return [
'UNKNOWN' => 'Ismeretlen',
'PLASTIC' => 'Műanyag',
'PAPER' => 'Papir',
'WOOD' => 'Fa',
];
}

}

+ 668
- 0
modules/custom/arlista/src/Entity/Product.php Dosyayı Görüntüle

@@ -0,0 +1,668 @@
<?php

namespace Drupal\arlista\Entity;

use Drupal\arlista\Entity\AbstractEntity;

class Product extends AbstractEntity {

private ?string $axicoId = null;
private ?string $axicoName = null;
private ?string $prevAxicoName = null;
private ?string $currency = null;
private ?Calculation $calculation = null;
private ?string $description = null;
private ?string $prevDescription = null;
private ?string $fabricId = null;
private ?string $fabricName = null;
private ?string $prevFabricName = null;
private ?string $ean = null;
private ?string $eol = null;
private ?string $prevEol = null;
private ?float $listPrice = null;
private ?float $length = null;
private ?float $height = null;
private ?string $notes = null;
private ?string $prevNotes = null;
private ?int $parentManufacturerId = null;
private ?int $parentCategoryId = null;
private ?int $parentComponentId = null;
private ?float $price = null;
private ?float $prevPrice = null;
/*
* Price with transport costs
*/
private ?float $purchasePrice = null;
private ?float $priceChanged = null;
private ?float $priceDOne = null;
private ?float $priceDTwo = null;
private ?float $priceSpec = null;
private ?float $priceVSpec = null;
private ?float $priceDevDOne = null;
private ?float $priceDevDTwo = null;
private ?float $priceDevSpec = null;
private ?float $priceDevVSpec = null;
private ?int $sheetIndex = null;
private ?string $correctStatus = null;
private ?int $uploadedFileId = null;
private ?string $vtsz = null;
private ?string $measureUnit = null;
private ?string $packingMaterial = null;
private ?int $warranty = null;
private ?int $prevWarranty = null;
private ?float $weight = null;
private ?float $width = null;
private ?string $workFlow = null;
/*
* Transitional
*/
private ?string $source = null;
/*
* Listed in other pricelists, generated with different software
*/
private ?int $listed = null;
/*
* Transients
*/
private ?string $manufacturerName = null;
private ?string $productGroupName = null;
private bool $different = false;

public function __construct() {
parent::__construct();
$this->listed = Status::ACTIVE;
$this->warranty = 60;
$this->source = 'uploaded';
}

public function isProduct(): bool {
if ($this->getPrice() > 0 && !empty($this->getName()) && !empty($this->getFabricId())) {
return true;
}
return false;
}

public function calculatePrices(): void {
$price = $this->getPrice() * $this->getCalculation()->getTransportExpense();
if (Currency::isSameCurrency(Currency::HUF, $this->getCurrency())) {
/*
* It has no foreign prices
*/
$this->setPriceDevDOne(0);
$this->setPriceDevDTwo(0);
$this->setPriceDevSpec(0);
$this->setPriceDevVSpec(0);
$priceHuf = $price;
} else {
/*
* Foreign prices are set with transport expenses
*/
$this->setPriceDevDOne(round($this->getCalculation()->getPriceFactorDevDOne() * $price, 2));
$this->setPriceDevDTwo(round($this->getCalculation()->getPriceFactorDevDTwo() * $price, 2));
$this->setPriceDevSpec(round($this->getCalculation()->getPriceFactorDevSpec() * $price, 2));
$this->setPriceDevVSpec(round($this->getCalculation()->getPriceFactorDevVSpec() * $price, 2));
/*
* Forint price based on exchange rate
*/
$priceHuf = $price * $this->getCalculation()->getExchangeRate();
}
/*
* Forint prices are set
* - transport expenses added
* - conditionally multiplied with exchange rate
*
*/
$this->setPriceDOne(ceil($this->getCalculation()->getPriceFactorDOne() * $priceHuf / 10) * 10);
$this->setPriceDTwo(ceil($this->getCalculation()->getPriceFactorDTwo() * $priceHuf / 10) * 10);
$this->setPriceSpec(ceil($this->getCalculation()->getPriceFactorSpec() * $priceHuf / 10) * 10);
$this->setPriceVSpec(ceil($this->getCalculation()->getPriceFactorVSpec() * $priceHuf / 10) * 10);
/*
* List price is for non-categorised buyers/re-sellers
*/
$this->setListPrice(ceil($this->getCalculation()->getListPriceFactor() * $priceHuf / 10) * 10);
/*
* Purchase price rounding
* - conditionally if HUF or foreign currency
*/
if (Currency::isSameCurrency(Currency::HUF, $this->getCurrency())) {
$this->setPurchasePrice(ceil($priceHuf / 10) * 10);
} else {
$this->setPurchasePrice(round($priceHuf, 2));
}
}

public function isComponentBased(): bool {
return $this->getParentComponentId() > 0;
}

public function isPriceFieldRequired($fieldName): bool {
if (strpos($fieldName, 'dev') !== false) {
return $this->currency !== Currency::HUF;
}

return $this->currency === Currency::HUF;
}

public function isForCorrect(): bool {
return $this->correctStatus !== Status::PASSIVE;
}

public function getAxicoId(): ?string {
return $this->axicoId;
}

public function getAxicoName(): ?string {
return $this->axicoName;
}

public function getPrevAxicoName(): ?string {
return $this->prevAxicoName;
}

public function getCurrency(): ?string {
return $this->currency;
}

public function getDescription(): ?string {
return $this->description;
}

public function getPrevDescription(): ?string {
return $this->prevDescription;
}

public function getFabricId(): ?string {
return $this->fabricId;
}

public function getFabricName(): ?string {
return $this->fabricName;
}

public function getPrevFabricName(): ?string {
return $this->prevFabricName;
}

public function getEan(): ?string {
return $this->ean;
}

public function getEol(): ?string {
return $this->eol;
}

public function getPrevEol(): ?string {
return $this->prevEol;
}

public function getListPrice(): ?float {
return $this->listPrice;
}

public function getLength(): ?float {
return $this->length;
}

public function getHeight(): ?float {
return $this->height;
}

public function getNotes(): ?string {
return $this->notes;
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function getParentCategoryId(): ?int {
return $this->parentCategoryId;
}

public function getParentComponentId(): ?int {
return $this->parentComponentId;
}

public function getPrice(): ?float {
return $this->price;
}

public function getPrevPrice(): ?float {
return $this->prevPrice;
}

public function getPurchasePrice(): ?float {
return $this->purchasePrice;
}

public function getPriceChanged(): ?float {
return $this->priceChanged;
}

public function isPriceChanged(): bool {
return $this->priceChanged > 0;
}

public function getPriceDOne(): ?float {
return $this->priceDOne;
}

public function getPriceDTwo(): ?float {
return $this->priceDTwo;
}

public function getPriceSpec(): ?float {
return $this->priceSpec;
}

public function getPriceVSpec(): ?float {
return $this->priceVSpec;
}

public function getPriceDevDOne(): ?float {
return $this->priceDevDOne;
}

public function getPriceDevDTwo(): ?float {
return $this->priceDevDTwo;
}

public function getPriceDevSpec(): ?float {
return $this->priceDevSpec;
}

public function getPriceDevVSpec(): ?float {
return $this->priceDevVSpec;
}

public function getSheetIndex(): ?int {
return $this->sheetIndex;
}

public function getCorrectStatus(): ?string {
return $this->correctStatus;
}

public function getUploadedFileId(): ?int {
return $this->uploadedFileId;
}

public function getVtsz(): ?string {
return $this->vtsz;
}

public function getMeasureUnit(): ?string {
return $this->measureUnit;
}

public function getPackingMaterial(): ?string {
return $this->packingMaterial;
}

public function getWarranty(): ?int {
return $this->warranty;
}

public function getPrevWarranty(): ?int {
return $this->prevWarranty;
}

public function getWeight(): ?float {
return $this->weight;
}

public function getWidth(): ?float {
return $this->width;
}

public function getWorkFlow(): ?string {
return $this->workFlow;
}

public function getManufacturerName(): ?string {
return $this->manufacturerName;
}

public function getProductGroupName(): ?string {
return $this->productGroupName;
}

public function getListed(): ?int {
return $this->listed;
}

public function setAxicoId(?string $axicoId): void {
$this->axicoId = $axicoId;
}

public function setAxicoName(?string $axicoName): void {
$this->axicoName = $axicoName;
}

public function setPrevAxicoName(?string $prevAxicoName): void {
$this->prevAxicoName = $prevAxicoName;
}

public function setCurrency(?string $currency): void {
$this->currency = $currency;
}

public function setDescription(?string $description): void {
$this->description = $description;
}

public function setPrevDescription(?string $prevDescription): void {
$this->prevDescription = $prevDescription;
}

public function setFabricId(?string $fabricId): void {
$this->fabricId = $fabricId;
}

public function setFabricName(?string $fabricName): void {
$this->fabricName = $fabricName;
}

public function setPrevFabricName(?string $prevFabricName): void {
$this->prevFabricName = $prevFabricName;
}

public function setEan(?string $ean): void {
$this->ean = $ean;
}

public function setEol(?string $eol): void {
$this->eol = $eol;
}

public function setPrevEol(?string $prevEol): void {
$this->prevEol = $prevEol;
}

public function setListPrice(?float $listPrice): void {
$this->listPrice = $listPrice;
}

public function setLength(?float $length): void {
$this->length = $length;
}

public function setHeight(?float $height): void {
$this->height = $height;
}

public function setNotes(?string $notes): void {
$this->notes = $notes;
}

public function setPrevNotes(?string $prevNotes): void {
$this->prevNotes = $prevNotes;
}

public function getPrevNotes(): ?string {
return $this->prevNotes;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}

public function setParentCategoryId(?int $parentCategoryId): void {
$this->parentCategoryId = $parentCategoryId;
}

public function setParentComponentId(?int $parentComponentId): void {
$this->parentComponentId = $parentComponentId;
}

public function setPrice(?float $price): void {
$this->price = $price;
}

public function setPrevPrice(?float $prevPrice): void {
$this->prevPrice = $prevPrice;
}

public function setPurchasePrice(?float $purchasePrice): void {
$this->purchasePrice = $purchasePrice;
}

public function setPriceChanged(?float $priceChanged): void {
$this->priceChanged = $priceChanged;
}

public function setPriceDOne(?float $priceDOne): void {
$this->priceDOne = $priceDOne;
}

public function setPriceDTwo(?float $priceDTwo): void {
$this->priceDTwo = $priceDTwo;
}

public function setPriceSpec(?float $priceSpec): void {
$this->priceSpec = $priceSpec;
}

public function setPriceVSpec(?float $priceVSpec): void {
$this->priceVSpec = $priceVSpec;
}

public function setPriceDevDOne(?float $priceDevDOne): void {
$this->priceDevDOne = $priceDevDOne;
}

public function setPriceDevDTwo(?float $priceDevDTwo): void {
$this->priceDevDTwo = $priceDevDTwo;
}

public function setPriceDevSpec(?float $priceDevSpec): void {
$this->priceDevSpec = $priceDevSpec;
}

public function setPriceDevVSpec(?float $priceDevVSpec): void {
$this->priceDevVSpec = $priceDevVSpec;
}

public function setSheetIndex(?int $sheetIndex): void {
$this->sheetIndex = $sheetIndex;
}

public function setCorrectStatus(?string $correctStatus): void {
$this->correctStatus = $correctStatus;
}

public function setUploadedFileId(?int $uploadedFileId): void {
$this->uploadedFileId = $uploadedFileId;
}

public function setVtsz(?string $vtsz): void {
$this->vtsz = $vtsz;
}

public function setMeasureUnit(?string $measureUnit): void {
$this->measureUnit = $measureUnit;
}

public function setPackingMaterial(?string $packingMaterial): void {
$this->packingMaterial = $packingMaterial;
}

public function setWarranty(?int $warranty): void {
$this->warranty = $warranty;
}

public function setPrevWarranty(?int $prevWarranty): void {
$this->prevWarranty = $prevWarranty;
}

public function setWeight(?float $weight): void {
$this->weight = $weight;
}

public function setWidth(?float $width): void {
$this->width = $width;
}

public function setWorkFlow(?string $workFlow): void {
$this->workFlow = $workFlow;
}

public function setManufacturerName(?string $manufacturerName): void {
$this->manufacturerName = $manufacturerName;
}

public function setProductGroupName(?string $productGroupName): void {
$this->productGroupName = $productGroupName;
}

public function setListed(?int $listed): void {
$this->listed = $listed;
}

public function setDifferent(bool $different): void {
$this->different = $different;
}

public function getCalculation(): ?Calculation {
return $this->calculation;
}

public function getCalculationId(): ?int {
return $this->calculationId;
}

public function setCalculationId(?int $calculationId): void {
$this->calculationId = $calculationId;
}

public function setCalculation(?Calculation $calculation): void {
$this->calculation = $calculation;
}

public function setSource(?string $source): void {
$this->source = $source;
}

public function getSource(): ?string {
return $this->source;
}

public function isDifferent(): bool {
return $this->getPriceChanged() || $this->isOtherProductDataChanged($this);
}

public function copyBaseProperties(Product $product): void {
$this->setSif($product->getSif());
$this->setAxicoId($product->getAxicoId());
$this->setParentCategoryId($product->getParentCategoryId());
$this->setParentComponentId($product->getParentComponentId());
$this->setParentManufacturerId($product->getParentManufacturerId());
}

public function copySpecialProperties(Product $product): void {
$this->setUploadedFileId($product->getUploadedFileId());
$this->setPrice($product->getPrice());
$this->setCurrency($product->getCurrency());
$this->setNotes($product->getNotes());
$this->setDescription($product->getDescription());
$this->setCorrectStatus(Status::CORRECT_IMPORTED);
$this->setSheetIndex($product->getSheetIndex());
}

public function isSorted(): bool {
return !empty($this->getParentCategoryId()) || !empty($this->getParentComponentId());
}

public function copyPrices(Product $product): void {
$this->setCurrency($product->getCurrency());
$this->setPriceDOne($product->getPriceDOne());
$this->setPriceDTwo($product->getPriceDTwo());
$this->setPriceSpec($product->getPriceSpec());
$this->setPriceVSpec($product->getPriceVSpec());
$this->setPriceDevDOne($product->getPriceDevDOne());
$this->setPriceDevDTwo($product->getPriceDevDTwo());
$this->setPriceDevSpec($product->getPriceDevSpec());
$this->setPriceDevVSpec($product->getPriceDevVSpec());
$this->setListPrice($product->getListPrice());
$this->setPurchasePrice($product->getPurchasePrice());
}

public function isProductPriceChanged(Product $product): bool {
return $this->getPrice() !== $product->getPrice() &&
Currency::isSameCurrency($this->getCurrency(), $product->getCurrency());
}

public function isOtherProductDataChanged(Product $product): bool {

$fabricNameChange = $this->isProductFabricNameChanged($product);
$eolChange = $this->isProductEolChanged($product);
$descriptionChange = $this->isProductDescriptionChanged($product);
$notesChangeChange = $this->isProductNotesChanged($product);
$warrantyChange = $this->isProductWarrantyChanged($product);
$axicoNameChange = $this->isProductAxicoNameChanged($product);

return $fabricNameChange || $eolChange || $descriptionChange || $notesChangeChange || $warrantyChange || $axicoNameChange;
}

public function isProductFabricNameChanged(Product $product): bool {
if ($product->getPrevFabricName()) {
return strpos(
strtolower($this->fabricName),
strtolower($product->getPrevFabricName())
) !== false;
}
return false;
}

public function isProductEolChanged(Product $product): bool {
if ($product->getPrevEol()) {
return strpos(
strtolower($this->eol),
strtolower($product->getPrevEol())
) !== false;
}
return false;
}

public function isProductDescriptionChanged(Product $product): bool {
if ($product->getPrevDescription()) {
return strpos(
strtolower($this->description),
strtolower($product->getPrevDescription())
) !== false;
}return false;
}

public function isProductNotesChanged(Product $product): bool {
if ($product->getPrevNotes()) {
return strpos(
strtolower($this->notes),
strtolower($product->getPrevNotes())
) !== false;
}
return false;
}

public function isProductAxicoNameChanged(Product $product): bool {
if ($product->getPrevAxicoName()) {
return strpos(
strtolower($this->axicoName),
strtolower($product->getPrevAxicoName())
) !== false;
}
return false;
}

public function isProductWarrantyChanged(Product $product): bool {
return false;
/**
* TODO delete or change this
*/
/* if ($product->getPrevWarranty()) {
return $this->warranty != $product->getPrevWarranty();
}

return false; */
}

}

+ 73
- 0
modules/custom/arlista/src/Entity/ResponseBody.php Dosyayı Görüntüle

@@ -0,0 +1,73 @@
<?php

namespace Drupal\arlista\Entity;

class ResponseBody {

private $success;
private $message;
private $fid;
private $time;
private $data;

public function __construct() {
$this->success = 0;
$this->message = 'n/a';
$this->time = date("Y-m-d H:i:s");
$this->fid = -1;
$this->data = -1;
}

public function getSuccess() {
return $this->success;
}

public function getMessage() {
return $this->message;
}

public function getFid() {
return $this->fid;
}

public function getTime() {
return $this->time;
}

public function setSuccess($success): void {
$this->success = $success;
}

public function setMessage($message): void {
$this->message = $message;
}

public function setFid($fid): void {
$this->fid = $fid;
}

public function setTime($time): void {
$this->time = $time;
}

public function toArray(): array {
return [
'success' => $this->success,
'message' => $this->message,
'fid' => $this->fid,
'time' => $this->time,
'data' => $this->data
];
}
public function getData() {
return $this->data;
}

public function setData($data): void {
$this->data = $data;
}



}

+ 280
- 0
modules/custom/arlista/src/Entity/SheetSetting.php Dosyayı Görüntüle

@@ -0,0 +1,280 @@
<?php

namespace Drupal\arlista\Entity;

use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SheetSetting extends AbstractEntity {

private ?int $manufacturerId = null;
private ?int $index = null;
private ?string $productName = null;
private ?string $productAxicoName = null;
private ?string $productFabricName = null;
private ?string $productFabricId = null;
private ?string $productEan = null;
private ?string $productWarranty = null;
private ?string $productEol = null;
private ?string $productNotes = null;
private ?string $productDescription = null;
private ?string $productCategory = null;
private ?string $productPrice = null;
private ?string $currency = null;
private ?string $productVtsz = null;
private int $filterable = 0;
private ?string $filterableRemarks = 'bulk,oem,MB Only,RMA Only,MOQ,for spare part & rma only';
private ?int $defaultSetting = 0;

public function __construct() {
parent::__construct();
$this->defaultSetting = false;
$this->currency = Currency::HUF;
}

public function isDefaultSetting(): bool {
return !empty($this->defaultSetting);
}

public function getManufacturerId(): ?int {
return $this->manufacturerId;
}

public function getIndex(): ?int {
return $this->index;
}

public function getProductName(): ?string {
return $this->productName;
}

public function getProductFabricId(): ?string {
return $this->productFabricId;
}

public function getProductEan(): ?string {
return $this->productEan;
}

public function getProductWarranty(): ?string {
return $this->productWarranty;
}

public function getProductEol(): ?string {
return $this->productEol;
}

public function getProductNotes(): ?string {
return $this->productNotes;
}

public function getProductDescription(): ?string {
return $this->productDescription;
}

public function getProductCategory(): ?string {
return $this->productCategory;
}

public function getProductPrice(): ?string {
return $this->productPrice;
}

public function getCurrency(): ?string {
return $this->currency;
}

public function getProductVtsz(): ?string {
return $this->productVtsz;
}

public function getFilterable(): int {
return $this->filterable;
}

public function getFilterableRemarks(): ?string {
return $this->filterableRemarks;
}

public function getDefaultSetting(): ?int {
return $this->defaultSetting;
}

public function setManufacturerId(?int $manufacturerId): void {
$this->manufacturerId = $manufacturerId;
}

public function setIndex(?int $index): void {
$this->index = $index;
}

public function setProductName(?string $productName): void {
$this->productName = $productName;
}

public function setProductFabricId(?string $productFabricId): void {
$this->productFabricId = $productFabricId;
}

public function setProductEan(?string $productEan): void {
$this->productEan = $productEan;
}

public function setProductWarranty(?string $productWarranty): void {
$this->productWarranty = $productWarranty;
}

public function setProductEol(?string $productEol): void {
$this->productEol = $productEol;
}

public function setProductNotes(?string $productNotes): void {
$this->productNotes = $productNotes;
}

public function setProductDescription(?string $productDescription): void {
$this->productDescription = $productDescription;
}

public function setProductCategory(?string $productCategory): void {
$this->productCategory = $productCategory;
}

public function setProductPrice(?string $productPrice): void {
$this->productPrice = $productPrice;
}

public function setCurrency(?string $currency): void {
$this->currency = $currency;
}

public function setProductVtsz(?string $productVtsz): void {
$this->productVtsz = $productVtsz;
}

public function setFilterable(int $filterable): void {
$this->filterable = $filterable;
}

public function setFilterableRemarks(?string $filterableRemarks): void {
$this->filterableRemarks = $filterableRemarks;
}

public function setDefaultSetting(?int $defaultSetting): void {
$this->defaultSetting = $defaultSetting;
}

public function getProductAxicoName(): ?string {
return $this->productAxicoName;
}

public function getProductFabricName(): ?string {
return $this->productFabricName;
}

public function setProductAxicoName(?string $productAxicoName): void {
$this->productAxicoName = $productAxicoName;
}

public function setProductFabricName(?string $productFabricName): void {
$this->productFabricName = $productFabricName;
}

public function findProductAxicoName(Worksheet $workSheet, int $i): ?string {
if (strlen($this->getProductAxicoName()) < 2) {
return $workSheet->getCell($this->getProductAxicoName() . $i)->getValue();
}

$columns = explode("+", $this->getProductAxicoName());
$productAxicoName = '';
foreach ($columns as $column) {
$productAxicoName = $productAxicoName . ' ' . $workSheet->getCell($column . $i)->getValue();
}

return $productAxicoName;
}

public function isFilteringOn(): bool {
return $this->getFilterable() === 1;
}

public function filterByKeyWords(array $products): array {
if (empty($products) || $this->getFilterable() === -1) {
return $products;
}
$list = [];
$keyWords = $this->getKeyWordsAsArray();
if ($this->getFilterable() === 1) {
/* @var $product Product */
foreach ($products as $product) {
if (isset($list[$product->getId()])) {
continue;
}
$list = $this->addProductIfProductsRemarkIsInKeyWords($list, $product, $keyWords);
}
}
if ($this->getFilterable() === 0) {
foreach ($products as $product) {
if (isset($list[$product->getId()])) {
continue;
}
$list = $this->addProductIfProductsRemarkIsNotInKeyWords($list, $product, $keyWords);
}
}

return $list;
}

private function getKeyWordsAsArray(): array {
$keyWords = explode(",", $this->getFilterableRemarks());
foreach ($keyWords as $key => $value) {
$keyWords[$key] = strtolower($value);
}

return $keyWords;
}

private function addProductIfProductsRemarkIsInKeyWords(array $list, Product $product, array $keyWords): array {
foreach ($keyWords as $keyWord) {
if ($this->isProductsRemarkCointainsKeyWord($product->getNotes(), $keyWord)) {
$list[$product->getId()] = $product;
}
}
return $list;
}

private function addProductIfProductsRemarkIsNotInKeyWords(array $list, Product $product, array $keyWords): array {
$remarkIsNotInKeyWords = true;
foreach ($keyWords as $keyWord) {
if ($this->isProductsRemarkCointainsKeyWord($product->getNotes(), $keyWord)) {
$remarkIsNotInKeyWords = false;
}
}
if ($remarkIsNotInKeyWords) {
$list[$product->getId()] = $product;
}
return $list;
}

private function isProductsRemarkCointainsKeyWord(?string $hayStack, string $keyWord): bool {
if (!$hayStack) {
return false;
}
return strpos(strtolower($hayStack), $keyWord) !== false;
}

public function filterBySheetIndex(array $products): array {
if (empty($products)) {
return $products;
}
$list = [];

/* @var $product Product */
foreach ($products as $product) {
if ($product->getSheetIndex() === $this->getIndex()) {
$list[] = $product;
}
}
return $list;
}

}

+ 54
- 0
modules/custom/arlista/src/Entity/Status.php Dosyayı Görüntüle

@@ -0,0 +1,54 @@
<?php

namespace Drupal\arlista\Entity;

class Status {

const ACTIVE = 1;
const PASSIVE = 0;
const OK = 'OK';
const FRISSITENDO = 'FRISSITENDO';
const UJRA_AKTIVALHATO = 'UJRA_AKTIVALHATO';
const VALTOZATLAN = 'VALTOZATLAN';
const TOROLT = 'TOROLT';
const ISMERETLEN = 'ISMERETLEN';
const UJ = 'UJ';
const AKTIVALVA = 'AKTIVALVA';
const CORRECT_IMPORTED = 'CORRECT_IMPORTED';

public static function findAll() {
return [
'FRISSITENDO' => 'Frissítendő',
'VALTOZATLAN' => 'Változatlan',
'TOROLT' => 'Törölt',
'ISMERETLEN' => 'Ismeretlen',
'UJ' => 'Új',
'CORRECT_IMPORTED' => 'Aktív adatbázisban',
];
}

public static function getCorrectStatusValueOf(int $status) {
if ($status === 2) {
return Status::UJ;
}
if ($status === 1) {
return Status::FRISSITENDO;
}
if ($status === 0) {
return Status::VALTOZATLAN;
}
}

public static function isChanged(string $correctStatus): bool {
return $correctStatus !== 'VALTOZATLAN';
}

public static function isUnchanged(string $correctStatus): bool {
return $correctStatus === 'VALTOZATLAN';
}

public static function isSameStatusAs(string $param0, string $param1) {
return strcmp($param0, $param1) === 0;
}

}

+ 63
- 0
modules/custom/arlista/src/Entity/UploadedFile.php Dosyayı Görüntüle

@@ -0,0 +1,63 @@
<?php

namespace Drupal\arlista\Entity;

class UploadedFile extends AbstractEntity {

private ?int $parentManufacturerId = null;
private ?int $componentBased = null;
private ?int $fid = null;
private ?string $workFlow = null;
private int $totalProducts = 0;

public function __construct() {
parent::__construct();
$this->setWorkFlow(WorkFlow::UPLOADED);
$this->componentBased = 0;
}

public function getParentManufacturerId(): ?int {
return $this->parentManufacturerId;
}

public function getComponentBased(): ?int {
return $this->componentBased;
}

public function getFid(): ?int {
return $this->fid;
}

public function getWorkFlow(): ?string {
return $this->workFlow;
}

public function getTotalProducts(): int {
return $this->totalProducts;
}

public function setParentManufacturerId(?int $parentManufacturerId): void {
$this->parentManufacturerId = $parentManufacturerId;
}

public function setComponentBased(?int $componentBased): void {
$this->componentBased = $componentBased;
}

public function setFid(?int $fid): void {
$this->fid = $fid;
}

public function setWorkFlow(?string $workFlow): void {
$this->workFlow = $workFlow;
}

public function setTotalProducts(int $totalProducts): void {
$this->totalProducts = $totalProducts;
}

public function isComponentBased(): bool {
return $this->componentBased === 1;
}

}

+ 25
- 0
modules/custom/arlista/src/Entity/WorkFlow.php Dosyayı Görüntüle

@@ -0,0 +1,25 @@
<?php

namespace Drupal\arlista\Entity;

class WorkFlow {

const UPLOADED = 'UPLOADED';
const IMPORTED = 'IMPORTED';
const NUMBERED = 'NUMBERED';
const COMPARED = 'COMPARED';
const ACTIVATED = 'ACTIVATED';
const DELETED = 'DELETED';

public static function findAll(): array {
return [
'UPLOADED' => 'Feltöltve',
'IMPORTED' => 'Importálva',
'NUMBERED' => 'Sorszámozva',
'COMPARED' => 'Összehasonlítva',
'ACTIVATED' => 'Aktiválva',
'DELETED' => 'Törölve',
];
}

}

+ 201
- 0
modules/custom/arlista/src/Factory/AbstractFactory.php Dosyayı Görüntüle

@@ -0,0 +1,201 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\arlista\Entity\AbstractEntity;
use Drupal\arlista\Entity\Status;
use Drupal\Core\Database\Connection;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\arlista\BaseEntityNotFoundException;
use stdClass;

abstract class AbstractFactory {

const TABLE_PREFIX = 'arlista_manager_';
const SPECIFIC_GROUPS = [
'HSW' => 'HSW', 'HAX' => 'HAX', 'SSG' => 'SSG'
];

/**
* Database connection.
*
* @var $connection \Drupal\Core\Database\Connection
*/
private $connection = null;
private $currentUser;
private ?string $table = null;
private $time;

/**
* Construct.
*
* @param Connection $connection
* Database connection.
*/
public function __construct(Connection $connection, AccountInterface $currentUser, TimeInterface $time, string $class) {
$this->connection = $connection;
$this->currentUser = $currentUser;
$this->time = $time;
$this->table = $this->createTableName($this::TABLE_PREFIX . $class);
}
private function createTableName($class) {
return $class;
}

abstract public function create();

public function getCurrentUser() {
return $this->currentUser;
}

public function getTime() {
return $this->time;
}

public function setCurrentUser($currentUser): void {
$this->currentUser = $currentUser;
}

public function setTime($time): void {
$this->time = $time;
}

public function getConnection(): Connection {
return $this->connection;
}

public function getSpecificGroups(): array {
return $this::SPECIFIC_GROUPS;
}

public function find(int $id) {
$data = $this->connection
->select($this->table, 'w')
->fields('w')
->condition('w.id', $id)
->isNull('w.deleted_at')
->execute()
->fetchObject();

if (empty($data)) {
throw new BaseEntityNotFoundException("FIND - Entity with id : {$id} in table : {$this->table} table not found!");
}

return $this->load($data);
}

public function findIn(int $id, string $tableName) {
$data = $this->connection
->select($tableName, 'w')
->fields('w')
->condition('w.id', $id)
->isNull('w.deleted_at')
->execute()
->fetchObject();

if (empty($data)) {
throw new BaseEntityNotFoundException("FIND IN - Entity with id : {$id} in table {$tableName} table not found!");
}

return $this->load($data);
}

abstract protected function load(stdClass $data);

public function findAll(string $orderBy = 'id', string $orderDirection = 'ASC') {
$list = $this->connection
->select($this->table, 'w')
->fields('w')
->isNull('w.deleted_at')
->orderBy($orderBy, $orderDirection)
->execute();

$entities = [];
foreach ($list as $item) {
$entities[] = $this->load($item);
}

return $entities;
}

public function findAllActive(string $orderBy = 'id', string $orderDirection = 'ASC') {
$list = $this->connection
->select($this->table, 'w')
->fields('w')
->condition('status', Status::ACTIVE)
->isNull('w.deleted_at')
->orderBy($orderBy, $orderDirection)
->execute();

$entities = [];
foreach ($list as $item) {
$entities[] = $this->load($item);
}

return $entities;
}

public function save(AbstractEntity $entity) {
if ($entity->isNew()) {
return $this->insert($entity);
}

return $this->update($entity);
}

public function saveAll(array $entities): void {
foreach ($entities as $entity) {
/* @var $entity AbstractEntity */
$this->save($entity);
}
}

public function saveTo(AbstractEntity $entity, string $targetTable) {
$defaultTable = $this->getActiveTable();
$this->setActiveTable($targetTable);
$stored = $this->save($entity);
$this->setActiveTable($defaultTable);
return $stored;
}

abstract protected function insert(AbstractEntity $entity);

abstract protected function update(AbstractEntity $entity);

public function delete(AbstractEntity $entity) {
$this->connection
->update($this->table)
->fields([
'modified_at' => date('Y-m-d H:i:s', $this->time->getRequestTime()),
'modified_by' => $this->currentUser->id(),
'deleted_at' => date('Y-m-d H:i:s', $this->time->getRequestTime())
])
->condition('id', $entity->getId())
->execute();
}

public function remove(AbstractEntity $entity) {
$this->connection
->delete($this->table)
->condition('id', $entity->getId())
->execute();
}

public function getActiveTable(): string {
return $this->table;
}

public function setActiveTable(string $table): void {
$this->table = $table;
}

public function import(string $tableName): array {
return $this->connection->select($tableName, 'w')
->fields('w')
->execute()
->fetchAll();
}

}

+ 56
- 0
modules/custom/arlista/src/Factory/AbstractSpreadSheetFactory.php Dosyayı Görüntüle

@@ -0,0 +1,56 @@
<?php

namespace Drupal\arlista\Factory;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Drupal\arlista\Entity\UploadedFile;

abstract class AbstractSpreadSheetFactory {

private $uploadedFileid;

public function initSpreadSheet(): Spreadsheet {
return new \PhpOffice\PhpSpreadsheet\Spreadsheet();
}

public function getSpreadSheetWriter(SpreadSheet $spreadSheetData) {
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadSheetData);
$writer->setOffice2003Compatibility(true);
return $writer;
}

public function getUploadedFileid() {
return $this->uploadedFileid;
}

public function setUploadedFileid($uploadedFileid): void {
$this->uploadedFileid = $uploadedFileid;
}

public function createNewSpreadSheet(): Spreadsheet {
return new Spreadsheet();
}

public function createXlsxWriterFromSpreadSheet(Spreadsheet $spreadsheet): Xlsx {
return new Xlsx($spreadsheet);
}

public function loadUploadedFile(UploadedFile $uploadedFile): Spreadsheet {
try {
$this->setUploadedFileid($uploadedFile->getId());
$fileManaged = \Drupal::entityTypeManager()
->getStorage('file')
->load($uploadedFile->getFid());


$path = $fileManaged->get('uri')->value;
$path = str_replace("public://", "sites/default/files/", $path);
$spreadSheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
return $spreadSheet;
} catch (exception $e) {
return null;
}
}

}

+ 546
- 0
modules/custom/arlista/src/Factory/AxicoIdFactory.php Dosyayı Görüntüle

@@ -0,0 +1,546 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\AxicoId;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\arlista\Traits\AxicoIdTrait;
use stdClass;

class AxicoIdFactory extends AbstractFactory {

use AxicoIdTrait;

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'axico_id');
}

public function create(): AxicoId {
return new AxicoId();
}

public function createForCategory(int $manufacturerId, int $categoryId): AxicoId {
$axicoIdEntity = $this->create();
$axicoIdEntity->setParentManufacturerId($manufacturerId);
$axicoIdEntity->setParentCategoryId($categoryId);
$axicoIdEntity->setParentComponentId(null);
$axicoIdEntity->setNextCount(1);

return $axicoIdEntity;
}

public function createForComponent(int $manufacturerId, int $componentId): AxicoId {
$axicoIdEntity = $this->create();

$axicoIdEntity->setParentManufacturerId($manufacturerId);
$axicoIdEntity->setParentComponentId($componentId);
$axicoIdEntity->setParentCategoryId(null);
$axicoIdEntity->setNextCount(1);

return $axicoIdEntity;
}

public function resetAxicoIdEntity(AxicoId $axicoIdEntity): void {
//$this->delete($axicoIdEntity);
$this->reviveAxicoIdEntity($axicoIdEntity);
}

public function reviveAxicoIdEntity(AxicoId $axicoIdEntity): AxicoId {
$axicoIdEntity->setNextCount(1);
$axicoIdEntity->setProductId(null);
//$this->deleteNextAxicoIdEntityIfExists($axicoIdEntity);

return $this->save($axicoIdEntity);
}

public function deleteNextAxicoIdEntityIfExists($axicoIdEntity): void {
$nextComponentAxicoId = null;
if ($axicoIdEntity->isComponentBased()) {
$nextComponentAxicoId = $this->findNextAxicoIdByComponent($axicoIdEntity->getParentManufacturerId(), $axicoIdEntity->getParentComponentId());
} else {
$nextComponentAxicoId = $this->findNextAxicoIdByCategory($axicoIdEntity->getParentManufacturerId(), $axicoIdEntity->getParentCategoryId());
}
if ($nextComponentAxicoId) {
if ($nextComponentAxicoId->getId() != $axicoIdEntity->getId())
$this->delete($nextComponentAxicoId);
}
}

public function findByProductId(int $id): ?AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('product_id', $id)
->execute()
->fetchObject();

if ($data) {
return $this->load($data);
}
return null;
}

public function findNextAxicoIdByCategory(int $parentManufacturerId, int $parentCategoryId): ?AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $parentManufacturerId)
->condition('w.parent_category_id', $parentCategoryId)
->condition('w.next_count', 1)
->orderBy('w.id', 'ASC')
->range(0, 1)
->execute()
->fetchObject();

if (empty($data)) {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $parentManufacturerId)
->condition('w.parent_category_id', $parentCategoryId)
->orderBy('w.current_count', 'DESC')
->range(0, 1)
->execute()
->fetchObject();
if ($data) {
$newEntity = $this->load($data);
$newEntity->setId(null);
$newEntity->setProductId(null);
$newEntity->addToCurrentCount(1);
$newEntity->setNextCount(1);

return $this->save($newEntity);
}
return null;
} else {
return $this->load($data);
}
}

public function findNextAxicoIdByComponent(int $manufacturerId, int $componentId): ?AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_component_id', $componentId)
->condition('w.next_count', 1)
->orderBy('w.id', 'ASC')
->range(0, 1)
->execute()
->fetchObject();

if (empty($data)) {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_component_id', $componentId)
->orderBy('w.current_count', 'DESC')
->range(0, 1)
->execute()
->fetchObject();
if ($data) {
$newEntity = $this->load($data);
$newEntity->setId(null);
$newEntity->setProductId(null);
$newEntity->setNextCount(1);
$newEntity->addToCurrentCount(1);
return $this->save($newEntity);
}
return null;
} else {
return $this->load($data);
}
}

public function isAxicoIdPresentInGroup(int $manufacturerId, ?int $categoryId, ?int $componentId): bool {
if ($categoryId) {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_category_id', $categoryId)
->execute()
->fetchObject();

return !empty($data);
}

$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_component_id', $componentId)
->execute()
->fetchObject();

return !empty($data);
}

protected function insert(AbstractEntity $entity): AxicoId {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_category_id' => $entity->getParentCategoryId(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'parent_component_id' => $entity->getParentComponentId(),
'product_id' => $entity->getProductId(),
'current_count' => $entity->getCurrentCount(),
'next_count' => $entity->getNextCount(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity): AxicoId {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_category_id' => $entity->getParentCategoryId(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'parent_component_id' => $entity->getParentComponentId(),
'product_id' => $entity->getProductId(),
'current_count' => $entity->getCurrentCount(),
'next_count' => $entity->getNextCount(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();

return $entity;
}

protected function load(stdClass $data): AxicoId {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setStatus($data->status);
$entity->setParentCategoryId($data->parent_category_id);
$entity->setParentManufacturerId($data->parent_manufacturer_id);
$entity->setParentComponentId($data->parent_component_id);
$entity->setProductId($data->product_id);
$entity->setCurrentCount($data->current_count);
$entity->setNextCount($data->next_count);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);

return $entity;
}

public function importAll(array $data): array {
foreach ($data as $i => $manufacturerData) {
/* @var $manufacturerData['manufacturer'] Manufacturer */
if ($manufacturerData['manufacturer']->isComponentBased()) {
continue;
}
/* @var $value Category */
foreach ($manufacturerData['categories'] as $key => $value) {
$axicoIdEntity = $this->createForCategory($manufacturerData['manufacturer']->getId(), $key);
$axicoIdEntity->setCurrentCount(1);
$axicoIdEntity->setName($manufacturerData['manufacturer']->getAxicoIdName() . $value->getAxicoIdName());
$entity = $this->save($axicoIdEntity);
$data[$i]['axicoId'][] = $entity;
}
}

return $data;
}

public function createForEachComponent(array $data): array {
foreach ($data as $key => $componentData) {
foreach ($componentData['components'] as $manufacturerId => $componentWrapper) {
/* @var $component Component */
foreach ($componentWrapper as $componentAxicoId => $component) {
if (!$component instanceof Component) {
continue;
}
$existingAxicoId = $this->findNextAxicoIdByComponent($manufacturerId, $component->getId());
if (empty($existingAxicoId)) {
$entity = $this->createForComponent($manufacturerId, $component->getId());
$entity->setName($data[$key]['manufacturers'][$manufacturerId]->getAxicoIdName() . $component->getAxicoIdName());
$this->save($entity);
$component->setAxicoId($entity);
} else {
$component->setAxicoId($existingAxicoId);
}
$data[$key]['components'][$manufacturerId][$component->getAxicoIdName()] = $component;
}
}
}
return $data;
}

public function findHighestCurrentAxicoIdByComponentId(int $componentId): ?AxicoId {
$item = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_component_id', $componentId)
->orderBy('w.current_count', 'DESC')
->range(0, 1)
->execute()
->fetchObject();

if ($item) {
return $this->load($item);
}

return null;
}

public function findHighestCurrentAxicoIdByManufacturerIdAndCategoryIdAndComponentId(int $manufacturerId, ?int $categoryId, ?int $componentId): ?AxicoId {
$data = null;
if ($categoryId) {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_category_id', $categoryId)
->orderBy('current_count', 'DESC')
->range(0, 1)
->execute()
->fetchAll();
} else {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_component_id', $componentId)
->orderBy('current_count', 'DESC')
->range(0, 1)
->execute()
->fetchAll();
}
if (!empty($data)) {
return $this->load($data[0]);
}
return null;
}

public function findFirstFakeAxicoIdByManufacturerIdAndCategoryIdAndComponentId(int $manufacturerId, ?int $categoryId, ?int $componentId): ?AxicoId {
$data = null;
if ($categoryId) {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->isNull('w.product_id')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_category_id', $categoryId)
->condition('w.next_count', 1)
->orderBy('w.current_count', 'ASC')
->range(0, 1)
->execute()
->fetchAll();
} else {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->isNull('w.product_id')
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.parent_component_id', $componentId)
->condition('w.next_count', 1)
->orderBy('w.current_count', 'ASC')
->range(0, 1)
->execute()
->fetchAll();
}
if (!empty($data)) {
return $this->load($data[0]);
}
return null;
}

public function findByFullProductAxicoId(string $productAxicoId): ?AxicoId {
$manufacturer = $this->getManufacturerAxicoId($productAxicoId);
$group = $this->getGroupAxicoId($productAxicoId);
$count = $this->getGroupCount($productAxicoId);
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('name', $manufacturer . $group)
->condition('current_count', $count)
->condition('next_count', 0)
->execute()
->fetchObject();
if ($data) {
return $this->load($data);
}
return null;
}

public function addZeros(int $currentCount): string {
if ($currentCount >= 999) {
return (string) $currentCount;
}

if ($currentCount >= 100) {
return (string) $currentCount;
}

if ($currentCount >= 10) {
return '0' . (string) $currentCount;
}

return '00' . (string) $currentCount;
}

public function findHighestCountByComponentAxicoIdName(string $erroneusAxicoId): AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->isNull('w.parent_category_id')
->condition('w.name', $erroneusAxicoId)
->orderBy('w.current_count', 'DESC')
->range(0, 1)
->execute()
->fetchObject();
if ($data) {
return $this->load($data);
}
}

public function findHighestCountByCategoryAxicoIdName(string $erroneusAxicoId): AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->isNull('w.parent_component_id')
->condition('w.name', $erroneusAxicoId)
->orderBy('w.current_count', 'DESC')
->range(0, 1)
->execute()
->fetchObject();
if ($data) {
return $this->load($data);
}
}

public function removeErrors(): void {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.current_count', 1)
->condition('w.next_count', 1)
->execute()
->fetchAll();

$entities = $this->loadAll($data);
foreach ($entities as $entity) {
if ($this->followingExists($entity)) {
$entity->setNextCount(0);
$this->save($entity);
}
}
}

public function loadAll(array $data): array {

$entities = [];
if (empty($data)) {
return $entities;
}

foreach ($data as $entity) {
$entities[] = $this->load($entity);
}
return $entities;
}

public function followingExists(AxicoId $entity): bool {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_category_id', $entity->getParentCategoryId())
->condition('w.parent_component_id', $entity->getParentComponentId())
->condition('w.parent_manufacturer_id', $entity->getParentManufacturerId())
->condition('w.current_count', '>', 0)
->condition('w.next_count', 1)
->range(0, 1)
->execute()
->fetchObject();
if ($data) {
return true;
}
return false;
}

public function findPreviousAxicoIdEntity(string $groupName, int $manufacturerId, int $previousCount): ?AxicoId {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.name', $groupName)
->condition('w.parent_manufacturer_id', $manufacturerId)
->condition('w.current_count', $previousCount)
->execute()
->fetchObject();
if ($data) {
return $this->load($data);
}
return null;
}

}

// $groupName = $this->getGroupAxicoId($axicoIdEntity->getName());
// $specificGroups = $this->getSpecificGroups();
//
// /*
// * Remove it from the other group if necessary
// */
//
//
//
//
//// if (!isset($specificGroups[$groupName])) {
//// return $this->reviveAxicoIdEntity($axicoIdEntity);
//// } else {
// /*
// * Total removal of this axico id entity
// * if sorted product belongs to a specific group
// */
//// $this->delete($axicoIdEntity);
//// if ($axicoIdEntity->getParentComponentId()) {
//// $lastSimilar = $this->findHighestCurrentAxicoIdByComponentId($axicoIdEntity->getParentComponentId());
//// } else {
//// $lastSimilar = $this->findHighestCurrentAxicoIdByManufacturerIdAndCategoryIdAndComponentId(
//// $axicoIdEntity->getParentManufacturerId(), $axicoIdEntity->getParentCategoryId(), null);
//// }
////
//// return $this->reviveAxicoIdEntity($lastSimilar);
//// return null;
//// }

+ 223
- 0
modules/custom/arlista/src/Factory/CalculationFactory.php Dosyayı Görüntüle

@@ -0,0 +1,223 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\Calculation;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Currency;
use Drupal\Core\Config\ConfigFactoryInterface;
use stdClass;

class CalculationFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time, ConfigFactoryInterface $configFactory) {
parent::__construct($connection, $currentUser, $time, 'calculation');
$this->config = $configFactory->get('arlista.settings');
}

public function getConfig() {
return $this->config;
}

public function getExchangeRate(string $currency): float {
if (Currency::isSameCurrency($currency, 'USD')) {
return $this->getConfig()->get('exchange_rate_usd');
}
if (Currency::isSameCurrency($currency, 'EUR')) {
return $this->getConfig()->get('exchange_rate_eur');
}

return 1.00;
}

public function create(): Calculation {
return new Calculation();
}

public function findByManufacturerAndCategory(Manufacturer $manufacturer, Category $category): ?Calculation {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.parent_manufacturer_id', $manufacturer->getId())
->condition('w.parent_category_id', $category->getId())
->isNull('w.deleted_at')
->execute()
->fetchObject();

if (empty($data)) {
return null;
}

return $this->load($data);
}

public function findByComponent(Component $component): ?Calculation {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.parent_component_id', $component->getId())
->condition('w.parent_manufacturer_id', $component->getParentManufacturerId())
->isNull('w.deleted_at')
->execute()
->fetchObject();

if (empty($data)) {
return null;
}

return $this->load($data);
}

public function createFor(Component $component = null, Category $category = null, Manufacturer $manufacturer = null): Calculation {
if (empty($component)) {
$entity = $this->create();
$entity->setParentManufacturerId($manufacturer->getId());
$entity->setParentCategoryId($category->getId());
$entity->setParentComponentId(null);
$entity->setName($manufacturer->getName() . ' - ' . $category->getName() . ' ' . 'kalkuláció');

return $this->save($entity);
} else {

$entity = $this->create();
$entity->setParentManufacturerId($component->getParentManufacturerId());
$entity->setParentComponentId($component->getId());
$entity->setParentCategoryId(null);
$entity->setName($manufacturer->getName() . ' - ' . $component->getName() . ' ' . 'kalkuláció');

return $this->save($entity);
}
}

protected function insert(AbstractEntity $entity): Calculation {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'parent_category_id' => $entity->getParentCategoryId(),
'parent_component_id' => $entity->getParentComponentId(),
'list_price_factor' => $entity->getListPriceFactor(),
'price_factor_d_one' => $entity->getPriceFactorDOne(),
'price_factor_d_two' => $entity->getPriceFactorDTwo(),
'price_factor_spec' => $entity->getPriceFactorSpec(),
'price_factor_v_spec' => $entity->getPriceFactorVSpec(),
'price_factor_dev_d_one' => $entity->getPriceFactorDevDOne(),
'price_factor_dev_d_two' => $entity->getPriceFactorDevDTwo(),
'price_factor_dev_spec' => $entity->getPriceFactorDevSpec(),
'price_factor_dev_v_spec' => $entity->getPriceFactorDevVSpec(),
'transport_expense' => $entity->getTransportExpense(),
'default_setting' => $entity->getDefaultCalculation(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity): Calculation {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'parent_category_id' => $entity->getParentCategoryId(),
'parent_component_id' => $entity->getParentComponentId(),
'list_price_factor' => $entity->getListPriceFactor(),
'price_factor_d_one' => $entity->getPriceFactorDOne(),
'price_factor_d_two' => $entity->getPriceFactorDTwo(),
'price_factor_spec' => $entity->getPriceFactorSpec(),
'price_factor_v_spec' => $entity->getPriceFactorVSpec(),
'price_factor_dev_d_one' => $entity->getPriceFactorDevDOne(),
'price_factor_dev_d_two' => $entity->getPriceFactorDevDTwo(),
'price_factor_dev_spec' => $entity->getPriceFactorDevSpec(),
'price_factor_dev_v_spec' => $entity->getPriceFactorDevVSpec(),
'transport_expense' => $entity->getTransportExpense(),
'default_setting' => $entity->getDefaultCalculation(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

protected function load(stdClass $data): Calculation {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setStatus($data->status);
$entity->setParentManufacturerId($data->parent_manufacturer_id);
$entity->setParentCategoryId($data->parent_category_id);
$entity->setParentComponentId($data->parent_component_id);
$entity->setListPriceFactor($data->list_price_factor);
$entity->setPriceFactorDOne($data->price_factor_d_one);
$entity->setPriceFactorDTwo($data->price_factor_d_two);
$entity->setPriceFactorSpec($data->price_factor_spec);
$entity->setPriceFactorVSpec($data->price_factor_v_spec);
$entity->setPriceFactorDevDOne($data->price_factor_dev_d_one);
$entity->setPriceFactorDevDTwo($data->price_factor_dev_d_two);
$entity->setPriceFactorDevSpec($data->price_factor_dev_spec);
$entity->setPriceFactorDevVSpec($data->price_factor_dev_v_spec);
$entity->setTransportExpense($data->transport_expense);
$entity->setDefaultCalculation($data->default_setting);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);

return $entity;
}

public function findAllByManufacturerAndItsCategories(Manufacturer $manufacturer): array {
$entities = [];
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.parent_manufacturer_id', $manufacturer->getId())
->isNull('w.parent_component_id')
->isNull('w.deleted_at')
->execute()
->fetchAll();

if (empty($data)) {
return $entities;
}

foreach ($data as $item) {
$entities[] = $this->load($item);
}

return $entities;
}
public function copyCalculationFactorFields(Calculation $source, Calculation $target) : Calculation{
$target->setListPriceFactor($source->getListPriceFactor());
$target->setPriceFactorDOne($source->getPriceFactorDOne());
$target->setPriceFactorDTwo($source->getPriceFactorDTwo());
$target->setPriceFactorSpec($source->getPriceFactorSpec());
$target->setPriceFactorVSpec($source->getPriceFactorVSpec());

$target->setPriceFactorDevDOne($source->getPriceFactorDevDOne());
$target->setPriceFactorDevDTwo($source->getPriceFactorDevDTwo());
$target->setPriceFactorDevSpec($source->getPriceFactorDevSpec());
$target->setPriceFactorDevVSpec($source->getPriceFactorDevVSpec());
$target->setTransportExpense($source->getTransportExpense());

return $target;
}

}

+ 145
- 0
modules/custom/arlista/src/Factory/CategoryFactory.php Dosyayı Görüntüle

@@ -0,0 +1,145 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use stdClass;

class CategoryFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'category');
}

public function create() {
return new Category();
}

public function createByCategoryAxicoId(string $categoryAxicoId): Category {
$entity = $this->create();
$entity->setName($categoryAxicoId);
$entity->setAxicoIdName($categoryAxicoId);
$entity->setStatus(Status::PASSIVE);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getTime()->getRequestTime()));
$entity->setCreatedBy(1);
$entity->setSif(0);
return $this->save($entity);
}

public function findByAxicoIdName(string $axicoIdName): ?Category {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.axico_id_name', $axicoIdName)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return null;
}
return $this->load($data);
}

protected function insert(AbstractEntity $entity) {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'axico_id_name' => $entity->getAxicoIdName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity) {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'axico_id_name' => $entity->getAxicoIdName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

protected function load(stdClass $data) {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setAxicoIdName($data->axico_id_name);
$entity->setStatus($data->status);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);
$entity->setSif($data->sif);

return $entity;
}

public function importAll(array $data): array {
foreach ($data as $i => $category) {
if (empty($category['table_name'])) {
continue;
}
$items = parent::import($category['table_name']);
foreach ($items as $item) {
/* @var $entity Category */
$entity = $this->findByAxicoIdName($item->csopkod);
if (empty($entity)) {
$entity = $this->create();
$entity->setName($item->csopnev);
$entity->setAxicoIdName($item->csopkod);
$entity->setStatus(0);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getTime()->getRequestTime()));
$entity->setCreatedBy(1);
$entity->setSif(0);
$entity = $this->save($entity);
}
$data[$i]['categories'][$entity->getId()] = $entity;
}
}
return $data;
}

public function importAllFromProductData(array $data): array {
/* @var $product Product */
foreach ($data['products'] as $product) {
$axicoId = $product->getAxicoId();

/* AXICO ID contains 'SUP' */

//if (strpos($axicoId, 'SUP') !== false) {
$categoryAxicoId = substr($axicoId, 3, 3);
$entity = $this->findByAxicoIdName($categoryAxicoId);
if (empty($entity)) {
$data['category_not_found'][$categoryAxicoId] = $axicoId;
} else {
$data['category_found'][$categoryAxicoId] = $entity;
}
//}
}
return $data;
}

}

+ 230
- 0
modules/custom/arlista/src/Factory/ComponentFactory.php Dosyayı Görüntüle

@@ -0,0 +1,230 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use stdClass;

class ComponentFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'component');
}

public function create(): Component {
return new Component();
}

public function enable(array $components, array $enabled) {
/* @var $component Component */
foreach ($components as $component) {

$this->getConnection()->query('UPDATE arlista_manager_component SET status = :enabled WHERE id = :id', [
':id' => $component->getId(),
':enabled' => isset($enabled[$component->getId()]) ? 1 : 0,
]);
}
}

protected function insert(AbstractEntity $entity): Component {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'axico_id_name' => $entity->getAxicoIdName(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity): Component {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'axico_id_name' => $entity->getAxicoIdName(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

protected function load(stdClass $data): Component {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setStatus($data->status);
$entity->setAxicoIdName($data->axico_id_name);
$entity->setParentManufacturerId($data->parent_manufacturer_id);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);
$entity->setSif($data->sif);

return $entity;
}

public function importAll(array $data): array {
foreach ($data as $i => $componentData) {
foreach ($componentData['components'] as $manufacturerId => $componentAxicoIdNames) {
foreach ($componentAxicoIdNames as $key => $value) {
if (empty($this->findByManufacturerIdAndComponentAxicoIdName((int) $manufacturerId, $value))) {
$entity = $this->create();
$entity->setName($value);
$entity->setAxicoIdName($value);
$entity->setParentManufacturerId($manufacturerId);
$entity->setStatus(1);
$entity->setCreatedBy(1);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getTime()->getRequestTime()));
$entity = $this->save($entity);
$data[$i]['components'][$manufacturerId][$value] = $entity;
}
}
}
}

return $data;
}

public function createAllFromTable(string $tableName, int $parentManufacturerId): array {
$componentsCreated = [];
$items = $this->import($tableName);
foreach ($items as $item) {
/* @var $entity Component */
$entity = $this->findByAxicoIdNameAndParentManufacturerId($item->csopkod, $parentManufacturerId);
if (empty($entity)) {
$entity = $this->create();
$entity->setAxicoIdName($item->csopkod);
$entity->setName($item->csopnev);
$entity->setParentManufacturerId($parentManufacturerId);
$entity->setStatus(1);
$entity->setCreatedBy(1);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getTime()->getRequestTime()));
$entity = $this->save($entity);
$componentsCreated[$item->csopkod] = $entity;
}
}
return $componentsCreated;
}

public function findByManufacturerIdAndComponentAxicoIdName(int $mid, string $axicoIdName): ?Component {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.parent_manufacturer_id', $mid)
->condition('w.axico_id_name', $axicoIdName)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return null;
}
return $this->load($data);
}

public function createByAxicoIdDataOfProduct(int $parentManufacturerId, $axicoIdName): Component {
$entity = $this->create();
$entity->setName($axicoIdName);
$entity->setAxicoIdName($axicoIdName);
$entity->setParentManufacturerId($parentManufacturerId);
$entity->setStatus(Status::PASSIVE);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getTime()->getRequestTime()));
$entity->setCreatedBy(1);
$entity->setSif(0);
return $this->save($entity);
}

public function importAllFromProductData(array $data): array {
/* @var $product Product */
foreach ($data['products'] as $product) {
$axicoId = $product->getAxicoId();
$componentAxicoId = substr($axicoId, 3, 3);
$manufacturer = $this->getConnection()->query('SELECT * FROM arlista_manager_manufacturer a WHERE a.component_based = :component_based AND a.axico_id = :axico_id',
[':component_based' => 1,':axico_id' => substr($axicoId, 4, 3),])->fetchObject();
if (empty($manufacturer)) {
continue;
}
$entity = $this->findByAxicoIdNameAndParentManufacturerId($componentAxicoId, $manufacturer->getId());
if (empty($entity)) {
$data['component_not_found'][$componentAxicoId] = $componentAxicoId;
} else {
$data['component_found'][$componentAxicoId] = $componentAxicoId;
}
}
return $data;
}

public function findByAxicoIdNameAndParentManufacturerId(string $axicoIdName, int $parentManufacturerId): ?Component {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.axico_id_name', $axicoIdName)
->condition('w.parent_manufacturer_id', $parentManufacturerId)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return null;
}
return $this->load($data);
}

public function findAllActiveWhereManufacturerIdIn(string $orderBy = 'id', string $orderDirection = 'ASC', array $ids): array {
$entities = [];
$items = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.status', Status::ACTIVE)
->condition('w.parent_manufacturer_id', $ids, 'IN')
->isNull('w.deleted_at')
->orderBy($orderBy, $orderDirection)
->execute()
->fetchAll();
if (empty($items)) {
return $entities;
}
foreach ($items as $item) {
$entities[] = $this->load($item);
}

return $entities;
}

public function findAllWhereManufacturerId(int $parentManufacturerId, string $orderBy = 'id', string $orderDirection = 'ASC') {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.parent_manufacturer_id', $parentManufacturerId)
->orderBy($orderBy, $orderDirection)
->execute();
$entities = [];
foreach ($list as $item) {
$entities[] = $this->load($item);
}

return $entities;
}

}

+ 152
- 0
modules/custom/arlista/src/Factory/EnabledGroupFactory.php Dosyayı Görüntüle

@@ -0,0 +1,152 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\EnabledGroup;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use stdClass;

class EnabledGroupFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'enabled_group');
}

public function create(): EnabledGroup {
return new EnabledGroup();
}

public function updateSheetSettingsEnabledGroups(int $sheetSettingId, array $newGroups, string $componentBased = null): void {
$activeGroups = $this->findAllEnabledGroups($sheetSettingId, $componentBased);
foreach ($activeGroups as $activeGroup) {
if ($activeGroup->isComponentBased() && $componentBased) {
$this->delete($activeGroup);
}
if (!$activeGroup->isComponentBased() && empty($componentBased)) {
$this->delete($activeGroup);
}
}
/* @var $item AbstractEntity */
foreach ($newGroups as $item) {
$newGroup = $this->create();
$newGroup->setName($item->getName());
$newGroup->setSheetSettingId($sheetSettingId);
if ($componentBased) {
$newGroup->setComponentId($item->getId());
} else {
$newGroup->setCategoryId($item->getId());
}
$this->save($newGroup);
}
}

public function findAllEnabledGroups(int $sheetSettingId = null, string $componentBased = null): array {
$list = [];
if ($componentBased) {
if ($sheetSettingId) {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('sheet_setting_id', $sheetSettingId)
->isNull('w.deleted_at')
->isNull('w.category_id')
->orderBy('id', 'ASC')
->execute()
->fetchAll();
} else {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.status', Status::ACTIVE)
->isNull('w.deleted_at')
->isNull('w.category_id')
->orderBy('id', 'ASC')
->execute()
->fetchAll();
}
} else {
if ($sheetSettingId) {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('sheet_setting_id', $sheetSettingId)
->isNull('w.deleted_at')
->isNull('w.component_id')
->orderBy('id', 'ASC')
->execute()
->fetchAll();
} else {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.status', Status::ACTIVE)
->isNull('w.deleted_at')
->isNull('w.component_id')
->orderBy('id', 'ASC')
->execute()
->fetchAll();
}
}
$entities = [];
foreach ($list as $item) {
$entities[$componentBased ? $item->component_id : $item->category_id] = $this->load($item);
}

return $entities;
}

protected function insert(AbstractEntity $entity): EnabledGroup {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'sheet_setting_id' => $entity->getSheetSettingId(),
'component_id' => $entity->getComponentId(),
'category_id' => $entity->getCategoryId(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity): EnabledGroup {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'sheet_setting_id' => $entity->getSheetSettingId(),
'component_id' => $entity->getComponentId(),
'category_id' => $entity->getCategoryId(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

protected function load(stdClass $data): EnabledGroup {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setCategoryId($data->category_id);
$entity->setComponentId($data->component_id);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);

return $entity;
}

}

+ 128
- 0
modules/custom/arlista/src/Factory/FileFactory.php Dosyayı Görüntüle

@@ -0,0 +1,128 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\UploadedFile;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\SheetSetting;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use stdClass;
use Drupal\arlista\Entity\WorkFlow;

class FileFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'uploaded_file');
}

public function create(): UploadedFile {
return new UploadedFile();
}

public function find(int $id): UploadedFile {
return parent::find($id);
}

public function findAllByParentManufacturerId(int $parentManufacturerId): array {
$entities = [];

$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.parent_manufacturer_id', $parentManufacturerId)
->isNull('w.deleted_at')
->execute()
->fetchAll();

if (empty($data)) {
return $entities;
}
foreach ($data as $item) {
$entities[] = $this->load($item);
}
return $entities;
}

protected function insert(AbstractEntity $entity): UploadedFile {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'component_based' => $entity->getComponentBased(),
'fid' => $entity->getFid(),
'work_flow' => $entity->getWorkFlow(),
'total_products' => $entity->getTotalProducts(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();
$entity->setId($id);

return $entity;
}

protected function update(AbstractEntity $entity): UploadedFile {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'parent_manufacturer_id' => $entity->getParentManufacturerId(),
'component_based' => $entity->getComponentBased(),
'fid' => $entity->getFid(),
'work_flow' => $entity->getWorkFlow(),
'total_products' => $entity->getTotalProducts(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

protected function load(stdClass $data): UploadedFile {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setStatus($data->status);
$entity->setParentManufacturerId($data->parent_manufacturer_id);
$entity->setComponentBased($data->component_based);
$entity->setFid($data->fid);
$entity->setWorkFlow($data->work_flow);
$entity->setTotalProducts($data->total_products);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);

return $entity;
}

public function delete(AbstractEntity $entity): void {
$fileManaged = \Drupal::entityTypeManager()
->getStorage('file')
->load($entity->getFid());
if ($fileManaged !== null) {
\Drupal::entityTypeManager()
->getStorage('file')->delete([$fileManaged]);
}
$this->getConnection()
->update($this->getActiveTable())
->fields([
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id(),
'deleted_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'work_flow' => WorkFlow::DELETED,
])
->condition('id', $entity->getId())
->execute();
}

}

+ 747
- 0
modules/custom/arlista/src/Factory/InstallFactory.php Dosyayı Görüntüle

@@ -0,0 +1,747 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\arlista\Factory\CategoryFactory;
use Drupal\arlista\Factory\AxicoIdFactory;
use Drupal\arlista\Factory\ManufacturerFactory;
use Drupal\arlista\Factory\CalculationFactory;
use Drupal\arlista\Factory\ComponentFactory;
use Drupal\arlista\Factory\ProductFactory;
use Drupal\arlista\Factory\FileFactory;
use Drupal\arlista\Factory\SpreadSheetFactory;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\AxicoId;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Calculation;
use Drupal\arlista\Entity\Install;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Traits\AxicoIdTrait;
use stdClass;

class InstallFactory {

use AxicoIdTrait;

private AxicoIdFactory $axicoIdFactory;
private CategoryFactory $categoryFactory;
private ComponentFactory $componentFactory;
private ManufacturerFactory $manufacturerFactory;
private ProductFactory $productFactory;
private CalculationFactory $calculationFactory;
private Product $product;
private Manufacturer $manufacturer;
private Calculation $calculation;
private Category $category;
private Component $component;
private AxicoId $axicoId;
private FileFactory $fileFactory;
private SpreadSheetFactory $spreadSheetFactory;
private array $manufacturerNames;
private array $groupNames;

public function __construct(
AxicoIdFactory $axicoIdFactory, CategoryFactory $categoryFactory,
ComponentFactory $componentFactory, ManufacturerFactory $manufacturerFactory,
ProductFactory $productFactory, CalculationFactory $calculationFactory,
FileFactory $fileFactory, SpreadSheetFactory $spreadSheetFactory) {
$this->axicoIdFactory = $axicoIdFactory;
$this->categoryFactory = $categoryFactory;
$this->componentFactory = $componentFactory;
$this->manufacturerFactory = $manufacturerFactory;
$this->productFactory = $productFactory;
$this->calculationFactory = $calculationFactory;
$this->fileFactory = $fileFactory;
$this->spreadSheetFactory = $spreadSheetFactory;
}

public function getAxicoIdFactory(): AxicoIdFactory {
return $this->axicoIdFactory;
}

public function getCategoryFactory(): CategoryFactory {
return $this->categoryFactory;
}

public function getComponentFactory(): ComponentFactory {
return $this->componentFactory;
}

public function getManufacturerFactory(): ManufacturerFactory {
return $this->manufacturerFactory;
}

public function getProductFactory(): ProductFactory {
return $this->productFactory;
}

public function getCalculationFactory(): CalculationFactory {
return $this->calculationFactory;
}

public function getSpreadSheetFactory(): SpreadSheetFactory {
return $this->spreadSheetFactory;
}

public function getProduct(): Product {
return $this->product;
}

public function getManufacturer(): Manufacturer {
return $this->manufacturer;
}

public function getCalculation(): Calculation {
return $this->calculation;
}

public function getCategory(): Category {
return $this->category;
}

public function getComponent(): Component {
return $this->component;
}

public function getAxicoId(): AxicoId {
return $this->axicoId;
}

public function setAxicoIdFactory(AxicoIdFactory $axicoIdFactory): void {
$this->axicoIdFactory = $axicoIdFactory;
}

public function setCategoryFactory(CategoryFactory $categoryFactory): void {
$this->categoryFactory = $categoryFactory;
}

public function setComponentFactory(ComponentFactory $componentFactory): void {
$this->componentFactory = $componentFactory;
}

public function setManufacturerFactory(ManufacturerFactory $manufacturerFactory): void {
$this->manufacturerFactory = $manufacturerFactory;
}

public function setProductFactory(ProductFactory $productFactory): void {
$this->productFactory = $productFactory;
}

public function setCalculationFactory(CalculationFactory $calculationFactory): void {
$this->calculationFactory = $calculationFactory;
}

public function setProduct(Product $product): void {
$this->product = $product;
}

public function setManufacturer(Manufacturer $manufacturer): void {
$this->manufacturer = $manufacturer;
}

public function setCalculation(Calculation $calculation): void {
$this->calculation = $calculation;
}

public function setCategory(Category $category): void {
$this->category = $category;
}

public function setComponent(Component $component): void {
$this->component = $component;
}

public function setAxicoId(AxicoId $axicoId): void {
$this->axicoId = $axicoId;
}

public function getFileFactory(): FileFactory {
return $this->fileFactory;
}

public function setFileFactory(FileFactory $fileFactory): void {
$this->fileFactory = $fileFactory;
}

public function getManufacturerNameByAxicoId(string $axicoIdName): ?string {
if (isset($this->manufacturerNames[$axicoIdName])) {
return $this->manufacturerNames[$axicoIdName];
}
return null;
}

public function getProductGroupNameByAxicoId(string $axicoIdName): ?string {
if (isset($this->groupNames[$axicoIdName])) {
return $this->groupNames[$axicoIdName];
}
return null;
}

public function importPrimaryDataBases() {
$data = [
[
'name' => 'Adaptec',
'table_name' => 'adaptec_csop',
'axico_id' => 'ADA',
'component_based' => 0,
'manufacturer' => null,
'categories' => [],
'axicoId' => []
],
[
'name' => 'BlackBox',
'table_name' => 'bbx_csop',
'axico_id' => 'BBX',
'component_based' => 0,
'manufacturer' => null,
'categories' => [],
'axicoId' => []
],
[
'name' => 'Supermicro - standard',
'table_name' => null,
'axico_id' => 'SUP',
'component_based' => 0,
'manufacturer' => null,
'categories' => [],
'axicoId' => []
],
[
'name' => 'Supermicro - komponens',
'table_name' => null,
'axico_id' => 'SUP',
'component_based' => 1,
'manufacturer' => null,
'categories' => [],
'axicoId' => []
],
];

$data = $this->getCategoryFactory()->importAll($data);
$data = $this->getManufacturerFactory()->importAll($data);
}

public function importSecondaryDataBases() {
$componentData = [
['table_name' => 'komp_amd',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_aoc',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_gpu',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_hdd',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_intel',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_mem',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_satadom',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_ssd',
'components' => [],
'manufacturers' => []],
['table_name' => 'komp_switch',
'components' => [],
'manufacturers' => []],
['table_name' => 'bbx_online',
'components' => [],
'manufacturers' => []],
['table_name' => 'adaptec',
'components' => [],
'manufacturers' => []]
];

$componentData = $this->getManufacturerFactory()->importAllFromComponentData($componentData);
$componentData = $this->getComponentFactory()->importAll($componentData);
}

public function importDataFromExcelFile(string $fileName, bool $reimport) {
$this->manufacturerNames = $this->getEntityNames('regi_kategoriak.xlsx', "A", "B");
$this->groupNames = $this->getEntityNames('regi_kategoriak.xlsx', "L", "M");

if ($reimport) {
$this->clearTables();
}
if (!$reimport) {
$this->storeStaticComponentData();
}
$componentManufacturerAxicoIds = Install::getComponentManufacturers();
if (!$reimport) {
$this->storeComponentManufacturerAxicoIds($componentManufacturerAxicoIds);
}

$baseCategories = Install::getBaseCategories();
if (!$reimport) {
$this->storeBaseCategories($baseCategories);
}

if (!$reimport) {
$this->getProductFactory()->setActiveTable('arlista_manager_active_product');
}
$workSheet = $this->getSpreadSheetFactory()->getWorkSheet($fileName, 0);
$highestRow = $workSheet->getHighestRow();
$ignorableManufacturers = Install::getIgnorableManufacturers();
$doubledGroups = Install::getSpecificGroupNames();
for ($i = 2; $i <= $highestRow; ++$i) {
$product = $this->getProductFactory()->createFromNextExcelFileRow($workSheet, $i);
if (empty($product->getAxicoId())) {
continue;
}
$manufacturerAxicoId = $this->getManufacturerAxicoId($product->getAxicoId());
if ($this->isManufacturersProductIgnorable($manufacturerAxicoId, $ignorableManufacturers)) {
continue;
}
$existingProduct = $this->getExistingProductFromActiveDatabase($product);
if ($existingProduct || empty($product->getName())) {
continue;
}
if (empty($product->getFabricId())) {
$product = $this->getProductFactory()->restoreProductsFabricIdToDefault($product);
}
$product = $this->getProductFactory()->saveTo($product, 'arlista_manager_active_product');

$groupAxicoId = $this->getGroupAxicoId($product->getAxicoId());
$componentBased = isset($componentManufacturerAxicoIds[$manufacturerAxicoId]) && !isset($baseCategories[$groupAxicoId]) ? 1 : 0;
if (isset($doubledGroups['groupAxicoId'])) {
$componentBased = $this->getProductFactory()->testIfSpecificProductIsComponentBased($product);
}
$manufacturer = $this->findManufacturer($manufacturerAxicoId, $componentBased);
$axicoIdName = $manufacturer->getAxicoIdName() . $groupAxicoId;
$count = $this->getGroupCount($product->getAxicoId());

if ($componentBased) {
$component = $this->findComponent($manufacturer, $groupAxicoId, $product);
$axicoId = $this->getAxicoIdFactory()->createForComponent($manufacturer->getId(), $component->getId());
$product->setParentComponentId($component->getId());
$product->setParentManufacturerId($component->getParentManufacturerId());
} else {
$category = $this->findCategory($groupAxicoId, $product);
$axicoId = $this->getAxicoIdFactory()->createForCategory($manufacturer->getId(), $category->getId());
$product->setParentCategoryId($category->getId());
$product->setParentManufacturerId($manufacturer->getId());
}
$axicoId->setName($axicoIdName);
$axicoId->setCurrentCount($count);
$axicoId->setNextCount(0);
$axicoId->setProductId($product->getId());
$this->getAxicoIdFactory()->save($axicoId);
$this->getProductFactory()->saveTo($product, 'arlista_manager_active_product');
}

$this->setAxicoIdDataAndCalculationForEachComponent();
$this->setAxicoIdDataAndCalculationForEachManufacturersEachCategory();
}

private function getExistingProductFromActiveDatabase(Product $product): ?Product {
$existingProduct = $this->getProductFactory()->findByAxicoIdInTable($product->getAxicoId());
if (empty($existingProduct) && !empty($product->getFabricId())) {
$existingProduct = $this->getProductFactory()->findByFabricIdInTable($product->getFabricId());
}

return $existingProduct;
}

private function isManufacturersProductIgnorable(string $manufacturerAxicoId, array $ignorableManufacturers): bool {
return in_array($manufacturerAxicoId, $ignorableManufacturers);
}

public function findManufacturer(string $manufacturerAxicoId, int $componentBased): Manufacturer {
$manufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($manufacturerAxicoId, $componentBased);
if (empty($manufacturer)) {
$manufacturerName = $this->getManufacturerNameByAxicoId($manufacturerAxicoId);
$manufacturer = $this->getManufacturerFactory()->create();
$manufacturer->setName($manufacturerName ? $manufacturerName : $manufacturerAxicoId);
$manufacturer->setAxicoIdName($manufacturerAxicoId);
$manufacturer->setComponentBased($componentBased);
$manufacturer->setStatus(Status::PASSIVE);
$manufacturer->setSif(0);
return $this->getManufacturerFactory()->save($manufacturer);
}

if ($manufacturer->getAxicoIdName() === $manufacturer->getName()) {
$name = $this->getManufacturerNameByAxicoId($manufacturerAxicoId);
if ($name) {
$suffix = $manufacturer->isComponentBased() ? ' - komponens' : ' - standard';
$fullName = $name . $suffix;
$manufacturer->setName($fullName);
return $this->getManufacturerFactory()->save($manufacturer);
}
}

return $manufacturer;
}

public function findComponent(Manufacturer $manufacturer, string $groupAxicoId, Product $product): Component {
$component = $this->getComponentFactory()->findByManufacturerIdAndComponentAxicoIdName($manufacturer->getId(), $groupAxicoId);
if (empty($component)) {
$component = $this->getComponentFactory()->createByAxicoIdDataOfProduct(
$manufacturer->getId(),
$groupAxicoId);
}
if ($component->getAxicoIdName() === $component->getName()) {
$name = $this->getProductGroupNameByAxicoId($groupAxicoId);
if ($name) {
$component->setName($name);
return $this->getComponentFactory()->save($component);
}
}

return $component;
}

public function findCategory(string $groupAxicoId, Product $product): Category {
$category = $this->getCategoryFactory()->findByAxicoIdName($groupAxicoId);
if (empty($category)) {
$category = $this->getCategoryFactory()->createByCategoryAxicoId($groupAxicoId);
}

if ($category->getAxicoIdName() === $category->getName()) {
$name = $this->getProductGroupNameByAxicoId($groupAxicoId);
if ($name) {
$category->setName($name);
$this->getCategoryFactory()->save($category);
}
}

return $category;
}

public function clearTables(): void {
$this->clearAxicoIdTable();
$this->clearActiveProductTable();
$this->clearUploadedFileTable();
$this->clearUploadedProductTable();
}

public function clearAxicoIdTable(): void {
$axicoIds = $this->getAxicoIdFactory()->findAll();
foreach ($axicoIds as $axicoId) {
$this->getAxicoIdFactory()->remove($axicoId);
}
}

public function clearUploadedFileTable(): void {
$uploadedFiles = $this->getFileFactory()->findAll();
foreach ($uploadedFiles as $uploadedFile) {
$this->getFileFactory()->remove($uploadedFile);
}
}

public function clearUploadedProductTable(): void {
$this->getProductFactory()->setActiveTable('arlista_manager_uploaded_product');
$products = $this->getProductFactory()->findAll();
foreach ($products as $product) {
$this->getProductFactory()->remove($product);
}
}

public function clearActiveProductTable(): void {
$this->getProductFactory()->setActiveTable('arlista_manager_active_product');
$products = $this->getProductFactory()->findAll();
foreach ($products as $product) {
$this->getProductFactory()->remove($product);
}
}

public function storeStaticComponentData(): void {
$componentAxicoIds = Install::getStaticComponentData();
$componentImporter = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased('SUP', 1);
foreach ($componentAxicoIds as $key => $value) {
$entity = $this->getComponentFactory()->create();
$entity->setName($value);
$entity->setAxicoIdName($key);
$entity->setParentManufacturerId($componentImporter->getId());
$entity->setStatus(Status::PASSIVE);
$entity->setCreatedBy(1);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getComponentFactory()->getTime()->getRequestTime()));
$this->getComponentFactory()->save($entity);
}
}

public function storeComponentManufacturerAxicoIds(array $componentManufacturerAxicoIds): void {
foreach ($componentManufacturerAxicoIds as $key => $value) {
$componentManufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($key, 1);
if (empty($componentManufacturer)) {
$entity = $this->getManufacturerFactory()->create();
$entity->setName($value);
$entity->setAxicoIdName($key);
$entity->setComponentBased(1);
$entity->setStatus(Status::PASSIVE);
$entity->setCreatedBy(1);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getManufacturerFactory()->getTime()->getRequestTime()));
$this->getManufacturerFactory()->save($entity);
}
}
}

public function storeBaseCategories(array $baseCategories): void {
foreach ($baseCategories as $key => $value) {
if (empty($this->getCategoryFactory()->findByAxicoIdName($key))) {
$entity = $this->getCategoryFactory()->create();
$entity->setName($value);
$entity->setAxicoIdName($key);
$entity->setStatus(Status::PASSIVE);
$entity->setCreatedAt(date('Y-m-d H:i:s', $this->getCategoryFactory()->getTime()->getRequestTime()));
$entity->setCreatedBy(1);
$entity->setSif(0);
$this->getCategoryFactory()->save($entity);
} else {
$entity->setName($value);
$this->getCategoryFactory()->save($entity);
}
}
}

public function fixSpecificAxicoIds(array $specificAxicoIds): void {
foreach ($specificAxicoIds as $specificAxicoId) {
$this->fixAxicoIdsOf($specificAxicoId);
}
}

private function fixAxicoIdsOf(string $specificAxicoId): void {

$manufacturerAxicoid = $this->getAxicoIdFactory()->getManufacturerAxicoId($specificAxicoId);
$groupAxicoId = $this->getAxicoIdFactory()->getGroupAxicoId($specificAxicoId);
$cikkszam = '%' . $specificAxicoId . '%';

$oldProductsKOMP_AOC = $this->axicoIdFactory->getConnection()->query(
'SELECT * FROM komp_aoc WHERE cikkszam LIKE :cikkszam',
[':cikkszam' => $cikkszam])->fetchAll();
$manufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($manufacturerAxicoid, 1);
$component = $this->getComponentFactory()->findByAxicoIdNameAndParentManufacturerId($groupAxicoId, $manufacturer->getId());
$differentFieldName = false;
$this->updateProductsAndComponents($oldProductsKOMP_AOC, $component, null, $manufacturer, $differentFieldName);

if ($groupAxicoId === 'HAX' || $groupAxicoId === 'HSW') {
$oldProductsKOMP_SWITCH = $this->axicoIdFactory->getConnection()->query(
'SELECT * FROM komp_switch WHERE cikkszam LIKE :cikkszam', [':cikkszam' => $cikkszam])
->fetchAll();
$this->updateProductsAndComponents($oldProductsKOMP_SWITCH, $component, null, $manufacturer, $differentFieldName);
}

$oldProductsSUP_ARLISTA = $this->axicoIdFactory->getConnection()->query(
'SELECT * FROM sm_arlista WHERE cikkszam LIKE :cikkszam', [':cikkszam' => $cikkszam])
->fetchAll();
$category = $this->getCategoryFactory()->findByAxicoIdName($groupAxicoId);
$manufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($manufacturerAxicoid, 0);
$differentFieldName = true;
$this->updateProductsAndCategories($oldProductsSUP_ARLISTA, null, $category,
$manufacturer, $differentFieldName);
}

private function updateProductsAndComponents(array $oldProducts, ?Component $component, ?Category $category, Manufacturer $manufacturer, bool $diffetentFieldName): void {
foreach ($oldProducts as $oldProduct) {
$product = $this->updateExistingProduct($oldProduct, $component, $category, $manufacturer, $diffetentFieldName);
if ($product) {
$this->updateExistingComponentsAxicoId($component, $product, $oldProduct);
}
}
}

private function updateProductsAndCategories(array $oldProducts, ?Component $component, ?Category $category, Manufacturer $manufacturer, bool $diffetentFieldName): void {
foreach ($oldProducts as $oldProduct) {
$product = $this->updateExistingProduct($oldProduct, $component, $category, $manufacturer, $diffetentFieldName);
if ($product) {
$this->updateExistingCategoriesAxicoId($category, $product, $manufacturer, $oldProduct);
}
}
}

private function updateExistingProduct(stdClass $oldProduct, ?Component $component,
?Category $category, Manufacturer $manufacturer, bool $diffetentFieldName): ?Product {
/* @var $product Product */
if ($diffetentFieldName) {
$product = $this->getProductFactory()->findByFabricIdInTable($oldProduct->Item, 'arlista_manager_active_product');
} else {
$product = $this->getProductFactory()->findByFabricIdInTable($oldProduct->P_N, 'arlista_manager_active_product');
}

if ($product) {
if (!empty($component)) {
$product->setParentComponentId($component->getId());
$product->setParentCategoryId(null);
}
if (!empty($category)) {
$product->setParentComponentId(null);
$product->setParentCategoryId($category->getId());
}
$product->setParentManufacturerId($manufacturer->getId());
return $this->getProductFactory()->save($product);
}

return $product;
}

private function updateExistingComponentsAxicoId(Component $component, Product $product, stdClass $oldProduct): void {
if (empty($product->getAxicoId())) {
return;
}
/* @var $axicoIdEntity AxicoId */
$axicoIdEntity = $this->getAxicoIdFactory()->findByProductId($product->getId());
if ($axicoIdEntity) {
$axicoIdEntity->setParentComponentId($component->getId());
$axicoIdEntity->setParentCategoryId(null);
$axicoIdEntity->setParentManufacturerId($product->getParentManufacturerId());
$this->getAxicoIdFactory()->save($axicoIdEntity);
return;
}
/* @var $axicoIdEntity AxicoId */
$axicoIdEntity = $this->getAxicoIdFactory()->createForComponent($product->getParentManufacturerId(), $component->getId());
$this->updateAxicoIdEntity($axicoIdEntity, $product, $oldProduct);
}

private function updateExistingCategoriesAxicoId(Category $category, Product $product, Manufacturer $manufacturer, stdClass $oldProduct): void {
if (empty($product->getAxicoId())) {
return;
}
/* @var $axicoIdEntity AxicoId */
$axicoIdEntity = $this->getAxicoIdFactory()->findByProductId($product->getId());
if ($axicoIdEntity) {
$axicoIdEntity->setParentComponentId(null);
$axicoIdEntity->setParentCategoryId($category->getId());
$axicoIdEntity->setParentManufacturerId($manufacturer->getId());
$this->getAxicoIdFactory()->save($axicoIdEntity);
return;
}
$axicoIdEntity = $this->getAxicoIdFactory()->createForCategory($manufacturer->getId(), $category->getId());
$this->updateAxicoIdEntity($axicoIdEntity, $product, $oldProduct);
}

private function updateAxicoIdEntity(AxicoId $axicoIdEntity, Product $product, stdClass $oldProduct): void {
$axicoIdEntity->setName($this->getAxicoIdFactory()->getGroupAxicoId($product->getAxicoId()));
$axicoIdEntity->setProductId($product->getId());
$axicoIdEntity->setCurrentCount($this->getAxicoIdFactory()->getGroupCount($oldProduct->cikkszam));
$axicoIdEntity->setNextCount(0);
$this->getAxicoIdFactory()->save($axicoIdEntity);
}

public function fixSpecificAxicoIdsNextCount(array $erroneusAxicoIds): void {
foreach ($erroneusAxicoIds as $erroneusAxicoId) {
$this->getAxicoIdFactory()
->getConnection()
->update('arlista_manager_axico_id')
->fields(['parent_component_id' => null])
->condition('name', $erroneusAxicoId)
->condition('parent_component_id', 0)
->execute();

$this->getAxicoIdFactory()
->getConnection()
->update('arlista_manager_axico_id')
->fields(['parent_category_id' => null])
->condition('name', $erroneusAxicoId)
->condition('parent_category_id', 0)
->execute();

$manufacturerAxicoid = $this->getAxicoIdFactory()->getManufacturerAxicoId($erroneusAxicoId);
$manufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($manufacturerAxicoid, 1);
$groupAxicoId = $this->getAxicoIdFactory()->getGroupAxicoId($erroneusAxicoId);
$component = $this->getComponentFactory()->findByAxicoIdNameAndParentManufacturerId($groupAxicoId, $manufacturer->getId());

/* @var $axicoIdEntity AxicoId */
$axicoIdEntity = $this->getAxicoIdFactory()->findHighestCurrentAxicoIdByComponentId($component->getId());
if (empty($axicoIdEntity)) {
\Drupal::messenger()->addMessage('Not found axico id of component : ' . $erroneusAxicoId);
} else {
$nextAxicoIdEntity = $this->getAxicoIdFactory()->createForComponent($manufacturer->getId(), $component->getId());
$nextAxicoIdEntity->setName($axicoIdEntity->getName());
$nextAxicoIdEntity->setCurrentCount($axicoIdEntity->getCurrentCount() + 1);
$this->getAxicoIdFactory()->save($nextAxicoIdEntity);
$axicoIdEntity->setNextCount(0);
$this->getAxicoIdFactory()->save($axicoIdEntity);
$deletable = $this->getAxicoIdFactory()->findFirstFakeAxicoIdByManufacturerIdAndCategoryIdAndComponentId($manufacturer->getId(), null, $component->getId());
$this->getAxicoIdFactory()->delete($deletable);
}

$manufacturer = $this->getManufacturerFactory()->findByAxicoIdNameAndComponentBased($manufacturerAxicoid, 0);
$category = $this->getCategoryFactory()->findByAxicoIdName($groupAxicoId);

$axicoIdEntity = $this->getAxicoIdFactory()->findHighestCurrentAxicoIdByManufacturerIdAndCategoryIdAndComponentId($manufacturer->getId(), $category->getId(), null);
if (empty($axicoIdEntity)) {
\Drupal::messenger()->addMessage('Not found axico id of category : ' . $erroneusAxicoId);
} else {
$nextAxicoIdEntity = $this->getAxicoIdFactory()->createForCategory($manufacturer->getId(), $category->getId());
$nextAxicoIdEntity->setName($axicoIdEntity->getName());
$nextAxicoIdEntity->setCurrentCount($axicoIdEntity->getCurrentCount() + 1);
$this->getAxicoIdFactory()->save($nextAxicoIdEntity);
$axicoIdEntity->setNextCount(0);
$this->getAxicoIdFactory()->save($axicoIdEntity);
$deletable = $this->getAxicoIdFactory()->findFirstFakeAxicoIdByManufacturerIdAndCategoryIdAndComponentId($manufacturer->getId(), $category->getId(), null);
$this->getAxicoIdFactory()->delete($deletable);
}
}
}

public function setAxicoIdDataAndCalculationForEachComponent(): void {
$components = $this->getComponentFactory()->findAll();
foreach ($components as $component) {
$axicoId = $this->getAxicoIdFactory()->findHighestCurrentAxicoIdByManufacturerIdAndCategoryIdAndComponentId($component->getParentManufacturerId(), null, $component->getId());
$manufacturer = $this->getManufacturerFactory()->find($component->getParentManufacturerId());
$newAxicoId = $this->getAxicoIdFactory()->createForComponent($component->getParentManufacturerId(), $component->getId());
$newAxicoId->setNextCount(1);
$currentCount = 1;
if ($axicoId) {
$currentCount = $axicoId->getCurrentCount() + 1;
$newAxicoId->setName($axicoId->getName());
} else {
$newAxicoId->setName($manufacturer->getAxicoIdName() . $component->getAxicoIdName());
}
$newAxicoId->setCurrentCount($currentCount);
$this->getAxicoIdFactory()->save($newAxicoId);
$calculation = $this->getCalculationFactory()->findByComponent($component);
if ($calculation) {
continue;
}
$this->getCalculationFactory()->createFor($component, null, $manufacturer);
}
}

public function setAxicoIdDataAndCalculationForEachManufacturersEachCategory(): void {
$manufacturers = $this->getManufacturerFactory()->findAll();
$categories = $this->getCategoryFactory()->findAll();
foreach ($manufacturers as $manufacturer) {
foreach ($categories as $category) {
$axicoId = $this->getAxicoIdFactory()->findHighestCurrentAxicoIdByManufacturerIdAndCategoryIdAndComponentId($manufacturer->getId(), $category->getId(), null);
$newAxicoId = $this->getAxicoIdFactory()->createForCategory($manufacturer->getId(), $category->getId());
$newAxicoId->setName($manufacturer->getAxicoIdName() . $category->getAxicoIdName());
if ($axicoId) {
$newAxicoId->setCurrentCount($axicoId->getCurrentCount() + 1);
} else {
$newAxicoId->setCurrentCount(1);
}
$newAxicoId->setNextCount(1);
$this->getAxicoIdFactory()->save($newAxicoId);
$calculation = $this->getCalculationFactory()->findByManufacturerAndCategory($manufacturer, $category);
if ($calculation) {
continue;
}
$this->getCalculationFactory()->createFor(null, $category, $manufacturer);
}
}
}

public function getEntityNames(string $fileName, string $axicoIdColumn, string $nameColumn) {
$workSheet = $this->getSpreadSheetFactory()->getWorkSheet($fileName, 0);
$highestRow = $workSheet->getHighestRow();
$entities = [];
for ($i = 2; $i <= $highestRow; ++$i) {
if (empty($workSheet->getCell($axicoIdColumn . $i)->getValue())) {
continue;
}
$entityAxicoId = $workSheet->getCell($axicoIdColumn . $i)->getValue();
$entityName = $workSheet->getCell($nameColumn . $i)->getValue();
$entities[$entityAxicoId] = $entityName;
}
return $entities;
}

}

+ 216
- 0
modules/custom/arlista/src/Factory/ManufacturerFactory.php Dosyayı Görüntüle

@@ -0,0 +1,216 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\arlista\Entity\SheetSetting;
use Drupal\Component\Datetime\TimeInterface;
use stdClass;

class ManufacturerFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'manufacturer');
}

public function create(): Manufacturer {
return new Manufacturer();
}

protected function insert(AbstractEntity $entity): Manufacturer {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'axico_id_name' => $entity->getAxicoIdName(),
'component_based' => $entity->getComponentBased(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);
if (empty($entity->getSheetSettings())) {
return $entity;
}
$sheetSettings = $entity->getSheetSettings();
foreach ($sheetSettings as $sheetSetting) {
/* @var $sheetSetting SheetSetting */
$sheetSetting->setManufacturerId($entity->getId());
}
$entity->setSheetSettings($sheetSettings);

return $entity;
}

protected function update(AbstractEntity $entity): Manufacturer {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'name' => $entity->getName(),
'status' => $entity->getStatus(),
'sif' => $entity->getSif(),
'axico_id_name' => $entity->getAxicoIdName(),
'component_based' => $entity->getComponentBased(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();
return $entity;
}

public function delete(AbstractEntity $entity) {
parent::delete($entity);

$this->getConnection()
->update($this::TABLE_PREFIX . 'sheet_setting')
->fields(['manufacturer_id' => 0])
->condition('manufacturer_id', $entity->getId())
->execute();
}

protected function load(stdClass $data): Manufacturer {
$entity = $this->create();
$entity->setId($data->id);
$entity->setName($data->name);
$entity->setAxicoIdName($data->axico_id_name);
$entity->setComponentBased($data->component_based);
$entity->setStatus($data->status);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);
$entity->setSif($data->sif);

return $entity;
}

public function importAll(array $data): array {
foreach ($data as $key => $manufacturerData) {
$entity = $this->create();
$manufacturerName = $this->getManufacturerNameByAxicoId($manufacturerData['axico_id']);
$entity->setName($manufacturerName ? $manufacturerName : $manufacturerData['axico_id']);
$entity->setAxicoIdName($manufacturerData['axico_id']);
$entity->setComponentBased($manufacturerData['component_based']);
$entity->setStatus(0);
$entity->setSif(0);
$data[$key]['manufacturer'] = $this->save($entity);
}

return $data;
}

public function importAllFromComponentData(array $data): array {
foreach ($data as $key => $value) {
$items = $this->import($value['table_name']);
foreach ($items as $item) {
$axicoId = $item->cikkszam;
$manufacturerAxicoId = substr($axicoId, 0, 3);
/* @var $entity Manufacturer */
$entity = $this->findByAxicoIdName($manufacturerAxicoId);
if (empty($entity)) {
$entity = $this->create();
$manufacturerName = $this->getManufacturerNameByAxicoId($manufacturerAxicoId);
$entity->setName($manufacturerName ? $manufacturerName : $manufacturerAxicoId);
$entity->setAxicoIdName($manufacturerAxicoId);
$entity->setComponentBased(1);
$entity->setStatus(Status::PASSIVE);
$entity->setSif(0);
$entity = $this->save($entity);
}
$data[$key]['manufacturers'][$entity->getId()] = $entity;
$componentAxicoId = substr($axicoId, 3, 3);
if (strpos($manufacturerAxicoId, 'SUP') !== false) {
$data[$key]['categories'][$entity->getId()][$componentAxicoId] = $componentAxicoId;
} else {
$data[$key]['components'][$entity->getId()][$componentAxicoId] = $componentAxicoId;
}
}
}
return $data;
}

public function importAllFromProductData(array $data): array {
/* @var $product Product */
foreach ($data['products'] as $product) {
$axicoId = $product->getAxicoId();
$manufacturerAxicoId = substr($axicoId, 0, 3);
$entity = $this->findByAxicoIdName($manufacturerAxicoId);
if (empty($entity)) {
$data['manufacturer_created'][$manufacturerAxicoId] = $manufacturerAxicoId;
} else {
$data['manufacturer_found'][$manufacturerAxicoId] = $manufacturerAxicoId;
}
}
if (!empty($data['manufacturer_created'])) {
foreach ($data['manufacturer_created'] as $key => $manufacturerAxicoId) {
$entity = $this->create();
$entity->setName($manufacturerAxicoId);
$entity->setAxicoIdName($manufacturerAxicoId);
$entity->setComponentBased(0);
$entity->setStatus(Status::PASSIVE);
$entity->setSif(0);
$entity = $this->save($entity);
}
}
return $data;
}

public function findByAxicoIdName(string $axicoIdName): ?Manufacturer {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.axico_id_name', $axicoIdName)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return null;
}
return $this->load($data);
}

public function findByAxicoIdNameAndComponentBased(string $axicoIdName, int $componentBased): ?Manufacturer {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.axico_id_name', $axicoIdName)
->condition('w.component_based', $componentBased)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return null;
}
return $this->load($data);
}

public function getComponentManufacturerIds() {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.component_based', 1)
->isNull('w.deleted_at')
->execute()
->fetchAll();
$ids = [];
if (empty($data)) {
return $ids;
}
foreach ($data as $item) {
$ids[] = $item->id;
}
return $ids;
}

}

+ 1400
- 0
modules/custom/arlista/src/Factory/ProductFactory.php
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle


+ 196
- 0
modules/custom/arlista/src/Factory/SheetSettingFactory.php Dosyayı Görüntüle

@@ -0,0 +1,196 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\Core\Database\Connection;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\arlista\Entity\SheetSetting;
use stdClass;

class SheetSettingFactory extends AbstractFactory {

public function __construct(Connection $connection, AccountInterface $currentUser,
TimeInterface $time) {
parent::__construct($connection, $currentUser, $time, 'sheet_setting');
}

public function findSettingBySheetIndex(int $mid, int $index): SheetSetting {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.manufacturer_id', $mid)
->condition('w.index', $index)
->isNull('w.deleted_at')
->execute()
->fetchObject();

if (empty($data)) {
return $this->findDefaultSheetSetting($mid);
}

return $this->load($data);
}

public function findSheetSettingsByManufacturerId(int $manufacturer_id, string $orderBy = 'index', string $orderDirection = 'ASC'): array {
$list = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->isNull('w.deleted_at')
->condition('w.manufacturer_id', $manufacturer_id)
->orderBy($orderBy, $orderDirection)
->execute();

$entities = [];
foreach ($list as $item) {
$entities[$item->index] = $this->load($item);
}

return $entities;
}

public function findDefaultSheetSetting(int $mid): SheetSetting {
$data = $this->getConnection()
->select($this->getActiveTable(), 'w')
->fields('w')
->condition('w.manufacturer_id', $mid)
->condition('w.default_setting', 1)
->isNull('w.deleted_at')
->execute()
->fetchObject();
if (empty($data)) {
return $this->create();
}
$data->id = null;
$data->name = null;
$data->default_setting = 0;
return $this->load($data);
}

public function create(): SheetSetting {
return new SheetSetting();
}

private function clearDefaultSettingOnOtherEntities(int $mid, int $id): void {
$sheetSettings = $this->findSheetSettingsByManufacturerId($mid);
if (count($sheetSettings) > 1) {
foreach ($sheetSettings as $sheetSetting) {
if ($sheetSetting->getId() !== $id) {
$sheetSetting->setDefaultSetting(0);
$this->update($sheetSetting);
}
}
}
}

protected function insert(AbstractEntity $entity): SheetSetting {
$id = $this->getConnection()
->insert($this->getActiveTable())
->fields([
'manufacturer_id' => $entity->getManufacturerId(),
'index' => $entity->getIndex(),
'name' => $entity->getName(),
'product_name' => $entity->getProductName(),
'product_axico_name' => $entity->getProductAxicoName(),
'product_fabric_name' => $entity->getProductFabricName(),
'product_fabric_id' => $entity->getProductFabricId(),
'product_ean' => $entity->getProductEan(),
'product_warranty' => $entity->getProductWarranty(),
'product_eol' => $entity->getProductEol(),
'product_notes' => $entity->getProductNotes(),
'product_description' => $entity->getProductDescription(),
'product_category' => $entity->getProductCategory(),
'product_price' => $entity->getProductPrice(),
'currency' => $entity->getCurrency(),
'product_vtsz' => $entity->getProductVtsz(),
'filterable' => $entity->getFilterable(),
'filterable_remarks' => $entity->getFilterableRemarks(),
'default_setting' => $entity->getDefaultSetting(),
'status' => $entity->getStatus(),
'created_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'created_by' => $this->getCurrentUser()->id()
])
->execute();

$entity->setId($id);

if ($entity->isDefaultSetting()) {
$this->clearDefaultSettingOnOtherEntities($entity->getManufacturerId(), $entity->getId());
}

return $entity;
}

protected function update(AbstractEntity $entity): SheetSetting {
$this->getConnection()
->update($this->getActiveTable())
->fields([
'manufacturer_id' => $entity->getManufacturerId(),
'index' => $entity->getIndex(),
'name' => $entity->getName(),
'product_name' => $entity->getProductName(),
'product_axico_name' => $entity->getProductAxicoName(),
'product_fabric_name' => $entity->getProductFabricName(),
'product_fabric_id' => $entity->getProductFabricId(),
'product_ean' => $entity->getProductEan(),
'product_eol' => $entity->getProductEol(),
'product_warranty' => $entity->getProductWarranty(),
'product_notes' => $entity->getProductNotes(),
'product_description' => $entity->getProductDescription(),
'product_category' => $entity->getProductCategory(),
'product_price' => $entity->getProductPrice(),
'currency' => $entity->getCurrency(),
'product_vtsz' => $entity->getProductVtsz(),
'filterable' => $entity->getFilterable(),
'filterable_remarks' => $entity->getFilterableRemarks(),
'default_setting' => $entity->getDefaultSetting(),
'status' => $entity->getStatus(),
'modified_at' => date('Y-m-d H:i:s', $this->getTime()->getRequestTime()),
'modified_by' => $this->getCurrentUser()->id()
])
->condition('id', $entity->getId())
->execute();

if ($entity->isDefaultSetting()) {
$this->clearDefaultSettingOnOtherEntities($entity->getManufacturerId(), $entity->getId());
}

return $entity;
}

protected function load(stdClass $data): SheetSetting {

$entity = $this->create();

$entity->setId($data->id);
$entity->setManufacturerId($data->manufacturer_id);
$entity->setIndex($data->index);
$entity->setName($data->name);
$entity->setStatus($data->status);
$entity->setCreatedAt($data->created_at);
$entity->setCreatedBy($data->created_by);
$entity->setModifiedAt($data->modified_at);
$entity->setModifiedBy($data->modified_by);
$entity->setDeletedAt($data->deleted_at);
$entity->setProductName($data->product_name);
$entity->setProductAxicoName($data->product_axico_name);
$entity->setProductFabricName($data->product_fabric_name);
$entity->setProductFabricId($data->product_fabric_id);
$entity->setProductEan($data->product_ean);
$entity->setProductWarranty($data->product_warranty);
$entity->setProductEol($data->product_eol);
$entity->setProductNotes($data->product_notes);
$entity->setProductDescription($data->product_description);
$entity->setProductCategory($data->product_category);
$entity->setProductPrice($data->product_price);
$entity->setCurrency($data->currency);
$entity->setProductVtsz($data->product_vtsz);
$entity->setFilterable($data->filterable);
$entity->setFilterableRemarks($data->filterable_remarks);
$entity->setDefaultSetting($data->default_setting);

return $entity;
}

}

+ 464
- 0
modules/custom/arlista/src/Factory/SpreadSheetFactory.php Dosyayı Görüntüle

@@ -0,0 +1,464 @@
<?php

namespace Drupal\arlista\Factory;

use Drupal\arlista\Factory\AbstractSpreadSheetFactory;
use Drupal\arlista\Factory\ComponentFactory;
use Drupal\arlista\Factory\ManufacturerFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Drupal\arlista\Entity\SheetSetting;
use Drupal\arlista\Entity\Product;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Status;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\PackingMaterial;
use Drupal\arlista\Entity\MeasureUnit;
use Drupal\arlista\Factory\CategoryFactory;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class SpreadSheetFactory extends AbstractSpreadSheetFactory {

private $componentFactory;
private $manufacturerFactory;
private $categoryFactory;
private $manufacturer;
private ?Category $category = null;
private ?Component $component = null;

/**
* Class constructor.
*/
public function __construct(ComponentFactory $componentFactory,
ManufacturerFactory $manufacturerFactory, CategoryFactory $categoryFactory) {
$this->componentFactory = $componentFactory;
$this->manufacturerFactory = $manufacturerFactory;
$this->categoryFactory = $categoryFactory;
}

public function getComponentFactory(): ComponentFactory {
return $this->componentFactory;
}

public function getManufacturerFactory(): ManufacturerFactory {
return $this->manufacturerFactory;
}

public function getCategoryFactory(): CategoryFactory {
return $this->categoryFactory;
}

public function getComponent(): ?Component {
return $this->component;
}

public function setComponent(Component $component): void {
$this->component = $component;
}

public function getCategory(): ?Category {
return $this->category;
}

public function setCategory(Category $category): void {
$this->category = $category;
}

public function extractDataFromSpreadSheet(Spreadsheet $spreadSheet, array $sheetSettings): array {

if (empty($spreadSheet)) {
return [];
}
$result = [];
$worksheetCount = $spreadSheet->getSheetCount();
if ($worksheetCount < 1) {
return $result;
}


for ($i = 0; $i < $worksheetCount; $i++) {
$sheetSetting = $this->getSheetSettingByIndex($sheetSettings, $i);
if (empty($sheetSetting)) {
continue;
}
$result = $this->loadProductsOfWorkSheet($result,
$this->loadWorkSheetBySheetIndex($spreadSheet, $i), $sheetSetting);
}

return $result;
}

private function getSheetSettingByIndex(array $sheetSettings, int $index): ?SheetSetting {
foreach ($sheetSettings as $sheetSetting) {
if ($sheetSetting->getIndex() == $index) {
return $sheetSetting;
}
}
return null;
}

public function loadWorkSheetBySheetIndex(Spreadsheet $spreadSheet, int $index): Worksheet {
return $spreadSheet->getSheet($index);
}

public function loadProductsOfWorkSheet(array $result, Worksheet $workSheet, SheetSetting $sheetSetting): array {
$result['extracted'][$sheetSetting->getIndex()]['workSheetName'] = empty($workSheet->getTitle()) ? $sheetSetting->getIndex() : $workSheet->getTitle();
$result['extracted'][$sheetSetting->getIndex()]['products'] = [];

$highestRow = $workSheet->getHighestRow();
if (empty($highestRow)) {
$result['extracted'][$sheetSetting->getIndex()]['empty'] = true;
return $result;
}

for ($i = 1; $i <= $highestRow; ++$i) {
$product = new Product();
$product->setName($workSheet->getCell($sheetSetting->getProductName() . $i)->getValue());
$product->setFabricName($workSheet->getCell($sheetSetting->getProductFabricName() . $i)->getValue());
$product->setAxicoName($sheetSetting->findProductAxicoName($workSheet, $i));
$product->setFabricId($workSheet->getCell($sheetSetting->getProductFabricId() . $i)->getValue());
$product->setPrice((float) ($workSheet->getCell($sheetSetting->getProductPrice() . $i)->getValue()));
$product->setNotes($workSheet->getCell($sheetSetting->getProductNotes() . $i)->getValue());
$product->setDescription($workSheet->getCell($sheetSetting->getProductDescription() . $i)->getValue());
$product->setWarranty($workSheet->getCell($sheetSetting->getProductWarranty() . $i)->getValue());
$product->setVtsz($workSheet->getCell($sheetSetting->getProductVtsz() . $i)->getValue());
$product->setEan($workSheet->getCell($sheetSetting->getProductEan() . $i)->getValue());
$product->setEol($workSheet->getCell($sheetSetting->getProductEol() . $i)->getValue());

if ($product->isProduct()) {
/*
* Caution :
* This data is subject to change, be advised :
* - axico id and product categorising process might overwrite this data
*/
$product->setParentManufacturerId($sheetSetting->getManufacturerId());
$product->setCurrency($sheetSetting->getCurrency());
$product->setUploadedFileId($this->getUploadedFileid());
$product->setSheetIndex($sheetSetting->getIndex());
$product->setCorrectStatus(Status::ISMERETLEN);
$product->setPriceChanged(Status::PASSIVE);
$product->setPackingMaterial(PackingMaterial::UNKNOWN);
$product->setMeasureUnit(MeasureUnit::PIECE);
$product->setWidth(0.00);
$product->setLength(0.00);
$product->setHeight(0.00);
$product->setWeight(0.00);
$product->setPurchasePrice(0);
$product->setListPrice(0);
$product->setPriceDOne(0.00);
$product->setPriceDTwo(0.00);
$product->setPriceSpec(0.00);
$product->setPriceVSpec(0.00);
$product->setPriceDevDOne(0.00);
$product->setPriceDevDTwo(0.00);
$product->setPriceDevSpec(0.00);
$product->setPriceDevVSpec(0.00);

$product = $this->findWarrantyData($product);

$product->setPrevAxicoName(!empty($product->getAxicoName()) ? $product->getAxicoName() : '');
$product->setPrevDescription(!empty($product->getDescription()) ? $product->getDescription() : '');
$product->setPrevEol(!empty($product->getEol()) ? $product->getEol() : '');
$product->setPrevFabricName(!empty($product->getFabricName()) ? $product->getFabricName() : '');
$product->setPrevNotes(!empty($product->getNotes()) ? $product->getNotes() : '');
$product->setPrevPrice(!empty($product->getPrice()) ? $product->getPrice() : 0.00);

$result['extracted'][$sheetSetting->getIndex()]['products'][$i] = $product;
}
}

if (isset($result['totalProducts'])) {
$result['totalProducts'] = $result['totalProducts'] + count($result['extracted'][$sheetSetting->getIndex()]['products']);
} else {
$result['totalProducts'] = count($result['extracted'][$sheetSetting->getIndex()]['products']);
}

return $result;
}

private function findWarrantyData(Product $product): Product {
if (empty($product->getWarranty())) {
$product->setWarranty(60);
$product->setPrevWarranty(60);
return $product;
}
$product->setPrevWarranty($product->getWarranty());
return $product;
}

public function getManufacturer(): ?Manufacturer {
return $this->manufacturer;
}

public function setManufacturer(Manufacturer $manufacturer): void {
$this->manufacturer = $manufacturer;
}

public function switchManufacturers(int $manufacturerId): void {
if (empty($this->getManufacturer())) {
$this->setManufacturer($this->getManufacturerFactory()->find($manufacturerId));
return;
}
if ($this->getManufacturer()->getId() === $manufacturerId) {
return;
}
$this->setManufacturer($this->getManufacturerFactory()->find($manufacturerId));
}

public function switchCategories(int $categoryId): void {
if (empty($this->getCategory())) {
$this->setCategory($this->getCategoryFactory()->find($categoryId));
return;
}
if ($this->getCategory()->getId() === $categoryId) {
return;
}
$this->setCategory($this->getCategoryFactory()->find($categoryId));
}

public function switchComponents(int $componentId): void {
if (empty($this->getComponent())) {
$this->setComponent($this->getComponentFactory()->find($componentId));
return;
}
if ($this->getComponent()->getId() === $componentId) {
return;
}
$this->setComponent($this->getComponentFactory()->find($componentId));
}

/**
* Get new files column names.
*
* The new file that will be generated can have only
* these column names.
*
* @return object
* Returns an object of std class with props 'A1'=>'Correctbe' ...
*/
public function getColumnNames() {
return (object) [
'columnNames' => [
'A1' => 'Correctbe',
'B1' => 'Gyártó',
'C1' => 'Gyártó cikkszám',
'D1' => 'Gyártó megnevezés',
'E1' => 'EAN',
'F1' => 'Vámtarifaszám',
'G1' => 'Axico cikkszám',
'H1' => 'Axico megnevezés',
'I1' => 'Garancia',
'J1' => 'Lista nettó',
'K1' => 'D2',
'L1' => 'D1',
'M1' => 'Spec',
'N1' => 'Vsp',
'O1' => 'Dev. D2',
'P1' => 'Dev. D1',
'Q1' => 'Dev. SP',
'R1' => 'Dev. VSP',
'S1' => 'Mértékegység',
'T1' => 'Beszerzési ár',
'U1' => 'Bekerülési ár',
'V1' => 'Devizanem',
'W1' => 'Webcsoport',
'X1' => 'Főcsoport',
'Y1' => 'Csoport kód',
'Z1' => 'Megjegyzés',
'AA1' => 'Árlistába',
'AB1' => 'B2B',
'AC1' => 'DFS',
'AD1' => 'OMB',
'AE1' => 'MilcS',
'AF1' => 'BBX',
'AG1' => 'SMC',
'AH1' => 'Terméksúly',
'AI1' => 'Cs. műanyag',
'AJ1' => 'Cs. papír',
'AK1' => 'Cs. fa',
'AL1' => 'Szélesség',
'AM1' => 'Hosszúság',
'AN1' => 'Magasság',
]
];
}

/**
* Add rows to excel file.
*
* @param $spreadSheet
* The spreadSheet.
* @param array $products
* The products
* @param string $manufacturer_name
* The manufacturers name.
* @param array $columns
* The column names.
* @param array $settings
* The manufacturers column settings if differs from default.
*
* @return mixed
*/
public function populateSpreadSheetCells(Spreadsheet $spreadSheet, array $products, string $manufacturerName, array $columns) {

foreach ($columns as $cell => $value) {
$spreadSheet = $this->fillColumnNames($spreadSheet, $cell, $value);
}

$i = 4;
/* @var $product Product */
foreach ($products as $product) {
$spreadSheet = $this->fillRow($spreadSheet, $i, $product);
$i++;
}


$spreadSheet->getProperties()
->setCreator("Correct Files Online")
->setLastModifiedBy("-")
->setTitle($manufacturerName . ' ' . date('d-m-Y', time()) . 'pricelist')
->setSubject("Products for Correct")
->setDescription("Automatically generated pricelist to update Correct database")
->setKeywords("correct drupal office 2007 openxml php")
->setCategory("Pricelist");

foreach ($columns as $key => $value) {
$spreadSheet->getActiveSheet()->getColumnDimension(str_replace('1', '', $key))->setAutoSize(true);
}

return $spreadSheet;
}

/**
* Fill column names
*
* @param $spreadSheet SpreadSheet
* @param string $cell
* @param string $value
*
* @return void
*/
private function fillColumnNames(SpreadSheet $spreadSheet, string $cell, string $value): SpreadSheet {
$spreadSheet->getActiveSheet()->getCell($cell)->setValue($value);
return $spreadSheet;
}

/**
* Fill excel row with data
*
* @param $spreadSheet SpreadSheet
* @param int $i
* @param $product Product
*
* @return SpreadSheet
*/
private function fillRow(SpreadSheet $spreadSheet, int $rowNum, Product $product): Spreadsheet {
$this->switchManufacturers($product->getParentManufacturerId());
if ($product->isComponentBased()) {
$this->switchComponents($product->getParentComponentId());
} else {
$this->switchCategories($product->getParentCategoryId());
}

$cellValuesByColumnNames = $this->getCellValuesByColumnNames($product);
foreach ($cellValuesByColumnNames as $key => $value) {
$spreadSheet->getActiveSheet()->getCell($key . $rowNum)->setValue($value);
}
// * EAN
$spreadSheet->getActiveSheet()->setCellValueExplicit('E' . $rowNum, (string) $product->getEan(), DataType::TYPE_STRING);

return $spreadSheet;
}

public function getCellValuesByColumnNames(Product $product): array {
return [
// CORRECT
'A' => $product->getStatus(),
// MANUFACTURER SIF
'B' => $product->isComponentBased() ? $this->getComponent()->getSif() : $this->getManufacturer()->getSif(),
// * FABRIC ID
'C' => $product->getFabricId(),
// * FABRIC NAME
'D' => $product->getFabricName(),
// * VTSZ
'F' => $product->getVtsz(),
// * AXICO ID
'G' => $product->getAxicoId(),
// * AXICO NAME
'H' => $product->getAxicoName(),
// * WARRANTY
'I' => $product->getWarranty() || $product->getWarranty() === 0 ? $product->getWarranty() : 60,
// * LIST PRICE
'J' => $product->getListPrice(),
// * PRICE D2
'K' => $product->getPriceDTwo(),
// * PRICE D1
'L' => $product->getPriceDOne(),
// * PRICE SP
'M' => $product->getPriceSpec(),
// * VSP
'N' => $product->getPriceVSpec(),
// * DEV D2
'O' => $product->getPriceDevDTwo(),
// * DEV D1
'P' => $product->getPriceDevDOne(),
// * DEV SP
'Q' => $product->getPriceDevSpec(),
// * DEV VSP
'R' => $product->getPriceDevVSpec(),
// * MEASURE UNIT
'S' => $product->getMeasureUnit() === MeasureUnit::UNDEFINED ? MeasureUnit::PIECE : $product->getMeasureUnit(),
// * PRICE
'T' => $product->getPrice(),
// * PURCHASE PRICE - BEKERULESI AR
'U' => $product->getPurchasePrice(),
// * CURRENCY
'V' => $product->getCurrency(),
// * WEBGROUP
'W' => 0,
// * MAINGROUP
'X' => $product->isComponentBased() ? $this->getComponent()->getAxicoIdName() : $this->getCategory()->getAxicoIdName(),
// * GROUP
'Y' => $product->isComponentBased() ? $this->getComponent()->getName() : $this->getCategory()->getName(),
// *NOTES
'Z' => $product->getNotes() . ' - ' . $product->getDescription(),
// ARLISTABA/WEBRE
'AA' => $product->getListed() ? 'T' : 'F',
// B2B
'AB' => 'F',
// DFS
'AC' => 'F',
// OMB
'AD' => 'F',
// MilcS
'AF' => 'F',
// BBX
'AF' => $this->getManufacturer()->isAxicoIdNameSameAs('BBX') ? 'T' : 'F',
// SMC
'AG' => $this->getManufacturer()->isAxicoIdNameSameAs('SUP') && $this->getManufacturer()->isComponentBased() ? 'T' : 'F',
// * WEIGHT
'AH' => $product->getWeight(),
// PACKAGING MATERIAL PLASTIC
'AI' => $product->getPackingMaterial() === PackingMaterial::PLASTIC ? 1 : 0,
// PACKAGING MATERIAL PAPER
'AJ' => $product->getPackingMaterial() === PackingMaterial::PAPER ? 1 : 0,
// PACKAGING MATERIAL WOOD
'AK' => $product->getPackingMaterial() === PackingMaterial::WOOD ? 1 : 0,
// width
'AL' => $product->getWidth(),
// length
'AM' => $product->getLength(),
// height
'AN' => $product->getHeight(),
];
}

public function getWorkSheet(string $fileName, int $index): Worksheet {
$moduleHandler = \Drupal::service('module_handler');
$modulePath = $moduleHandler->getModule('arlista')->getPath();
$spreadSheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($modulePath . '/' . $fileName);
return $spreadSheet->getSheet($index);
}

}

+ 107
- 0
modules/custom/arlista/src/Form/AbstractConfirmForm.php Dosyayı Görüntüle

@@ -0,0 +1,107 @@
<?php

namespace Drupal\arlista\Form;

use Drupal\arlista\Service\CacheService;
use Drupal\arlista\Factory\CategoryFactory;
use Drupal\arlista\Factory\ComponentFactory;
use Drupal\Core\Form\ConfirmFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\arlista\Factory\FileFactory;
use Drupal\arlista\Factory\ManufacturerFactory;
use Drupal\arlista\Factory\SheetSettingFactory;
use Drupal\arlista\Factory\ProductFactory;
use Drupal\arlista\Factory\InstallFactory;

abstract class AbstractConfirmForm extends ConfirmFormBase {

private $categoryFactory;
private $componentFactory;
private $fileFactory;
private $manufacturerFactory;
private $sheetSettingFactory;
private $cacheService;
private $productFactory;
private $installFactory;

/**
* Class constructor.
*/
public function __construct(ComponentFactory $componentFactory, CategoryFactory $categoryFactory,
FileFactory $fileFactory, ManufacturerFactory $manufacturerFactory,
SheetSettingFactory $SheetSettingFactory, CacheService $cacheService, ProductFactory $productFactory, InstallFactory $installFactory) {
$this->componentFactory = $componentFactory;
$this->categoryFactory = $categoryFactory;
$this->fileFactory = $fileFactory;
$this->manufacturerFactory = $manufacturerFactory;
$this->sheetSettingFactory = $SheetSettingFactory;
$this->cacheService = $cacheService;
$this->productFactory = $productFactory;
$this->installFactory = $installFactory;
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('arlista.component.factory'),
$container->get('arlista.category.factory'),
$container->get('arlista.file.factory'),
$container->get('arlista.manufacturer.factory'),
$container->get('arlista.sheet-setting.factory'),
$container->get('arlista.cache-service'),
$container->get('arlista.product.factory'),
$container->get('arlista.install.factory')
);
}

public function getCategoryFactory(): CategoryFactory {
return $this->categoryFactory;
}

public function getComponentFactory(): ComponentFactory {
return $this->componentFactory;
}

public function getManufacturerFactory(): ManufacturerFactory {
return $this->manufacturerFactory;
}

public function getFileFactory(): FileFactory {
return $this->fileFactory;
}

public function getSheetSettingFactory(): SheetSettingFactory {
return $this->sheetSettingFactory;
}

public function getCacheService(): CacheService {
return $this->cacheService;
}

public function getProductFactory(): ProductFactory {
return $this->productFactory;
}
public function getInstallFactory(): InstallFactory {
return $this->installFactory;
}

protected function addMessage(string $message = null): void {
if (empty($message)) {
\Drupal::messenger()->addStatus('Sikeres törlés!');
return;
}
\Drupal::messenger()->addStatus($message);
}

public function resetEachFormByManufacturerId(array $formIds, int $id) {
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($id);
foreach ($sheetSettings as $item) {
foreach ($formIds as $formId) {
$this->getCacheService()->resetCache([$formId, $id, $item->getIndex()]);
}
}
}

}

+ 268
- 0
modules/custom/arlista/src/Form/ArlistaAbstractForm.php Dosyayı Görüntüle

@@ -0,0 +1,268 @@
<?php

/**
* @file
* The base form for other forms
*/

namespace Drupal\arlista\Form;

use Drupal\arlista\Service\CacheService;
use Drupal\arlista\Factory\CategoryFactory;
use Drupal\arlista\Factory\ComponentFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\arlista\Factory\FileFactory;
use Drupal\arlista\Factory\AxicoIdFactory;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Factory\ManufacturerFactory;
use Drupal\arlista\Factory\SheetSettingFactory;
use Drupal\arlista\Entity\AbstractEntity;
use Drupal\arlista\Factory\ProductFactory;
use Drupal\arlista\Factory\SpreadSheetFactory;
use Drupal\arlista\Factory\CalculationFactory;
use Drupal\arlista\Factory\EnabledGroupFactory;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Manufacturer;

/**
* The base form class for other form classes
*/
abstract class ArlistaAbstractForm extends FormBase {

private $categoryFactory;
private $componentFactory;
private $fileFactory;
private $manufacturerFactory;
private $sheetSettingFactory;
private $cacheService;
private $axicoIdFactory;
private $productFactory;
private $spreadSheetFactory;
private $calculationFactory;
private $enabledGroupFactory;
private $config;

public function __construct(ComponentFactory $componentFactory, CategoryFactory $categoryFactory,
FileFactory $fileFactory, ManufacturerFactory $manufacturerFactory,
SheetSettingFactory $SheetSettingFactory, CacheService $cacheService,
AxicoIdFactory $axicoIdFactory, ProductFactory $productFactory,
SpreadSheetFactory $spreadSheetFactory, CalculationFactory $calculationFactory,
EnabledGroupFactory $enabledGroupFactory) {
$this->componentFactory = $componentFactory;
$this->categoryFactory = $categoryFactory;
$this->fileFactory = $fileFactory;
$this->manufacturerFactory = $manufacturerFactory;
$this->sheetSettingFactory = $SheetSettingFactory;
$this->cacheService = $cacheService;
$this->axicoIdFactory = $axicoIdFactory;
$this->productFactory = $productFactory;
$this->spreadSheetFactory = $spreadSheetFactory;
$this->calculationFactory = $calculationFactory;
$this->enabledGroupFactory = $enabledGroupFactory;
$this->config = \Drupal::config('arlista.settings');
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {

return new static(
$container->get('arlista.component.factory'),
$container->get('arlista.category.factory'),
$container->get('arlista.file.factory'),
$container->get('arlista.manufacturer.factory'),
$container->get('arlista.sheet-setting.factory'),
$container->get('arlista.cache-service'),
$container->get('arlista.axico-id.factory'),
$container->get('arlista.product.factory'),
$container->get('arlista.spread-sheet.factory'),
$container->get('arlista.calculation.factory'),
$container->get('arlista.enabled-group.factory'),
);
}

public function validateForm(array &$form, FormStateInterface $form_state) {
}

public function getQueryValue($queryParam) {
return \Drupal::request()->query->get($queryParam);
}

public function getNoDataAvailable(string $message): string {
if (!empty($message)) {
return $message;
}
return 'Nincs adat';
}

public function getCategoryFactory(): CategoryFactory {
return $this->categoryFactory;
}

public function getComponentFactory(): ComponentFactory {
return $this->componentFactory;
}

public function getFileFactory(): FileFactory {
return $this->fileFactory;
}

public function getManufacturerFactory(): ManufacturerFactory {
return $this->manufacturerFactory;
}

public function getSheetSettingFactory(): SheetSettingFactory {
return $this->sheetSettingFactory;
}

public function getCacheService(): CacheService {
return $this->cacheService;
}

public function getAxicoIdFactory(): AxicoIdFactory {
return $this->axicoIdFactory;
}

public function getProductFactory(): ProductFactory {
return $this->productFactory;
}

public function getSpreadSheetFactory(): SpreadSheetFactory {
return $this->spreadSheetFactory;
}

public function getCalculationFactory(): CalculationFactory {
return $this->calculationFactory;
}

public function getEnabledGroupFactory(): EnabledGroupFactory {
return $this->enabledGroupFactory;
}

public function getConfig(): ImmutableConfig {
return $this->config;
}

public function getNameField(array $form, AbstractEntity $entity, int $weight): array {
$form['name'] = [
'#title' => 'Név',
'#required' => true,
'#max' => 32,
'#type' => 'textfield',
'#default_value' => $entity->getName(),
'#weight' => $weight,
];
return $form;
}

public function getSifField(array $form, AbstractEntity $entity, int $weight): array {
$form['sif'] = [
'#title' => 'Correct azonosító',
'#type' => 'textfield',
'#required' => true,
'#max' => 32,
'#default_value' => $entity->getSif(),
'#weight' => $weight
];
return $form;
}

public function getDeleteButton(AbstractEntity $entity, bool $showName = true): array {
return [
'#type' => 'submit',
'#disabled' => $entity->isNew(),
'#submit' => [
'::deleteEntity',
],
'#value' => $showName ? $entity->getName() . ' - törlése' : 'Törlés',
'#limit_validation_errors' => [],
'#attributes' => [
'class' => ['btn-default']]
];
}

public function getDeactivateButton(AbstractEntity $entity, bool $showName = true): array {
return [
'#type' => 'submit',
'#disabled' => $entity->isNew(),
'#submit' => [
'::deactivateEntity',
],
'#value' => $showName ? $entity->getName() . ' - passzivvá tétele' : 'Passziválás',
'#limit_validation_errors' => [],
];
}

public function getReactivateButton(AbstractEntity $entity, bool $showName = true): array {
return [
'#type' => 'submit',
'#disabled' => $entity->isNew(),
'#submit' => [
'::reactivateEntity',
],
'#value' => $showName ? $entity->getName() . ' - aktívvá tétele' : 'Aktiválás',
'#limit_validation_errors' => [],
];
}

public function getSelectOptions(array $selectSettings, array $selectables, AbstractEntity $entity) {
$options = [];
$options[0] = 'Kérem válasszon';

foreach ($selectables as $selectable) {
if ($selectable->getStatus() === 1) {
$options[$selectable->getId()] = $selectable->getName();
}
}

$defaultValue = '';
if ($selectSettings['name'] === 'category') {
$defaultValue = $entity->getParentCategoryId() ? $entity->getParentCategoryId() : 0;
} elseif ($selectSettings['name'] === 'component') {
$defaultValue = $entity->getParentComponentId();
} elseif ($selectSettings['name'] === 'manufacturer' || $selectSettings['name'] === 'parent_manufacturer_id') {
$defaultValue = $entity->getParentManufacturerId();
} elseif ($selectSettings['name'] === 'parent_category_id') {
$defaultValue = $entity->getParentId();
}

return [
'#title' => $selectSettings['title'],
'#name' => $selectSettings['name'],
'#type' => 'select',
'#options' => $options,
'#id' => $selectSettings['name'] . '_select',
'#default_value' => [$defaultValue]
];
}

public function getComponentManufacturersList(array $components, bool $setComponentName = null): array {
$list = [];
$list = [0 => 'Kérem válasszon'];
$manufacturers = $this->getManufacturerFactory()->findAll('name', 'ASC');
/* @var $component Component */
foreach ($components as $component) {
/* @var $manufacturer Manufacturer */
foreach ($manufacturers as $manufacturer) {
$list = $this->addToList($list, $component, $manufacturer, $setComponentName);
}
}

return $list;
}

public function addToList(array $list, Component $component, Manufacturer $manufacturer, bool $setComponentName = null): array {
if ($component->getParentManufacturerId() === $manufacturer->getId()) {
$list[$component->getId()] = '(' . $manufacturer->getAxicoIdName() . ') ' . $manufacturer->getName();
if ($setComponentName) {
$list[$component->getId()] = $list[$component->getId()] . $component->getName();
}
}
return $list;
}

}

+ 487
- 0
modules/custom/arlista/src/Form/Calculation/CalculationEdit.php Dosyayı Görüntüle

@@ -0,0 +1,487 @@
<?php

namespace Drupal\arlista\Form\Calculation;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Calculation;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\UploadedFile;
use Drupal\Core\Link;
use Drupal\Core\Url;

class CalculationEdit extends ArlistaAbstractForm {

private $categories;
private $components;
private $mid;

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_manufacturer_calculation_edit_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state,
int $mid = null, int $catId = null, int $cmpId = null) {
/* @var $manufacturer Manufacturer */
$manufacturer = $this->getManufacturerFactory()->find($mid);
$this->mid = $manufacturer->getId();
$axicoIdName = '';
if ($catId) {
/* @var $category Category */
$category = $this->getCategoryFactory()->find($catId);
$manufacturer->setCalculation($this->getCalculationFactory()->findByManufacturerAndCategory($manufacturer, $category));
$axicoIdName = $category->getAxicoIdName();
} else {
/* @var $component Component */
$component = $this->getComponentFactory()->find($cmpId);
$manufacturer->setCalculation($this->getCalculationFactory()->findByComponent($component));
$axicoIdName = $component->getAxicoIdName();
}

$form['items_wrapper']['#prefix'] ='<div class="col-lg-6">';
$form['items_wrapper'][]['calculation_edit']['link_one'] = Link::fromTextAndUrl(
'Vissza',
Url::fromRoute('arlista.manufacturer.calculations.list', [
'mid' => $mid
])
)->toRenderable();
$form['items_wrapper'][]['calculation_edit']['link_one'] = ['#prefix' => '<br>'];
if ($cmpId) {
$form['items_wrapper'][]['calculation_edit']['link_two'] = Link::fromTextAndUrl(
'Vissza a komponens szerkesztéshez',
Url::fromRoute('arlista.component.edit', [
'cmpId' => $cmpId
])
)->toRenderable();
$form['items_wrapper'][]['calculation_edit']['link_two'] = ['#prefix' => '<br>'];
}
$form['items_wrapper'][]['calculation_edit']['link_three'] = Link::fromTextAndUrl(
'Vissza a gyártó szerkesztéshez',
Url::fromRoute('arlista.manufacturer.edit', [
'mid' => $mid
])
)->toRenderable();
$form['items_wrapper'][]['calculation_edit']['link_two'] = ['#prefix' => '<br>'];
$form['items_wrapper']['mid'] = [
'#type' => 'hidden',
'#value' => $mid,
'#prefix' => '<div class="row">'];
$form['items_wrapper']['calcId'] = [
'#type' => 'hidden',
'#value' => $manufacturer->getCalculation()->getid()];
$form['items_wrapper']['name'] = [
'#title' => 'Gyártó név',
'#type' => 'textfield',
'#required' => true,
'#max' => 32,
'#disabled' => true,
'#default_value' => $manufacturer->getName(),
'#prefix' => '<div class="column">'
];
$form['items_wrapper']['axico_id_name'] = [
'#title' => 'Axico cikkszáma',
'#type' => 'textfield',
'#required' => true,
'#disabled' => true,
'#default_value' => $manufacturer->getAxicoIdName(),
];

$form['items_wrapper']['calculation_name'] = [
'#title' => 'Kalkulációs paraméterek neve',
'#type' => 'textfield',
'#required' => true,
'#max' => 32,
'#disabled' => true,
'#default_value' => $manufacturer->getCalculation()->getName() . ' ( ' . $axicoIdName . ' )',
];

$priceFactors = [
'list_price_factor' => [
'title' => 'Lista ár szorzó',
'default_value' => $manufacturer->getCalculation()->getListPriceFactor()
],
'price_factor_d_one' => [
'title' => 'D1 szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDOne()
],
'price_factor_d_two' => [
'title' => 'D2 szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDTwo()
],
'price_factor_spec' => [
'title' => 'Spec szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorSpec()
],
'price_factor_v_spec' => [
'title' => 'VSpec szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorVSpec()
],
'price_factor_dev_d_one' => [
'title' => 'Deviza D1 szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDevDOne()
],
'price_factor_dev_d_two' => [
'title' => 'Deviza D2 szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDevDTwo()
],
'price_factor_dev_spec' => [
'title' => 'Deviza Spec szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDevSpec()
],
'price_factor_dev_v_spec' => [
'title' => 'Deviza VSpec szorzó',
'default_value' => $manufacturer->getCalculation()->getPriceFactorDevVSpec()
],
];
$weight = 100;
foreach ($priceFactors as $key => $value) {
$form['columns'][$key] = [
'#title' => $value['title'],
'#type' => 'number',
'#precision' => 3,
'#scale' => 5,
'#step' => 0.0001,
'#max' => 5,
'#min' => 1,
'#required' => strpos($key, 'dev') > 0 ? false : true,
'#default_value' => $value['default_value'],
'#weight' => $weight,
];
$weight = $weight + 10;
}
$form['columns']['transport_expenses'] = [
'#title' => 'Szállítási költségek szorzó',
'#type' => 'number',
'#precision' => 5,
'#scale' => 20,
'#step' => 0.0001,
'#max' => 5,
'#min' => 1,
'#required' => true,
'#default_value' => $manufacturer->getCalculation()->getTransportExpense(),
];

$statusOptions = [
0 => 'Mentés nem alapértelmezettként',
1 => $manufacturer->isComponentBased() ?
'Mentés alapértelmezettként minden gyártó ilyen cikkszámú komponensére' : 'Mentés alapértelmezettként ezen gyártó minden termékcsoportjára',
2 => 'Alapértelmezettként mentés a kijelölt csoportokra'
];
if ($manufacturer->isComponentBased()) {
$form['columns']['default_status'] = [
'#title' => 'Alapértermezett ' . '( ' . $axicoIdName . ' )' . 'komponens kalkuláció',
'#name' => 'default_status',
'#type' => 'select',
'#options' => $statusOptions,
'#id' => 'default_status_select',
'#default_value' => [$manufacturer->getCalculation()->getDefaultCalculation()],
'#weight' => 1050,];
} else {
$form['columns']['default_status'] = [
'#title' => 'Alapértermezett gyártó kalkuláció',
'#name' => 'default_status',
'#type' => 'select',
'#options' => $statusOptions,
'#id' => 'default_status_select',
'#default_value' => [$manufacturer->getCalculation()->getDefaultCalculation()],
'#weight' => 1050,];
}

if ($manufacturer->isComponentBased()) {
$form = $this->getEnabledComponentsRenderedForm($form);
} else {
$form = $this->getEnabledCategoriesRenderedForm($form);
}

$form['buttons'] = array(
'#type' => 'container',
'#weight' => 1000,
);
$form['buttons']['arlista_manufacturer_calculation_edit_form_submit'] = [
'#type' => 'submit',
'#value' => 'Mentés',
'#attributes' => ['class' => ['btn-success']]];
$form['items_wrapper']['#suffix'] ='</div>';

return $form;
}

public function getEnabledComponentsRenderedForm(array $form): array {
$componentManufacturerIds = $this->getManufacturerFactory()->getComponentManufacturerIds();
$this->components = $this->getComponentFactory()->findAllActiveWhereManufacturerIdIn('name', 'ASC', $componentManufacturerIds);
$enabledGroups = $this->getEnabledGroupFactory()->findAllEnabledGroups(null, true);
$selected = [];
/* @var $enabledGroup EnabledGroup */
foreach ($enabledGroups as $enabledGroup) {
$selected[$enabledGroup->getComponentId()] = $enabledGroup->getComponentId();
}
if (!empty($this->components)) {
$renderableItems = [
'#theme' => 'arlista_component_enable_calculations',
'#components' => $this->components,
'#manufacturerNames' => $this->getComponentManufacturersList($this->components),
'#enabledList' => $selected,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['columns']['components'] = ['#markup' => $renderedList];
$form['columns']['components']['#weight'] = 1100;
}
return $form;
}

public function getEnabledCategoriesRenderedForm(array $form): array {
$this->categories = $this->getCategoryFactory()->findAllActive('name', 'ASC');
$enabledGroups = $this->getEnabledGroupFactory()->findAllEnabledGroups(null, null);
$selected = [];
/* @var $enabledGroup EnabledGroup */
foreach ($enabledGroups as $enabledGroup) {
$selected[$enabledGroup->getCategoryId()] = $enabledGroup->getCategoryId();
}
if (!empty($this->categories)) {
$renderableItems = [
'#theme' => 'arlista_category_enable_calculations',
'#categories' => $this->categories,
'#enabledList' => $selected,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['columns']['categories'] = ['#markup' => $renderedList];
$form['columns']['categories']['#weight'] = 1100;
}
return $form;
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!$this->isDevFactorSetComplete($form_state->getvalues())) {
$message = 'Amennyiben egyik mező értéke adott, a többi értéknek is definiáltnak kell lennie, minimum 1,000 értékkel';
$form_state->setErrorByName('price_factor_dev_d_one', $message);
$form_state->setErrorByName('price_factor_dev_d_two', $message);
$form_state->setErrorByName('price_factor_dev_spec', $message);
$form_state->setErrorByName('price_factor_dev_v_spec', $message);
}
}

private function isDevFactorSetComplete(array $values): bool {
$i = 0;

$values['price_factor_dev_d_one'] > 0 ? $i++ : null;
$values['price_factor_dev_d_two'] > 0 ? $i++ : null;
$values['price_factor_dev_spec'] > 0 ? $i++ : null;
$values['price_factor_dev_v_spec'] > 0 ? $i++ : null;

return $i === 0 || $i === 4;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
/* @var $manufacturer Manufacturer */
$manufacturer = $this->getManufacturerFactory()->find($values['mid']);
/* @var $calculation Calculation */
$calculation = $this->getCalculationFactory()->find($values['calcId']);
$calculation->setListPriceFactor(floatval($values['list_price_factor']));
$calculation->setPriceFactorDOne(floatval($values['price_factor_d_one']));
$calculation->setPriceFactorDTwo(floatval($values['price_factor_d_two']));
$calculation->setPriceFactorSpec(floatval($values['price_factor_spec']));
$calculation->setPriceFactorVSpec(floatval($values['price_factor_v_spec']));
$calculation->setPriceFactorDevDOne($values['price_factor_dev_d_one'] ? floatval($values['price_factor_dev_d_one']) : 0.000);
$calculation->setPriceFactorDevDTwo($values['price_factor_dev_d_two'] ? floatval($values['price_factor_dev_d_two']) : 0.000);
$calculation->setPriceFactorDevSpec($values['price_factor_dev_spec'] ? floatval($values['price_factor_dev_spec']) : 0.000);
$calculation->setPriceFactorDevVSpec($values['price_factor_dev_v_spec'] ? floatval($values['price_factor_dev_v_spec']) : 0.000);
$calculation->setTransportExpense(floatval($values['transport_expenses']));

if ($values['default_status'] == "0") {
/**
* Store only for this group
*/
$calculation->setDefaultCalculation(0);
$calculation = $this->getCalculationFactory()->save($calculation);

if ($calculation->getParentComponentId()) {
$component = $this->getComponentFactory()->find($calculation->getParentComponentId());
$this->updateComponentsEachProductsPrice($component, $calculation);
} else {
$category = $this->getCategoryFactory()->find($calculation->getParentCategoryId());
$this->updateProductPricesByCategoryAndManufacturer($calculation, $category, $manufacturer);
}

\Drupal::messenger()->addStatus($this->t('Nem alapértelmezett kalkuláció sikeres mentése!'));
}
$calculation->setDefaultCalculation(1);
$calculation = $this->getCalculationFactory()->save($calculation);

if ($values['default_status'] == "1") {
/**
* Store data for each existing group
*/
if ($manufacturer->isComponentBased()) {
$this->setDefaultCalulationForOtherManufacturersSimilarComponent($calculation);
} else {
$this->saveForEachCategoryOfThisManufacturer($calculation, $manufacturer);
}
}
if ($values['default_status'] == "2") {
/**
* Store only for selected group/s
*/
if ($manufacturer->isComponentBased()) {
$this->setDefaultCalulationForSelectedComponents($calculation);
} else {
$this->setDefaultCalulationForSelectedCategories($calculation, $manufacturer);
}
}
}

/**
* Selected categories of selected manufacturer
*
* @param Calculation $calculation
* @param Manufacturer $manufacturer
* @return void
*/
public function setDefaultCalulationForSelectedCategories(Calculation $calculation, Manufacturer $manufacturer): void {
$calculationIsEnabledFor = [];
foreach ($_POST as $key => $value) {
if (preg_match('/^enable_category_calculation_*/', $key)) {
$id = (int) explode("_", $key)[3];
if (!empty($id)) {
$calculationIsEnabledFor[$id] = $id;
}
}
}
foreach ($this->categories as $category) {
if (isset($calculationIsEnabledFor[$category->getId()])) {
$calculationIsEnabledFor[$category->getId()] = $category;
}
}
foreach ($calculationIsEnabledFor as $category) {
$selectedCategoriesCalculation = $this->getCalculationFactory()->findByManufacturerAndCategory($manufacturer, $category);
$updatedCalculation = $this->getCalculationFactory()->copyCalculationFactorFields($calculation, $selectedCategoriesCalculation);
$updatedCalculation = $this->getCalculationFactory()->save($updatedCalculation);
$this->updateProductPricesByCategoryAndManufacturer($updatedCalculation, $category, $manufacturer);
}
\Drupal::messenger()->addStatus($this->t('Alapértelmezett termékcsoport kalkulációk sikeresen mentve a gyártó minden kijelölt termékcsoportjára!'));
}

/**
* Each category of selected manufacturer
*
* @param Calculation $calculation
* @param Manufacturer $manufacturer
* @return void
*/
public function saveForEachCategoryOfThisManufacturer(Calculation $calculation, Manufacturer $manufacturer): void {
$calculations = $this->getCalculationFactory()->findAllByManufacturerAndItsCategories($manufacturer);
/* @var $manufacturersOtherCategoryCalculation Calculation */
foreach ($calculations as $manufacturersOtherCategoryCalculation) {
if ($calculation->getId() === $manufacturersOtherCategoryCalculation->getId()) {
continue;
}

$manufacturersOtherCategoryCalculation = $this->getCalculationFactory()->copyCalculationFactorFields($calculation, $manufacturersOtherCategoryCalculation);
$manufacturersOtherCategoryCalculation->setDefaultCalculation(0);
/* @var $updatedCalculation Calculation */
$updatedCalculation = $this->getCalculationFactory()->save($manufacturersOtherCategoryCalculation);

$category = $this->getCategoryFactory()->find($updatedCalculation->getParentCategoryId());
$this->updateProductPricesByCategoryAndManufacturer($updatedCalculation, $category, $manufacturer);
}
\Drupal::messenger()->addStatus($this->t('Alapértelmezett termékcsoport kalkulációk sikeresen mentve a gyártó minden aktiv termékcsoportjára!'));
}

/**
* Selected components of selected manufacturer
*
* @param Calculation $calculation
* @return void
*/
public function setDefaultCalulationForSelectedComponents(Calculation $calculation): void {
$calculationIsEnabledFor = [];
foreach ($_POST as $key => $value) {
if (preg_match('/^enable_component_calculation_*/', $key)) {
$id = (int) explode("_", $key)[3];
if (!empty($id)) {
$calculationIsEnabledFor[$id] = $id;
}
}
}
foreach ($this->components as $component) {
if (isset($calculationIsEnabledFor[$component->getId()])) {
$calculationIsEnabledFor[$component->getId()] = $component;
}
}
foreach ($calculationIsEnabledFor as $component) {
$selectedComponentsCalculation = $this->getCalculationFactory()->findByComponent($component);
$updatedCalculation = $this->getCalculationFactory()->copyCalculationFactorFields($calculation, $selectedComponentsCalculation);
$updatedCalculation = $this->getCalculationFactory()->save($updatedCalculation);
$this->updateComponentsEachProductsPrice($component, $updatedCalculation);
}
\Drupal::messenger()->addStatus($this->t('Alapértelmezett komponens kalkulációk sikeresen mentve a gyártó minden kijelölt komponensére!'));
}

/**
* Each manufacturers similar component
*
* @param Calculation $calculation
* @return void
*/
public function setDefaultCalulationForOtherManufacturersSimilarComponent(Calculation $calculation): void {
$component = $this->getComponentFactory()->find($calculation->getParentComponentId());
$manufacturerIds = $this->getManufacturerFactory()->getComponentManufacturerIds();
foreach ($manufacturerIds as $manufacturerId) {
$otherManufacturersSimilarComponent = $this->getComponentFactory()->findByManufacturerIdAndComponentAxicoIdName($manufacturerId, $component->getAxicoIdName());
if (!empty($otherManufacturersSimilarComponent)) {
$otherManufacturersSimilarComponentsCalculation = $this->getCalculationFactory()->findByComponent($otherManufacturersSimilarComponent);
if ($otherManufacturersSimilarComponentsCalculation) {
$otherManufacturersSimilarComponentsCalculation = $this->getCalculationFactory()->copyCalculationFactorFields($calculation, $otherManufacturersSimilarComponentsCalculation);
$otherManufacturersSimilarComponentsCalculation->setDefaultCalculation(0);
$updatedCalculation = $this->getCalculationFactory()->save($otherManufacturersSimilarComponentsCalculation);
$this->updateComponentsEachProductsPrice($component, $updatedCalculation);
}
}
}
\Drupal::messenger()->addStatus($this->t('Alapértelmezett komponens kalkulációk sikeresen mentve a többi komponens gyártó minden ilyen cikkszámú komponensére!'));
}

public function updateComponentsEachProductsPrice(Component $component, Calculation $updatedCalculation): void {

$files = $this->getFileFactory()->findAllActive();

/* @var $uploadedFile UploadedFile */
foreach ($files as $uploadedFile) {
if ($uploadedFile->getParentManufacturerId() !== $this->mid) {
continue;
}
$this->getProductFactory()->reCalculatePricesForProductsOfComponentInUploadedFile($updatedCalculation, $component, $uploadedFile);
}
}

public function updateProductPricesByCategoryAndManufacturer(Calculation $updatedCalculation, Category $category, Manufacturer $manufacturer) {
$files = $this->getFileFactory()->findAllActive();

/* @var $uploadedFile UploadedFile */
foreach ($files as $uploadedFile) {
if ($uploadedFile->getParentManufacturerId() !== $this->mid) {
continue;
}
$this->getProductFactory()->reCalculatePricesForProductsOfCategoryInUploadedFile(
$updatedCalculation, $uploadedFile, $category, $manufacturer);
}
}

}

+ 83
- 0
modules/custom/arlista/src/Form/Calculation/CalculationList.php Dosyayı Görüntüle

@@ -0,0 +1,83 @@
<?php

/**
* @file
* Calculations list all form.
*/

namespace Drupal\arlista\Form\Calculation;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\Core\Url;
use Drupal\Core\Link;

class CalculationList extends ArlistaAbstractForm {

private $mid;

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_manufacturer_calculations_list_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $mid = null) {

$this->mid = $mid;
$form['items_wrapper']['#prefix'] ='<div class="col-lg-6">';
$form['items_wrapper']['link'][] = Link::fromTextAndUrl('Vissza', Url::fromRoute('arlista.manufacturer.edit', [
'mid' => $mid,
]))->toRenderable();
/* @var $manufacturer Manufacturer */
$manufacturer = $this->getManufacturerFactory()->find($mid);

$options = [];
$options[0] = 'Kérem válasszon';

if ($manufacturer->isComponentBased()) {
$components = $this->getComponentFactory()->findAllActiveWhereManufacturerIdIn('name', 'DESC', [$manufacturer->getId()]);
foreach ($components as $selectable) {
$options[$selectable->getId()] = $selectable->getName();
}

$form['items_wrapper']['components'] = [
'#title' => 'Komponensek',
'#name' => 'components',
'#type' => 'select',
'#options' => $options,
'#id' => 'manufacturer-component-calculation-select',
];
} else {
$categories = $this->getCategoryFactory()->findAllActive('name', 'DESC');
foreach ($categories as $selectable) {
$options[$selectable->getId()] = $selectable->getName();
}

$form['items_wrapper']['categories'] = [
'#title' => $manufacturer->getName() . ' - Kategóriák',
'#name' => 'categories',
'#type' => 'select',
'#options' => $options,
'#id' => 'manufacturer-category-calculation-select',
];
}
$form['items_wrapper']['#suffix'] ='</div>';

return $form;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}

}

+ 133
- 0
modules/custom/arlista/src/Form/Category/CategoryEdit.php Dosyayı Görüntüle

@@ -0,0 +1,133 @@
<?php

namespace Drupal\arlista\Form\Category;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Category;

class CategoryEdit extends ArlistaAbstractForm {

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_category_edit_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cid = $this->getQueryValue('cid');
$category = empty($cid) ? $this->getCategoryFactory()->create() : $this->getCategoryFactory()->find($cid);
if (!$category->isNew()) {
if ($data = $this->getCacheService()->getCachedDataByName([$this->getFormId(), $category->getId()])) {
return $data;
}
}
$form['#prefix'] ='<div class="col-lg-6">';
$form['items_wrapper']['cid'] = [
'#type' => 'hidden',
'#value' => $cid
];

$form = $this->getNameField($form, $category, -1000);

$form['items_wrapper']['axico_id_name'] = [
'#title' => 'Termékcsoport Axico cikkszáma',
'#type' => 'textfield',
'#weight' => -900,
'#default_value' => $category->getAxicoIdName(),
];

$form = $this->getSifField($form, $category, -800);

$form['items_wrapper']['buttons'] = array(
'#type' => 'container',
'#weight' => -700,
'##attributes' => ['class' => ['col-lg-6']],
);
$form['items_wrapper']['buttons']['arlista_category_edit_form_submit'] = [
'#type' => 'submit',
'#value' => empty($category->getName()) ? 'Új termékcsoport mentése' : $category->getName() . ' - mentés',
'#attributes' => ['class' => ['btn-success']]
];

$form['items_wrapper']['buttons']['arlista_category_edit_form_submit']['#attributes']['class'][] = 'btn-primary';
$form['items_wrapper']['buttons']['deleteCategory'] = $this->getDeleteButton($category);
$form['items_wrapper']['buttons']['deleteCategory']['#disabled'] = true;
$form['#suffix'] ='</div>';

$this->getCacheService()->setCachedDataByName([$this->getFormId(), $cid], $form);

return $form;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {


$values = $form_state->getValues();
/* @var $category Category */
$category = empty($values['cid']) ? $this->getCategoryFactory()->create() : $this->getCategoryFactory()->find($values['cid']);
$category->setName($values['name']);
$category->setAxicoIdName($values['axico_id_name']);
$category->setSif($values['sif']);

$this->resetCaches($category);

$category = $this->getCategoryFactory()->save($category);


$manufacturers = $this->getManufacturerFactory()->findAll();
foreach ($manufacturers as $manufacturer) {
/*
* Create axico id for each existing category upon saving a new manufacturer
*/
if (!$this->getAxicoIdFactory()->isAxicoIdPresentInGroup($manufacturer->getId(), $category->getId(), null)) {
/* @var $axicoId AxicoId */
$axicoId = $this->getAxicoIdFactory()->createForCategory($manufacturer->getId(), $category->getId());
$axicoId->setName($manufacturer->getAxicoIdName() . $category->getAxicoIdName());
$this->getAxicoIdFactory()->save($axicoId);
}
/*
* Create calculation for each newly created category
*/
if (empty($this->getCalculationFactory()->findByManufacturerAndCategory($manufacturer, $category))) {
$this->getCalculationFactory()->createFor(null, $category, $manufacturer);
}
}

\Drupal::messenger()->addStatus($this->t('Sikeres mentés!'));

$form_state->setRedirect('arlista.category.edit', ['cid' => $category->getId()]);
}

public function deleteEntity(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('arlista.category.delete', ['id' => $this->getQueryValue('cid')]);
}

public function resetCaches(Category $category) {
if (!$category->isNew()) {
$this->getCacheService()->resetCache([$this->getFormId(), $category->getId()]);
}
$this->getCacheService()->resetCache(['arlista_category_list_form']);
$manufacturers = $this->getManufacturerFactory()->findAllActive();
foreach ($manufacturers as $manufacturer) {
if ($manufacturer->isComponentBased()) {
continue;
}
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($manufacturer->getId());
foreach ($sheetSettings as $sheetSetting) {
$this->getCacheService()->resetCache(['arlista_product_uploaded_list_form', $manufacturer->getId(),
$sheetSetting->getId(), 'enabled_categories']);
}
}
}

}

+ 91
- 0
modules/custom/arlista/src/Form/Category/CategoryList.php Dosyayı Görüntüle

@@ -0,0 +1,91 @@
<?php

/**
* @file
* Categorys list all form.
*/

namespace Drupal\arlista\Form\Category;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\Core\Url;
use Drupal\Core\Link;

class CategoryList extends ArlistaAbstractForm {

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_category_list_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
if ($data = $this->getCacheService()->getCachedDataByName([$this->getFormId()])) {
return $data;
}

$categories = $this->getCategoryFactory()->findAll('name', 'ASC');
$form['items_wrapper']['#prefix'] ='<div class="col-lg-6">';
$form['items_wrapper']['link'] = Link::fromTextAndUrl('Új termékcsoport hozzáadása', Url::fromRoute('arlista.category.edit', ['cid' => 0]))->toRenderable();
if (!empty($categories)) {
$renderableItems = [
'#theme' => 'arlista_category_list',
'#categories' => $categories,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['items_wrapper']['categories'] = ['#markup' => $renderedList];
}
$form['items_wrapper']['buttons'] = array(
'#type' => 'container',
'#weight' => 1000,
);
if (!empty($categories)) {
$form['items_wrapper']['buttons']['arlista_enable_categories_form_submit'] = array(
'#type' => 'submit',
'#value' => 'Termékcsoportok engedélyezése',
);
$form['items_wrapper']['buttons']['arlista_enable_categories_form_submit']['#attributes']['class'][] = 'btn-primary';
}
$form['items_wrapper']['#suffix'] ='</div>';

$this->getCacheService()->setCachedDataByName([$this->getFormId()], $form);

return $form;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$categories = $this->getCategoryFactory()->findAll('name', 'ASC');
$enabled = [];

foreach ($_POST as $key => $value) {
if (preg_match('/^enable_category_*/', $key)) {
$cid_array = explode("_", $key);
$id = (int) $cid_array[2];
if (!$id <= 0) {
$enabled[$id] = 1;
}
}
}
foreach ($categories as $category) {
$this->getCategoryFactory()->getConnection()->query('UPDATE arlista_manager_category SET status = :enabled WHERE id = :id', [
':id' => $category->getId(),
':enabled' => isset($enabled[$category->getId()]) ? 1 : 0,
]);
}

$this->getCacheService()->resetCache([$this->getFormId()]);

\Drupal::messenger()->addStatus('Sikeres mentés!');
}

}

+ 76
- 0
modules/custom/arlista/src/Form/Category/ConfirmCategoryDelete.php Dosyayı Görüntüle

@@ -0,0 +1,76 @@
<?php

namespace Drupal\arlista\Form\Category;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;
use Drupal\arlista\Entity\Category;

class ConfirmCategoryDelete extends AbstractConfirmForm {

/**
* ID of the item to delete.
*
* @var int
*/
private $id;

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, string $id = NULL) {
$this->id = $id;
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$category = $this->getCategoryFactory()->find($this->id);
$this->getCategoryFactory()->delete($category);
$this->resetCaches($category);
parent::addMessage();

$form_state->setRedirect('arlista.category.list');
}

public function resetCaches(Category $category) {
$this->getCacheService()->resetCache(['arlista_category_list_form']);
$manufacturers = $this->getManufacturerFactory()->findAllActive();

foreach ($manufacturers as $manufacturer) {
if ($manufacturer->isComponentBased()) {
continue;
}
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($manufacturer->getId());
foreach ($sheetSettings as $sheetSetting) {
$this->getCacheService()->resetCache(['arlista_product_uploaded_list_form', $manufacturer->getId(),
$sheetSetting->getId(), 'enabled_categories']);
}
}
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_category_delete_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.category.list');
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

}

+ 149
- 0
modules/custom/arlista/src/Form/Component/ComponentEdit.php Dosyayı Görüntüle

@@ -0,0 +1,149 @@
<?php

namespace Drupal\arlista\Form\Component;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Component;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\AxicoId;
use Drupal\Core\Link;
use Drupal\Core\Url;

class ComponentEdit extends ArlistaAbstractForm {

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_component_edit_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cmpId = $this->getQueryValue('cmpId');
/** @var $component Component */
$component = empty($cmpId) ? $this->getComponentFactory()->create() : $this->getComponentFactory()->find($cmpId);

$form['#prefix'] = '<div class="col-lg-6">';
$form['cmpId'] = [
'#type' => 'hidden',
'#value' => $cmpId,
];

if (!$component->isNew()) {
$form['link'] = Link::fromTextAndUrl(
'Kalkulációs paraméterek',
Url::fromRoute('arlista.manufacturer.calculation.edit', [
'mid' => $component->getParentManufacturerId(),
'catId' => 0,
'cmpId' => $component->getId()
])
)->toRenderable();
$form['link']['#weight'] = -1100;
$axicoId = $this->getAxicoIdFactory()->findHighestCurrentAxicoIdByComponentId($component->getId());
if ($axicoId) {
$form['axico_id_count'] = [
'#title' => 'Utolsó kiosztott cikkszám azonosító sorszám [AAA-BBB-xxx]',
'#type' => 'textfield',
'#default_value' => $axicoId->getCurrentCount(),
'#disabled' => true,
'#weight' => -975,
];
}
}

$form = $this->getNameField($form, $component, -1000);

$form['axico_id_name'] = [
'#title' => 'Komponens Axico cikkszáma',
'#type' => 'textfield',
'#default_value' => $component->getAxicoIdName(),
'#weight' => -900,
];

$form = $this->getSifField($form, $component, -850);


$manufacturers = $this->getManufacturerFactory()->findAll();
$selectSettings = [
'name' => 'parent_manufacturer_id', 'title' => 'Gyártó'];
$form['parent_manufacturer_id'] = $this->getSelectOptions($selectSettings,
$manufacturers, $component);
$form['parent_manufacturer_id']['#disabled'] = $component->isNew() ? false : true;
$form['parent_manufacturer_id']['#weight'] = -700;
$form['buttons'] = array(
'#type' => 'container',
'#weight' => -500,
);
$form['buttons']['arlista_component_edit_form_submit'] = [
'#type' => 'submit',
'#value' => empty($component->getName()) ? 'Új komponens mentése' : $component->getName() . ' - mentés',
'#attributes' => ['class' => ['btn-success']]
];

$form['buttons']['deleteComponent'] = $this->getDeleteButton($component);
$form['buttons']['deleteComponent']['#disabled'] = true;
$form['#suffix'] = '</div>';
return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$values = $form_state->getValues();

/* @var $component Component */
$component = empty($values['cmpId']) ? $this->getComponentFactory()->create() : $this->getComponentFactory()->find($values['cmpId']);
$component->setName($values['name']);
$component->setAxicoIdName($values['axico_id_name']);
$component->setSif($values['sif']);
/* @var $manufacturer Manufacturer */
$manufacturer = $this->getManufacturerFactory()->find($values['parent_manufacturer_id'][0]);
if ($component->isNew()) {
$component->setParentManufacturerId($manufacturer->getId());
$component = $this->getComponentFactory()->save($component);
if (!$this->getAxicoIdFactory()->isAxicoIdPresentInGroup($manufacturer->getId(), null, $component->getId())) {
/* @var $axicoId AxicoId */
$axicoId = $this->getAxicoIdFactory()->createForComponent($manufacturer->getId(), $component->getId());
$axicoId->setName($manufacturer->getAxicoIdName() . $component->getAxicoIdName());
$axicoId = $this->getAxicoIdFactory()->save($axicoId);
}
/* @var $calculation Calculation */
$calculation = $this->getCalculationFactory()->findByComponent($component);
if (empty($calculation)) {
$this->getCalculationFactory()->createFor($component, null, $manufacturer);
}
\Drupal::messenger()->addStatus('Új komponens sikeresen mentve!');
} else {
$component = $this->getComponentFactory()->save($component);
\Drupal::messenger()->addStatus('Sikeres mentés!');
}

$this->clearCaches($manufacturer);

$form_state->setRedirect('arlista.component.edit', ['cmpId' => $component->getId()]);
}

public function deleteEntity(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('arlista.component.delete', ['id' => $this->getQueryValue('cmpId')]);
}

public function clearCaches(Manufacturer $manufacturer) {
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($manufacturer->getId());
foreach ($sheetSettings as $sheetSetting) {
$this->getCacheService()->resetCache(['arlista_product_uploaded_list_form', $manufacturer->getId(),
$sheetSetting->getId(), 'enabled_components_manufacturers_list']);
}
$this->getCacheService()->resetCache(['arlista_component_list_form', $manufacturer->getId()]);
}

}

+ 120
- 0
modules/custom/arlista/src/Form/Component/ComponentList.php Dosyayı Görüntüle

@@ -0,0 +1,120 @@
<?php

/**
* @file
* Components list all form.
*/

namespace Drupal\arlista\Form\Component;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\Core\Url;

class ComponentList extends ArlistaAbstractForm {

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_component_list_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$mid = (int) $this->getQueryValue('mid');
if ($data = $this->getCacheService()->getCachedDataByName([$this->getFormId(), $mid])) {
return $data;
}
$manufacturers = $this->getManufacturerFactory()->findAll('name', 'ASC');
$options = [];
$options[0] = 'Kérem válasszon';
/* @var $manufacturer Manufacturer */
foreach ($manufacturers as $manufacturer) {
// && $manufacturer->isComponentBased()
if ($manufacturer->isEnabled() && $manufacturer->isComponentBased()) {
$options[$manufacturer->getId()] = $manufacturer->getName();
}
}
if (isset($options[(int) $this->getQueryValue('mid')])) {
$selected = $mid;
} else {
reset($options);
$selected = key($options);
}

$form['items_wrapper']['#prefix'] ='<div class="col-lg-6">';
$form['items_wrapper']['components_manufacturer'] = [
'#title' => 'Gyártó',
'#name' => 'components_manufacturer',
'#type' => 'select',
'#options' => $options,
'#id' => 'components-manufacturer-select',
'#default_value' => $selected
];
$form['items_wrapper']['link'] = \Drupal\Core\Link::fromTextAndUrl('Új komponens hozzáadása', Url::fromRoute('arlista.component.edit', ['cmpId' => 0]))->toRenderable();

$manufacturersComponents = [];
$components = $this->getComponentFactory()->findAll('name', 'ASC');
foreach ($components as $component) {
if ($component->getParentManufacturerId() === $selected) {
$manufacturersComponents[] = $component;
}
}

$this->getQueryValue('mid');
if (!empty($components)) {

$list = $this->getComponentManufacturersList($manufacturersComponents);
$renderableItems = [
'#theme' => 'arlista_component_list',
'#components' => $manufacturersComponents,
'#manufacturerNames' => $list,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['items_wrapper']['components'] = ['#markup' => $renderedList];
}
$form['items_wrapper']['buttons'] = array(
'#type' => 'container',
'#weight' => 1000,
);
if (!empty($components)) {
$form['items_wrapper']['buttons']['arlista_enable_components_form_submit'] = array(
'#type' => 'submit',
'#value' => 'Komponensek engedélyezése',
);
$form['items_wrapper']['buttons']['arlista_enable_components_form_submit']['#attributes']['class'][] = 'btn-primary';
}
$form['items_wrapper']['#suffix'] ='</div>';
$this->getCacheService()->setCachedDataByName([$this->getFormId(), $mid], $form);

return $form;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$mid = $this->getQueryValue('mid');
$components = $this->getComponentFactory()->findAllWhereManufacturerId($mid, 'name', 'ASC');
$enabled = [];
foreach ($_POST as $key => $value) {
if (preg_match('/^enable_component_*/', $key)) {
$componentIds = explode("_", $key);
$id = (int) $componentIds[2];
if (!$id <= 0) {
$enabled[$id] = 1;
}
}
}
$this->getComponentFactory()->enable($components, $enabled);
$this->getCacheService()->resetCache([$this->getFormId(), $mid]);
}

}

+ 75
- 0
modules/custom/arlista/src/Form/Component/ConfirmComponentDelete.php Dosyayı Görüntüle

@@ -0,0 +1,75 @@
<?php

namespace Drupal\arlista\Form\Component;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;
use Drupal\arlista\Entity\Component;

class ConfirmComponentDelete extends AbstractConfirmForm {

/**
* ID of the item to delete.
*
* @var int
*/
private $id;

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, string $id = NULL) {
$this->id = $id;
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$component = $this->getComponentFactory()->find($this->id);
$this->getComponentFactory()->delete($component);
$this->resetCaches($component);

parent::addMessage($component->getName() . ' törölve!');

$form_state->setRedirect('arlista.component.list');
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_component_delete_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.component.list');
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

public function resetCaches(Component $component) {
$manufacturer = $this->getManufacturerFactory()->find($component->getParentManufacturerId());
$this->getCacheService()->resetCache(['arlista_component_list_form', 0]);
$this->getCacheService()->resetCache(['arlista_component_list_form', $manufacturer->getId()]);
$sheetSettings = $this->getSheetSettingFactory()->findSheetSettingsByManufacturerId($manufacturer->getId());
foreach ($sheetSettings as $sheetSetting) {
$this->getCacheService()->resetCache(['arlista_product_uploaded_list_form', $manufacturer->getId(),
$sheetSetting->getId(), 'enabled_components']);
$this->getCacheService()->resetCache(['arlista_product_uploaded_list_form', $manufacturer->getId(),
$sheetSetting->getId(), 'enabled_components_manufacturers_list']);
}
}

}

+ 185
- 0
modules/custom/arlista/src/Form/Config/ArlistaSetupForm.php Dosyayı Görüntüle

@@ -0,0 +1,185 @@
<?php

namespace Drupal\arlista\Form\Config;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Service\ProductService;

/**
* Configure settings for Price List manager.
*/
class ArlistaSetupForm extends ConfigFormBase {
/* @var $productService ProductService */

private $productService;

/**
* Config settings.
*
* @var string
*/
const SETTINGS = 'arlista.settings';

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {

return new static(
$container->get('arlista.product.service'),
$container->get('config.factory')
);
}

public function __construct(ProductService $productService, ConfigFactoryInterface $configFactory) {
parent::__construct($configFactory);
$this->productService = $productService;
}

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_settings';
}

/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
static::SETTINGS,
];
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config(static::SETTINGS);
$options = [
10 => 10,
20 => 20,
50 => 50,
100 => 100,
200 => 200,
500 => 500,
9999 => 'Mind'
];
$form['#prefix'] ='<div class="col-lg-3">';
$form['default_listed'] = [
'#title' => 'Oldalanként megjelenített termékek alapértelmezett száma',
'#name' => 'default_listed',
'#type' => 'select',
'#options' => $options,
'#id' => 'default_listed_select',
'#default_value' => [$config->get('default_listed') ? $config->get('default_listed') : 10]
];
$form['exchange_rate_eur'] = [
'#title' => 'Alapértelmezett EUR árfolyam',
'#name' => 'exchange_rate_eur',
'#id' => 'exchange_rate_eur',
'#type' => 'number',
'#precision' => 3,
'#scale' => 6,
'#step' => 0.01,
'#max' => 999,
'#min' => 1,
'#default_value' => [$config->get('exchange_rate_eur') ? $config->get('exchange_rate_eur') : 350]
];
$form['exchange_rate_usd'] = [
'#title' => 'Alapértelmezett USD árfolyam',
'#name' => 'exchange_rate_usd',
'#id' => 'exchange_rate_usd',
'#type' => 'number',
'#precision' => 3,
'#scale' => 6,
'#step' => 0.01,
'#max' => 999,
'#min' => 1,
'#default_value' => [$config->get('exchange_rate_usd') ? $config->get('exchange_rate_usd') : 350]
];
$form = parent::buildForm($form, $form_state);
$form['actions']['submit']['#value'] = 'Mentés';
$form['buttons_secondary'] = [
'#type' => 'container',
'#weight' => 500,
];
$form['buttons_secondary']['actions_secondary']['reinstall'] = [
'#type' => 'submit',
'#submit' => [
'::reinstallProducts',
],
'#value' => 'Termékekadat újraimportálás',
'#limit_validation_errors' => [],
'#weight' => 910,
];
$form['buttons_ternary'] = [
'#type' => 'container',
'#weight' => 600,
];
$form['buttons_ternary']['actions_ternary']['fixAxicoIds'] = [
'#type' => 'submit',
'#submit' => [
'::fixAxicoIds',
],
'#value' => 'Cikkszám revízió',
'#limit_validation_errors' => [],
'#weight' => 1000,
];

$form['#suffix'] ='</div>';
return $form;
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config(static::SETTINGS);

$exchangeRateChanges = [
'EUR' => ['name' => 'EUR', 'change' => false, 'exchangeRate' => 0],
'USD' => ['name' => 'USD', 'change' => false, 'exchangeRate' => 0],
];

if ($config->get('exchange_rate_eur') <> $form_state->getValue('exchange_rate_eur')) {
$exchangeRateChanges['EUR']['change'] = true;
$exchangeRateChanges['EUR']['exchangeRate'] = $form_state->getValue('exchange_rate_eur');
$message = $message . 'termékárak újrakalkulálva';
}
if ($config->get('exchange_rate_usd') <> $form_state->getValue('exchange_rate_usd')) {
$exchangeRateChanges['USD']['change'] = true;
$exchangeRateChanges['USD']['exchangeRate'] = $form_state->getValue('exchange_rate_usd');
}

$this->configFactory->getEditable(static::SETTINGS)
->set('default_listed', $form_state->getValue('default_listed'))
->set('exchange_rate_eur', $form_state->getValue('exchange_rate_eur'))
->set('exchange_rate_usd', $form_state->getValue('exchange_rate_usd'))
->save();

$this->productService->updateAllProductPrices($exchangeRateChanges);

$message = 'Beállítások sikeresen mentve. ';
if ($exchangeRateChanges['EUR']['change'] || $exchangeRateChanges['USD']['change']) {
$message = $message . ' Termék árak újrakalkulálva! Frissítse a Correct adatbázisát!';
}

$this->messenger()->addStatus($message);
}

public function reinstallProducts(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('arlista.config.reimport');
}

public function fixAxicoIds(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('arlista.config.fix.axico.id');
}

}

+ 54
- 0
modules/custom/arlista/src/Form/Config/ConfirmFixAxicoId.php Dosyayı Görüntüle

@@ -0,0 +1,54 @@
<?php

namespace Drupal\arlista\Form\Config;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;

class ConfirmFixAxicoId extends AbstractConfirmForm {

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$erroneusAxicoIds = ['SUPVIX', 'SUPHAX', 'SUPSSG', 'SUPHSW'];
$this->getInstallFactory()->fixSpecificAxicoIds($erroneusAxicoIds);
$this->getInstallFactory()->fixSpecificAxicoIdsNextCount($erroneusAxicoIds);
$this->getInstallFactory()->getAxicoIdFactory()->removeErrors();
parent::addMessage('Cikkszám revízió befejeződött.');
$form_state->setRedirect('arlista.config.setup');
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_fix_axico_id_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.config.setup');
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

}

+ 49
- 0
modules/custom/arlista/src/Form/Config/ConfirmProductReImport.php Dosyayı Görüntüle

@@ -0,0 +1,49 @@
<?php

namespace Drupal\arlista\Form\Config;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;

class ConfirmProductReImport extends AbstractConfirmForm {

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$this->getInstallFactory()->importDataFromExcelFile('termekek.xls', true);
parent::addMessage('Termékek és Axico cikkszámok siskeresen re-importálva');
$form_state->setRedirect('arlista.config.setup');
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_product_reimport_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.config.setup');
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

}

+ 236
- 0
modules/custom/arlista/src/Form/EnabledGroup/EnabledGroupListForm.php Dosyayı Görüntüle

@@ -0,0 +1,236 @@
<?php

/**
* @file
* Manufacturers list all form for sheet specific setup.
*/

namespace Drupal\arlista\Form\EnabledGroup;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\EnabledGroup;
use Drupal\arlista\Entity\Category;
use Drupal\arlista\Entity\Component;
use Drupal\Core\Url;

class EnabledGroupListForm extends ArlistaAbstractForm {

private $mid;
private $sheetSettingId;
private $componentBased;

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_enabled_group_list_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $mid = null, int $sheetSettingId = null, int $componentBased = null) {
$this->mid = $mid;
$this->sheetSettingId = $sheetSettingId;
$this->componentBased = $componentBased;

if ($componentBased === 1) {
$form = $this->getEnableComponentsForm($form, $mid, $sheetSettingId);
} else {
$form = $this->getEnableCategoriesForm($form, $mid, $sheetSettingId);
}

return $form;
}

public function getEnableCategoriesForm(array $form, int $mid, int $sheetSettingId): array {

$categories = $this->getCategoryFactory()->findAllActive('name', 'ASC');
$enabledGroups = $this->getEnabledGroupFactory()->findAllEnabledGroups($sheetSettingId, null);
$selected = [];
/* @var $enabledGroup EnabledGroup */
foreach ($enabledGroups as $enabledGroup) {
$selected[$enabledGroup->getCategoryId()] = $enabledGroup->getCategoryId();
}
$form = $this->getManufacturerAndSheetSettingData($form, $mid, $sheetSettingId);
if (!empty($categories)) {
$renderableItems = [
'#theme' => 'arlista_category_list',
'#categories' => $categories,
'#enabledList' => $selected,
'#sheetSettingList' => true,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['items_wrapper']['categories'] = ['#markup' => $renderedList];
}

$form['buttons'] = [
'#type' => 'container',
'#weight' => 1000,
];

$form['buttons']['arlista_enable_sheet_setting_categories_form_submit'] = [
'#type' => 'submit',
'#submit' => [
'::enableCategories',
],
'#value' => 'Termékcsoportok engedélyezése',
'#limit_validation_errors' => [],
];
$form['buttons']['arlista_enable_sheet_setting_categories_form_submit']['#attributes']['class'][] = 'btn-primary';
$form[] = \Drupal\Core\Link::fromTextAndUrl('Új termékcsoport hozzáadása', Url::fromRoute('arlista.category.edit', ['cid' => 0]))->toRenderable();

return $form;
}

public function getEnableComponentsForm(array $form, int $mid, int $sheetSettingId): array {

$componentManufacturerIds = $this->getManufacturerFactory()->getComponentManufacturerIds();
$components = $this->getComponentFactory()->findAllActiveWhereManufacturerIdIn('name', 'ASC', $componentManufacturerIds);

$enabledGroups = $this->getEnabledGroupFactory()->findAllEnabledGroups($sheetSettingId, true);
$selected = [];
/* @var $enabledGroup EnabledGroup */
foreach ($enabledGroups as $enabledGroup) {
$selected[$enabledGroup->getComponentId()] = $enabledGroup->getComponentId();
}
$form = $this->getManufacturerAndSheetSettingData($form, $mid, $sheetSettingId);

if (!empty($components)) {
$renderableItems = [
'#theme' => 'arlista_component_list',
'#components' => $components,
'#manufacturerNames' => $this->getComponentManufacturersList($components),
'#enabledList' => $selected,
'#sheetSettingList' => true,
'#form' => $form,
];
$renderedList = \Drupal::service('renderer')->render($renderableItems);
$form['items_wrapper']['components'] = ['#markup' => $renderedList];
}

$form['buttons'] = [
'#type' => 'container',
'#weight' => 1000,
];

$form['buttons']['arlista_enable_sheet_setting_components_form_submit'] = [
'#type' => 'submit',
'#submit' => [
'::enableComponents',
],
'#value' => 'Komponensek engedélyezése',
'#limit_validation_errors' => [],
];

$form['buttons']['arlista_enable_sheet_setting_components_form_submit']['#attributes']['class'][] = 'btn-primary';
$form[] = \Drupal\Core\Link::fromTextAndUrl('Új komponens hozzáadása', Url::fromRoute('arlista.component.edit', ['cmpId' => 0]))->toRenderable();

return $form;
}

/**
* {@inheritdoc}
*/
public function enableComponents(array &$form, FormStateInterface $form_state) {
$components = $this->getComponentFactory()->findAll('name', 'ASC');
$enabled = [];

foreach ($_POST as $key => $value) {
if (preg_match('/^enable_component_*/', $key)) {
$cmpIds = explode("_", $key);
$id = (int) $cmpIds[2];
if (!empty($id)) {
$enabled[$id] = $id;
}
}
}
foreach ($components as $component) {
if (isset($enabled[$component->getId()])) {
$enabled[$component->getId()] = $component;
}
}
foreach ($enabled as $key => $value) {
if (!$value instanceof Component) {
unset($enabled[$key]);
}
}
$this->getEnabledGroupFactory()->updateSheetSettingsEnabledGroups($this->sheetSettingId, $enabled, true);
$this->getCacheService()->resetCache([
'arlista_product_uploaded_list_form', $this->mid, $this->sheetSettingId, 'enabled_components']);
\Drupal::messenger()->addStatus('Sikeres mentés!');
}

/**
* {@inheritdoc}
*/
public function enableCategories(array &$form, FormStateInterface $form_state) {

$categories = $this->getCategoryFactory()->findAll('name', 'ASC');
$enabled = [];

foreach ($_POST as $key => $value) {
if (preg_match('/^enable_category_*/', $key)) {
$cids = explode("_", $key);
$id = (int) $cids[2];
if (!empty($id)) {
$enabled[$id] = $id;
}
}
}
foreach ($categories as $category) {
if (isset($enabled[$category->getId()])) {
$enabled[$category->getId()] = $category;
}
}
foreach ($enabled as $key => $value) {
if (!$value instanceof Category) {
unset($enabled[$key]);
}
}
$this->getEnabledGroupFactory()->updateSheetSettingsEnabledGroups($this->sheetSettingId, $enabled);
$this->getCacheService()->resetCache([
'arlista_product_uploaded_list_form', $this->mid, $this->sheetSettingId, 'enabled_categories']);
\Drupal::messenger()->addStatus('Sikeres mentés!');
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}

public function getManufacturerAndSheetSettingData($form, $mid, $sheetSettingId) {
$manufacturer = $this->getManufacturerFactory()->find($mid);
$sheetSetting = $this->getSheetSettingFactory()->find($sheetSettingId);
$form['items_wrapper'][]['sheet_setting']['link'] = \Drupal\Core\Link::fromTextAndUrl(
'Vissza a munkalap szerkesztéshez',
Url::fromRoute('arlista.manufacturer.sheet-setting.edit', [
'mid' => $manufacturer->getId(),
'sheetIndex' => $sheetSetting->getIndex(),
'mid' => $sheetSetting->getManufacturerId()]
)
)->toRenderable();
$form['items_wrapper']['manufacturer'] = [
'#type' => 'textfield',
'#disabled' => true,
'#title' => 'Gyártó',
'#default_value' => $manufacturer->getName(),
'#weight' => 0
];

$form['items_wrapper']['sheet_setting'] = [
'#type' => 'textfield',
'#disabled' => true,
'#title' => 'Munkalap',
'#default_value' => $sheetSetting->getName(),
'#weight' => 0
];

return $form;
}

}

+ 67
- 0
modules/custom/arlista/src/Form/File/ConfirmUploadedFileDelete.php Dosyayı Görüntüle

@@ -0,0 +1,67 @@
<?php

namespace Drupal\arlista\Form\File;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;

class ConfirmUploadedFileDelete extends AbstractConfirmForm {

/**
* ID of the item to delete.
*
* @var int
*/
private $id;
private $mid;

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $mid = NULL, int $id = NULL) {
$this->mid = $mid;
$this->id = $id;
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$file = $this->getFileFactory()->find($this->id);
$this->getFileFactory()->delete($file);
$products = $this->getProductFactory()->findProductsByUploadedFileId($this->id);
foreach ($products as $product) {
$this->getProductFactory()->delete($product);
}

$this->getCacheService()->resetCache(['arlista_file_upload_form']);

parent::addMessage();

$form_state->setRedirect('arlista.file.list', ['mid' => $this->mid]);
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_uploaded_file_delete_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.file.list', ['mid' => $this->mid]);
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

}

+ 162
- 0
modules/custom/arlista/src/Form/File/FileUpload.php Dosyayı Görüntüle

@@ -0,0 +1,162 @@
<?php

namespace Drupal\arlista\Form\File;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\file\Entity\File;
use Drupal\arlista\Entity\UploadedFile;
use Drupal\arlista\Entity\WorkFlow;
use Drupal\arlista\Entity\Manufacturer;

class FileUpload extends ArlistaAbstractForm {

private $mid;

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_file_upload_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $mid = null) {
$form['#attributes'] = [
'enctype' => 'multipart/form-data'];
$this->mid = $mid;
$form_state->disableCache();
$manufacturers = $this->getManufacturerFactory()->findAll();
$enabled = [];
$options = [];
$options[0] = 'Kérem válasszon';
/* @var $manufacturer Manufacturer */
foreach ($manufacturers as $manufacturer) {
if ($manufacturer->isEnabled()) {
$options[$manufacturer->getId()] = $manufacturer->getName();
$enabled[$manufacturer->getId()] = $manufacturer;
}
}

$form['items_wrapper']['#prefix'] ='<div class="col-sm-4 col-md-6 col-lg-9">';
$form['items_wrapper']['manufacturer'] = [
'#title' => 'Gyártó',
'#name' => 'manufacturer',
'#type' => 'select',
'#options' => $options,
'#default_value' => [$mid ?? 0],
'#id' => 'uploaded_files_manufacturer_select',
];
if (empty($mid)) {
return $form;
}

/* @var $activeManufacturer Manufacturer */
$activeManufacturer = $this->getManufacturerFactory()->find($mid);
if (!empty($activeManufacturer)) {
$files = $this->getFileFactory()->findAllByParentManufacturerId($activeManufacturer->getId());
if (!empty($files)) {
$sheetSettings = [];
/* @var $file UploadedFile */
foreach ($files as $file) {
$sheetSetting = $this->getSheetSettingFactory()->findSettingBySheetIndex($manufacturer->getId(), 0);
$sheetSettings[$activeManufacturer->getId()] = $sheetSetting;
}
$renderable_items = [
'#theme' => 'arlista_file_list',
'#files' => $files,
'#manufacturers' => $enabled,
'#sheetSettings' => $sheetSettings,
'#listed' => $this->getConfig()->get('default_listed') ?? 10,
'#form' => $form,
];
$rendered_list = \Drupal::service('renderer')->render($renderable_items);
$form['items_wrapper']['files'] = ['#markup' => $rendered_list];
}

$form['items_wrapper']['columns']['components'] = [
'#title' => 'Komponens alapú termékbesorolás',
'#type' => 'checkbox',
'#default_value' => $activeManufacturer->isComponentBased(),
'#disabled' => true,
];
// if (count($files) == 1) {
// return $form;
// }

$form['items_wrapper']['file_excel'] = [
'#type' => 'managed_file',
'#title' => 'Excel fájl',
'#description' => 'A gyártó illetve beszállító által meghatározott szerkezetű és tartalmú fájl',
'#upload_location' => 'public://arlista/uploaded/',
'#default_value' => '',
'#upload_validators' => [
'file_validate_extensions' => [
'xls' => 'xls',
'xlsx' => 'xlsx'
],
],
];
$form['items_wrapper']['buttons'] = [
'#type' => 'container',
'#weight' => 1000,
];
$form['items_wrapper']['buttons']['arlista_file_upload_submit'] = [
'#type' => 'submit',
'#value' => 'Feltöltés',
'#attributes' => ['class' => ['btn-success']]
];
}
$form['items_wrapper']['#suffix'] ='</div>';

return $form;
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (empty($form_state->getValue('file_excel'))) {
$form_state->setErrorByName('file', 'Nincs fájl');
}
if (empty($form_state->getValue('manufacturer'))) {
$form_state->setErrorByName('manufacturer', 'Nincs gyártó');
}

$manufacturer = $this->getManufacturerFactory()->find($this->mid);
if (empty($manufacturer)) {
$form_state->setErrorByName('manufacturer', 'Ismeretlen gyártó');
}
}

/**
* {@inheritdoc}
*
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if (empty($form_state->getValue('file_excel')[0])) {
\Drupal::messenger()->addError('Fájl feltöltés hiba!');
}
$file = File::load($form_state->getValue('file_excel')[0]);
$file->setPermanent();
$file->save();

/* @var $manufacturer Manufacturer */
$manufacturer = $this->getManufacturerFactory()->find($this->mid);

/* @var $uploadedFile UploadedFile */
$uploadedFile = $uploadedFile = $this->getFileFactory()->create();
$uploadedFile->setFid($file->id());
$uploadedFile->setName($file->get('filename')->getValue()[0]['value']);
$uploadedFile->setParentManufacturerId($manufacturer->getId());
$uploadedFile->setStatus(1);
$uploadedFile->setWorkFlow(WorkFlow::UPLOADED);
$uploadedFile->setComponentBased($manufacturer->isComponentBased() ? 1 : 0);
$this->getFileFactory()->save($uploadedFile);

\Drupal::messenger()->addStatus($file->get('filename')->getValue()[0]['value'] . ' sikeresen mentve!');
}

}

+ 61
- 0
modules/custom/arlista/src/Form/Manufacturer/ConfirmManufacturerDelete.php Dosyayı Görüntüle

@@ -0,0 +1,61 @@
<?php

namespace Drupal\arlista\Form\Manufacturer;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\arlista\Form\AbstractConfirmForm;

class ConfirmManufacturerDelete extends AbstractConfirmForm {

/**
* ID of the item to delete.
*
* @var int
*/
private $id;

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $id = NULL) {
$this->id = $id;
return parent::buildForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$manufacturer = $this->getManufacturerFactory()->find($this->id);
$this->getManufacturerFactory()->delete($manufacturer);
$this->getCacheService()->setCachedDataByName('arlista_manufacturer_list_form', []);
parent::addMessage();
$form_state->setRedirect('arlista.manufacturer.list');
}

/**
* {@inheritdoc}
*/
public function getFormId(): string {
return "confirm_manufacturer_delete_form";
}

/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('arlista.manufacturer.list');
}

/**
* {@inheritdoc}
*/
public function getQuestion() {
return 'Biztos benne ?';
}

}

+ 180
- 0
modules/custom/arlista/src/Form/Manufacturer/ManufacturerEdit.php Dosyayı Görüntüle

@@ -0,0 +1,180 @@
<?php

namespace Drupal\arlista\Form\Manufacturer;

use Drupal\Core\Form\FormStateInterface;
use Drupal\arlista\Form\ArlistaAbstractForm;
use Drupal\arlista\Entity\Manufacturer;
use Drupal\arlista\Entity\Status;
use Drupal\Core\Link;
use Drupal\Core\Url;

class ManufacturerEdit extends ArlistaAbstractForm {

private $mid;

/**
* {@inheritdoc}
*/
public function getFormId() {
return 'arlista_manufacturer_edit_form';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, int $mid = null) {
/* @var $manufacturer Manufacturer */
$manufacturer = empty($mid) ? $this->getManufacturerFactory()->create() : $this->getManufacturerFactory()->find($mid);

$this->mid = $mid;
$form['#prefix'] ='<div class="col-lg-6">';
$form[]['link'] = Link::fromTextAndUrl(
'Vissza a gyártókhoz',
Url::fromRoute('arlista.manufacturer.list')
)->toRenderable();
$form['mid'] = [
'#type' => 'hidden',
'#value' => $mid,
'#weight' => 10,];

$form = $this->getNameField($form, $manufacturer, 20);

$form['axico_id_name'] = [
'#title' => 'Axico cikkszáma',
'#type' => 'textfield',
'#required' => true,
'#default_value' => $manufacturer->getAxicoIdName(),
'#weight' => 30,
];

$form = $this->getSifField($form, $manufacturer, 40);

$componentBasedOptions = [
0 => 'Termékcsoport alapú besorolás',
1 => 'Komponens alapú besorolás'
];

$form['component_based'] = [
'#title' => 'Termékbesorolás',
'#name' => 'component_based',
'#type' => 'select',
'#options' => $componentBasedOptions,
'#id' => 'component_based_select',
'#default_value' => [$manufacturer->getComponentBased()],
'#weight' => 65,
];

$statusOptions = [
Status::PASSIVE => 'Nem',
Status::ACTIVE => 'Igen'
];

$form['active_status'] = [
'#title' => 'Aktív',
'#name' => 'active_status',
'#type' => 'select',
'#options' => $statusOptions,
'#id' => 'active_status_select',
'#default_value' => [$manufacturer->getStatus()],
'#weight' => 65,
];

$form['calculations']['prefix'] = ['#prefix' => '<br>'];
if (!$manufacturer->isNew()) {
$form['items_wrapper'][]['calculation']['link'] = \Drupal\Core\Link::fromTextAndUrl(
'Kalkulációk szerkesztése',
Url::fromRoute('arlista.manufacturer.calculations.list', [
'mid' => $mid]
)
)->toRenderable();
}
$form['sheet_settings'][]['link'] = ['#prefix' => '<br>'];
if (!$manufacturer->isNew()) {
$form['items_wrapper'][]['sheet_settings']['link'] = \Drupal\Core\Link::fromTextAndUrl(
'Munkalapok szerkesztése',
Url::fromRoute('arlista.manufacturer.sheet-setting.edit', [
'mid' => $mid,
'sheetIndex' => 0]
)
)->toRenderable();
}

$form['buttons'] = [
'#type' => 'container',
'#weight' => 1000,
];

$form['buttons']['arlista_manufacturer_edit_form_submit'] = [
'#type' => 'submit',
'#value' => empty($manufacturer->getName()) ? 'Új gyártó mentése' : $manufacturer->getName() . ' mentése',
'#attributes' => ['class' => ['btn-success']]
];

$form['buttons']['deleteManufacturer'] = $this->getDeleteButton($manufacturer);
$form['buttons']['deleteManufacturer']['#disabled'] = true;
$form['#suffix'] ='</div>';
return $form;
}

/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
foreach ($form_state->getValues() as $key => $value) {
if ($form_state->hasAnyErrors()) {
continue;
}
}
}

/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {

$values = $form_state->getValues();
/* @var $manufacturer Manufacturer */
$manufacturer = empty($values['mid']) ? $this->getManufacturerFactory()->create() : $this->getManufacturerFactory()->find($values['mid']);
$manufacturer->setName($values['name']);
$manufacturer->setStatus($values['active_status'][0]);
$manufacturer->setAxicoIdName($values['axico_id_name']);
$manufacturer->setComponentBased($values['component_based']);
$manufacturer->setSif($values['sif']);

$createCalculation = false;

if ($manufacturer->isNew()) {
$createCalculation = true;
}

$manufacturer = $this->getManufacturerFactory()->save($manufacturer);
$this->getCacheService()->resetCache(['arlista_manufacturer_list_form']);
$this->getCacheService()->resetCache(['arlista_component_list_form',0]);
$this->getCacheService()->resetCache(['arlista_component_list_form',$manufacturer->getId()]);


if ($createCalculation) {
$categories = $this->getCategoryFactory()->findAll();
foreach ($categories as $category) {
/* @var $calculation Calculation */
$calculation = $this->getCalculationFactory()->findByManufacturerAndCategory($manufacturer, $category);
if (empty($calculation)) {
$this->getCalculationFactory()->createFor(null, $category, $manufacturer);
}
}
}

\Drupal::messenger()->addStatus($this->t('Sikeres mentés!'));
$form_state->setRedirect('arlista.manufacturer.edit', ['mid' => $manufacturer->getId()]);

}

public function deleteEntity(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('arlista.manufacturer.delete', ['id' => $this->mid]);
}

}

+ 0
- 0
modules/custom/arlista/src/Form/Manufacturer/ManufacturerList.php Dosyayı Görüntüle


Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor

Yükleniyor…
İptal
Kaydet