Commit 39a5c17f by François C.

Merge branch 'dev_principale' into 'master'

Cooperatic and LGDS improvements

See merge request !24
parents a868d541 28dd803c
Pipeline #1027 passed with stage
in 21 seconds
COUCHDB_USER=admin
COUCHDB_PASSWORD=123abc
POSTGRES_USER=foodcoops
POSTGRES_PASSWORD=foodcoops
POSTGRES_DB=foodcoops
# Scripts
*.sh text eol=lf
\ No newline at end of file
......@@ -10,8 +10,10 @@ outils/settings_secret.py
outils/config.py
outils/texts/*
outils/js_errors.log
outils/scripts/scripts_settings.py
db.sqlite3
*/max_timeslot_carts.txt
.gitlab-ci.yml
shop/shop_admin_settings.json
shop/errors.log
.idea
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
"""Company specific data values."""
MAG_NAME = 'Cleme'
OFFICE_NAME = ''
MAX_BEGIN_HOUR = '19:00'
COMPANY_NAME = 'La Cagette'
WELCOME_ENTRANCE_MSG = 'Bienvenue à La Cagette !'
WELCOME_MAIL_SUBJECT = 'Dernière étape de votre inscription à la Cagette.'
WELCOME_MAIL_TEMPLATE = 'members/bienvenue.html'
EMAIL_DOMAIN = 'lacagette-coop.fr'
OPEN_ON_SUNDAY = True
FLV_CSV_NB = 4
CAP_JOURNAL_ID = 9
CAP_APPELE_NON_VERSE_ACCOUNT_ID = 529
CAP_APPELE_VERSE_ACCOUNT_ID = 8
CAP_INVOICE_LINE_ACCOUNT_ID = 8
FUNDRAISING_CAT_ID = 1
UNITE_UOM_ID = 1
PARTS_A_PRODUCT_ID = 1008
PARTS_A_PRICE_UNIT = 10.0
COOP_BARCODE_RULE_ID = 11
CHECK_PAYMENT_ID = 8
CASH_PAYMENT_ID = 18
STOCK_LOC_ID = 12
STOCK_LOC_ID = 12
CATEG_FRUIT = 151
CATEG_LEGUME = 152
FLV_CSV_NB = 4
COEFF_MAG_ID = 1
......@@ -50,7 +55,7 @@ EM_URL = ''
RECEPTION_MERGE_ORDERS_PSWD = 'jpsrcp'
DAV_PATH = '/data/dav/cagette'
DAV_PATH = '/shared_dir/dav/'
TOOLS_SERVER = 'https://outils.lacagette-coop.fr'
......@@ -78,6 +83,8 @@ SHOP_CATEGORIES = {'epicerie': {'id': 75, 'label': 'Epicerie'},
'parfumerie': {'id': 133, 'label': 'Parfumerie'}}
SHOP_EXTRA_MENUS = ['shop/planning_livraison_pains.html', 'shop/combien_ca_pese.html']
SHOP_SURVEY_LINK = 'https://docs.google.com/forms/d/e/1FAIpQLSczl0mMRwx3s9LbUSPYwwFTiiRa6agx7YkQM9cL41eiQnXNUw/viewform'
SHOP_LIMIT_PRODUCTS = ['relatively_available', 'no_shelf']
EXCLUDE_SHOP_CATEGORIES = [108]
PROMOTE_SHELFS_IDS = [68]
DISCOUNT_SHELFS_IDS = [74]
......@@ -85,11 +92,18 @@ FL_SHELFS = [16, 17, 18]
VRAC_SHELFS = [20, 38]
SHIFT_EXCHANGE_DAYS_TO_HIDE = ''
SHIFT_INFO = """A la cagette, un service est une plage de trois heures un jour en particulier, par exemple : le mardi 25/09/2018 à 13h15.
<br />A l'inverse, un créneau est une plage de trois heures régulière, par exemple, tous les mardi de semaine A à 13h15."""
PB_INSTRUCTIONS = """Si j'ai un problème, que je suis désinscrit, que je veux changer de créneaux ou quoi que ce soit, merci de vous rendre dans la section \"J'ai un problème\" sur le site web de <a href=\"https://lacagette-coop.fr/?MonEspaceMembre\">La Cagette</a>"""
ENTRANCE_COME_FOR_SHOPING_MSG = "Hey coucou toi ! Cet été nous sommes plus de <strong>1000 acheteur·euses</strong> pour seulement <strong>300 coopérateur·rice·s</strong> en service. <br />Tu fais tes courses à La Cagette cet été ?<br/> Inscris-toi sur ton espace membre !"
# Members space / shifts
UNSUBSCRIBED_MSG = 'Vous êtes désincrit·e, merci de remplir <a href="https://docs.google.com/forms/d/e/1FAIpQLSfPiC2PkSem9x_B5M7LKpoFNLDIz0k0V5I2W3Mra9AnqnQunw/viewform">ce formulaire</a> pour vous réinscrire sur un créneau.<br />Vous pouvez également contacter le Bureau des Membres en remplissant <a href="https://docs.google.com/forms/d/e/1FAIpQLSeZP0m5-EXPVJxEKJk6EjwSyZJtnbiGdYDuAeFI3ENsHAOikg/viewform">ce formulaire</a>'
CONFIRME_PRESENT_BTN = 'Clique ici pour valider ta présence'
RECEPTION_PB = "Ici, vous pouvez signaler toute anomalie lors d'une réception, les produits non commandés, cassés ou pourris. \
Merci d'indiquer un maximum d'informations, le nom du produit et son code barre. \
Dans le cas de produits déteriorés, merci d'envoyer une photo avec votre téléphone à [Adresse_email]"
......@@ -91,4 +91,4 @@ BRINKS_MUST_IDENTIFY = True
ENTRANCE_FTOP_BUTTON_DISPLAY = False
CUSTOM_CSS_FILES = {'all': ['common_lgds.css'],
'members': ['inscription_lgds.css']}
'members': ['inscription_lgds.css','member_lgds.css']}
version: '3'
services:
app:
build:
context: .
dockerfile: dockerfiles/Dockerfile
env_file: .env
restart: always
ports:
- "8080:8080"
links:
- "couchdb:couchdb"
- "odoo:odoo"
volumes:
- "./:/home/app/"
couchdb:
build:
context: .
dockerfile: dockerfiles/Dockerfile.couchdb
env_file: .env
restart: always
ports:
- "5984:5984" # Expose port because it's used by the frontend
volumes:
- "couchdb-data:/opt/couchdb/data"
database:
image: "postgres:10"
env_file: .env
restart: always
volumes:
- "odoo-pg-data:/var/lib/postgresql/data"
odoo:
image: "registry.gitlab.com/lgds/foodcoops:9.0-cooperatic-2021-04-02"
env_file: .env
restart: always
ports:
- "8069:8069"
links:
- "database:database"
volumes:
- "odoo-shared-data:/home/app/.local/share/Odoo"
volumes:
odoo-shared-data:
odoo-pg-data:
couchdb-data:
FROM python:3
ENV PYTHONUNBUFFERED=1
# Add french locale
RUN apt update && \
apt install -y --no-install-recommends locales && \
rm -rf /var/lib/apt/lists/* && \
sed -i '/^#.* fr_FR.UTF-8 /s/^#//' /etc/locale.gen && \
locale-gen
WORKDIR /home/app
RUN pip install --upgrade pip
COPY requirements.txt /home/app/
RUN pip install -r requirements.txt
# Setup volume to be able to dev application locally
VOLUME /home/app
COPY . /home/app
# Run the application:
EXPOSE 8080
CMD ["./launch.sh", "0.0.0.0", "8080"]
FROM couchdb:3
COPY dockerfiles/local.ini /opt/couchdb/etc/
[couchdb]
single_node=true
users_db_security_editable = true
[httpd]
enable_cors = true
[cors]
credentials = true
origins = *
[replicator]
db = _replicator
[admins]
;admin = 123abc
admin = -pbkdf2-c5101d6618dfa702b4fb72b1ea0f335e1d1d84f9,506213b6a001da088296f40327cc2e86,10
......@@ -46,6 +46,7 @@ def archive_envelop(request):
"done": False,
"error": repr(e)
}
coop_logger.error("Payment error : %s \n %s", str(data), str(e))
if res['done']:
# Immediately save a token than this payment has been saved
......@@ -59,22 +60,19 @@ def archive_envelop(request):
try:
res['partner_name'] = envelop['envelop_content'][partner_id]['partner_name']
res['amount'] = envelop['envelop_content'][partner_id]['amount']
except:
except Exception as e:
res['error'] = "Wrong envelop structure"
coop_logger.error("Wrong envelop structure : %s", str(e))
res_payments.append(res)
try:
# Log the error
lf = open("/tmp/erreurs_django.log", "a")
lf.write(datetime.date.today().strftime("%Y-%m-%d") + " - Erreur lors de l'enregistrement du paiement de " + res['partner_name'] + "(odoo_id:" + partner_id + " )")
lf.write(res['error'] + "\n")
lf.close()
msg = 'Erreur lors de l\'enregistrement du paiement ' + envelop['type']
msg += ' ' + envelop['envelop_content'][partner_id]['amount'] + ' euros '
msg += ' ' + str(envelop['envelop_content'][partner_id]['amount']) + ' euros '
msg += ' (' + res['error'] + ')'
CagetteMember(int(partner_id)).attach_message(msg)
except:
pass
except Exception as e:
coop_logger.error("Cannot attach payment error message to member : %s", str(e))
try:
# Delete envelop from couchdb
......
#! /bin/sh
#!/usr/bin/env bash
port=34001
ip=127.0.0.1
if [ ! -z "$1" ]
then
if [ -n "$1" ]
then
ip=$1
fi
if [ ! -z "$2" ]
then
if [ -n "$2" ]
then
port=$2
fi
current_path=$(pwd)
export PYTHONPATH="$current_path:$current_path/lib:$PYTHONPATH"
echo yes | django-admin collectstatic --settings=outils.settings
django-admin runserver $ip:$port --settings=outils.settings
export DJANGO_SETTINGS_MODULE=outils.settings
# Collect static files
echo yes | django-admin collectstatic
# Make sure couchdb databases exist
python manage.py couchdb
# Run server
django-admin runserver "$ip:$port"
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
import couchdb
class Command(BaseCommand):
help = 'Initialize needed couchDB databases'
def handle(self, *args, **options):
if 'admin' not in settings.COUCHDB:
raise CommandError('''
Veuillez définir les accès d'admin à CouchDB dans votre fichier settings_secret.py
Vérifiez le fichier settings_secret_example.py pour un exemple.''')
url = settings.COUCHDB['admin']['url'] % (settings.COUCHDB['admin']['user'], settings.COUCHDB['admin']['password'])
dbnames = settings.COUCHDB['dbs']
couchserver = couchdb.Server(url)
for dbname in dbnames.values():
if dbname not in couchserver:
self.stdout.write(self.style.WARNING("Missing database %s" % dbname))
db = couchserver.create(dbname)
self.stdout.write(self.style.SUCCESS("✓ created db"))
if dbname == 'coops':
self.createCoopsViews(db)
elif dbname == 'envelop':
self.createEnvelopViews(db)
# db.security
self.createPublicAccess(db)
def createCoopsViews(self, dbConn):
byFpMapFunction = '''function(doc) {
emit(doc.fingerprint);
}'''
byCompletedMapFunction = '''function(doc) {
emit(doc.completed);
}'''
byOdooMapFunction = '''function(doc) {
emit(doc.odoo_id);
}'''
views = {
"by_fp": {
"map": byFpMapFunction
},
"by_completed": {
"map": byCompletedMapFunction
},
"by_odoo_id": {
"map": byOdooMapFunction
},
}
self.createView(dbConn, "index", views)
def createEnvelopViews(self, dbConn):
byTypeMapFunction = '''function(doc) {
emit(doc.type);
}'''
views = {
"by_type": {
"map": byTypeMapFunction
}
}
self.createView(dbConn, "index", views)
def createView(self, dbConn, designDoc, views):
self.stdout.write(self.style.SUCCESS("✓ created view %s" % designDoc))
data = {
"_id": "_design/%s" % designDoc,
"views": views,
"language": "javascript",
"options": {"partitioned": False }
}
dbConn.save(data)
def createPublicAccess(self, dbConn):
self.stdout.write(self.style.SUCCESS("✓ created security rule"))
security_doc = dbConn.resource.get_json("_security")[2]
dbConn.resource.put("_security", {})
......@@ -93,7 +93,9 @@ class CagetteMember(models.Model):
fp = request.POST.get('fp') # fingerprint (prevent using stolen cookies)
if login and password:
api = OdooAPI()
cond = [['email', '=', login], ['is_member', '=', True]]
cond = [['email', '=', login]]
if getattr(settings, 'ALLOW_NON_MEMBER_TO_CONNECT', False) is False:
cond.append(['is_member', '=', True])
fields = ['name', 'email', 'birthdate', 'create_date', 'cooperative_state']
res = api.search_read('res.partner', cond, fields)
if (res and len(res) >= 1):
......@@ -317,7 +319,7 @@ class CagetteMember(models.Model):
if 'street2' in post_data:
received_data['street2'] = post_data['street2']
if 'phone' in post_data:
received_data['phone'] = post_data['phone']
received_data['phone'] = format_phone_number(post_data['phone'])
r = c_db.updateDoc(received_data, 'odoo_id')
if r:
if ('odoo_id' in r):
......@@ -394,7 +396,7 @@ class CagetteMember(models.Model):
'street': post_data['address'],
'zip': post_data['zip'],
'city': post_data['city'],
'phone': post_data['mobile'], # Because list view default show Phone and people mainly gives mobile
'phone': format_phone_number(post_data['mobile']), # Because list view default show Phone and people mainly gives mobile
'barcode_rule_id': settings.COOP_BARCODE_RULE_ID
}
if ('_id' in post_data):
......@@ -407,10 +409,10 @@ class CagetteMember(models.Model):
f['street2'] = post_data['street2']
if ('phone' in post_data) and len(post_data['phone']) > 0:
if len(f['phone']) == 0:
f['phone'] = post_data['phone']
f['phone'] = format_phone_number(post_data['phone'])
else:
f['mobile'] = f['phone']
f['phone'] = post_data['phone']
f['phone'] = format_phone_number(post_data['phone'])
# Create coop
if not ('odoo_id' in post_data):
......
......@@ -21,6 +21,16 @@ var to_fill_box = $('#to_fill'),
problem_delete = $('#problem_delete'),
vform = $('#coop_validation_form');
// date validation
Date.prototype.isValid = function () {
// If the date object is invalid it
// will return 'NaN' on getTime()
// and NaN is never equal to itself.
return this.getTime() === this.getTime();
};
sync.on('change', function (info) {
// handle change
if (info.direction == 'pull') {
......@@ -248,17 +258,30 @@ function save_current_coop(callback) {
sex_error = false;
if (/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/.exec(birthdate)) {
try{
var jj = RegExp.$1,
mm = RegExp.$2,
aaaa = RegExp.$3;
if (jj > 31 || mm > 12 || aaaa < 1900 || aaaa > 2018) {
let tmp_date = aaaa + "-" + mm + "-" + jj;
// try to create a date object
date_test = new Date(tmp_date);
// if date is invalid a correction is apply in date object. Check it
// january start at 0, so we add + 1 for the month
if ((date_test.getDate() !== parseInt(jj)) || ((date_test.getMonth()+1) !== parseInt(mm)) || (date_test.getFullYear() !== parseInt(aaaa)) || !date_test.isValid())
{
birthdate_error = true;
}
}catch(Exception){
birthdate_error = true;
}
} else {
birthdate_error = true;
}
let street2_input = form.find('[name="street2"]'),
phone_input = form.find('[name="phone"]');
......
......@@ -48,5 +48,4 @@ urlpatterns = [
url(r'^add_pts_to_everybody/([0-9]+)/([a-zA-Z0-9_ ]+)$', admin.add_pts_to_everybody),
# conso / groupe recherche / socio
url(r'^panel_get_purchases$', views.panel_get_purchases),
]
......@@ -23,7 +23,8 @@ def index(request):
'WELCOME_ENTRANCE_MSG': getattr(settings, 'WELCOME_ENTRANCE_MSG', 'Bienvenue !'),
'WELCOME_SUBTITLE_ENTRANCE_MSG': getattr(settings, 'WELCOME_SUBTITLE_ENTRANCE_MSG', ''),
'ENTRANCE_SHOPPING_BTN': getattr(settings, 'ENTRANCE_SHOPPING_BTN', 'Je viens faire mes courses'),
'ENTRANCE_SERVICE_BTN': getattr(settings, 'ENTRANCE_SERVICE_BTN', 'Je viens faire mon service')
'ENTRANCE_SERVICE_BTN': getattr(settings, 'ENTRANCE_SERVICE_BTN', 'Je viens faire mon service'),
'CONFIRME_PRESENT_BTN' : getattr(settings, 'CONFIRME_PRESENT_BTN', 'Présent.e')
}
for_shoping_msg = getattr(settings, 'ENTRANCE_COME_FOR_SHOPING_MSG', '')
......@@ -102,6 +103,7 @@ def prepa_odoo(request):
'office_place_string': settings.OFFICE_NAME,
'max_begin_hour': settings.MAX_BEGIN_HOUR,
'payment_meanings': settings.SUBSCRIPTION_PAYMENT_MEANINGS,
'input_phone_pattern': getattr(settings, 'INPUT_PHONE_PATTERN', default_input_phone_pattern),
'input_barcode': getattr(settings, 'SUBSCRIPTION_INPUT_BARCODE', False),
'ask_for_sex': getattr(settings, 'SUBSCRIPTION_ASK_FOR_SEX', False),
'ask_for_street2': getattr(settings, 'SUBSCRIPTION_ADD_STREET2', False),
......@@ -135,6 +137,7 @@ def validation_inscription(request, email):
'office_place_string': settings.OFFICE_NAME,
'max_begin_hour': settings.MAX_BEGIN_HOUR,
'payment_meanings': settings.SUBSCRIPTION_PAYMENT_MEANINGS,
'input_phone_pattern': getattr(settings, 'INPUT_PHONE_PATTERN', default_input_phone_pattern),
'ask_for_sex': getattr(settings, 'SUBSCRIPTION_ASK_FOR_SEX', False),
'ask_for_street2': getattr(settings, 'SUBSCRIPTION_ADD_STREET2', False),
'ask_for_second_phone': getattr(settings, 'SUBSCRIPTION_ADD_SECOND_PHONE', False),
......
......@@ -77,6 +77,9 @@ class OdooAPI:
class CouchDB:
"""Class to handle interactions with CouchDB"""
if 'private_url' in settings.COUCHDB:
url = settings.COUCHDB['private_url']
else:
url = settings.COUCHDB['url']
dbs = settings.COUCHDB['dbs']
db = None
......
# -*- coding: utf-8 -*-
"""commons apps functions ."""
from django.conf import settings
default_input_phone_pattern = "^((\+33(-| )\d{1})|\d{2})(\.| )\d{2}(\.| )\d{2}(\.| )\d{2}(\.| )\d{2}$"
def format_phone_number(phone_string):
"""Format phone number for DB insertion (french format)"""
try:
import re
# keep only figures
figures = re.sub(r'[^0-9]', '', phone_string)
international_prefix = ''
if len(figures) > 10:
international_prefix = figures[:len(figures) -9]
figures = figures[-9:]
# for the moment, international prefix is omitted, since only french format is processed
if len(figures) == 9:
figures = '0' + figures
if len(figures) == 10:
number_pairs = [figures[:2]]
for i in range(1,5):
idx = i*2
number_pairs.append(figures[idx:idx + 2])
phone_pairs_separator = getattr(settings, 'PHONE_PAIRS_SEPARATOR', ' ')
output_phone_number = phone_pairs_separator.join(number_pairs)
else:
output_phone_number = phone_string
except:
output_phone_number = phone_string
return output_phone_number
......@@ -79,3 +79,4 @@ LOGGING = {
}
"""
coop_logger = logging.getLogger("coop.framework")
......@@ -106,6 +106,14 @@
Maximum accepted checks numbers
- INPUT_PHONE_PATTERN = "^(0\d{9})$"
Regexp pattern which is used to validate values input in phone fields
Default is "^((\+33(-| )\d{1})|\d{2})(\.| )\d{2}(\.| )\d{2}(\.| )\d{2}(\.| )\d{2}$"
- PHONE_PAIRS_SEPARATOR = "."
Character which by used to separate every 2 phone figures (04.67.23.89.21 for example)
Default is " "
### Scales and labels files generation
- DAV_PATH = '/data/dav/cagette'
......
......@@ -22,7 +22,7 @@ class CagetteMail:
html_message=html_msg)
@staticmethod
def sendCartValidation(email, cart):
def sendCartValidation(email, cart, mode="shop"):
"""Used by Shop"""
from django.core.mail import send_mail
from django.utils.html import strip_tags
......@@ -43,7 +43,10 @@ class CagetteMail:
html_msg = render_to_string(mail_template, ctx)
msg = strip_tags(html_msg)
send_mail("Votre commande en ligne à " + settings.COMPANY_NAME,
subject_prefix = "Votre commande en ligne à "
if mode == "delivery":
subject_prefix = "Votre demande de livraison à "
send_mail(subject_prefix + settings.COMPANY_NAME,
msg,
settings.DEFAULT_FROM_EMAIL,
[email],
......
# coding: utf-8
import sys, getopt, os
sys.path.append(os.path.abspath('../..'))
from outils.common import OdooAPI
from outils.config import COOP_BARCODE_RULE_ID
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment
import datetime
# from django.conf import settings
from openpyxl.utils.exceptions import InvalidFileException
def main():
""" Pass file as script arg """
if len(sys.argv) < 2:
print("Il faut renseigner le chemin du fichier contenant les données des rattachés (format Excel).")
exit(2)
api = OdooAPI()
data_file = sys.argv[1]
try:
wb = load_workbook(data_file)
except FileNotFoundError:
print("Fichier introuvable.")
exit(2)
except InvalidFileException:
print("Le fichier fourni est invalide, il doit être au format Excel (.xlsx,.xlsm,.xltx,.xltm)")
exit(2)
while True:
try:
worksheet_number = input(f'Numéro de la feuille contenant les données (entre 0 et {len(wb.worksheets)-1}) : ')
worksheet_number = int(worksheet_number)
ws = wb.worksheets[worksheet_number]
except ValueError:
print("Veuillez rentrer un numéro entier.")
continue
except IndexError:
print("Cette feuille n'existe pas.")
continue
else:
break
columns_valid = input("""
Les colonnes doivent être les suivantes :
A: active*
B: barode_base*
C: name*
D: (ignorée)
E: date_inclusion
F: email
G: birthdate
H: mobile
I: phone
J: street
K: street2
L: zip
M: city
N: sex
O: (ignorée)
P: parent_member_id*
(* ces champs doivent être renseignés)
Vous confirmez ? (O/n) """)
while True:
if (columns_valid == 'n' or columns_valid == 'N'):
print("Veuillez formatter correctement le fichier avant de continuer !")
exit()
elif (columns_valid == 'o' or columns_valid == 'O' or columns_valid== ''):
break
else:
columns_valid = input("Vous confirmez ? (O/n) ")
continue
users = []
has_error = False
for row in ws.iter_rows(min_row=2, values_only=True):
# active
if row[0] is None or row[0] is False or row[0] == "=FALSE()" or row[0] == "=false":
active = False
else:
active = True
# If line is not empty (mandatory field check)
if row[2] is not None:
user = {
"is_member": False,
"is_associated_people": True,
"active": active,
"barcode_rule_id": COOP_BARCODE_RULE_ID,
"name": row[2],
"parent_id": int(row[15]), # for development, override with local existing member id
}
if row[1] is not None and row[1] != "NON":
try:
user["barcode_base"] = int(row[1])
except Exception:
print(f"[Mauvais format du champ 'barcode_base' pour l'utilisateur '{row[2]}' (Attendu : nombre entier)")
has_error = True
if row[4] is not None:
user["comment"] = f"Date d'inclusion : {row[4].date().strftime('%d/%m/%Y')}"
if row[5] is not None:
user["email"] = row[5]
if row[6] is not None:
user["birthdate"] = str(row[6].date())
if row[7] is not None:
try:
mobile = str(row[7]).replace(" ", "")
if mobile[0] != '+' and mobile[0] != '0':
mobile = '0' + mobile
user["mobile"] = mobile
except Exception:
print(f"[Mauvais format du champ 'mobile' pour l'utilisateur '{row[2]}'")
has_error = True
if row[8] is not None:
try:
phone = str(row[8]).replace(" ", "")
if phone[0] != '+' and phone[0] != '0':
phone = '0' + phone
user["phone"] = phone
except Exception:
print(f"[Mauvais format du champ 'phone' pour l'utilisateur '{row[2]}'")
has_error = True
if row[9] is not None:
user["street"] = row[9]
if row[10] is not None:
user["street2"] = row[10]
if row[11] is not None:
try:
zipcode = str(int(row[11]))
if len(zipcode) == 4:
zipcode = '0' + zipcode
user["zip"] = zipcode
except Exception:
print(f"[Mauvais format du champ 'zipcode' pour l'utilisateur '{row[2]}'")
has_error = True
if row[12] is not None:
user["city"] = row[12]
if row[13] == "Femme":
user["sex"] = "f"
elif row[13] == "Homme":
user["sex"] = "m"
users.append(user)
if has_error:
print("L'import a été interrompu, veuillez régler les erreurs.")
exit(2)
res = None
marshal_none_error = 'cannot marshal None unless allow_none is enabled'
for user in users:
try:
res = api.create('res.partner', user)
if res:
print(f"Rattaché.e importé.e avec succès : {user['name']} (id : {res})")
except Exception as e:
if not (marshal_none_error in str(e)):
print(f"Erreur lors de l'insertion de {user['name']}, vérifiez ses données dans le tableau ({str(e)})")
else:
pass
if __name__ == "__main__":
main()
\ No newline at end of file
SECRET_KEY = 'Mettre_plein_de_caracteres_aleatoires_iezezezeezezci'
ODOO = {
'url': 'http://127.0.0.1:8069'
'user': 'api',
'passwd': 'xxxxxxxxxxxx',
'db': 'bd_test',
}
COUCHDB = {
'url': 'http://127.0.0.1:5984',
'dbs': {
'member': 'coops',
'inventory': 'inventory',
'envelops': 'envelop',
'shop': 'shopping_carts'
}
}
......@@ -14,7 +14,6 @@ https://docs.djangoproject.com/en/1.8/ref/settings/
import os
from .settings_secret import *
from .texts.cagette import *
from .config import *
from .customized_errors_filter import *
......@@ -53,6 +52,7 @@ INSTALLED_APPS = (
'orders',
'shop',
'shelfs',
'sales',
# 'tests'
)
......@@ -222,3 +222,5 @@ LOGGING = {
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CORS_ORIGIN_ALLOW_ALL = True # Needed to make dev test with different IP and ports
ADMIN_IDS = [1]
"""Secret data for DB connexion ."""
ODOO = {
'url': 'http://127.0.0.1:8069'
'url': 'http://odoo:8069',
'user': 'api',
'passwd': 'xxxxxxxxxxxx',
'db': 'bd_test',
'passwd': 'foodcoops',
'db': 'foodcoops',
}
COUCHDB = {
'private_url': 'http://couchdb:5984',
'url': 'http://127.0.0.1:5984',
'admin': {
'url': 'http://%s:%s@couchdb:5984',
'user': 'admin',
'password': '123abc',
},
'dbs': {
'member': 'coops',
'inventory': 'inventory',
......@@ -17,7 +23,7 @@ COUCHDB = {
}
}
""" To ignore """
SQL_OFF = {
'db': 'open_food_facts',
'user': 'off_user',
......
......@@ -44,6 +44,7 @@ urlpatterns = [
url(r'^website/', include('website.urls')),
url(r'^shop/', include('shop.urls')),
url(r'^shelfs/', include('shelfs.urls')),
url(r'^sales/', include('sales.urls')),
]
try:
......
......@@ -20,12 +20,12 @@
"dev": true
},
"@babel/highlight": {
"version": "7.10.4",
"resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz",
"integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==",
"version": "7.13.10",
"resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.13.10.tgz",
"integrity": "sha512-5aPpe5XQPzflQrFwL1/QoeHkP2MsA4JCntcXHRhEsdsfPVkvPi2w7Qix4iV7t5S/oC9OodGrggd8aco1g3SZFg==",
"dev": true,
"requires": {
"@babel/helper-validator-identifier": "^7.10.4",
"@babel/helper-validator-identifier": "^7.12.11",
"chalk": "^2.0.0",
"js-tokens": "^4.0.0"
},
......@@ -44,9 +44,9 @@
}
},
"@eslint/eslintrc": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.2.2.tgz",
"integrity": "sha512-EfB5OHNYp1F4px/LI/FEnGylop7nOqkQ1LRzCM0KccA2U8tvV8w01KBv37LbO7nW4H+YhKyo2LcJhRwjjV17QQ==",
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.0.tgz",
"integrity": "sha512-2ZPCc+uNbjV5ERJr+aKSPRwZgKd2z11x0EgLvb1PURmUrn9QNRXFqje0Ldq454PfAVyaJYyrDvvIKSFP4NnBog==",
"dev": true,
"requires": {
"ajv": "^6.12.4",
......@@ -56,9 +56,19 @@
"ignore": "^4.0.6",
"import-fresh": "^3.2.1",
"js-yaml": "^3.13.1",
"lodash": "^4.17.19",
"minimatch": "^3.0.4",
"strip-json-comments": "^3.1.1"
},
"dependencies": {
"globals": {
"version": "12.4.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz",
"integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==",
"dev": true,
"requires": {
"type-fest": "^0.8.1"
}
}
}
},
"acorn": {
......@@ -122,9 +132,9 @@
"dev": true
},
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true
},
"brace-expansion": {
......@@ -137,6 +147,16 @@
"concat-map": "0.0.1"
}
},
"call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
"integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
"dev": true,
"requires": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
}
},
"callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
......@@ -272,13 +292,13 @@
"dev": true
},
"eslint": {
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-7.16.0.tgz",
"integrity": "sha512-iVWPS785RuDA4dWuhhgXTNrGxHHK3a8HLSMBgbbU59ruJDubUraXN8N5rn7kb8tG6sjg74eE0RA3YWT51eusEw==",
"version": "7.24.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-7.24.0.tgz",
"integrity": "sha512-k9gaHeHiFmGCDQ2rEfvULlSLruz6tgfA8DEn+rY9/oYPFFTlz55mM/Q/Rij1b2Y42jwZiK3lXvNTw6w6TXzcKQ==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.0.0",
"@eslint/eslintrc": "^0.2.2",
"@babel/code-frame": "7.12.11",
"@eslint/eslintrc": "^0.4.0",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
"cross-spawn": "^7.0.2",
......@@ -289,12 +309,12 @@
"eslint-utils": "^2.1.0",
"eslint-visitor-keys": "^2.0.0",
"espree": "^7.3.1",
"esquery": "^1.2.0",
"esquery": "^1.4.0",
"esutils": "^2.0.2",
"file-entry-cache": "^6.0.0",
"file-entry-cache": "^6.0.1",
"functional-red-black-tree": "^1.0.1",
"glob-parent": "^5.0.0",
"globals": "^12.1.0",
"globals": "^13.6.0",
"ignore": "^4.0.6",
"import-fresh": "^3.0.0",
"imurmurhash": "^0.1.4",
......@@ -302,7 +322,7 @@
"js-yaml": "^3.13.1",
"json-stable-stringify-without-jsonify": "^1.0.1",
"levn": "^0.4.1",
"lodash": "^4.17.19",
"lodash": "^4.17.21",
"minimatch": "^3.0.4",
"natural-compare": "^1.4.0",
"optionator": "^0.9.1",
......@@ -375,9 +395,9 @@
"dev": true
},
"esquery": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/esquery/-/esquery-1.3.1.tgz",
"integrity": "sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz",
"integrity": "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==",
"dev": true,
"requires": {
"estraverse": "^5.1.0"
......@@ -439,9 +459,9 @@
"dev": true
},
"file-entry-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.0.tgz",
"integrity": "sha512-fqoO76jZ3ZnYrXLDRxBR1YvOvc0k844kcOg40bgsPrE25LAb/PDqTY+ho64Xh2c8ZXgIKldchCFHczG2UVRcWA==",
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
"integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==",
"dev": true,
"requires": {
"flat-cache": "^3.0.4"
......@@ -458,9 +478,9 @@
}
},
"flatted": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.1.0.tgz",
"integrity": "sha512-tW+UkmtNg/jv9CSofAKvgVcO7c2URjhTdW1ZTkcAritblu8tajiYy7YisnIflEwtKssCtOxpnBRoCB7iap0/TA==",
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.1.1.tgz",
"integrity": "sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==",
"dev": true
},
"fs.realpath": {
......@@ -469,12 +489,29 @@
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
},
"function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
"dev": true
},
"functional-red-black-tree": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz",
"integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=",
"dev": true
},
"get-intrinsic": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz",
"integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==",
"dev": true,
"requires": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
}
},
"glob": {
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz",
......@@ -490,21 +527,38 @@
}
},
"glob-parent": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz",
"integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==",
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"requires": {
"is-glob": "^4.0.1"
}
},
"globals": {
"version": "12.4.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz",
"integrity": "sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg==",
"version": "13.8.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-13.8.0.tgz",
"integrity": "sha512-rHtdA6+PDBIjeEvA91rpqzEvk/k3/i7EeNQiryiWuJH0Hw9cpyJMAt2jtbAwUaRdhD+573X4vWw6IcjKPasi9Q==",
"dev": true,
"requires": {
"type-fest": "^0.8.1"
"type-fest": "^0.20.2"
},
"dependencies": {
"type-fest": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
"dev": true
}
}
},
"has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"dev": true,
"requires": {
"function-bind": "^1.1.1"
}
},
"has-flag": {
......@@ -513,6 +567,12 @@
"integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
"dev": true
},
"has-symbols": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz",
"integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==",
"dev": true
},
"ignore": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz",
......@@ -551,6 +611,15 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true
},
"is-boolean-object": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.0.tgz",
"integrity": "sha512-a7Uprx8UtD+HWdyYwnD1+ExtTgqQtD2k/1yJgtXP6wnMm8byhkoTZRl+95LLThpzNZJ5aEvi46cdH+ayMFRwmA==",
"dev": true,
"requires": {
"call-bind": "^1.0.0"
}
},
"is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
......@@ -572,6 +641,18 @@
"is-extglob": "^2.1.1"
}
},
"is-number-object": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.4.tgz",
"integrity": "sha512-zohwelOAur+5uXtk8O3GPQ1eAcu4ZX3UwxQhUlfFFMNpUd83gXgjbhJh6HmB6LUNV/ieOLQuDwJO3dWJosUeMw==",
"dev": true
},
"is-string": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz",
"integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==",
"dev": true
},
"isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
......@@ -617,9 +698,27 @@
}
},
"lodash": {
"version": "4.17.20",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
"integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true
},
"lodash.clonedeep": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz",
"integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=",
"dev": true
},
"lodash.flatten": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
"integrity": "sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=",
"dev": true
},
"lodash.truncate": {
"version": "4.4.2",
"resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz",
"integrity": "sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=",
"dev": true
},
"lru-cache": {
......@@ -720,6 +819,12 @@
"integrity": "sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q==",
"dev": true
},
"require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"dev": true
},
"resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
......@@ -736,9 +841,9 @@
}
},
"semver": {
"version": "7.3.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.3.4.tgz",
"integrity": "sha512-tCfb2WLjqFAtXn4KEdxIhalnRtoKFN7nAwj0B3ZXCbQloV2tq5eDbcTmT68JJD3nRJq24/XgxtQKFIpQdtvmVw==",
"version": "7.3.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz",
"integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==",
"dev": true,
"requires": {
"lru-cache": "^6.0.0"
......@@ -803,9 +908,9 @@
"dev": true
},
"string-width": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz",
"integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz",
"integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==",
"dev": true,
"requires": {
"emoji-regex": "^8.0.0",
......@@ -838,15 +943,40 @@
}
},
"table": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/table/-/table-6.0.4.tgz",
"integrity": "sha512-sBT4xRLdALd+NFBvwOz8bw4b15htyythha+q+DVZqy2RS08PPC8O2sZFgJYEY7bJvbCFKccs+WIZ/cd+xxTWCw==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/table/-/table-6.1.0.tgz",
"integrity": "sha512-T4G5KMmqIk6X87gLKWyU5exPpTjLjY5KyrFWaIjv3SvgaIUGXV7UEzGEnZJdTA38/yUS6f9PlKezQ0bYXG3iIQ==",
"dev": true,
"requires": {
"ajv": "^6.12.4",
"lodash": "^4.17.20",
"ajv": "^8.0.1",
"is-boolean-object": "^1.1.0",
"is-number-object": "^1.0.4",
"is-string": "^1.0.5",
"lodash.clonedeep": "^4.5.0",
"lodash.flatten": "^4.4.0",
"lodash.truncate": "^4.4.2",
"slice-ansi": "^4.0.0",
"string-width": "^4.2.0"
},
"dependencies": {
"ajv": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.1.0.tgz",
"integrity": "sha512-B/Sk2Ix7A36fs/ZkuGLIR86EdjbgR6fsAcbx9lOP/QBSXujDNbVmIS/U4Itz5k8fPFDeVZl/zQ/gJW4Jrq6XjQ==",
"dev": true,
"requires": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2",
"uri-js": "^4.2.2"
}
},
"json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"dev": true
}
}
},
"text-table": {
......@@ -871,18 +1001,18 @@
"dev": true
},
"uri-js": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.0.tgz",
"integrity": "sha512-B0yRTzYdUCCn9n+F4+Gh4yIDtMQcaJsmYBDsTSG8g/OejKBodLQ2IHfN3bM7jUsRXndopT7OIXWdYqc1fjmV6g==",
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
"dev": true,
"requires": {
"punycode": "^2.1.0"
}
},
"v8-compile-cache": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.2.0.tgz",
"integrity": "sha512-gTpR5XQNKFwOd4clxfnhaqvfqMpqEwr4tOtCyz4MtYZX2JYhfr1JvBFKdS+7K/9rfpZR3VLX+YWBbKoxCgS43Q==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz",
"integrity": "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==",
"dev": true
},
"which": {
......
......@@ -5,7 +5,7 @@
"main": "index.js",
"dependencies": {},
"devDependencies": {
"eslint": "^7.16.0"
"eslint": "^7.24.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
......
......@@ -108,6 +108,16 @@ class CagetteProduct(models.Model):
def register_start_supplier_shortage(product_id, partner_id, date_start):
"""Start a supplier shortage for a product"""
api = OdooAPI()
c = [['product_id', '=', product_id],
['partner_id', '=', partner_id],
['date_start', '=', date_start]]
existing = api.search_read('product.supplier.shortage', c)
if existing:
res = "already on shortage"
return res
f = {
'product_id' : product_id,
'partner_id' : partner_id,
......
......@@ -32,6 +32,21 @@ IFCBarcodes = {
display_last_error: function() {
alert(this.errors[this.errors.length - 1]);
},
get_quantity_eq_to_encoded_price: function (value, list_price, currency) {
let qty = 0;
try {
let price = parseFloat(value);
if (currency == 'FF')
price = price / 6.55957;
qty = parseFloat(price / list_price).toFixed(3);
} catch (error) {
console.log(error);
}
return qty;
},
get_corresponding_odoo_product: function(bc) {
//console.log('To analyze :' + bc)
var index = 0,
......@@ -49,31 +64,45 @@ IFCBarcodes = {
if (bc.indexOf(significant_prefix) === 0) {
/*
Submitted barcode-code matches a pattern rule
For example,
bc = 0493213018809
pattern = 0493...{NNDDD}
*/
//console.log(pattern)
// console.log(bc)
odoo_bc = '';
pattern_found = true;
pattern_type = this.patterns[index].type;
pattern = pattern.replace(/[^0-9.ND]/, '');
bc = bc.slice(0, -1); // remove original check figure
// Read pattern character by character
/*
Read pattern character by character
to find out Odoo article barcode
and encoded_value (weight, price, units, if exists)
*/
for (var i = 0; i < pattern.length; i++) {
if (/[0-9]/.exec(pattern[i])) {
// it's a figure, nothing to do but to add it to string
odoo_bc += pattern[i];
} else if (pattern[i].indexOf('.') === 0) {
/*
it's a substitution character,
so add the submitted barcode figure which is in this position
*/
odoo_bc += bc[i];
} else if (/[ND]/.exec(pattern[i])) {
/*
A figure which encoding a value is in this position
(corresponding to a 0 in Odoo article barcode)
*/
odoo_bc += '0';
/* let's add a decimal sepator if D is read for the first time */
if (pattern[i] === 'D' && encoded_value.indexOf('.') < 0)
encoded_value += '.';
encoded_value += bc[i];
}
}
// Add check digit at the end of odoo_bc to find out "normalized" code
bc = odoo_bc + eanCheckDigit(odoo_bc);
}
......@@ -101,16 +130,35 @@ IFCBarcodes = {
if (product_data !== null) {
p_uom = (this.uoms)[product_data[this.keys.uom_id]];
let qty = 1;
if (encoded_value.length > 0 && !isNaN(encoded_value)) {
qty = 0; //if no rule is found it will advise user that there is a problem
/*
Warning :
Tests are dependant on La Cagette / Cooperatic uom system and barcode rules
TODO : Defines them outside of this part of code
*/
if (p_uom == 'Unit(s)' || p_uom == 'unité') {
encoded_value = parseInt(encoded_value, 10);
qty = encoded_value;
} else {
encoded_value = parseFloat(encoded_value);
if (pattern_type == 'weight' || pattern_type == 'FF_price_to_weight' || pattern_type == 'price_to_weight') {
if (pattern_type == 'weight') {
qty = encoded_value;
} else {
let list_price = product_data[this.keys.list_price];
let currency = null;
if (pattern_type == 'FF_price_to_weight') currency = 'FF'
qty = parseFloat(this.get_quantity_eq_to_encoded_price(encoded_value, list_price, currency));
}
}
odoo_product = {barcode: bc, data: product_data, rule: pattern_type, value: encoded_value};
}
}
odoo_product = {barcode: bc, data: product_data, rule: pattern_type, value: encoded_value, qty: qty};
}
return odoo_product;
......
var order = {
'id' : null
},
table_orders = null,
callback_update = false,
callback_report = false,
selection_type = null,
......@@ -25,7 +26,7 @@ function goto(id) {
* i : index of group in 'saved_groups' array
*/
function group_goto(i) {
// Check if all group's orders are saved in local storage
// Make sure all group's orders are saved in local storage
for (j in saved_groups[i]) {
set_local_storage(saved_groups[i][j]);
}
......@@ -48,6 +49,144 @@ function set_local_storage(order_data) {
}
}
/*
* Remove from local storage orders that have a wrong status
* (-> order has been updated elsewhere)
*/
function clean_local_storage() {
var stored_order = null;
// Loop through local storage
for (key of Object.keys(localStorage)) {
if (key.startsWith('order_')) {
stored_order = JSON.parse(localStorage.getItem(key));
// Loop through orders in table to find match
var i = 0;
var found = false;
while (i < table_orders.rows().data().length && !found) {
var uptodate_order = table_orders.rows(i).data()[0];
// If status in local storage is wrong
if (stored_order.id == uptodate_order.id
&& stored_order.reception_status != uptodate_order.reception_status) {
// Remove from local storage
localStorage.removeItem("order_" + uptodate_order.id);
// Evolution: warn user (order modified elsewhere, local data has been deleted)
found = true;
}
i++;
}
if (!found) {
// Remove too if order isn't in server data
localStorage.removeItem("order_" + stored_order.id);
}
}
}
}
function create_groups_from_server_data() {
// Get array of stored grouped orders
var grouped_orders = JSON.parse(localStorage.getItem('grouped_orders'));
// Create if not exists
if (grouped_orders == null) {
grouped_orders = [];
} else {
// Remove from server data groups already in local storage
for (stored_group of grouped_orders) {
for (sg_order_item of stored_group) {
for (i in server_stored_groups) {
if (server_stored_groups[i].includes(sg_order_item)) {
server_stored_groups.splice(i, 1);
break;
}
}
}
}
}
// Add server groups to stored groups
grouped_orders = grouped_orders.concat(server_stored_groups);
localStorage.setItem('grouped_orders', JSON.stringify(grouped_orders));
}
/*
* If there are groups in local storage, extract them from the table, set the groups actions.
*/
function extract_grouped_orders() {
var saved_grouped_orders = JSON.parse(localStorage.getItem('grouped_orders'));
var groups_to_delete = []; // indexes
// if there are grouped orders
if (saved_grouped_orders != null) {
// for each group
for (group_index in saved_grouped_orders) {
var g = [];
// for each order in group
for (group_element_id of saved_grouped_orders[group_index]) {
// Look for order in datatable
for (var i = 0; i < table_orders.rows().data().length; i++) {
if (group_element_id == table_orders.rows(i).data()[0].id) {
var order = table_orders.rows(i).data()[0];
g.push(order);
// remove raw from table
table_orders.rows(i).remove()
.draw();
}
}
}
// No order found, delete group and skip the rest
if (g.length == 0) {
groups_to_delete.push(group_index);
continue;
}
// Display group
document.getElementById("container_groups").hidden = false;
var group_row = "<ul> <li> Commandes de ";
for (i in g) {
if (i == g.length-1) { // last element of list
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : ";
} else {
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", ";
}
}
if (g[0].reception_status == 'False') {
group_row += "<button class='btn--primary' onClick='group_goto("
+ saved_groups.length
+ ")'>Compter les produits</button>";
} else {
group_row += "<button class='btn--success' onClick='group_goto("
+ saved_groups.length
+ ")'>Mettre à jour les prix</button>";
}
group_row += "</li>";
$('#groups_items').append(group_row);
saved_groups.push(g);
}
}
if (groups_to_delete.length > 0) {
for (index of groups_to_delete) {
saved_grouped_orders.splice(index, 1);
}
localStorage.setItem('grouped_orders', JSON.stringify(saved_grouped_orders));
}
}
/* ACTIONS */
......@@ -63,7 +202,6 @@ function validatePrices() {
update_data.orders[order['id']] = { 'po' : [] };
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({
type: "PUT",
url: "/reception/update_orders",
......@@ -71,7 +209,7 @@ function validatePrices() {
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(update_data),
success: function(data) {
success: function() {
localStorage.removeItem("order_" + order["id"]);
callback_update = true;
reload();
......@@ -100,7 +238,7 @@ function validatePrices() {
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(updates),
success: function(data) {
success: function() {
callback_report = true;
reload();
},
......@@ -119,23 +257,34 @@ function group_action() {
var pswd = prompt('Merci de demander à un.e salarié.e le mot de passe pour fusionner ces commandes.');
if (pswd == merge_orders_pswd) { // Minimum security level
var table_orders = $('#orders').DataTable();
// Use local storage to pass order data to next page
if (Modernizr.localstorage) {
var selected_data = table_orders.rows('.selected').data();
var group_ids = [];
var min_id = 999999;
// Select orders id
for (var i = 0; i < selected_data.length; i++) {
// Add order to group
group_ids.push(selected_data[i].id);
}
// Notify server that group is created
$.ajax({
type: "POST",
url: "/reception/save_order_group",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(group_ids),
success: function() {
var min_id = 9999999;
for (var i = 0; i < selected_data.length; i++) {
// get smallest id
if (selected_data[i].id < min_id) {
min_id = selected_data[i].id;
}
// Add each order to local storage
set_local_storage(selected_data[i]);
}
......@@ -147,15 +296,28 @@ function group_action() {
grouped_orders = [];
}
// Add group (removed verif if group already exists, it shouldn't)
// Add group
grouped_orders.push(group_ids);
// store grouped orders array
localStorage.setItem('grouped_orders', JSON.stringify(grouped_orders));
}
// Go to products page of order with smallest id
goto(min_id);
},
error: function(data) {
if (data != null && data.status == 409) {
alert("Un groupe a déjà été formé sur un autre poste "
+ "avec au moins l'une des commandes sélectionnées. Merci de rafraichir la page.");
}
}
});
} else {
alert("Le local storage n'est pas disponible. Merci de contacter un.e salarié.e !");
}
} else if (pswd == null) {
return;
} else {
......@@ -165,19 +327,21 @@ function group_action() {
$(document).ready(function() {
openModal();
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
// Set date format for DataTable so date ordering can work
$.fn.dataTable.moment('D/M/Y');
var saved_grouped_orders = JSON.parse(localStorage.getItem('grouped_orders'));
var table_orders = $('#orders').DataTable({
table_orders = $('#orders').DataTable({
ajax: "get_list_orders",
columns:[
{
data:"id",
title:"Sélectionner",
className:"dt-body-center",
render: function (data, type, full, meta) {
render: function (data) {
return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">';
},
width: "4%",
......@@ -187,7 +351,7 @@ $(document).ready(function() {
{
data:"partner",
title:"Fournisseur",
render: function (data, type, full, meta) {
render: function (data, type, full) {
// Add tooltip with PO over partner name
return '<div class="tooltip">' + data + ' <span class="tooltiptext">' + full.name + '</span> </div>';
}
......@@ -195,7 +359,7 @@ $(document).ready(function() {
{
data:"reception_status",
className:"dt-body-center",
render: function (data, type, full, meta) {
render: function (data) {
if (data == "qty_valid") {
return "<span class='btn--danger'>Pas de prix sur le bon de livraison</span>";
} else {
......@@ -209,7 +373,7 @@ $(document).ready(function() {
data:"reception_status",
title:"Statut",
className:"dt-body-center",
render: function (data, type, full, meta) {
render: function (data) {
switch (data) {
case 'qty_valid':
return "<span class='btn--success'>Mettre à jour les prix</span>";
......@@ -231,57 +395,11 @@ $(document).ready(function() {
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'},
initComplete: function(settings, json) { // After data is loaded
// if there are grouped orders
if (saved_grouped_orders != null) {
$('#groups_items').append("<ul>");
// for each group
for (group of saved_grouped_orders) {
var g = [];
// for each order in group
for (group_element_id of group) {
// Look for order in datatable
for (var i = 0; i < table_orders.rows().data().length; i++) {
if (group_element_id == table_orders.rows(i).data()[0].id) {
var order = table_orders.rows(i).data()[0];
g.push(order);
// remove raw from table
table_orders.rows(i).remove()
.draw();
}
}
}
// Display group
document.getElementById("container_groups").hidden = false;
var group_row = "<ul> <li> Commandes de ";
for (i in g) {
if (i == g.length-1) { // last element of list
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : ";
} else {
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", ";
}
}
if (g[0].reception_status == 'False') {
group_row += "<button class='btn--primary' onClick='group_goto(" + saved_groups.length + ")'>Compter les produits</button>";
} else {
group_row += "<button class='btn--success' onClick='group_goto(" + saved_groups.length + ")'>Mettre à jour les prix</button>";
}
group_row += "</li>";
$('#groups_items').append(group_row);
saved_groups.push(g);
}
}
$('#groups_items').append("</ul>");
initComplete: function() { // After data is loaded
clean_local_storage();
create_groups_from_server_data();
extract_grouped_orders();
closeModal();
}
});
......@@ -340,9 +458,7 @@ $(document).ready(function() {
selection_type = null;
document.getElementById("group_action").hidden = true;
}
}
// Click on last cell button -> go to products page
else if (this.cellIndex == 4) {
} else if (this.cellIndex == 4) { // Click on last cell button -> go to products page
// Extra security if order with a different status gets lost in here
if (row_data.reception_status == "qty_valid" || row_data.reception_status == "False") {
// Use local storage to pass order data to next page
......@@ -350,9 +466,8 @@ $(document).ready(function() {
goto(row_data.id);
}
}
} else if (this.cellIndex == 3 && row_data.reception_status == "qty_valid") {
// If 'update prices' step, click on before-last cell -> validate all prices
else if (this.cellIndex == 3 && row_data.reception_status == "qty_valid") {
order = row_data;
openModal($('#modal_no_prices').html(), validatePrices, 'Confirmer', false);
}
......
......@@ -18,13 +18,13 @@ var orders = {},
is_group = false,
group_ids = [];
var reception_status,
var reception_status = null,
list_to_process = [],
list_processed = [],
table_to_process,
table_processed,
table_to_process = null,
table_processed = null,
editing_product = null, // Store the product currently being edited
editing_origin, // Keep track of where editing_product comes from
editing_origin = null, // Keep track of where editing_product comes from
processed_row_counter = 0, // Order in which products were added in processed list
user_comments = "",
updatedProducts = [], // Keep record of updated products
......@@ -108,6 +108,8 @@ function select_product_from_bc(barcode) {
console.error(err);
report_JS_error(err, 'reception');
}
return 0;
}
/* INIT */
......@@ -231,7 +233,7 @@ function initLists() {
data:"product_id.1",
title:"Produit",
width: "45%",
render: function (data, type, full, meta) {
render: function (data, type, full) {
// Add tooltip with barcode over product name
let display_barcode = "Aucun";
......@@ -300,7 +302,7 @@ function initLists() {
data:"product_id.1",
title:"Produit",
width: "55%",
render: function (data, type, full, meta) {
render: function (data, type, full) {
// Add tooltip with barcode over product name
let display_barcode = "Aucun";
......@@ -344,7 +346,7 @@ function initLists() {
title:"Autres",
className:"dt-body-center",
orderable: false,
render: function (data, type, full, meta) {
render: function (data, type, full) {
let disabled = (full.supplier_shortage) ? "disabled" : '';
return "<select class='select_product_action'>"
......@@ -889,7 +891,7 @@ function editProductInfo (productToEdit, value = null) {
}
// Validate product edition
function validateEdition(form) {
function validateEdition(form = null) {
if (editing_product != null) {
if (editProductInfo(editing_product)) {
clearLineEdition();
......@@ -900,10 +902,12 @@ function validateEdition(form) {
// Set the quantity to 0 for all the products in to_process
function setAllQties() {
// Iterate over all rows in to_process
table_to_process.rows().every(function (rowIdx, tableLoop, rowLoop) {
table_to_process.rows().every(function () {
var data = this.data();
editProductInfo(data, 0);
return true;
});
list_to_process = [];
table_to_process.rows().remove()
......@@ -1128,7 +1132,9 @@ function send() {
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(update_data),
success: function(data) {
success: function() {
closeModal();
try {
// If step 1 (counting), open pop-up with procedure explanation
if (reception_status == "False") {
......@@ -1213,11 +1219,11 @@ function send() {
}
// Go back to to_process list if modal closed
$('#modal_closebtn_top').on('click', function (e) {
$('#modal_closebtn_top').on('click', function () {
document.location.href = "/reception";
});
$('#modal_closebtn_bottom').on('click', function (e) {
$('#modal_closebtn_bottom').on('click', function () {
document.location.href = "/reception";
});
......@@ -1303,7 +1309,7 @@ function confirmPricesAllValid() {
function confirm_all_left_is_good() {
// all products left are to be considered as well filled
// Iterate over all rows in to_process
table_to_process.rows().every(function (rowIdx, tableLoop, rowLoop) {
table_to_process.rows().every(function () {
let data = this.data();
var value = null;
......@@ -1313,6 +1319,8 @@ function confirm_all_left_is_good() {
value = data.price_unit;
}
editProductInfo(data, value);
return true;
});
list_to_process = [];
table_to_process.rows().remove()
......@@ -1328,9 +1336,18 @@ function openFAQ() {
function openErrorReport() {
openModal($('#templates #modal_error_report').html(), saveErrorReport, 'Confirmer');
// listener for error report textarea
// this is necessary because default behavior is overwritten by the listener defined in jquery.pos.js;
$("#error_report").keypress(function(e) {
var key = e.keyCode;
if (key === 13) {
this.value += "\n";
}
});
var textarea = document.getElementById("error_report");
textarea.value = user_comments;
textarea.value = (user_comments != undefined) ? user_comments : "";
textarea.focus();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
}
......@@ -1473,7 +1490,7 @@ $(document).ready(function() {
reception_status = orders[Object.keys(orders)[0]].reception_status;
// Load user comments from local storage, get it from first order
user_comments = orders[Object.keys(orders)[0]].user_comments;
user_comments = orders[Object.keys(orders)[0]].user_comments || "";
}
// Fetch orders data
......@@ -1560,12 +1577,12 @@ $(document).ready(function() {
container_edition.addEventListener('animationend', onAnimationEnd);
container_edition.addEventListener('webkitAnimationEnd', onAnimationEnd);
function onAnimationEnd(e) {
function onAnimationEnd() {
container_edition.classList.remove('blink_me');
}
// Disable mousewheel on an input number field when in focus
$('#edition_input').on('focus', function (e) {
$('#edition_input').on('focus', function () {
$(this).on('wheel.disableScroll', function (e) {
e.preventDefault();
/*
......@@ -1580,7 +1597,7 @@ $(document).ready(function() {
*/
});
})
.on('blur', function (e) {
.on('blur', function () {
$(this).off('wheel.disableScroll');
});
......@@ -1635,6 +1652,13 @@ $(document).ready(function() {
}
});
$("#edition_input").keypress(function(event) {
// Force validation when enter pressed in edition
if (event.keyCode == 13 || event.which == 13) {
validateEdition();
}
});
// Barcode reader
$(document).pos();
$(document).on('scan.pos.barcode', function(event) {
......
......@@ -16,5 +16,6 @@ urlpatterns = [
url(r'^reception_qtiesValidated', views.reception_qtiesValidated),
url(r'^reception_pricesValidated', views.reception_pricesValidated),
# url(r'^update_order_status/([0-9]+)$', views.tmp_update_order_status),
url(r'^po_process_picking$', views.po_process_picking)
url(r'^po_process_picking$', views.po_process_picking),
url(r'^save_order_group$', views.save_order_group)
]
......@@ -2,6 +2,8 @@
from outils.common_imports import *
from outils.for_view_imports import *
from django.views.generic import View
from django.http import HttpResponse
from django.http import JsonResponse
import os
from datetime import date
......@@ -14,6 +16,9 @@ from outils.common import OdooAPI
from members.models import CagetteUser
from products.models import CagetteProduct
# create temp directory if needed
if not os.path.exists("temp"):
os.mkdir("temp")
def as_text(value):
""" Utils """
......@@ -21,9 +26,18 @@ def as_text(value):
def home(request):
"""Page de selection de la commande suivant un fournisseurs"""
# Get grouped orders stored on the server
try:
with open('temp/grouped_order.json', 'r') as json_file:
saved_groups = json.load(json_file)
except Exception:
saved_groups = []
context = {
'title': 'Reception',
'merge_orders_pswd': settings.RECEPTION_MERGE_ORDERS_PSWD
'merge_orders_pswd': settings.RECEPTION_MERGE_ORDERS_PSWD,
'server_stored_groups' : saved_groups
}
template = loader.get_template('reception/index.html')
......@@ -65,10 +79,10 @@ def produits(request, id):
"TOOLS_SERVER": settings.TOOLS_SERVER}
fixed_barcode_prefix = '0490'
if hasattr(settings, 'RECEPTION_PB_EMAIL'):
context['RECEPTION_PB_EMAIL'] = settings.RECEPTION_PB_EMAIL
if hasattr(settings, 'RECEPTION_PB'):
context['RECEPTION_PB'] = settings.RECEPTION_PB
else:
context['RECEPTION_PB_EMAIL'] = ' [mail à renseigner dans config.py]'
context['RECEPTION_PB'] = ' [texte à renseigner dans config.py]'
if hasattr(settings, 'FIXED_BARCODE_PREFIX'):
fixed_barcode_prefix = settings.FIXED_BARCODE_PREFIX
......@@ -117,11 +131,48 @@ def data_validation(request):
coop_logger.error("Orders data validation : %s", str(e))
return JsonResponse({'error': str(e)}, status=500)
def save_order_group(request):
"""
When an order group is created, save it to force group these orders later.
Raise an error if one of the orders is already in a group.
"""
order_ids = json.loads(request.body.decode())
try:
try:
# Check if any of the orders attempted to be grouped is already in a group
with open('temp/grouped_order.json', 'r') as json_file:
saved_groups = json.load(json_file)
for order_id in order_ids:
for group in saved_groups:
if order_id in group:
# Found in a group, stop
msg = 'One of the orders is already in a group'
return JsonResponse({'message': msg}, status=409)
except Exception:
saved_groups = []
# All good, save group
with open('temp/grouped_order.json', 'w+') as json_file:
saved_groups.append(order_ids)
json.dump(saved_groups, json_file)
msg = 'Group saved'
return JsonResponse({'message': msg})
except Exception as e:
print(str(e))
return JsonResponse({'message': str(e)}, status=500)
def update_orders(request):
"""Update orders lines: quantity and unit prices"""
import requests
# don't print barcode which begin with these codes
noprint_list = ["0493", "0492", "0499"]
rep = HttpResponse("Not")
if request.is_ajax():
if request.method == 'PUT':
......@@ -130,7 +181,10 @@ def update_orders(request):
print_labels = True
if hasattr(settings, 'RECEPTION_SHELF_LABEL_PRINT'):
print_labels = settings.RECEPTION_SHELF_LABEL_PRINT
order_ids = []
for order_id, order in data['orders'].items():
order_ids.append(int(order_id))
answer_data[order_id] = {}
errors = []
......@@ -166,8 +220,8 @@ def update_orders(request):
except Exception as e:
errors.append('error registering shortage on p'+order_line['id']+':'+str(e))
# Print etiquette with new price if update if successful
if (print_labels is True) and (update is True) and (data['update_type'] == 'br_valid') and order_line['new_shelf_price']:
# Print etiquette with new price if update if successful and barcode is authorized
if (print_labels is True) and (update is True) and (data['update_type'] == 'br_valid') and order_line['new_shelf_price'] and order_line['barcode'][:4] not in noprint_list:
try:
tools_url = settings.TOOLS_SERVER + '/products/label_print/'
tools_url += str(order_line['product_tmpl_id']) + '/'
......@@ -181,11 +235,30 @@ def update_orders(request):
answer_data[order_id]['order_data'] = order
answer_data[order_id]['errors'] = errors
if len(errors) == 0:
m.update_order_status(order_id, data['update_type'])
if data['update_type'] == 'br_valid':
answer_data[order_id]['finalyze_result'] = m.register_purchase_order_to_finalyze()
# Remove order's group
try:
if os.path.exists('temp/grouped_order.json'):
with open('temp/grouped_order.json', 'r') as json_file:
saved_groups = json.load(json_file)
for oi in order_ids:
for i, group in enumerate(saved_groups):
if oi in group:
saved_groups.pop(i)
break
with open('temp/grouped_order.json', 'w') as json_file:
json.dump(saved_groups, json_file)
except Exception as e:
# no saved groups
print(str(e))
rep = JsonResponse(answer_data, safe=False)
return rep
......@@ -228,6 +301,7 @@ def save_error_report(request):
orders_partner = orders_partner + ', '
orders_partner = orders_partner + order['partner'] + ' du ' + order['date_order']
# If group of orders
if len(data['orders']) > 1 :
temp_group_file_name = "temp/" + orders_name + "_rapport-reception_temp.xlsx"
......@@ -245,6 +319,7 @@ def save_error_report(request):
data['orders'].append(group_order)
# Save qties & comments after step 1
if data['update_type'] == 'qty_valid':
for order in data['orders']:
......@@ -264,8 +339,8 @@ def save_error_report(request):
# If in group add group name
if len(data['orders']) > 1 :
ws.append( ['group', orders_name] )
try:
if 'updated_products' in order:
for product in order['updated_products']:
# Don't store products with same qties
if product['old_qty'] != product['product_qty']:
......@@ -287,10 +362,9 @@ def save_error_report(request):
product['product_qty'],
product['price_unit'],
supplier_shortage] )
except:
# no updated products, do nothing
pass
except Exception as exp:
print("Error while updating products")
print(exp)
if ('user_comments' in data) and data['user_comments'] != "":
ws.append( ['commentaire', data['user_comments']] )
else:
......@@ -299,6 +373,8 @@ def save_error_report(request):
# Save file
wb.save(filename=order['temp_file_name'])
# Create report with data from steps 1 & 2
else:
for order in data['orders']:
......@@ -333,7 +409,6 @@ def save_error_report(request):
os.remove(order['temp_file_name'])
except:
data_comment_s1 = "Rapport de la première étape absent !"
# Add data from step 2
data_full = []
error_total = 0
......@@ -345,6 +420,7 @@ def save_error_report(request):
# Concatenate products info from each step
try:
if "updated_products" in order:
for product in order['updated_products']:
if 'supplier_code' in product:
supplier_code = str(product['supplier_code'])
......@@ -389,10 +465,10 @@ def save_error_report(request):
error_total_abs += abs(item['error_line'])
data_full.append(item)
except:
except Exception as exp:
# no updated products, do nothing
pass
print("Error while updating products")
print(exp)
# Add remaining products, the ones edited only in step 1
for product in data_qties.values():
item = {
......@@ -422,7 +498,6 @@ def save_error_report(request):
wb = Workbook()
ws = wb.active
ws.title = "Commande " + order['name']
# Group
if 'group_ids' in order :
ws.append( ['Rapport de réception d\'un groupe de commandes'] )
......@@ -464,7 +539,6 @@ def save_error_report(request):
round(product['expected_amount'], 2),
round(product['error_line'], 2),
product['supplier_shortage']] )
ws.append( [] )
ws.append( ['Montant total de l\'erreur :', '', '', '', '', '', '', '', round(error_total, 2)] )
ws.append( ['Montant total en valeur absolue :', '', '', '', '', '', '', '', round(error_total_abs, 2)] )
......@@ -499,7 +573,6 @@ def save_error_report(request):
top_left_cell.alignment = Alignment(vertical="top")
top_left_cell = ws['B'+str(merge_begin)]
top_left_cell.alignment = Alignment(vertical="top")
# "Auto fit" columns width to content
for column_cells in ws.columns:
length = max(len(as_text(cell.value)) for cell in column_cells)
......@@ -508,23 +581,23 @@ def save_error_report(request):
length = 20
ws.column_dimensions[column_cells[3].column_letter].width = length
# Save file
fileName = "temp/" + order['name'] + "_rapport-reception.xlsx"
try:
wb.save(filename=fileName)
except Exception as exp:
print("Error while saving file %s"%fileName)
print(str(exp))
#Attach file to order
if 'group_ids' in order : # group report
# Attach group report to each order
for group_item_id in order['group_ids'] :
m = CagetteReception(group_item_id)
m.attach_file(fileName, False)
os.remove(fileName)
else:
m = CagetteReception(order['id'])
m.attach_file(fileName)
return JsonResponse("ok", safe=False)
def reception_FAQ(request):
......
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class SalesConfig(AppConfig):
name = 'sales'
from django.db import models
from outils.common_imports import *
from outils.common import OdooAPI
class CagetteSales(models.Model):
"""Class to manage operations on envelops"""
def __init__(self):
"""Init with odoo id."""
self.o_api = OdooAPI()
def get_sales(self, date_from, date_to):
res = []
# Get pos sessions
cond = [['stop_at', '>=', date_from], ['stop_at', '<=', date_to], ['state', '=', "closed"]]
fields = []
sessions = self.o_api.search_read('pos.session', cond, fields)
# Get bank statements of these sessions
statements = []
for s in sessions:
statements = statements + s["statement_ids"]
# Get payment lines
cond = [['statement_id', 'in', statements]]
fields = ["partner_id", "amount", "journal_id", "create_date", "date"]
payments = self.o_api.search_read('account.bank.statement.line', cond, fields, order="create_date ASC", limit=50000)
item = None
try:
for payment in payments:
# POS session can contain payments from another day (closing session on next morning, ...)
if payment["date"] >= date_from and payment["date"] <= date_to:
# If the consecutive payment in the results is from the same partner on the same day, we consider it's the same basket
if item is not None and item["partner_id"][0] == payment["partner_id"][0] and item["date"] == payment["date"]:
res[len(res)-1]["total_amount"] += round(float(payment["amount"]), 2)
res[len(res)-1]["payments"].append({
"amount": round(float(payment["amount"]), 2),
"journal_id": payment["journal_id"]
})
else:
item = {
"partner_id": payment["partner_id"],
"create_date": payment["create_date"],
"date": payment["date"],
"total_amount": round(float(payment["amount"]), 2),
"payments": [
{
"amount": round(float(payment["amount"]), 2),
"journal_id": payment["journal_id"]
}
]
}
res.append(item)
except Exception as e:
pass
return res
.select_sales_dates {
margin-top: 25px;
}
.sales_date {
display: inline-block;
margin-right: 10px;
}
.main {
margin-top: 25px;
}
.table_area {
margin: auto;
width: 90%;
padding: 10px;
}
.select_sales_date_input {
border-radius:5px;
}
.btn_export_movements {
margin-top: 10px;
}
\ No newline at end of file
var dateFormat = "yy-mm-dd",
from_datepicker = null,
to_datepicker = null,
orders_table = null;
// Return a date from a string if valid, else return null
function getDate(element) {
var date = null;
try {
date = $.datepicker.parseDate(dateFormat, element);
} catch (error) {
date = null;
}
return date;
}
// Enable validation button if all fields are valid
function enable_validation() {
if (getDate(from_datepicker.val()) &&
getDate(to_datepicker.val())) {
$('#dates_selection_button').prop('disabled', false);
} else {
$('#dates_selection_button').prop('disabled', true);
}
}
function display_orders(orders) {
// Empty datatable if already exists
if (orders_table) {
orders_table.destroy();
}
orders_table = $('#orders_table').DataTable({
data: orders,
columns:[
{
data:"create_date",
title:"Date de vente",
width: "10%"
},
{
data:"partner_id",
title:"Membre",
width: "50%",
render: function (data) {
return data[1];
}
},
{
data:"total_amount",
title: "Montant du panier",
className:"dt-body-center",
render: function (data) {
return parseFloat(data).toFixed(2) + ' €';
}
},
{
data:"payments",
title:"Paiements",
orderable: false,
render: function (data) {
let res = '<ul>';
for (p of data) {
res += `<li>${p.journal_id[1]} : ${p.amount} €</li>`
}
res += "</ul>"
return res;
}
}
],
order: [
[
0,
"asc"
]
],
buttons: [
{
extend: 'excelHtml5',
text: 'Export en Excel',
className: 'btn--primary btn_export_movements'
}
],
dom: '<lr<t>ip><"clear"><B>',
iDisplayLength: 100,
language: {url : '/static/js/datatables/french.json'}
});
$('.main').show();
}
function get_sales() {
openModal();
var url = "/sales/get_sales";
url += '?from=' + encodeURIComponent(from_datepicker.val());
url += '&to=' + encodeURIComponent(to_datepicker.val());
$.ajax({
type: 'GET',
url: url,
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
display_orders(data.res);
closeModal();
},
error: function(data) {
err = {msg: "erreur serveur lors de la sélection des mouvements de stock", ctx: 'get_movements'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'stock');
closeModal();
alert('Erreur lors de la récupération, réessayez plus tard');
}
});
}
$(document).ready(function() {
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
// Set datepicker
$.datepicker.regional['fr'] = {
monthNames: [
'Janvier',
'Fevrier',
'Mars',
'Avril',
'Mai',
'Juin',
'Juillet',
'Aout',
'Septembre',
'Octobre',
'Novembre',
'Decembre'
],
dayNamesMin: [
'Di',
'Lu',
'Ma',
'Me',
'Je',
'Ve',
'Sa'
],
dateFormat: dateFormat,
firstDay: 1,
minDate: 1,
maxDate: '+12M +0D'
};
$.datepicker.setDefaults($.datepicker.regional['fr']);
from_datepicker = $("#from")
.datepicker({
defaultDate: "-1d",
changeMonth: true,
changeYear: true,
yearRange: "-03:+00",
minDate: new Date(2007, 1 - 1, 1),
maxDate: new Date()
})
.on("change", function() {
to_datepicker.datepicker("option", "minDate", getDate(this.value));
});
to_datepicker = $("#to")
.datepicker({
defaultDate: "-1d",
changeMonth: true,
changeYear: true,
yearRange: "-03:+00",
minDate: new Date(2007, 1 - 1, 1),
maxDate: new Date()
})
.on("change", function() {
from_datepicker.datepicker("option", "maxDate", getDate(this.value));
});
$('.select_sales_date_input').change(function() {
enable_validation();
});
$( "#sales_form" ).submit(function( event ) {
event.preventDefault();
get_sales();
});
});
"""."""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^get_sales$', views.get_sales),
]
from outils.common_imports import *
from outils.for_view_imports import *
from sales.models import CagetteSales
def index(request):
"""Display sales export screen"""
context = {'title': 'Export de ventes'}
template = loader.get_template('sales/index.html')
# m = CagetteSales()
# sales = m.get_sales()
# print(sales)
return HttpResponse(template.render(context, request))
def get_sales(request):
res = {}
date_from = request.GET.get('from', '')
date_to = request.GET.get('to', '')
m = CagetteSales()
res = m.get_sales(date_from, date_to)
if 'errors' in res and res['errors']:
return JsonResponse(res, status=500)
else:
return JsonResponse({'res': res})
\ No newline at end of file
......@@ -47,7 +47,11 @@ def get_all_children(branch):
children += get_all_children(c)
return children
def get_all_children_ids(branch):
ids = []
for c in get_all_children(branch):
ids.append(c['id'])
return ids
class CagetteShop(models.Model):
"""Class to handle cagette Shop."""
......@@ -62,7 +66,7 @@ class CagetteShop(models.Model):
def filter_products_according_settings(pdts):
res = pdts
try:
conditions = settings.SHOP_LIMIT_PRODUCTS
conditions = getattr(settings, 'SHOP_LIMIT_PRODUCTS', [])
filtered = []
for p in pdts:
keep_it = True
......@@ -124,13 +128,14 @@ class CagetteShop(models.Model):
fields = ['parent_id', 'name']
res = api.search_read('product.category', [], fields)
tree = build_tree_from_categories(res)
except:
pass
except Exception as e:
coop_logger.error('get_product_categories : %s', str(e))
return tree
@staticmethod
def get_cat_children_ids(categ_id):
cat_ids = [categ_id]
tree = CagetteShop.get_product_categories()
branch = None
for cats in tree:
......@@ -159,15 +164,23 @@ class CagetteShop(models.Model):
return children
@staticmethod
def get_categories_nb_of_products():
"""Needs lacagette_categories Odoo module to be activated"""
res = {}
try:
api = OdooAPI()
res = api.execute('lacagette.categories', 'get_all_with_products_count', {})
except Exception as e:
coop_logger.error('get_categories_nb_of_products %s', str(e))
res['error'] = str(e)
return res
@staticmethod
def get_category_products(categ_id):
res = {}
try:
pdts = []
limit_conditions = []
try:
limit_conditions = settings.SHOP_LIMIT_PRODUCTS
except:
pass
limit_conditions = getattr(settings, 'SHOP_LIMIT_PRODUCTS', [])
api = OdooAPI()
cat_ids = CagetteShop.get_cat_children_ids(categ_id)
# removed ['qty_available', '>', 0]
......@@ -183,6 +196,7 @@ class CagetteShop(models.Model):
res['pdts'] = CagetteShop.filter_products_according_settings(pdts)
except Exception as e:
coop_logger.error('get_category_products %s %s', categ_id, str(e))
res['error'] = str(e)
return res
......@@ -239,7 +253,7 @@ class CagetteShop(models.Model):
@staticmethod
def registrerCart(cart, partner_id):
def registrerCart(cart, partner_id, mode="shop"):
result = {}
try:
cart['submitted_time'] = time.time()
......@@ -260,7 +274,7 @@ class CagetteShop(models.Model):
if result:
try:
from outils.mail import CagetteMail
CagetteMail.sendCartValidation(partner['email'], cart)
CagetteMail.sendCartValidation(partner['email'], cart, mode)
except Exception as e:
coop_logger.error("Shop, registrerCart : %s, %s", str(e), str(cart))
except Exception as e:
......
......@@ -252,7 +252,10 @@ li.tab { border-right: 1px solid white; }
#my-orders-sumup .date {text-align: left;padding: 0 4px;}
#my-orders-sumup tbody tr:hover {background-color: #b3b7c4;}
td.actions .fa-trash, td.actions .fa-paper-plane, td.date .fa-edit {cursor: pointer;}
td.actions .fa-trash,
td.actions .fa-eye,
td.actions .fa-paper-plane,
td.date .fa-edit {cursor: pointer;}
.no-action-available-msg {margin-top: 15px;}
#survey_link {text-decoration: none;}
......
......@@ -26,6 +26,7 @@ var main_content = $('#main-content'),
dragSrcEl = null,
forbidden_slots = [],
closing_dates = [],
my_sent_orders = [],
right_column = $('#right-column'),
visit_mode = false,
timer = null;
......@@ -717,7 +718,7 @@ var addProductToCart = function() {
var msg = "";
var too_much = "Vous avez pris plus de produit que le stock indicatif.\nVous n'aurez peut-être pas toute la quantité.";
if (parseFloat(qty) > available_qty) {
if (parseFloat(qty) > available_qty && stock_warning == true) {
msg = too_much;
}
var u = p_div.find('.unit').text()
......@@ -757,7 +758,7 @@ var addProductToCart = function() {
}
}
if (typeof answer.warning !== "undefined") {
if (answer.warning == "max_qty")
if (answer.warning == "max_qty" && stock_warning == true)
msg = too_much;
}
});
......@@ -1059,11 +1060,28 @@ var loadAllAvailableBoughtProducts = function() {
}
};
var shouldCategoryBeShown = function (cat_id) {
let answer = true;
if (excluded_cat.indexOf(cat_id) > -1) {
answer = false;
}
if (typeof cat_nb_pdts != "undefined") {
let list = cat_nb_pdts.list;
let cat_ids = Object.keys(list).map(x => parseInt(x,10));
//cat_ids is now an array of category ids which have product
if (cat_ids.indexOf(cat_id) < 0) {
// cat_id is corresponding to a category which have no product
answer = false;
}
}
return answer;
}
var appendChildrenCatToMenu = function (catdiv, children) {
var ul = catdiv.find('ul');
$.each(children, function(i, e) {
if (excluded_cat.indexOf(e.id) < 0) {
if (shouldCategoryBeShown(e.id)) {
var li = $('<li>').addClass("nav-item");
// Remove TVA in cat name
......@@ -1092,7 +1110,6 @@ var getCategChildren = function() {
if (typeof category_elts[cat_id] == "undefined") {
try {
$.ajax({
//url :'/shop/get_categ_products',
url : '/shop/get_cat_children',
data: {id: cat_id},
dataType: 'json'
......@@ -1236,12 +1253,13 @@ var displaySentOrders = function() {
}
} else if (typeof rData.res.data.orders != "undefined") {
if (rData.res.data.orders.length > 0) {
my_sent_orders = rData.res.data.orders;
var eye = '<i class="fas fa-eye fl"></i>';
var delete_icon = '<i class="fas fa-trash fr"></i>';
var edit = '<i class="fas fa-edit"></i>';
var show_no_action_available_msg = false;
$.each(rData.res.data.orders, function(i, o) {
$.each(my_sent_orders, function(i, o) {
var bdate_content = "<span>" + o.best_date + "</span>";
if (o.state == "init" || o.state == "validating") bdate_content += " " + edit;
......@@ -1267,7 +1285,8 @@ var displaySentOrders = function() {
.text(o.products.length);
var td4 = $('<td>').addClass('amount')
.text(parseFloat(o.total).toFixed(2));
//var td5 = $('<td>').addClass('actions').html(eye + ' ' + delete_icon)
actions_content = eye + ' ' + actions_content;
var td5 = $('<td>').addClass('actions')
.html(actions_content);
......@@ -1374,6 +1393,36 @@ var changeBestDate = function() {
};
var showSentCart = function() {
let clicked = $(this),
clicked_tr = clicked.closest('tr'),
id = clicked_tr.data('id'),
content = $('<div>'),
table = $('<table>');
let header = $('<tr><th>Article</th><th>Qté</th><th>Prix Total (T.T.C)</th></tr>');
let bottom_msg = $('<p>').html("<em>Contenu non modifiable.</em>")
table.append(header);
$.each(my_sent_orders, function(i,e) {
if (e._id == id) {
$.each(e.products, function (j,p) {
let tr = $('<tr>'),
name = $('<td>').text(p.name),
qty = $('<td>').text(p.qty),
total = $('<td>').text(p.total)
tr.append(name);
tr.append(qty);
tr.append(total);
table.append(tr);
})
}
})
content.append(table);
content.append(bottom_msg);
displayMsg(content.html());
}
var destroySentCart = function() {
var clicked = $(this);
var clicked_tr = clicked.closest('tr'),
......@@ -1561,15 +1610,19 @@ valid_cart.click(function() {
$('#get_my_bought_products').click(loadAllAvailableBoughtProducts);
$(document).on('change', '[name^="bday"]', filterHourOptions);
$(document).on('change', '[name="bhour"]', adaptTimeGivenForValidationMsg);
$(document).on('click', '#alim_categ > div, #non_alim_categ > div', getCategChildren);
$(document).on('click', '#alim_categ ul li span, #non_alim_categ ul li span', getCategProducts);
$(document).on('click', '.product button', addProductToCart);
$(document).on('click', '.forbidden-slots .fs-close', closeForbiddenList);
$(document).on('click', 'td.date .fa-edit', changeBestDate);
$(document).on('click', 'td.actions .fa-eye', showSentCart);
$(document).on('click', 'td.actions .fa-trash', destroySentCart);
if (shop_mode == 'shop')
$(document).on('change', '[name^="bday"]', filterHourOptions);
$(document).on(
'click', '.new-order',
function() {
......
......@@ -13,44 +13,23 @@ def shop_index(request):
def delivery_index(request):
return index(request, mode='delivery')
def index(request, mode="shop"):
template = loader.get_template('shop/index.html')
credentials = CagetteMember.get_credentials(request)
shop_settings = CagetteShop.get_shop_settings()
def _get_index_context(credentials, shop_settings, mode):
context = {'title': 'Commande / Réservation',
'mode': mode,
'COMPANY_NAME': settings.COMPANY_NAME,
'SHOP_CATEGORIES': settings.SHOP_CATEGORIES,
'EXCLUDE_SHOP_CATEGORIES': settings.EXCLUDE_SHOP_CATEGORIES,
'MIN_DELAY_FOR_SLOT': settings.MIN_DELAY_FOR_SLOT,
'HOURS_FOR_VALIDATION': settings.HOURS_FOR_VALIDATION_SHOP}
'header_img': getattr(settings, 'SHOP_HEADER_IMG', '/static/img/header.jpg')
}
if 'capital_message' in shop_settings:
context['capital_message'] = shop_settings['capital_message']
allowed_states = ["up_to_date", "alert", "delay"]
# Uncomment if 'coop_state' in credentials .... etc
# to prevent other states people to use the shop
allowed = True
if ('failure' in credentials):
# Visitor has not been identified
template = loader.get_template('website/connect.html')
context['msg'] = ''
if 'msg' in credentials:
context['msg'] = credentials['msg']
context['password_placeholder'] = 'Mot de passe'
context['password_notice'] = "Par défaut, la date de naissance (jjmmaaaa)"
context['with_shop_header'] = True
try:
context['header_img'] = settings.SHOP_HEADER_IMG
except:
context['header_img'] = '/static/img/header.jpg'
else:
if hasattr(settings, 'SHOP_OPENING'):
context['SHOP_OPENING'] = settings.SHOP_OPENING
if hasattr(settings, 'SHOP_SLOT_SIZE'):
context['SHOP_SLOT_SIZE'] = settings.SHOP_SLOT_SIZE
if hasattr(settings, 'SHOP_OPENING_START_DATE'):
context['SHOP_OPENING_START_DATE'] = settings.SHOP_OPENING_START_DATE
if mode == 'shop' and hasattr(settings, 'SHOP_CAN_BUY'):
context['SHOP_CAN_BUY'] = settings.SHOP_CAN_BUY
context['DELIVERY_CAN_BUY'] = False
......@@ -58,22 +37,53 @@ def index(request, mode="shop"):
context['SHOP_CAN_BUY'] = False
context['DELIVERY_CAN_BUY'] = settings.DELIVERY_CAN_BUY
context['SHOP_CATEGORIES'] = getattr(settings, 'SHOP_CATEGORIES', [])
context['EXCLUDE_SHOP_CATEGORIES'] = getattr(settings, 'EXCLUDE_SHOP_CATEGORIES', [])
context['MIN_DELAY_FOR_SLOT'] = getattr(settings, 'MIN_DELAY_FOR_SLOT', 30)
context['HOURS_FOR_VALIDATION'] = getattr(settings, 'HOURS_FOR_VALIDATION_SHOP', 2)
context['SHOP_OPENING'] = getattr(settings, 'SHOP_OPENING', {})
context['SHOP_SLOT_SIZE'] = getattr(settings, 'SHOP_SLOT_SIZE', 15)
context['SHOP_OPENING_START_DATE'] = getattr(settings, 'SHOP_OPENING_START_DATE', None)
context['survey_link'] = getattr(settings, 'SHOP_SURVEY_LINK', '')
context['extra_menus'] = getattr(settings, 'SHOP_EXTRA_MENUS', None)
context['SHOW_SUBSTITUTION_OPTION'] = getattr(settings, 'SHOW_SUBSTITUTION_OPTION', False)
context['CART_VALIDATION_BOTTOM_MSG'] = getattr(settings, 'CART_VALIDATION_BOTTOM_MSG', "")
context['SHOP_BOTTOM_VALIDATION_MSG'] = getattr(settings, 'SHOP_BOTTOM_VALIDATION_MSG',\
"Si vous arrivez avec un retard de plus d'une heure, la commande pourrait ne plus être disponible.")
stock_warning = getattr(settings, 'SHOP_STOCK_WARNING', True)
if stock_warning is True:
context['SHOP_STOCK_WARNING'] = 'true'
else:
context['SHOP_STOCK_WARNING'] = 'false'
return context
def index(request, mode="shop"):
template = loader.get_template('shop/index.html')
credentials = CagetteMember.get_credentials(request)
shop_settings = CagetteShop.get_shop_settings()
allowed_states = ["up_to_date", "alert", "delay"]
# Uncomment if 'coop_state' in credentials .... etc
# to prevent other states people to use the shop
allowed = True
context = _get_index_context(credentials, shop_settings, mode)
if ('failure' in credentials):
# Visitor has not been identified
template = loader.get_template('website/connect.html')
else:
d_p_pdts = CagetteShop.get_promoted_and_discounted_products()
context['discounted_pdts'] = d_p_pdts['discounted']
context['promoted_pdts'] = d_p_pdts['promoted']
context['survey_link'] = ''
if hasattr(settings, 'SHOP_EXTRA_MENUS'):
context['extra_menus'] = settings.SHOP_EXTRA_MENUS
if hasattr(settings, 'SHOP_SURVEY_LINK'):
context['survey_link'] = settings.SHOP_SURVEY_LINK
context['SHOW_SUBSTITUTION_OPTION'] = True
if hasattr(settings, 'SHOW_SUBSTITUTION_OPTION'):
if settings.SHOW_SUBSTITUTION_OPTION is False:
del context['SHOW_SUBSTITUTION_OPTION']
if hasattr(settings, 'CART_VALIDATION_BOTTOM_MSG'):
context['CART_VALIDATION_BOTTOM_MSG'] = settings.CART_VALIDATION_BOTTOM_MSG
cat_nb_pdts = CagetteShop.get_categories_nb_of_products()
if 'error' in cat_nb_pdts:
context['cat_nb_pdts'] = None
else:
context['cat_nb_pdts'] = cat_nb_pdts
# if 'coop_state' in credentials and not (credentials['coop_state'] in allowed_states):
# allowed = False
......@@ -119,6 +129,7 @@ def get_categ_products(request):
result['error'] = 'Authentification non valide'
return JsonResponse({'res': result})
def search_product(request):
result = {}
credentials = CagetteMember.get_credentials(request)
......@@ -177,7 +188,10 @@ def cart(request):
credentials = CagetteMember.get_credentials(request)
if 'success' in credentials:
try:
result['cart'] = CagetteShop.registrerCart(cart, request.COOKIES['id'])
mode = "shop"
if 'type' in cart:
mode = cart['type']
result['cart'] = CagetteShop.registrerCart(cart, request.COOKIES['id'], mode)
except Exception as e:
result['error'] = str(e)
else:
......
......@@ -256,10 +256,10 @@ function init_confirmation_datatable() {
});
}
function without_consent_update_product(p) {
function without_consent_update_product(p, added_qty) {
let undo_option = true;
update_existing_product(p, undo_option);
update_existing_product(p, added_qty, undo_option);
}
function get_stored_product_with_bc(barcode) {
......@@ -307,19 +307,17 @@ function fetch_product_from_bc(barcode) {
'uom': barcodes['uoms'][p.data[barcodes['keys']['uom_id']]],
'standard_price' : p.data[barcodes['keys']['standard_price']], // cost
'list_price': p.data[barcodes['keys']['list_price']] // public price
'list_price': p.data[barcodes['keys']['list_price']], // public price
'qty': p.qty
};
product['uom']['id'] = p.data[barcodes['keys']['uom_id']];
product['value'] = parseFloat(p.value) || 1;
product['rule'] = p.rule;
p_existing = get_stored_product_with_bc(p.barcode);
if (p_existing !== null) {
product.qty = p_existing.qty;
without_consent_update_product(product);
without_consent_update_product(p_existing, product.qty);
return 0;
} else {
add_product(product);
......@@ -335,16 +333,6 @@ function fetch_product_from_bc(barcode) {
var add_product = function(product) {
try {
// Add to list
product.qty = 1;
if (typeof product.value == "number" || (product.value.length > 0 && !isNaN(product.value))) {
//encoded value will be translated in quantity
if (product.rule == "FF_price_to_weight") {
product.qty = get_quantity_eq_to_franc_price(product);
} else {
product.qty = parseFloat(product.value);
}
}
products.push(product);
......@@ -385,26 +373,11 @@ var update_in_products = function(product) {
else console.log("Le produit n'a pas pu être trouvé dans la variable products !");
};
var get_quantity_eq_to_franc_price = function(product) {
let value = 0;
try {
let price = parseFloat(product.value / 6.55957);
value = parseFloat(price / product.list_price).toFixed(3);
} catch (error) {
console.log(error);
}
return value;
};
/*
* Update a line in the table: update quantity
*/
var update_existing_product = function(product, undo_option = false) {
// By default added qty is 1 unit
let added_qty = 1;
var update_existing_product = function(product, added_qty, undo_option = false) {
let op = "augmentée";
let notify_options = {
......@@ -413,35 +386,8 @@ var update_existing_product = function(product, undo_option = false) {
clickToHide: false
};
// type product qty value
if (product.rule == 'weight' || product.rule == 'FF_price_to_weight' && product.value) {
// Quantities are kg or price
product.qty = parseFloat(product.qty) || 0;
if (product.rule == 'weight') {
added_qty = parseFloat(product.value);
} else {
if (product.value < 0) added_qty = parseFloat(product.value); // value is already a qty
else added_qty = parseFloat(get_quantity_eq_to_franc_price(product));
}
} else {
//Quantity is by "defaut" considered as to be in "unit"
product.qty = parseInt(product.qty, 10);
if (product.rule == "" && product.value) {
added_qty = product.value;
}
}
product.qty += added_qty;
/* Surprisingly, this assignment by addition (0 + value)
always correctly "typing" the value
whereas "product.qty = added_qty"
is sometimes typed as "string" !!
*/
// always set to empty to avoid next operation on same product to be misprocessed
product.value = "";
// Find index of row which match product id in the first column
var indexes = products_table.rows().eq(0)
......@@ -470,10 +416,7 @@ var update_existing_product = function(product, undo_option = false) {
notify_options.autoHide = false;
// notify_options.autoHideDelay = 10000;
notify_options.style = 'cancelable';
// msg = $('<span>').text(msg)
// .attr('data-barcode', product.barcode)
// .attr('data-addedqty', added_qty);
// msg = msg.html()
msg = '<span class="msg" data-barcode="' + product.barcode + '" data-added_qty="' + added_qty + '">'
+ "<b>" + product.name + "</b><br/>" + msg
+ '</span>';
......@@ -919,8 +862,7 @@ $(document).ready(function() {
let product = get_stored_product_with_bc(bc);
if (product !== null) {
product.value = - added_qty;
update_existing_product(product);
update_existing_product(product, - added_qty);
} else {
alert("Le produit n'a pas été retrouvé dans la mémoire de travail.");
}
......
......@@ -4,9 +4,9 @@
* Ecran de rechreche d'un article sur le nom et sur le code barre */
var table_article;
var table_article = null;
var dataSet =[];
var csrftoken;
var csrftoken = '';
// lance la recherche sur le nom des l'article
function search_table_article() {
......@@ -30,7 +30,7 @@ $(document).ready(function() {
{
data:"image_small",
"title":"Photo",
"render": function (data, type, full, meta) {
"render": function (data, type, full) {
debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.id + ' class="btn btn-primary">';
fin = "</button>";
......@@ -41,14 +41,14 @@ $(document).ready(function() {
{data:"name", "title":"Article", "width": "50%"},
{data:"qty_available", "title":"En Stock", "width": "10%"},
{data:"uom_id",
"render":function (data, type, row) {
"render":function (data) {
return data[1];
},
"title":"Unité", "width":"5%"},
{data:"reception_status",
"title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) {
"render": function (data, type, full) {
if (full.qty_available > 0) {
return "<div><button id='bt_change' href='#'>Rupture</button></div>";
} else {
......@@ -135,7 +135,7 @@ $(document).ready(function() {
});
// Lancement de la rupture sur l'article choisie
function ruptureArticle(test) {
function ruptureArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id[0] };
......@@ -148,7 +148,7 @@ function ruptureArticle(test) {
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
success: function() {
document.location.href = "/stock/listArticleBreaking";
},
......@@ -159,7 +159,7 @@ function ruptureArticle(test) {
});
}
var selArctileData;
var selArctileData = null;
// Fenetre de validation sur l'article
......
......@@ -64,7 +64,7 @@ $(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken;
var csrftoken = '';
$(document).ready(function() {
csrftoken = getCookie('csrftoken');
......@@ -98,7 +98,7 @@ function actionButton (vUrl, jIdArcticle, followPage) {
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
success: function() {
document.location.href = followPage;
},
error: function(resultat, statut, erreur) {
......@@ -108,7 +108,7 @@ function actionButton (vUrl, jIdArcticle, followPage) {
});
}
var selArctileData;
var selArctileData = null;
// Fenetre de validation sur l'article
......
......@@ -15,7 +15,7 @@ $(document).ready(function() {
{data:"name", "title":"Article", "width": "50%"},
{data:"maxdate",
"render":function (data, type, row) {
"render":function (data) {
my = new Date(data);
return my.toLocaleDateString() +" " + my.toLocaleTimeString();
......@@ -23,7 +23,7 @@ $(document).ready(function() {
"title":"Date", "width":"15%"},
{data:"maxdate",
"render":function (data, type, row) {
"render":function (data) {
my = new Date(data);
var today = new Date();
......@@ -37,7 +37,7 @@ $(document).ready(function() {
{data:"purchase_ok", "width":"5%",
"title":"Achetable", "className":"dt-body-center",
"render": function (data, type, full, meta) {
"render": function (data) {
if (data == true) {
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';
......@@ -48,14 +48,14 @@ $(document).ready(function() {
},
{data:"reception_status", "width":"5%",
"title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) {
"render": function () {
return "<div><button id='bt_change' href='#'>Stock à 0</button></div>";
}
},
{data:"reception_status", "width":"5%",
"title":"Archive", "className":"dt-body-center",
"render": function (data, type, full, meta) {
"render": function () {
return "<div><button id='bt_archive' href='#'>Archive</button></div>";
}
}
......@@ -103,7 +103,7 @@ $(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken;
var csrftoken ='';
$(document).ready(function() {
csrftoken = getCookie('csrftoken');
......@@ -137,7 +137,7 @@ function actionButton (vUrl, jIdArcticle, followPage) {
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
success: function() {
document.location.href = followPage;
},
error: function(resultat, statut, erreur) {
......@@ -147,7 +147,7 @@ function actionButton (vUrl, jIdArcticle, followPage) {
});
}
var selArctileData;
var selArctileData = null;
// Fenetre de validation sur l'article
......
......@@ -161,7 +161,7 @@
<div class="validation_wrapper col-6">
<section id="service_validation" class="col-6 grid-6 has-gutter">
<div class="col-2"></div>
<a class="col-2 btn present">Présent.e</a>
<a class="col-2 btn present">{{CONFIRME_PRESENT_BTN|safe}}</a>
<span class="loading2"><img width="75" src="/static/img/Pedro_luis_romani_ruiz.gif" alt="Chargement en cours...." /></span>
<div class="col-2"></div>
</section>
......
......@@ -21,9 +21,9 @@
<input name="city" placeholder="Ville" class="b_green" autocomplete="address-level4"/>
<input name="country" placeholder="Pays" class="b_yellow" autocomplete="address-level4"/>
<span class="phone-wrapper{% if ask_for_second_phone %}-2{% endif %}">
<input type="tel" name="mobile" placeholder="Tél. mobile" class="b_green" pattern="^(\+\d{1,3}(-| ))?\d{1,2}(\.| )\d{1,2}(\.| )\d{1,2}(\.| )\d{1,2}(\.| )\d{0,2}?$" autocomplete="address-level4"/>
<input type="tel" name="mobile" placeholder="Tél. mobile" class="b_green" pattern="{{input_phone_pattern}}" autocomplete="address-level4"/>
{% if ask_for_second_phone %}
<input type="tel" name="phone" placeholder="Tél. fixe" class="b_green" pattern="^(\+\d{1,3}(-| ))?\d{1,2}(\.| )\d{1,2}(\.| )\d{1,2}(\.| )\d{1,2}(\.| )\d{0,2}?$" autocomplete="address-level4"/>
<input type="tel" name="phone" placeholder="Tél. fixe" class="b_green" pattern="{{input_phone_pattern}}" autocomplete="address-level4"/>
{% endif %}
</span>
</p>
......
......@@ -54,6 +54,7 @@
<script src="{% static "js/all_common.js" %}?v="></script>
<script type="text/javascript">
var merge_orders_pswd = '{{merge_orders_pswd}}';
var server_stored_groups = {{server_stored_groups}};
</script>
<script src="{% static "js/common.js" %}?v="></script>
{% endblock %}
......@@ -120,9 +120,7 @@
<hr />
<p class="txtleft">
Ici, vous pouvez signaler toute anomalie lors d'une réception, les produits non commandés, cassés ou pourris.
Merci d'indiquer un maximum d'informations, le nom du produit et son code barre.
Dans le cas de produits déteriorés, merci d'envoyer une photo avec votre téléphone à <strong>{{RECEPTION_PB_EMAIL}}</strong>
{{RECEPTION_PB}}
</p>
<br>
<textarea id="error_report"></textarea>
......
{% extends "base.html" %}
{% load static %}
{% block additionnal_css %}
<link rel="stylesheet" href="{% static 'css/datatables/jquery.dataTables.css' %}">
<link rel="stylesheet" href="{% static 'jquery-ui-1.12.1/jquery-ui.min.css' %}">
<link rel="stylesheet" href="{% static "css/sales.css" %}?v=">
{% endblock %}
{% block additionnal_scripts %}
<script type="text/javascript" src="{% static 'jquery-ui-1.12.1/jquery-ui.min.js' %}?v="></script>
<script type="text/javascript" src="{% static 'js/datatables/jquery.dataTables.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/datatables/dataTables.plugins.js' %}"></script>
<script type="text/javascript" src="{% static 'js/datatables/datatables.buttons.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/datatables/buttons.html5.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/datatables/jszip.min.js' %}"></script>
{% endblock %}
{% block content %}
<div class="page_body">
<div id="content_main" class="page_content">
<div class="header txtcenter">
<h1>Extraction de ventes</h1>
</div>
<div class="select_sales_dates txtcenter">
<form id="sales_form" action="javascript:;">
<div class="sales_date">
<label for="from">Entre :</label>
<input type="text" name="from" id="from" class="select_sales_date_input" required>
</div>
<div class="sales_date">
<label for="to">et :</label>
<input type="text" name="to" id="to" class="select_sales_date_input" required>
</div>
<button type="submit" class="btn--primary" id="dates_selection_button" disabled>C'est parti !</button>
</form>
</div>
<div class="main" style="display:none;">
<div class="table_area">
<table id="orders_table" class="display" cellspacing="0" width="100%"></table>
</div>
</div>
</div>
<div id="templates" style="display:none;">
</div>
</div>
<script src="{% static "js/all_common.js" %}?v="></script>
<script src="{% static "js/sales.js" %}?v="></script>
{% endblock %}
......@@ -436,7 +436,7 @@
</p>
<p>
{% if mode == 'shop' %}
<strong><i>Si vous arrivez avec un retard de plus d'une heure, la commande pourrait ne plus être disponible.</i></strong>
<strong><i>{{SHOP_BOTTOM_VALIDATION_MSG}}</i></strong>
{%endif%}
</p>
<p>
......@@ -500,6 +500,10 @@
{%if SHOP_OPENING_START_DATE%}
const opening_start_date = new Date('{{SHOP_OPENING_START_DATE}}')
{%endif%}
{%if cat_nb_pdts%}
const cat_nb_pdts = {{cat_nb_pdts|safe}}
{%endif%}
const stock_warning = {{SHOP_STOCK_WARNING|safe}}
</script>
<script src="{% static 'js/all_common.js' %}?v="></script>
<script type="text/javascript" src="{% static 'js/shop.js' %}?v="></script>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment