Merge remote-tracking branch 'origin/master'

This commit is contained in:
Rob H
2013-02-01 13:15:25 +11:00
86 changed files with 13775 additions and 586 deletions

View File

@@ -1,7 +1,7 @@
source 'http://rubygems.org'
ruby "1.9.3"
gem 'rails', '3.2.8'
gem 'rails', '3.2.11'
gem 'pg'
gem 'spree', :git => 'git://github.com/spree/spree.git', :branch => '1-1-stable'
@@ -39,6 +39,7 @@ end
gem 'jquery-rails'
group :test, :development do
# Pretty printed test output
gem 'turn', '~> 0.8.3', :require => false
@@ -51,5 +52,6 @@ group :test, :development do
gem 'spork', '~> 1.0rc'
gem 'pry-debugger'
gem 'awesome_print'
gem "letter_opener"
end

View File

@@ -89,19 +89,19 @@ GIT
GEM
remote: http://rubygems.org/
specs:
actionmailer (3.2.8)
actionpack (= 3.2.8)
actionmailer (3.2.11)
actionpack (= 3.2.11)
mail (~> 2.4.4)
actionpack (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
actionpack (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.0)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.1.3)
sprockets (~> 2.2.1)
active_link_to (1.0.0)
active_utils (1.0.5)
activesupport (>= 2.3.11)
@@ -114,18 +114,18 @@ GEM
json (>= 1.5.1)
money
nokogiri
activemodel (3.2.8)
activesupport (= 3.2.8)
activemodel (3.2.11)
activesupport (= 3.2.11)
builder (~> 3.0.0)
activerecord (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
activerecord (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.8)
activemodel (= 3.2.8)
activesupport (= 3.2.8)
activesupport (3.2.8)
activeresource (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
activesupport (3.2.11)
i18n (~> 0.6)
multi_json (~> 1.0)
acts_as_list (0.1.4)
@@ -145,13 +145,13 @@ GEM
multi_json (~> 1.0)
builder (3.0.4)
cancan (1.6.7)
capybara (1.1.3)
capybara (2.0.2)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 2.0)
xpath (~> 0.1.4)
xpath (~> 1.0.0)
childprocess (0.3.6)
ffi (~> 1.0, >= 1.0.6)
cocaine (0.4.2)
@@ -196,7 +196,7 @@ GEM
faker (1.0.1)
i18n (~> 0.4)
ffaker (1.12.1)
ffi (1.1.5)
ffi (1.3.1)
haml (3.1.6)
highline (1.6.11)
hike (1.2.1)
@@ -208,15 +208,20 @@ GEM
jquery-rails (2.1.3)
railties (>= 3.1.0, < 5.0)
thor (~> 0.14)
json (1.7.5)
json (1.7.6)
kaminari (0.13.0)
actionpack (>= 3.0.0)
activesupport (>= 3.0.0)
railties (>= 3.0.0)
kgio (2.7.4)
launchy (2.1.2)
addressable (~> 2.3)
letter_opener (1.0.0)
launchy (>= 2.0.4)
libv8 (3.3.10.4)
libwebsocket (0.1.5)
libwebsocket (0.1.7.1)
addressable
websocket
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
@@ -226,12 +231,12 @@ GEM
money (5.0.0)
i18n (~> 0.4)
json
multi_json (1.3.6)
multi_json (1.5.0)
multi_xml (0.5.1)
nested_set (1.7.0)
activerecord (>= 3.0.0)
railties (>= 3.0.0)
nokogiri (1.5.5)
nokogiri (1.5.6)
orm_adapter (0.0.7)
paperclip (2.8.0)
activerecord (>= 2.3.0)
@@ -252,30 +257,30 @@ GEM
rabl (0.6.5)
activesupport (>= 2.3.14)
multi_json (~> 1.0)
rack (1.4.1)
rack (1.4.4)
rack-cache (1.2)
rack (>= 0.4)
rack-ssl (1.3.2)
rack
rack-test (0.6.2)
rack (>= 1.0)
rails (3.2.8)
actionmailer (= 3.2.8)
actionpack (= 3.2.8)
activerecord (= 3.2.8)
activeresource (= 3.2.8)
activesupport (= 3.2.8)
rails (3.2.11)
actionmailer (= 3.2.11)
actionpack (= 3.2.11)
activerecord (= 3.2.11)
activeresource (= 3.2.11)
activesupport (= 3.2.11)
bundler (~> 1.0)
railties (= 3.2.8)
railties (3.2.8)
actionpack (= 3.2.8)
activesupport (= 3.2.8)
railties (= 3.2.11)
railties (3.2.11)
actionpack (= 3.2.11)
activesupport (= 3.2.11)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
raindrops (0.9.0)
rake (0.9.2.2)
rake (10.0.3)
ransack (0.6.0)
actionpack (~> 3.0)
activerecord (~> 3.0)
@@ -309,7 +314,7 @@ GEM
railties (~> 3.2.0)
sass (>= 3.1.10)
tilt (~> 1.3)
selenium-webdriver (2.25.0)
selenium-webdriver (2.27.2)
childprocess (>= 0.2.5)
libwebsocket (~> 0.1.3)
multi_json (~> 1.0)
@@ -318,8 +323,9 @@ GEM
activesupport (>= 3.0.0)
slop (3.3.3)
spork (1.0.0rc3)
sprockets (2.1.3)
sprockets (2.2.2)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
state_machine (1.1.2)
@@ -334,7 +340,7 @@ GEM
truncate_html (0.5.5)
turn (0.8.3)
ansi
tzinfo (0.3.34)
tzinfo (0.3.35)
uglifier (1.2.4)
execjs (>= 0.3.0)
multi_json (>= 1.0.2)
@@ -345,7 +351,8 @@ GEM
uuidtools (2.1.3)
warden (1.1.1)
rack (>= 1.0)
xpath (0.1.4)
websocket (1.0.6)
xpath (1.0.0)
nokogiri (~> 1.3)
PLATFORMS
@@ -364,9 +371,10 @@ DEPENDENCIES
faker
haml
jquery-rails
letter_opener
pg
pry-debugger
rails (= 3.2.8)
rails (= 3.2.11)
representative_view
rspec-rails
sass-rails (~> 3.2.3)

661
LICENCE.txt Normal file
View File

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

View File

@@ -85,4 +85,4 @@ speak to Andrew Spinks.
## Licence
TODO
Copyright (c) 2012 Eaterprises, released under the AGPL licence.

View File

@@ -1,153 +0,0 @@
function AdminCreateOrderCycleCtrl($scope, OrderCycle, Enterprise) {
$scope.enterprises = Enterprise.index();
$scope.order_cycle = OrderCycle.order_cycle;
$scope.addSupplier = function($event) {
OrderCycle.addSupplier($event, $scope.new_supplier_id);
};
$scope.submit = function() {
OrderCycle.create();
};
}
function AdminEditOrderCycleCtrl($scope, OrderCycle, Enterprise) {
$scope.enterprises = Enterprise.index();
var order_cycle_id = window.location.pathname.match(/\/admin\/order_cycles\/(\d+)/)[1];
$scope.order_cycle = OrderCycle.load(order_cycle_id);
$scope.addSupplier = function($event) {
OrderCycle.addSupplier($event, $scope.new_supplier_id);
};
$scope.submit = function() {
OrderCycle.update();
};
}
angular.module('order_cycle', ['ngResource']).
config(function($httpProvider) {
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
}).
factory('OrderCycle', function($resource) {
var OrderCycle = $resource('/admin/order_cycles/:order_cycle_id.json', {},
{'index': { method: 'GET', isArray: true},
'create': { method: 'POST'},
'update': { method: 'PUT'}});
return {
order_cycle: {incoming_exchanges: [],
outgoing_exchanges: []},
addSupplier: function(event, new_supplier_id) {
event.preventDefault();
this.order_cycle.incoming_exchanges.push({enterprise_id: new_supplier_id, active: true});
},
load: function(order_cycle_id) {
var service = this;
OrderCycle.get({order_cycle_id: order_cycle_id}, function(oc) {
$.extend(service.order_cycle, oc);
service.order_cycle.incoming_exchanges = [];
service.order_cycle.outgoing_exchanges = [];
for(i in service.order_cycle.exchanges) {
var exchange = service.order_cycle.exchanges[i];
if(exchange.sender_id == service.order_cycle.coordinator_id) {
service.order_cycle.outgoing_exchanges.push({enterprise_id: exchange.receiver_id, active: true});
} else if(exchange.receiver_id == service.order_cycle.coordinator_id) {
service.order_cycle.incoming_exchanges.push({enterprise_id: exchange.sender_id, active: true});
} else {
console.log('Exchange between two enterprises, neither of which is coordinator!');
}
}
delete(service.order_cycle.exchanges);
});
return this.order_cycle;
},
create: function() {
this.removeInactiveExchanges();
var oc = new OrderCycle({order_cycle: this.order_cycle});
oc.$create(function(data) {
if(data['success']) {
window.location = '/admin/order_cycles';
} else {
console.log('fail');
}
});
},
update: function() {
this.removeInactiveExchanges();
var oc = new OrderCycle({order_cycle: this.order_cycle});
oc.$update({order_cycle_id: this.order_cycle.id}, function(data) {
if(data['success']) {
window.location = '/admin/order_cycles';
} else {
console.log('fail');
}
});
},
removeInactiveExchanges: function() {
for(var i=0; i < this.order_cycle.incoming_exchanges.length; i++) {
if(!this.order_cycle.incoming_exchanges[i].active) {
this.order_cycle.incoming_exchanges.splice(i, 1);
i--;
}
}
}
};
}).
factory('Enterprise', function($resource) {
var Enterprise = $resource('/admin/enterprises/:enterprise_id.json', {},
{'index': { method: 'GET', isArray: true}});
return {
enterprises: {},
index: function() {
var service = this;
Enterprise.index(function(data) {
for(i in data) {
service.enterprises[data[i]['id']] = data[i];
}
});
return this.enterprises;
}
};
}).
directive('datetimepicker', ['$parse', function($parse) {
return function(scope, element, attrs) {
// using $parse instead of scope[attrs.datetimepicker] for cases
// where attrs.datetimepicker is 'foo.bar.lol'
$(element).datetimepicker({
dateFormat: 'yy-mm-dd',
timeFormat: 'HH:mm:ss',
showOn: "button",
buttonImage: "<%= asset_path 'datepicker/cal.gif' %>",
buttonImageOnly: true,
stepMinute: 15,
onSelect: function(dateText, inst) {
scope.$apply(function() {
parsed = $parse(attrs.datetimepicker);
parsed.assign(scope, dateText);
});
}
});
};
}]);

View File

@@ -0,0 +1,225 @@
app = angular.module('order_cycle', ['ngResource'])
app.controller 'AdminCreateOrderCycleCtrl', ($scope, OrderCycle, Enterprise) ->
$scope.enterprises = Enterprise.index()
$scope.supplied_products = Enterprise.supplied_products
$scope.order_cycle = OrderCycle.order_cycle
$scope.exchangeSelectedVariants = (exchange) ->
OrderCycle.exchangeSelectedVariants(exchange)
$scope.enterpriseTotalVariants = (enterprise) ->
Enterprise.totalVariants(enterprise)
$scope.productSuppliedToOrderCycle = (product) ->
OrderCycle.productSuppliedToOrderCycle(product)
$scope.variantSuppliedToOrderCycle = (variant) ->
OrderCycle.variantSuppliedToOrderCycle(variant)
$scope.incomingExchangesVariants = ->
OrderCycle.incomingExchangesVariants()
$scope.toggleProducts = ($event, exchange) ->
$event.preventDefault()
OrderCycle.toggleProducts(exchange)
$scope.addSupplier = ($event) ->
$event.preventDefault()
OrderCycle.addSupplier($scope.new_supplier_id)
$scope.addDistributor = ($event) ->
$event.preventDefault()
OrderCycle.addDistributor($scope.new_distributor_id)
$scope.submit = ->
OrderCycle.create()
app.controller 'AdminEditOrderCycleCtrl', ($scope, $location, OrderCycle, Enterprise) ->
$scope.enterprises = Enterprise.index()
$scope.supplied_products = Enterprise.supplied_products
order_cycle_id = $location.absUrl().match(/\/admin\/order_cycles\/(\d+)/)[1]
$scope.order_cycle = OrderCycle.load(order_cycle_id)
$scope.exchangeSelectedVariants = (exchange) ->
OrderCycle.exchangeSelectedVariants(exchange)
$scope.enterpriseTotalVariants = (enterprise) ->
Enterprise.totalVariants(enterprise)
$scope.productSuppliedToOrderCycle = (product) ->
OrderCycle.productSuppliedToOrderCycle(product)
$scope.variantSuppliedToOrderCycle = (variant) ->
OrderCycle.variantSuppliedToOrderCycle(variant)
$scope.incomingExchangesVariants = ->
OrderCycle.incomingExchangesVariants()
$scope.toggleProducts = ($event, exchange) ->
$event.preventDefault()
OrderCycle.toggleProducts(exchange)
$scope.addSupplier = ($event) ->
$event.preventDefault()
OrderCycle.addSupplier($scope.new_supplier_id)
$scope.addDistributor = ($event) ->
$event.preventDefault()
OrderCycle.addDistributor($scope.new_distributor_id)
$scope.submit = ->
OrderCycle.update()
app.config ($httpProvider) ->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
app.factory 'OrderCycle', ($resource, $window) ->
OrderCycle = $resource '/admin/order_cycles/:order_cycle_id.json', {}, {
'index': { method: 'GET', isArray: true}
'create': { method: 'POST'}
'update': { method: 'PUT'}}
{
order_cycle:
incoming_exchanges: []
outgoing_exchanges: []
exchangeSelectedVariants: (exchange) ->
numActiveVariants = 0
numActiveVariants++ for id, active of exchange.variants when active
numActiveVariants
toggleProducts: (exchange) ->
exchange.showProducts = !exchange.showProducts
addSupplier: (new_supplier_id) ->
this.order_cycle.incoming_exchanges.push({enterprise_id: new_supplier_id, active: true, variants: {}})
addDistributor: (new_distributor_id) ->
this.order_cycle.outgoing_exchanges.push({enterprise_id: new_distributor_id, active: true, variants: {}})
productSuppliedToOrderCycle: (product) ->
product_variant_ids = (variant.id for variant in product.variants)
variant_ids = [product.master_id].concat(product_variant_ids)
incomingExchangesVariants = this.incomingExchangesVariants()
# TODO: This is an O(n^2) implementation of set intersection and thus is slooow.
# Use a better algorithm if needed.
# Also, incomingExchangesVariants is called every time, when it only needs to be
# called once per change to incoming variants. Some sort of caching?
ids = (variant_id for variant_id in variant_ids when incomingExchangesVariants.indexOf(variant_id) != -1)
ids.length > 0
variantSuppliedToOrderCycle: (variant) ->
this.incomingExchangesVariants().indexOf(variant.id) != -1
incomingExchangesVariants: ->
variant_ids = []
for exchange in this.order_cycle.incoming_exchanges
variant_ids.push(parseInt(id)) for id, active of exchange.variants when active
variant_ids
load: (order_cycle_id) ->
service = this
OrderCycle.get {order_cycle_id: order_cycle_id}, (oc) ->
angular.extend(service.order_cycle, oc)
service.order_cycle.incoming_exchanges = []
service.order_cycle.outgoing_exchanges = []
for exchange in service.order_cycle.exchanges
if exchange.sender_id == service.order_cycle.coordinator_id
angular.extend(exchange, {enterprise_id: exchange.receiver_id, active: true})
delete(exchange.sender_id)
service.order_cycle.outgoing_exchanges.push(exchange)
else if exchange.receiver_id == service.order_cycle.coordinator_id
angular.extend(exchange, {enterprise_id: exchange.sender_id, active: true})
delete(exchange.receiver_id)
service.order_cycle.incoming_exchanges.push(exchange)
else
console.log('Exchange between two enterprises, neither of which is coordinator!')
delete(service.order_cycle.exchanges)
this.order_cycle
create: ->
this.removeInactiveExchanges()
oc = new OrderCycle({order_cycle: this.order_cycle})
oc.$create (data) ->
if data['success']
$window.location = '/admin/order_cycles'
else
console.log('fail')
update: ->
this.removeInactiveExchanges()
oc = new OrderCycle({order_cycle: this.order_cycle})
oc.$update {order_cycle_id: this.order_cycle.id}, (data) ->
if data['success']
$window.location = '/admin/order_cycles'
else
console.log('fail')
removeInactiveExchanges: ->
this.order_cycle.incoming_exchanges =
(exchange for exchange in this.order_cycle.incoming_exchanges when exchange.active)
this.order_cycle.outgoing_exchanges =
(exchange for exchange in this.order_cycle.outgoing_exchanges when exchange.active)
}
app.factory 'Enterprise', ($resource) ->
Enterprise = $resource('/admin/enterprises/:enterprise_id.json', {}, {'index': {method: 'GET', isArray: true}})
{
Enterprise: Enterprise
enterprises: {}
supplied_products: []
index: ->
service = this
Enterprise.index (data) ->
for enterprise in data
service.enterprises[enterprise.id] = enterprise
for product in enterprise.supplied_products
service.supplied_products.push(product)
this.enterprises
totalVariants: (enterprise) ->
numVariants = 0
counts = for product in enterprise.supplied_products
numVariants += if product.variants.length == 0 then 1 else product.variants.length
numVariants
}
app.directive 'datetimepicker', ['$parse', ($parse) ->
(scope, element, attrs) ->
# using $parse instead of scope[attrs.datetimepicker] for cases
# where attrs.datetimepicker is 'foo.bar.lol'
$(element).datetimepicker
dateFormat: 'yy-mm-dd'
timeFormat: 'HH:mm:ss'
showOn: "button"
buttonImage: "<%= asset_path 'datepicker/cal.gif' %>"
buttonImageOnly: true
stepMinute: 15
onSelect: (dateText, inst) ->
scope.$apply ->
parsed = $parse(attrs.datetimepicker)
parsed.assign(scope, dateText)
]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -36,5 +36,36 @@ form.order_cycle {
tr td.active {
width: 20px;
}
tr.supplier td {
border-bottom: 2px solid #C3D9FF;
}
.exchange-product {
float: left;
overflow: auto;
width: 18%;
min-height: 7.5em;
margin: 0 1% 1% 0;
border: 1px solid #DAE7FF;
padding: 5px;
.exchange-product-details {
clear: both;
margin-bottom: 1em;
.supplier {
font-weight: bold;
}
}
.exchange-product-variant {
float: left;
margin-right: 2em;
}
}
}
.actions {
margin-top: 3em;
}
}

View File

@@ -225,3 +225,13 @@ fieldset#product-distributor-details {
}
}
}
/* Alert for EFT Payment during checkout process */
div#eft-payment-alert {
border: 2px solid red;
}
/* Cleared div for clearing previous floating elements */
div.cleared {
clear: both;
}

View File

@@ -42,7 +42,7 @@ module Admin
if @order_cycle.update_attributes(params[:order_cycle])
OpenFoodWeb::OrderCycleFormApplicator.new(@order_cycle).go!
flash[:notice] = 'Your order cycle has been saved.'
flash[:notice] = 'Your order cycle has been updated.'
format.html { redirect_to admin_order_cycles_path }
format.json { render :json => {:success => true} }
else

View File

@@ -26,28 +26,4 @@ class EnterprisesController < BaseController
@searcher = Spree::Config.searcher_class.new(options)
@products = @searcher.retrieve_products
end
def select_distributor
distributor = Enterprise.is_distributor.find params[:id]
order = current_order(true)
if order.can_change_distributor?
order.distributor = distributor
order.save!
end
redirect_to distributor
end
def deselect_distributor
order = current_order(true)
if order.can_change_distributor?
order.distributor = nil
order.save!
end
redirect_to root_path
end
end

View File

@@ -1,5 +1,6 @@
Spree::OrdersController.class_eval do
before_filter :populate_order_distributor, :only => :populate
before_filter :populate_order_count_on_hand, :only => :populate
after_filter :populate_variant_attributes, :only => :populate
def populate_order_distributor
@@ -15,6 +16,24 @@ Spree::OrdersController.class_eval do
end
end
def populate_order_count_on_hand
params[:products].each do |product_id, variant_id|
product = Spree::Product.find product_id
if product.count_on_hand < params[:quantity].to_i
flash[:error] = "Unfortunately " + (product.count_on_hand == 0 ? "no" : "only" + product.count_on_hand.to_s ) + " units of the selected item remain."
redirect_populate_to_first_product
end
end if params[:products]
params[:variants].each do |variant_id, quantity|
variant = Spree::Variant.find variant_id
if variant.count_on_hand < params[:quantity].to_i
flash[:error] = "Unfortunately " + (variant.count_on_hand == 0 ? "no" : "only" + variant.count_on_hand.to_s ) + " units of the selected item remain."
redirect_populate_to_first_product
end
end if params[:variants]
end
def populate_variant_attributes
if params.key? :variant_attributes
params[:variant_attributes].each do |variant_id, attributes|
@@ -30,6 +49,24 @@ Spree::OrdersController.class_eval do
end
end
def select_distributor
distributor = Enterprise.is_distributor.find params[:id]
order = current_order(true)
order.distributor = distributor
order.save!
redirect_to main_app.enterprise_path(distributor)
end
def deselect_distributor
order = current_order(true)
order.distributor = nil
order.save!
redirect_to root_path
end
private
@@ -50,7 +87,7 @@ Spree::OrdersController.class_eval do
# -- If products in cart, distributor can't be changed
order = current_order(false)
if !order.nil? && !order.can_change_distributor? && order.distributor != distributor
if !order.nil? && !DistributorChangeValidator.new(order).can_change_to_distributor?(distributor)
return false
end

View File

@@ -2,4 +2,8 @@ module EnterprisesHelper
def current_distributor
@current_distributor ||= current_order(false).andand.distributor
end
def enterprises_options enterprises
enterprises.map { |enterprise| [enterprise.name + ": " + enterprise.address.address1 + ", " + enterprise.address.city, enterprise.id.to_i] }
end
end

View File

@@ -0,0 +1,5 @@
module OrderCyclesHelper
def coordinating_enterprises
Enterprise.is_distributor.order('name')
end
end

View File

@@ -5,5 +5,9 @@ module Spree
amount = order.line_items.map { |li| li.itemwise_shipping_cost }.sum
options.delete(:format_as_currency) ? number_to_currency(amount) : amount
end
def alternative_available_distributors(order)
DistributorChangeValidator.new(order).available_distributors(Enterprise.all) - [order.distributor]
end
end
end

View File

@@ -27,6 +27,10 @@ class Enterprise < ActiveRecord::Base
def to_param
"#{id}-#{name.parameterize}"
end
def available_variants
ProductDistribution.find_all_by_distributor_id( self.id ).map{ |pd| pd.product.variants + [pd.product.master] }.flatten
end
private

View File

@@ -12,4 +12,6 @@ class Exchange < ActiveRecord::Base
validates_presence_of :order_cycle, :sender, :receiver
validates_uniqueness_of :sender_id, :scope => [:order_cycle_id, :receiver_id]
accepts_nested_attributes_for :variants
end

View File

@@ -1,17 +1,18 @@
require 'open_food_web/distributor_change_validator'
Spree::Order.class_eval do
belongs_to :distributor, :class_name => 'Enterprise'
before_validation :shipping_address_from_distributor
validate :products_available_from_new_distributor, :if => :distributor_id_changed?
attr_accessible :distributor_id
after_create :set_default_shipping_method
def can_change_distributor?
# Distributor may not be changed once an item has been added to the cart/order
line_items.empty?
end
def distributor=(distributor)
raise "You cannot change the distributor of an order with products" unless distributor == self.distributor || can_change_distributor?
super(distributor)
def products_available_from_new_distributor
# Check that the line_items in the current order are available from a newly selected distributor
errors.add(:distributor_id, "cannot supply the products in your cart") unless DistributorChangeValidator.new(self).can_change_to_distributor?(distributor)
end
def set_distributor!(distributor)
@@ -19,11 +20,6 @@ Spree::Order.class_eval do
save!
end
def can_add_product_to_cart?(product)
can_change_distributor? || product.distributors.include?(distributor)
end
def set_variant_attributes(variant, attributes)
line_item = contains?(variant)
@@ -34,6 +30,10 @@ Spree::Order.class_eval do
line_item.assign_attributes(attributes)
line_item.save!
end
def line_item_variants
line_items.map{ |li| li.variant }
end
private

View File

@@ -1,4 +1,4 @@
Deface::Override.new(:virtual_path => "spree/checkout/_delivery",
:insert_before => "fieldset#shipping_method",
:text => "<%= cms_page_content(:content, Cms::Page.find_by_full_path('/delivery')) %>",
:name => "process_my_order_button")
:text => "<%= cms_snippet_content(Cms::Snippet.find_by_identifier('distribution')) %>",
:name => "cms_checkout_distribution")

View File

@@ -0,0 +1,4 @@
Deface::Override.new(:virtual_path => "spree/orders/edit",
:insert_after => "h1",
:text => "<%= cms_snippet_content(Cms::Snippet.find_by_identifier('cart')) %>",
:name => "cms_to_cart")

View File

@@ -0,0 +1,4 @@
Deface::Override.new(:virtual_path => "spree/shared/_order_details",
:replace => "[data-hook='order_item_description']",
:partial => "spree/orders/order_item_description",
:name => "order_item_description")

View File

@@ -1,4 +1,9 @@
Deface::Override.new(:virtual_path => "spree/checkout/_address",
:replace => "[data-hook='shipping_fieldset_wrapper']",
:partial => "spree/checkout/distributor",
:name => "delivery_address")
:replace => "[data-hook='shipping_fieldset_wrapper']",
:partial => "spree/checkout/distributor",
:name => "replace_shipping_form")
Deface::Override.new(:virtual_path => "spree/checkout/edit",
:insert_after => "[data-hook='checkout_summary_box']",
:partial => "spree/checkout/other_available_distributors",
:name => "other_available_distributors")

View File

@@ -0,0 +1,4 @@
Deface::Override.new(:virtual_path => "spree/shared/_order_details",
:replace => "div.row.steps-data",
:partial => "spree/shared/order_details_steps_data",
:name => "order_details_steps_data")

View File

@@ -0,0 +1,13 @@
class VariantPresenter
attr_accessor :variant
def initialize(variant)
@variant = variant
end
delegate :id, :to => :variant
def image_url
@variant.images.first.attachment.url :mini if @variant.images.present?
end
end

View File

@@ -1,4 +1,15 @@
r.list_of :enterprises, @collection do
r.element :id
r.element :name
r.list_of :supplied_products do |product|
r.element :name
r.element :supplier_name, product.supplier.andand.name
r.element :image_url, product.images.present? ? product.images.first.attachment.url(:mini) : nil
r.element :master_id, product.master.id
r.list_of :variants do |variant|
r.element :id
r.element :label, variant.options_text
end
end
end

View File

@@ -0,0 +1,10 @@
%td{:colspan => 3}
.exchange-product{'ng-repeat' => 'product in supplied_products | filter:productSuppliedToOrderCycle'}
.exchange-product-details
.supplier {{ product.supplier_name }}
= check_box_tag 'order_cycle_outgoing_exchange_{{ $parent.$index }}_variants_{{ product.master_id }}', 1, 1, 'ng-hide' => 'product.variants', 'ng-model' => 'exchange.variants[product.master_id]', 'id' => 'order_cycle_outgoing_exchange_{{ $parent.$index }}_variants_{{ product.master_id }}'
%img{'ng-src' => '{{ product.image_url }}'}
{{ product.name }}
.exchange-product-variant{'ng-repeat' => 'variant in product.variants | filter:variantSuppliedToOrderCycle'}
= check_box_tag 'order_cycle_outgoing_exchange_{{ $parent.$parent.$index }}_variants_{{ variant.id }}', 1, 1, 'ng-model' => 'exchange.variants[variant.id]', 'id' => 'order_cycle_outgoing_exchange_{{ $parent.$parent.$index }}_variants_{{ variant.id }}'
{{ variant.label }}

View File

@@ -0,0 +1,15 @@
%td.active= check_box_tag 'order_cycle_exchange_{{ $index }}_active', 1, 1, 'ng-model' => 'exchange.active', 'id' => 'order_cycle_exchange_{{ $index }}_active'
%td{:class => "#{type}_name"} {{ enterprises[exchange.enterprise_id].name }}
%td.products
= f.submit 'Products', 'ng-click' => 'toggleProducts($event, exchange)'
{{ exchangeSelectedVariants(exchange) }} /
- if type == 'supplier'
{{ enterpriseTotalVariants(enterprises[exchange.enterprise_id]) }}
- else
{{ incomingExchangesVariants().length }}
selected
- if type == 'distributor'
%td.collection-details
= text_field_tag 'order_cycle_outgoing_exchange_{{ $index }}_pickup_time', '', 'id' => 'order_cycle_outgoing_exchange_{{ $index }}_pickup_time', 'placeholder' => 'Pickup time / date', 'ng-model' => 'exchange.pickup_time'
%br/
= text_field_tag 'order_cycle_outgoing_exchange_{{ $index }}_pickup_instructions', '', 'id' => 'order_cycle_outgoing_exchange_{{ $index }}_pickup_instructions', 'placeholder' => 'Delivery instructions', 'ng-model' => 'exchange.pickup_instructions'

View File

@@ -0,0 +1,10 @@
/ TODO: Unify this with exchange_distributed_products_form
%td{:colspan => 3}
.exchange-product{'ng-repeat' => 'product in enterprises[exchange.enterprise_id].supplied_products'}
.exchange-product-details
= check_box_tag 'order_cycle_incoming_exchange_{{ $parent.$index }}_variants_{{ product.master_id }}', 1, 1, 'ng-hide' => 'product.variants', 'ng-model' => 'exchange.variants[product.master_id]', 'id' => 'order_cycle_incoming_exchange_{{ $parent.$index }}_variants_{{ product.master_id }}'
%img{'ng-src' => '{{ product.image_url }}'}
{{ product.name }}
.exchange-product-variant{'ng-repeat' => 'variant in product.variants'}
= check_box_tag 'order_cycle_incoming_exchange_{{ $parent.$parent.$index }}_variants_{{ variant.id }}', 1, 1, 'ng-model' => 'exchange.variants[variant.id]', 'id' => 'order_cycle_incoming_exchange_{{ $parent.$parent.$index }}_variants_{{ variant.id }}'
{{ variant.label }}

View File

@@ -13,9 +13,16 @@
%h2 Incoming
%table.exchanges
%tr{'ng-repeat' => 'exchange in order_cycle.incoming_exchanges'}
%td.active= check_box_tag 'order_cycle_exchange_{{ $index }}_active', 1, 1, 'ng-model' => 'exchange.active', 'id' => 'order_cycle_exchange_{{ $index }}_active'
%td {{ enterprises[exchange.enterprise_id].name }}
%thead
%tr
%th
%th Supplier
%th Products
%tbody{'ng-repeat' => 'exchange in order_cycle.incoming_exchanges'}
%tr.supplier
= render 'exchange_form', :f => f, :type => 'supplier'
%tr.products{'ng-show' => 'exchange.showProducts'}
= render 'exchange_supplied_products_form'
= select_tag :new_supplier_id, options_from_collection_for_select(Enterprise.is_primary_producer, :id, :name), {'ng-model' => 'new_supplier_id'}
= f.submit 'Add supplier', 'ng-click' => 'addSupplier($event)'
@@ -23,17 +30,33 @@
%h2 Coordinator
= f.label :coordinator_id, 'Coordinator'
= f.collection_select :coordinator_id, Enterprise.all, :id, :name, {}, {'ng-model' => 'order_cycle.coordinator_id', 'required' => true}
= f.collection_select :coordinator_id, coordinating_enterprises, :id, :name, {}, {'ng-model' => 'order_cycle.coordinator_id', 'required' => true}
%h2 Outgoing
%p TODO
%table.exchanges
%thead
%tr
%th
%th Distributor
%th Products
%th Collection details
%tbody{'ng-repeat' => 'exchange in order_cycle.outgoing_exchanges'}
%tr.distributor
= render 'exchange_form', :f => f, :type => 'distributor'
%tr.products{'ng-show' => 'exchange.showProducts'}
= render 'exchange_distributed_products_form'
= f.submit @order_cycle.new_record? ? 'Create' : 'Update'
or
= link_to 'Cancel', main_app.admin_order_cycles_path
= select_tag :new_distributor_id, options_from_collection_for_select(Enterprise.is_distributor, :id, :name), {'ng-model' => 'new_distributor_id'}
= f.submit 'Add distributor', 'ng-click' => 'addDistributor($event)'
.actions
= f.submit @order_cycle.new_record? ? 'Create' : 'Update'
or
= link_to 'Cancel', main_app.admin_order_cycles_path
<h2>Debug information</h2>
%h2 Debug information
%pre order_cycle = {{ order_cycle | json }}
%pre enterprises = {{ enterprises | json }}
%pre supplied_products = {{ supplied_products | json }}

View File

@@ -26,11 +26,11 @@
%td= order_cycle_form.text_field :orders_open_at, :class => 'datetimepicker', :value => order_cycle.orders_open_at
%td= order_cycle_form.text_field :orders_close_at, :class => 'datetimepicker', :value => order_cycle.orders_close_at
%td= order_cycle.coordinator.name
%td
%td.suppliers
- order_cycle.suppliers.each do |s|
= s.name
%br/
%td
%td.distributors
- order_cycle.distributors.each do |d|
= d.name
%br/

View File

@@ -1,11 +1,17 @@
r.element :order_cycle, @order_cycle do
r.element :id
r.element :name
r.element :orders_open_at
r.element :orders_close_at
r.element :orders_open_at, @order_cycle.orders_open_at.to_s
r.element :orders_close_at, @order_cycle.orders_close_at.to_s
r.element :coordinator_id
r.list_of :exchanges do
r.list_of :exchanges do |exchange|
r.element :id
r.element :sender_id
r.element :receiver_id
r.element :variants, Hash[ exchange.variants.map { |v| [v.id, true] } ], {}
r.element :pickup_time
r.element :pickup_instructions
end
end

View File

@@ -1,8 +0,0 @@
<script type="text/javascript">
var uvOptions = {};
(function() {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/mCbT1cbjQZkPELXOix9Ag.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>

View File

@@ -0,0 +1,10 @@
<% if Rails.env.production? %>
<script type="text/javascript">
var uvOptions = {};
(function() {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/mCbT1cbjQZkPELXOix9Ag.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>
<% end %>

View File

@@ -0,0 +1,39 @@
<% content_for :head do %>
<% if Rails.env.production? %>
<%= stylesheet_link_tag 'https://api.jirafe.com/dashboard/css/spree_ui.css', :media => 'all' %>
<%= javascript_include_tag 'https://jirafe.com/dashboard/js/spree_namespaced_ui.js' %>
<% end %>
<% end %>
<% if Rails.env.production? %>
<% if Spree::Dash::Config.configured? %>
<h1><%= t(:overview) %></h1>
<div id="jirafe"></div>
<%= javascript_tag :defer => 'defer' do %>
jirafe.jQuery('#jirafe').jirafe({
api_url: 'https://api.jirafe.com/v1',
api_token: '<%= Spree::Dash::Config.token %>',
app_id: '<%= Spree::Dash::Config.app_id %>',
version: 'spree-v0.1.0',
locale: '<%= Spree::Dash::Config.locale %>' });
setTimeout(function() {
if ($('mod-jirafe') == undefined) {
$('messages').insert ("<ul class=\"messages\"><li class=\"error-msg\">We're unable to connect with the Jirafe service for the moment. Please wait a few minutes and refresh this page later.</li></ul>");
}
}, 10000);
<% end %>
<div id="jirafe_locales">
<%= raw jirafe_locale_links.join(' | ') %>
</div>
<% else %>
<div class="analytics_splash">
<%= image_tag 'analytics_dashboard_preview.png', :alt => 'Spree Analytics' %>
</div>
<br/>
<div class="preview-buttons">
<%= link_to content_tag(:span, t(:activate)), admin_analytics_sign_up_path, :class => 'button green' %>
<%= t(:or) %> &nbsp;
<%= link_to content_tag(:span, t(:learn_more)), "http://spreecommerce.com/blog/2012/01/31/introducing-spree-analytics/", :class => 'button', :target => '_blank' %>
</div>
<% end %>
<% end %>

View File

@@ -0,0 +1,13 @@
<% unless @order.state != 'address' %>
<div class="columns omega four" style="padding-top: 30px">
<% unless alternative_available_distributors(@order).empty? %>
<%= form_for(@order) do |f| %>
<%= f.label :distributor_label, "Alternative distributors for this order:" %>
<%= f.select :distributor_id, options_for_select( enterprises_options(alternative_available_distributors(@order)) ) %>
<%= f.submit "Change Distributor" %>
<% end %>
<% else %>
No alternative distributors available.
<% end %>
</div>
<% end %>

View File

@@ -1,10 +1,11 @@
Dear Customer,
Dear <%= @order.bill_address.firstname %>,
Please review and retain the following order information for your records.
============================================================
Order Summary
============================================================
Order for: <%= @order.bill_address.full_name %>
<% @order.line_items.each do |item| %>
<%= item.variant.sku %> <%= raw(item.variant.product.name) %> <%= raw(item.variant.options_text) -%> (<%=item.quantity%>) @ <%= number_to_currency item.price %> = <%= number_to_currency(item.price * item.quantity) %>
<% end %>
@@ -15,15 +16,22 @@ Subtotal: <%= number_to_currency @order.item_total %>
<% end %>
Order Total: <%= number_to_currency(@order.total) %>
<% if @order.payment_method.name.include? "EFT" %>
============================================================
Delivery Details
Payment Details
============================================================
<%= @order.payment_method.description.html_safe %>
<% end %>
============================================================
Collection / Delivery Details
============================================================
Address:
<%= @order.distributor.name %>
<% address = @order.distributor.address %>
<%= address.address1 %> <%= ",\n #{address.address2}" unless address.address2.blank? %>
<%= [address.city, address.state_text, address.zipcode, address.country.name].compact.join ', ' %>
Colection time:
Collection time:
<%= @order.distributor.next_collection_at %>
Contact:
<%= @order.distributor.contact %>

View File

@@ -4,5 +4,4 @@
- if @order.insufficient_stock_lines.include? line_item
%span.out-of-stock
= variant.in_stock? ? t(:insufficient_stock, :on_hand => variant.on_hand) : t(:out_of_stock)
%br/
= truncate_html(variant.product.description, :length => 100, :omission => "...")
%br/

View File

@@ -1,6 +1,6 @@
#delivery-fees
= cms_page_content(:content, Cms::Page.find_by_full_path('/cart-delivery-fees'))
%h2 Delivery Fees
%h2 Distribution Costs
= cms_snippet_content(Cms::Snippet.find_by_identifier('cart_distribution_costs'))
%table#delivery
%thead

View File

@@ -0,0 +1,3 @@
%td(data-hook = "order_item_description")
%h4= item.variant.product.name
= "(" + variant_options(item.variant) + ")" unless item.variant.option_values.empty?

View File

@@ -1,26 +1,34 @@
.add-to-cart
- order = current_order(false)
- if !@product.has_stock? && !Spree::Config[:allow_backorders]
= content_tag('strong', t(:out_of_stock))
- elsif current_order(false) && !current_order(false).can_add_product_to_cart?(@product)
- elsif !order.nil? && !DistributorChangeValidator.new(order).can_change_distributor? && !@product.distributors.include?(order.distributor)
.error-distributor
Please complete your order at
= link_to current_distributor.name, root_path
before shopping with another distributor.
- else
%p Quantity
= number_field_tag (@product.has_variants? ? :quantity : "variants[#{@product.master.id}]"), 1, :class => 'title', :in => 1..@product.on_hand
%div(class = "columns alpha two")
%div Quantity
= number_field_tag (@product.has_variants? ? :quantity : "variants[#{@product.master.id}]"), 1, :class => 'title', :in => 1..@product.on_hand
- if @product.group_buy
%p Max quantity
= number_field_tag (@product.has_variants? ? :max_quantity : "variant_attributes[#{@product.master.id}][max_quantity]"), 1, :class => 'title max_quantity', :in => 1..@product.on_hand
- order = current_order(false)
- if order.nil? || order.can_change_distributor?
%p Distributor
= select_tag "distributor_id", options_from_collection_for_select([Enterprise.new]+@product.distributors, "id", "name", current_distributor.andand.id)
- else
= hidden_field_tag "distributor_id", order.distributor.id
.distributor-fixed= "Your distributor for this order is #{order.distributor.name}"
%br/
%div(class = "columns alpha three")
%div Max quantity
= number_field_tag (@product.has_variants? ? :max_quantity : "variant_attributes[#{@product.master.id}][max_quantity]"), 1, :class => 'title max_quantity', :in => 1..@product.on_hand
%div.cleared
%br
- if order.nil? || order.distributor.nil?
%div Distributor for your order:
= select_tag "distributor_id", options_from_collection_for_select([Enterprise.new]+@product.distributors, "id", "name", :include_blank => '')
- else
- available_distributors = DistributorChangeValidator.new(order).available_distributors(@product.distributors)
- if available_distributors.length > 1
%div Distributor for your order:
= select_tag "distributor_id", options_from_collection_for_select(available_distributors, "id", "name", current_distributor.andand.id)
- else
= hidden_field_tag "distributor_id", order.distributor.id
.distributor-fixed= "Your distributor for this order is #{order.distributor.name}"
%br
= button_tag :class => 'large primary', :id => 'add-to-cart-button', :type => :submit do
= t(:add_to_cart)
= t(:add_to_cart)

View File

@@ -1,17 +1,30 @@
%div{:data-hook => "product_source"}
%h6.product-section-title Source
%h6.product-section-title SUPPLIER
%table#product-source.table-display{:width => "100%"}
%tbody
- if @product.supplier
%tr.odd
%td
%strong Supplier
%td= @product.supplier.name
%td= link_to @product.supplier.name, [main_app, @product.supplier]
%br/
%h6.product-section-title DISTRIBUTORS
%table#product-source.table-display{:width => "100%"}
%tbody
- order = current_order(false)
- validator = DistributorChangeValidator.new(order)
- @product.distributors.each do |distributor|
%tr.even
%td
%strong Distributor
%td= distributor.name
- if !order.nil? && distributor == order.distributor
%tr.odd
%td
%b= link_to(distributor.name, [main_app, distributor])
%td
%b Current
- elsif order.nil? || validator.can_change_to_distributor?(distributor)
%tr.even
%td= link_to distributor.name, [main_app, distributor]
%td Available
-#%td= link_to "Change to distributor", select_distributor_order_path(distributor)
- else
%tr.even
%td= link_to distributor.name, [main_app, distributor]
%td

View File

@@ -9,13 +9,14 @@
%h6.filter_name Shop by Distributor
%ul.filter_choices
- order = current_order(false)
- validator = DistributorChangeValidator.new(order)
- @distributors.each do |distributor|
%li.nowrap
- if order.nil? || order.can_change_distributor?
= link_to distributor.name, main_app.select_distributor_enterprise_path(distributor)
- if order.nil? || validator.can_change_to_distributor?(distributor)
= link_to distributor.name, [main_app, distributor]
- elsif order.distributor == distributor
= link_to distributor.name, [main_app, distributor]
- else
%span.inactive= distributor.name
- if current_distributor && order.can_change_distributor?
= button_to 'Browse All Distributors', main_app.deselect_distributor_enterprises_path, :method => :get
%abbr(title="One or more of the products in your cart is not available from this distributor")= distributor.name
- if current_distributor && validator.can_change_distributor?
= button_to 'Browse All Distributors', deselect_distributor_orders_path, :method => :get

View File

@@ -0,0 +1,49 @@
<div class="row steps-data">
<div class="columns alpha six">
<h6><%= "Customer Details" %> <%= link_to "(#{t(:edit)})", checkout_state_path(:address) unless @order.completed? %></h6>
<div class="address">
Name: <%= order.bill_address.full_name %><br />
Address: <%= order.bill_address.address1 + ", " + order.bill_address.city %>
</div>
</div>
<div class="columns alpha six">
<h6><%= "Distributor Details" %> <%# link_to "(#{t(:edit)})", checkout_state_path(:address) unless @order.completed? %></h6>
<div class="address">
Distributor: <%= order.distributor.name %><br />
Address: <%= order.distributor.address.address1 + ", " + order.distributor.address.city %>
</div>
</div>
<!-- <div class="columns alpha four">
<h6><%= t(:shipping_method) %> <%= link_to "(#{t(:edit)})", checkout_state_path(:delivery) unless @order.completed? %></h6>
<div class="delivery">
<%= order.shipping_method.name %>
</div>
</div> -->
</div>
<div class="row steps-data">
<div class="columns alpha six" <% if order.payment_method.name.include? "EFT" %>id="eft-payment-alert"<% end %>>
<h6><%= t(:payment_information) %> <%= link_to "(#{t(:edit)})", checkout_state_path(:payment) unless @order.completed? %></h6>
<div class="payment-info">
<% if order.payment_method.name.include? "PayPal" %>
<div class="flash notice">Your payment via PayPal has been processed successfully.</div>
<% elsif order.payment_method.name.include? "EFT" %>
<span><%= order.payment_method.description.html_safe %></span>
<% elsif order.creditcards.empty? == false %>
<span class="cc-type">
<%= image_tag "creditcards/icons/#{order.creditcards.first.cc_type}.png" %>
<%= t(:ending_in)%> <%= order.creditcards.first.last_digits %>
</span>
<br />
<span class="full-name">
<%= order.creditcards.first.first_name %>
<%= order.creditcards.first.last_name %>
</span>
<% elsif order.payment_method.type == "Spree::PaymentMethod::Check" %>
<span><%= order.payment_method.description %></span>
<% end %>
</div>
</div>
</div>

View File

@@ -0,0 +1,22 @@
basePath = '../';
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/**/*.js'
];
autoWatch = false;
browsers = ['Chrome'];
singleRun = true;
proxies = {
'/': 'http://localhost:8000/'
};
junitReporter = {
outputFile: 'test_out/e2e.xml',
suite: 'e2e'
};

View File

@@ -0,0 +1,24 @@
basePath = '../';
files = [
JASMINE,
JASMINE_ADAPTER,
'app/assets/javascripts/shared/jquery-1.8.0.js', // TODO: Can we link to Rails' jquery?
'app/assets/javascripts/shared/angular.js',
'app/assets/javascripts/shared/angular-*.js',
'app/assets/javascripts/admin/order_cycle.js.erb.coffee',
'spec/javascripts/unit/**/*.js*'
];
exclude = ['**/.#*']
autoWatch = true;
browsers = ['Chrome'];
junitReporter = {
outputFile: 'log/testacular-unit.xml',
suite: 'unit'
};

View File

@@ -27,6 +27,9 @@ Openfoodweb::Application.configure do
# Expands the lines which load the assets
config.assets.debug = true
# Show emails using Letter Opener
config.action_mailer.delivery_method = :letter_opener
end

View File

@@ -4,8 +4,6 @@ Openfoodweb::Application.routes.draw do
resources :enterprises do
get :suppliers, :on => :collection
get :distributors, :on => :collection
get :select_distributor, :on => :member
get :deselect_distributor, :on => :collection
end
namespace :admin do
@@ -33,4 +31,9 @@ Spree::Core::Engine.routes.prepend do
match '/admin/reports/bulk_coop' => 'admin/reports#bulk_coop', :as => "bulk_coop_admin_reports", :via => [:get, :post]
match '/admin/reports/payments' => 'admin/reports#payments', :as => "payments_admin_reports", :via => [:get, :post]
match '/admin/reports/order_cycles' => 'admin/reports#order_cycles', :as => "order_cycles_admin_reports", :via => [:get, :post]
resources :orders do
get :select_distributor, :on => :member
get :deselect_distributor, :on => :collection
end
end

View File

@@ -0,0 +1,9 @@
class ChangeExchangePickupTimeToString < ActiveRecord::Migration
def up
change_column :exchanges, :pickup_time, :string
end
def down
change_column :exchanges, :pickup_time, :datetime
end
end

View File

@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20121125232613) do
ActiveRecord::Schema.define(:version => 20130118031610) do
create_table "cms_blocks", :force => true do |t|
t.integer "page_id", :null => false
@@ -177,7 +177,7 @@ ActiveRecord::Schema.define(:version => 20121125232613) do
t.integer "sender_id"
t.integer "receiver_id"
t.integer "payment_enterprise_id"
t.datetime "pickup_time"
t.string "pickup_time"
t.string "pickup_instructions"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false

View File

@@ -0,0 +1,22 @@
class DistributorChangeValidator
def initialize order
@order = order
end
def can_change_distributor?
# Distributor may not be changed once an item has been added to the cart/order
@order.line_items.empty?
end
def can_change_to_distributor? distributor
# Distributor may not be changed once an item has been added to the cart/order, unless all items are available from the specified distributor
@order.line_items.empty? || (available_distributors(Enterprise.all) || []).include?(distributor)
end
def available_distributors enterprises
enterprises.select do |e|
(@order.line_item_variants - e.available_variants).empty?
end
end
end

View File

@@ -8,29 +8,47 @@ module OpenFoodWeb
@touched_exchanges = []
@order_cycle.incoming_exchanges.each do |exchange|
variant_ids = exchange_variant_ids(exchange)
if exchange_exists?(exchange[:enterprise_id], @order_cycle.coordinator_id)
update_exchange(exchange[:enterprise_id], @order_cycle.coordinator_id)
update_exchange(exchange[:enterprise_id], @order_cycle.coordinator_id, {variant_ids: variant_ids})
else
add_exchange(exchange[:enterprise_id], @order_cycle.coordinator_id)
add_exchange(exchange[:enterprise_id], @order_cycle.coordinator_id, {variant_ids: variant_ids})
end
end
@order_cycle.outgoing_exchanges.each do |exchange|
variant_ids = exchange_variant_ids(exchange)
if exchange_exists?(@order_cycle.coordinator_id, exchange[:enterprise_id])
update_exchange(@order_cycle.coordinator_id, exchange[:enterprise_id], {variant_ids: variant_ids, pickup_time: exchange[:pickup_time], pickup_instructions: exchange[:pickup_instructions]})
else
add_exchange(@order_cycle.coordinator_id, exchange[:enterprise_id], {variant_ids: variant_ids, pickup_time: exchange[:pickup_time], pickup_instructions: exchange[:pickup_instructions]})
end
end
destroy_untouched_exchanges
end
private
attr_accessor :touched_exchanges
def exchange_exists?(sender_id, receiver_id)
@order_cycle.exchanges.where(:sender_id => sender_id, :receiver_id => receiver_id).present?
end
def add_exchange(sender_id, receiver_id)
exchange = @order_cycle.exchanges.create! :sender_id => sender_id, :receiver_id => receiver_id
def add_exchange(sender_id, receiver_id, attrs={})
attrs = attrs.reverse_merge(:sender_id => sender_id, :receiver_id => receiver_id)
exchange = @order_cycle.exchanges.create! attrs
@touched_exchanges << exchange
end
def update_exchange(sender_id, receiver_id)
# NOOP - when we're setting data on the exchange, we can do so here
def update_exchange(sender_id, receiver_id, attrs={})
exchange = @order_cycle.exchanges.where(:sender_id => sender_id, :receiver_id => receiver_id).first
exchange.update_attributes!(attrs)
@touched_exchanges << exchange
end
@@ -42,5 +60,9 @@ module OpenFoodWeb
@order_cycle.exchanges - @touched_exchanges
end
def exchange_variant_ids(exchange)
exchange[:variants].select { |k, v| v }.keys.map { |k| k.to_i }
end
end
end

View File

@@ -0,0 +1,11 @@
@echo off
REM Windows script for running e2e tests
REM You have to run server and capture some browser first
REM
REM Requirements:
REM - NodeJS (http://nodejs.org/)
REM - Testacular (npm install -g testacular)
set BASE_DIR=%~dp0
testacular start "%BASE_DIR%\..\config\testacular-e2e.conf.js" %*

9
script-angular/e2e-test.sh Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/bash
BASE_DIR=`dirname $0`
echo ""
echo "Starting Testacular Server (http://vojtajina.github.com/testacular)"
echo "-------------------------------------------------------------------"
testacular start $BASE_DIR/../config/testacular-e2e.conf.js $*

View File

@@ -0,0 +1,19 @@
@echo off
REM Windows script for starting JSTD server
REM
REM Requirements:
REM - Java (http://www.java.com)
set BASE_DIR=%~dp0
set PORT=9876
echo Starting JsTestDriver Server (http://code.google.com/p/js-test-driver/)
echo Please open the following url and capture one or more browsers:
echo http://localhost:%PORT%/
java -jar "%BASE_DIR%\..\test\lib\jstestdriver\JsTestDriver.jar" ^
--port %PORT% ^
--browserTimeout 20000 ^
--config "%BASE_DIR%\..\config\jsTestDriver.conf" ^
--basePath "%BASE_DIR%\.."

14
script-angular/test-server.sh Executable file
View File

@@ -0,0 +1,14 @@
#!/bin/bash
BASE_DIR=`dirname $0`
PORT=9876
echo "Starting JsTestDriver Server (http://code.google.com/p/js-test-driver/)"
echo "Please open the following url and capture one or more browsers:"
echo "http://localhost:$PORT"
java -jar "$BASE_DIR/../test/lib/jstestdriver/JsTestDriver.jar" \
--port $PORT \
--browserTimeout 20000 \
--config "$BASE_DIR/../config/jsTestDriver.conf" \
--basePath "$BASE_DIR/.."

11
script-angular/test.bat Normal file
View File

@@ -0,0 +1,11 @@
@echo off
REM Windows script for running unit tests
REM You have to run server and capture some browser first
REM
REM Requirements:
REM - NodeJS (http://nodejs.org/)
REM - Testacular (npm install -g testacular)
set BASE_DIR=%~dp0
testacular start "%BASE_DIR%\..\config\testacular.conf.js" %*

9
script-angular/test.sh Executable file
View File

@@ -0,0 +1,9 @@
#!/bin/bash
BASE_DIR=`dirname $0`
echo ""
echo "Starting Testacular Server (http://vojtajina.github.com/testacular)"
echo "-------------------------------------------------------------------"
testacular start $BASE_DIR/../config-angular/testacular.conf.js $*

13
script-angular/update-repo.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/bin/bash
###
# This scripts updates the local repo with the latest changes from github.
#
# The master branch will be REPLACED with what's in github and all local changes
# will be LOST.
###
git checkout master
git fetch -f origin
git fetch --tags origin
git reset --hard origin/master

19
script-angular/watchr.rb Executable file
View File

@@ -0,0 +1,19 @@
#!/usr/bin/env watchr
# config file for watchr http://github.com/mynyml/watchr
# install: gem install watchr
# run: watch watchr.rb
# note: make sure that you have jstd server running (server.sh) and a browser captured
log_file = File.expand_path(File.dirname(__FILE__) + '/../logs/jstd.log')
`cd ..`
`touch #{log_file}`
puts "String watchr... log file: #{log_file}"
watch( '(app/js|test/unit)' ) do
`echo "\n\ntest run started @ \`date\`" > #{log_file}`
`scripts/test.sh &> #{log_file}`
end

244
script-angular/web-server.js Executable file
View File

@@ -0,0 +1,244 @@
#!/usr/bin/env node
var util = require('util'),
http = require('http'),
fs = require('fs'),
url = require('url'),
events = require('events');
var DEFAULT_PORT = 8000;
function main(argv) {
new HttpServer({
'GET': createServlet(StaticServlet),
'HEAD': createServlet(StaticServlet)
}).start(Number(argv[2]) || DEFAULT_PORT);
}
function escapeHtml(value) {
return value.toString().
replace('<', '&lt;').
replace('>', '&gt;').
replace('"', '&quot;');
}
function createServlet(Class) {
var servlet = new Class();
return servlet.handleRequest.bind(servlet);
}
/**
* An Http server implementation that uses a map of methods to decide
* action routing.
*
* @param {Object} Map of method => Handler function
*/
function HttpServer(handlers) {
this.handlers = handlers;
this.server = http.createServer(this.handleRequest_.bind(this));
}
HttpServer.prototype.start = function(port) {
this.port = port;
this.server.listen(port);
util.puts('Http Server running at http://localhost:' + port + '/');
};
HttpServer.prototype.parseUrl_ = function(urlString) {
var parsed = url.parse(urlString);
parsed.pathname = url.resolve('/', parsed.pathname);
return url.parse(url.format(parsed), true);
};
HttpServer.prototype.handleRequest_ = function(req, res) {
var logEntry = req.method + ' ' + req.url;
if (req.headers['user-agent']) {
logEntry += ' ' + req.headers['user-agent'];
}
util.puts(logEntry);
req.url = this.parseUrl_(req.url);
var handler = this.handlers[req.method];
if (!handler) {
res.writeHead(501);
res.end();
} else {
handler.call(this, req, res);
}
};
/**
* Handles static content.
*/
function StaticServlet() {}
StaticServlet.MimeMap = {
'txt': 'text/plain',
'html': 'text/html',
'css': 'text/css',
'xml': 'application/xml',
'json': 'application/json',
'js': 'application/javascript',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'png': 'image/png',
  'svg': 'image/svg+xml'
};
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
StaticServlet.prototype.sendError_ = function(req, res, error) {
res.writeHead(500, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>Internal Server Error</title>\n');
res.write('<h1>Internal Server Error</h1>');
res.write('<pre>' + escapeHtml(util.inspect(error)) + '</pre>');
util.puts('500 Internal Server Error');
util.puts(util.inspect(error));
};
StaticServlet.prototype.sendMissing_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>404 Not Found</title>\n');
res.write('<h1>Not Found</h1>');
res.write(
'<p>The requested URL ' +
escapeHtml(path) +
' was not found on this server.</p>'
);
res.end();
util.puts('404 Not Found: ' + path);
};
StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(403, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>403 Forbidden</title>\n');
res.write('<h1>Forbidden</h1>');
res.write(
'<p>You do not have permission to access ' +
escapeHtml(path) + ' on this server.</p>'
);
res.end();
util.puts('403 Forbidden: ' + path);
};
StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
res.writeHead(301, {
'Content-Type': 'text/html',
'Location': redirectUrl
});
res.write('<!doctype html>\n');
res.write('<title>301 Moved Permanently</title>\n');
res.write('<h1>Moved Permanently</h1>');
res.write(
'<p>The document has moved <a href="' +
redirectUrl +
'">here</a>.</p>'
);
res.end();
util.puts('301 Moved Permanently: ' + redirectUrl);
};
StaticServlet.prototype.sendFile_ = function(req, res, path) {
var self = this;
var file = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': StaticServlet.
MimeMap[path.split('.').pop()] || 'text/plain'
});
if (req.method === 'HEAD') {
res.end();
} else {
file.on('data', res.write.bind(res));
file.on('close', function() {
res.end();
});
file.on('error', function(error) {
self.sendError_(req, res, error);
});
}
};
StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
var self = this;
if (path.match(/[^\/]$/)) {
req.url.pathname += '/';
var redirectUrl = url.format(url.parse(url.format(req.url)));
return self.sendRedirect_(req, res, redirectUrl);
}
fs.readdir(path, function(err, files) {
if (err)
return self.sendError_(req, res, error);
if (!files.length)
return self.writeDirectoryIndex_(req, res, path, []);
var remaining = files.length;
files.forEach(function(fileName, index) {
fs.stat(path + '/' + fileName, function(err, stat) {
if (err)
return self.sendError_(req, res, err);
if (stat.isDirectory()) {
files[index] = fileName + '/';
}
if (!(--remaining))
return self.writeDirectoryIndex_(req, res, path, files);
});
});
});
};
StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
path = path.substring(1);
res.writeHead(200, {
'Content-Type': 'text/html'
});
if (req.method === 'HEAD') {
res.end();
return;
}
res.write('<!doctype html>\n');
res.write('<title>' + escapeHtml(path) + '</title>\n');
res.write('<style>\n');
res.write(' ol { list-style-type: none; font-size: 1.2em; }\n');
res.write('</style>\n');
res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>');
res.write('<ol>');
files.forEach(function(fileName) {
if (fileName.charAt(0) !== '.') {
res.write('<li><a href="' +
escapeHtml(fileName) + '">' +
escapeHtml(fileName) + '</a></li>');
}
});
res.write('</ol>');
res.end();
};
// Must be last,
main(process.argv);

View File

@@ -19,65 +19,4 @@ describe EnterprisesController do
assigns(:suppliers).should == [s]
end
it "selects distributors" do
d = create(:distributor_enterprise)
spree_get :select_distributor, :id => d.id
response.should be_redirect
order = current_order(false)
order.distributor.should == d
end
it "deselects distributors" do
d = create(:distributor_enterprise)
order = current_order(true)
order.distributor = d
order.save!
spree_get :deselect_distributor
response.should be_redirect
order.reload
order.distributor.should be_nil
end
context "when a product has been added to the cart" do
it "does not allow selecting another distributor" do
# Given some distributors and an order with a product
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p = create(:product, :distributors => [d1])
o = current_order(true)
o.distributor = d1
o.save!
o.add_variant(p.master, 1)
# When I attempt to select a distributor
spree_get :select_distributor, :id => d2.id
# Then my distributor should remain unchanged
o.reload
o.distributor.should == d1
end
it "does not allow deselecting distributors" do
# Given a distributor and an order with a product
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
o = current_order(true)
o.distributor = d
o.save!
o.add_variant(p.master, 1)
# When I attempt to deselect the distributor
spree_get :deselect_distributor
# Then my distributor should remain unchanged
o.reload
o.distributor.should == d
end
end
end

View File

@@ -7,7 +7,32 @@ describe Spree::OrdersController do
def current_user
controller.current_user
end
it "selects distributors" do
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
spree_get :select_distributor, :id => d.id
response.should be_redirect
order = current_order(false)
order.distributor.should == d
end
it "deselects distributors" do
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
order = current_order(true)
order.distributor = d
order.save!
spree_get :deselect_distributor
response.should be_redirect
order.reload
order.distributor.should be_nil
end
context "adding the first product to the cart" do
it "does not add the product if the user does not specify a distributor" do

View File

@@ -5,22 +5,20 @@ FactoryGirl.define do
factory :order_cycle, :parent => :simple_order_cycle do
after(:create) do |oc|
# Suppliers
create(:exchange, :order_cycle => oc, :receiver => oc.coordinator)
create(:exchange, :order_cycle => oc, :receiver => oc.coordinator)
ex1 = create(:exchange, :order_cycle => oc, :receiver => oc.coordinator)
ex2 = create(:exchange, :order_cycle => oc, :receiver => oc.coordinator)
# Distributors
create(:exchange, :order_cycle => oc, :sender => oc.coordinator)
create(:exchange, :order_cycle => oc, :sender => oc.coordinator)
create(:exchange, :order_cycle => oc, :sender => oc.coordinator, :pickup_time => 'time 0', :pickup_instructions => 'instructions 0')
create(:exchange, :order_cycle => oc, :sender => oc.coordinator, :pickup_time => 'time 1', :pickup_instructions => 'instructions 1')
# Products with images
ex = oc.exchanges.first
2.times do
product = create(:product)
[ex1, ex2].each do |exchange|
product = create(:product, supplier: exchange.sender)
image = File.open(File.expand_path('../../app/assets/images/logo.jpg', __FILE__))
Spree::Image.create({:viewable_id => product.master.id, :viewable_type => 'Spree::Variant', :alt => "position 1", :attachment => image, :position => 1})
ex.variants << product.master
exchange.variants << product.master
end
end
end
@@ -31,7 +29,7 @@ FactoryGirl.define do
orders_open_at { Time.zone.now - 1.day }
orders_close_at { Time.zone.now + 1.week }
coordinator { Enterprise.first || FactoryGirl.create(:enterprise) }
coordinator { Enterprise.is_distributor.first || FactoryGirl.create(:distributor_enterprise) }
end
factory :exchange, :class => Exchange do

View File

@@ -28,7 +28,7 @@ feature %q{
login_to_consumer_section
visit cms_admin_path
page.should_not have_content "ComfortableMexicanSofa"
page.should have_content "Open Food Web"
page.should have_content "Home"
end
end

View File

@@ -84,7 +84,7 @@ feature %q{
# And I click delete
click_link 'Delete'
page.driver.wait_until(page.driver.browser.switch_to.alert.accept)
page.driver.browser.switch_to.alert.accept
# Then my enterprise fee should have been deleted
visit admin_enterprise_fees_path

View File

@@ -0,0 +1,241 @@
require 'spec_helper'
feature %q{
As an administrator
I want to manage order cycles
}, js: true do
include AuthenticationWorkflow
include WebHelper
scenario "listing order cycles" do
# Given an order cycle
oc = create(:order_cycle)
# When I go to the admin order cycles page
login_to_admin_section
click_link 'Order Cycles'
# Then I should see the basic fields
page.should have_selector 'a', text: oc.name
page.should have_selector "input[value='#{oc.orders_open_at}']"
page.should have_selector "input[value='#{oc.orders_close_at}']"
page.should have_content oc.coordinator.name
# And I should see the suppliers and distributors
oc.suppliers.each { |s| page.should have_content s.name }
oc.distributors.each { |d| page.should have_content d.name }
# And I should see a thumbnail image for each product
all('td.products img').count.should == 2
end
scenario "creating an order cycle" do
# Given coordinating, supplying and distributing enterprises with some products with variants
create(:distributor_enterprise, name: 'My coordinator')
supplier = create(:supplier_enterprise, name: 'My supplier')
product = create(:product, supplier: supplier)
create(:variant, product: product)
create(:variant, product: product)
distributor = create(:distributor_enterprise, name: 'My distributor')
# When I go to the new order cycle page
login_to_admin_section
click_link 'Order Cycles'
click_link 'New Order Cycle'
# And I fill in the basic fields
fill_in 'order_cycle_name', with: 'Plums & Avos'
fill_in 'order_cycle_orders_open_at', with: '2012-11-06 06:00:00'
fill_in 'order_cycle_orders_close_at', with: '2012-11-13 17:00:00'
select 'My coordinator', from: 'order_cycle_coordinator_id'
# And I add a supplier and some products
select 'My supplier', from: 'new_supplier_id'
click_button 'Add supplier'
page.find('table.exchanges tr.supplier td.products input').click
check 'order_cycle_incoming_exchange_0_variants_2'
check 'order_cycle_incoming_exchange_0_variants_3'
# And I add a distributor with the same products
select 'My distributor', from: 'new_distributor_id'
click_button 'Add distributor'
fill_in 'order_cycle_outgoing_exchange_0_pickup_time', with: 'pickup time'
fill_in 'order_cycle_outgoing_exchange_0_pickup_instructions', with: 'pickup instructions'
page.find('table.exchanges tr.distributor td.products input').click
check 'order_cycle_outgoing_exchange_0_variants_2'
check 'order_cycle_outgoing_exchange_0_variants_3'
# And I click Create
click_button 'Create'
# Then my order cycle should have been created
page.should have_content 'Your order cycle has been created.'
page.should have_selector 'a', text: 'Plums & Avos'
page.should have_selector "input[value='2012-11-06 06:00:00 UTC']"
page.should have_selector "input[value='2012-11-13 17:00:00 UTC']"
page.should have_content 'My coordinator'
page.should have_selector 'td.suppliers', text: 'My supplier'
page.should have_selector 'td.distributors', text: 'My distributor'
# And it should have some variants selected
OrderCycle.last.exchanges.first.variants.count.should == 2
OrderCycle.last.exchanges.last.variants.count.should == 2
# And my pickup time and instructions should have been saved
oc = OrderCycle.last
exchange = oc.exchanges.where(:sender_id => oc.coordinator_id).first
exchange.pickup_time.should == 'pickup time'
exchange.pickup_instructions.should == 'pickup instructions'
end
scenario "editing an order cycle" do
# Given an order cycle with all the settings
oc = create(:order_cycle)
# When I edit it
login_to_admin_section
click_link 'Order Cycles'
click_link oc.name
wait_until { page.find('#order_cycle_name').value.present? }
# Then I should see the basic settings
page.find('#order_cycle_name').value.should == oc.name
page.find('#order_cycle_orders_open_at').value.should == oc.orders_open_at.to_s
page.find('#order_cycle_orders_close_at').value.should == oc.orders_close_at.to_s
page.find('#order_cycle_coordinator_id').value.to_i.should == oc.coordinator_id
# And I should see the suppliers with products
page.should have_selector 'td.supplier_name', :text => oc.suppliers.first.name
page.should have_selector 'td.supplier_name', :text => oc.suppliers.last.name
page.all('table.exchanges tbody tr.supplier').each do |row|
row.find('td.products input').click
products_row = page.all('table.exchanges tr.products').select { |r| r.visible? }.first
products_row.should have_selector "input[type='checkbox'][checked='checked']"
row.find('td.products input').click
end
# And I should see the distributors with products
page.should have_selector 'td.distributor_name', :text => oc.distributors.first.name
page.should have_selector 'td.distributor_name', :text => oc.distributors.last.name
page.find('#order_cycle_outgoing_exchange_0_pickup_time').value.should == 'time 0'
page.find('#order_cycle_outgoing_exchange_0_pickup_instructions').value.should == 'instructions 0'
page.find('#order_cycle_outgoing_exchange_1_pickup_time').value.should == 'time 1'
page.find('#order_cycle_outgoing_exchange_1_pickup_instructions').value.should == 'instructions 1'
page.all('table.exchanges tbody tr.distributor').each do |row|
row.find('td.products input').click
products_row = page.all('table.exchanges tr.products').select { |r| r.visible? }.first
products_row.should have_selector "input[type='checkbox'][checked='checked']"
row.find('td.products input').click
end
end
scenario "updating an order cycle" do
# Given an order cycle with all the settings
oc = create(:order_cycle)
# And a coordinating, supplying and distributing enterprise with some products with variants
create(:distributor_enterprise, name: 'My coordinator')
supplier = create(:supplier_enterprise, name: 'My supplier')
distributor = create(:distributor_enterprise, name: 'My distributor')
product = create(:product, supplier: supplier)
v1 = create(:variant, product: product)
v2 = create(:variant, product: product)
# When I go to its edit page
login_to_admin_section
click_link 'Order Cycles'
click_link oc.name
wait_until { page.find('#order_cycle_name').value.present? }
# And I update it
fill_in 'order_cycle_name', with: 'Plums & Avos'
fill_in 'order_cycle_orders_open_at', with: '2012-11-06 06:00:00'
fill_in 'order_cycle_orders_close_at', with: '2012-11-13 17:00:00'
select 'My coordinator', from: 'order_cycle_coordinator_id'
# And I add a supplier and some products
select 'My supplier', from: 'new_supplier_id'
click_button 'Add supplier'
page.all("table.exchanges tr.supplier td.products input").each { |e| e.click }
uncheck "order_cycle_incoming_exchange_1_variants_2"
check "order_cycle_incoming_exchange_2_variants_#{v1.id}"
check "order_cycle_incoming_exchange_2_variants_#{v2.id}"
# And I add a distributor and some products
select 'My distributor', from: 'new_distributor_id'
click_button 'Add distributor'
fill_in 'order_cycle_outgoing_exchange_0_pickup_time', with: 'New time 0'
fill_in 'order_cycle_outgoing_exchange_0_pickup_instructions', with: 'New instructions 0'
fill_in 'order_cycle_outgoing_exchange_1_pickup_time', with: 'New time 1'
fill_in 'order_cycle_outgoing_exchange_1_pickup_instructions', with: 'New instructions 1'
page.all("table.exchanges tr.distributor td.products input").each { |e| e.click }
uncheck "order_cycle_outgoing_exchange_2_variants_#{v1.id}"
check "order_cycle_outgoing_exchange_2_variants_#{v2.id}"
# And I click Update
click_button 'Update'
# Then my order cycle should have been updated
page.should have_content 'Your order cycle has been updated.'
page.should have_selector 'a', text: 'Plums & Avos'
page.should have_selector "input[value='2012-11-06 06:00:00 UTC']"
page.should have_selector "input[value='2012-11-13 17:00:00 UTC']"
page.should have_content 'My coordinator'
page.should have_selector 'td.suppliers', text: 'My supplier'
page.should have_selector 'td.distributors', text: 'My distributor'
# And it should have some variants selected
OrderCycle.last.variants.map { |v| v.id }.sort.should == [1, v1.id, v2.id].sort
# And the collection details should have been updated
OrderCycle.last.exchanges.where(pickup_time: 'New time 0', pickup_instructions: 'New instructions 0').should be_present
OrderCycle.last.exchanges.where(pickup_time: 'New time 1', pickup_instructions: 'New instructions 1').should be_present
end
scenario "updating many order cycle opening/closing times at once" do
# Given three order cycles
3.times { create(:order_cycle) }
# When I go to the order cycles page
login_to_admin_section
click_link 'Order Cycles'
# And I fill in some new opening/closing times and save them
fill_in 'order_cycle_set_collection_attributes_0_orders_open_at', :with => '2012-12-01 12:00:00'
fill_in 'order_cycle_set_collection_attributes_0_orders_close_at', :with => '2012-12-01 12:00:01'
fill_in 'order_cycle_set_collection_attributes_1_orders_open_at', :with => '2012-12-01 12:00:02'
fill_in 'order_cycle_set_collection_attributes_1_orders_close_at', :with => '2012-12-01 12:00:03'
fill_in 'order_cycle_set_collection_attributes_2_orders_open_at', :with => '2012-12-01 12:00:04'
fill_in 'order_cycle_set_collection_attributes_2_orders_close_at', :with => '2012-12-01 12:00:05'
click_button 'Update'
# Then my times should have been saved
flash_message.should == 'Order cycles have been updated.'
OrderCycle.all.map { |oc| oc.orders_open_at.sec }.should == [0, 2, 4]
OrderCycle.all.map { |oc| oc.orders_close_at.sec }.should == [1, 3, 5]
end
end

View File

@@ -17,6 +17,16 @@ feature %q{
:state => Spree::State.find_by_name('Victoria'),
:country => Spree::Country.find_by_name('Australia')),
:pickup_times => 'Tuesday, 4 PM')
@distributor_alternative = create(:distributor_enterprise, :name => 'Alternative Distributor',
:address => create(:address,
:address1 => '1600 Rathdowne St',
:city => 'Carlton North',
:zipcode => 3054,
:state => Spree::State.find_by_name('Victoria'),
:country => Spree::Country.find_by_name('Australia')),
:pickup_times => 'Tuesday, 4 PM')
@shipping_method_1 = create(:shipping_method, :name => 'Shipping Method One')
@shipping_method_1.calculator.set_preference :amount, 1
@@ -28,9 +38,11 @@ feature %q{
@product_1 = create(:product, :name => 'Fuji apples')
@product_1.product_distributions.create(:distributor => @distributor, :shipping_method => @shipping_method_1)
@product_1.product_distributions.create(:distributor => @distributor_alternative, :shipping_method => @shipping_method_1)
@product_2 = create(:product, :name => 'Garlic')
@product_2.product_distributions.create(:distributor => @distributor, :shipping_method => @shipping_method_2)
@product_2.product_distributions.create(:distributor => @distributor_alternative, :shipping_method => @shipping_method_2)
@zone = create(:zone)
c = Spree::Country.find_by_name('Australia')
@@ -110,7 +122,9 @@ feature %q{
page.should have_content value
end
end
page.should have_selector "select#order_distributor_id option[value='#{@distributor_alternative.id}']"
click_button 'Save and Continue'
# -- Checkout: Delivery

View File

@@ -67,11 +67,10 @@ feature %q{
it "displays the distributor's name on the home page" do
# Given a distributor with a product
d = create(:distributor_enterprise, :name => 'Melb Uni Co-op', :description => '<p>Hello, world!</p>')
create(:product, :distributors => [d])
p1 = create(:product, :distributors => [d])
# When I select the distributor
visit spree.root_path
click_link d.name
visit spree.select_distributor_order_path(d)
visit spree.root_path
# Then I should see the name of the distributor that I've selected
@@ -90,8 +89,7 @@ feature %q{
p2 = create(:product, :distributors => [d2], :taxons => [taxon])
# When I select the first distributor
visit spree.root_path
click_link d1.name
visit spree.select_distributor_order_path(d1)
visit spree.root_path
# Then I should see products split by local/remote distributor
@@ -112,11 +110,11 @@ feature %q{
it "allows the user to leave the distributor" do
# Given a distributor with a product
d = create(:distributor_enterprise, :name => 'Melb Uni Co-op')
create(:product, :distributors => [d])
p1 = create(:product, :distributors => [d])
# When I select the distributor and then leave it
visit spree.select_distributor_order_path(d)
visit spree.root_path
click_link d.name
click_button 'Browse All Distributors'
# Then I should have left the distributor
@@ -139,16 +137,16 @@ feature %q{
it "displays the local distributor as the default choice when available for the current product" do
# Given a distributor and a product under it
distributor = create(:distributor_enterprise)
product = create(:product, :distributors => [distributor])
distributor1 = create(:distributor_enterprise)
distributor2 = create(:distributor_enterprise)
product = create(:product, :distributors => [distributor1,distributor2])
# When we select the distributor and view the product
visit spree.root_path
click_link distributor.name
visit spree.select_distributor_order_path(distributor1)
visit spree.product_path(product)
# Then we should see our distributor as the default option when adding the item to our cart
page.should have_selector "select#distributor_id option[value='#{distributor.id}'][selected='selected']"
page.should have_selector "select#distributor_id option[value='#{distributor1.id}'][selected='selected']"
end
it "works when viewing a product from a remote distributor" do

View File

@@ -36,8 +36,7 @@ feature %q{
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
visit spree.root_path
click_link d.name
visit spree.select_distributor_order_path(d)
visit spree.product_path p
within '#product-distributor-details' do

View File

@@ -49,8 +49,8 @@ feature %q{
2.times { create(:product, :taxons => [taxon_three], :distributors => [my_distributor]) }
# When I visit the home page and select my distributor
visit spree.root_path
click_link my_distributor.name
visit spree.select_distributor_order_path(my_distributor)
within('nav#filters') { click_link my_distributor.name }
page.should have_content 'You are shopping at My Distributor'
# Then I should see distributor-scoped product counts next to the taxons

View File

@@ -0,0 +1,394 @@
describe 'OrderCycle controllers', ->
describe 'AdminCreateOrderCycleCtrl', ->
ctrl = null
scope = null
event = null
OrderCycle = null
Enterprise = null
beforeEach ->
scope = {}
event =
preventDefault: jasmine.createSpy('preventDefault')
OrderCycle =
order_cycle: 'my order cycle'
exchangeSelectedVariants: jasmine.createSpy('exchangeSelectedVariants').andReturn('variants selected')
productSuppliedToOrderCycle: jasmine.createSpy('productSuppliedToOrderCycle').andReturn('product supplied')
variantSuppliedToOrderCycle: jasmine.createSpy('variantSuppliedToOrderCycle').andReturn('variant supplied')
toggleProducts: jasmine.createSpy('toggleProducts')
addSupplier: jasmine.createSpy('addSupplier')
addDistributor: jasmine.createSpy('addDistributor')
create: jasmine.createSpy('create')
Enterprise =
index: jasmine.createSpy('index').andReturn('enterprises list')
supplied_products: 'supplied products'
totalVariants: jasmine.createSpy('totalVariants').andReturn('variants total')
module('order_cycle')
inject ($controller) ->
ctrl = $controller 'AdminCreateOrderCycleCtrl', {$scope: scope, OrderCycle: OrderCycle, Enterprise: Enterprise}
it 'Loads enterprises and supplied products', ->
expect(Enterprise.index).toHaveBeenCalled()
expect(scope.enterprises).toEqual('enterprises list')
expect(scope.supplied_products).toEqual('supplied products')
it 'Loads order cycles', ->
expect(scope.order_cycle).toEqual('my order cycle')
it 'Delegates exchangeSelectedVariants to OrderCycle', ->
expect(scope.exchangeSelectedVariants('exchange')).toEqual('variants selected')
expect(OrderCycle.exchangeSelectedVariants).toHaveBeenCalledWith('exchange')
it 'Delegates enterpriseTotalVariants to Enterprise', ->
expect(scope.enterpriseTotalVariants('enterprise')).toEqual('variants total')
expect(Enterprise.totalVariants).toHaveBeenCalledWith('enterprise')
it 'Delegates productSuppliedToOrderCycle to OrderCycle', ->
expect(scope.productSuppliedToOrderCycle('product')).toEqual('product supplied')
expect(OrderCycle.productSuppliedToOrderCycle).toHaveBeenCalledWith('product')
it 'Delegates variantSuppliedToOrderCycle to OrderCycle', ->
expect(scope.variantSuppliedToOrderCycle('variant')).toEqual('variant supplied')
expect(OrderCycle.variantSuppliedToOrderCycle).toHaveBeenCalledWith('variant')
it 'Delegates toggleProducts to OrderCycle', ->
scope.toggleProducts(event, 'exchange')
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.toggleProducts).toHaveBeenCalledWith('exchange')
it 'Adds order cycle suppliers', ->
scope.new_supplier_id = 'new supplier id'
scope.addSupplier(event)
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.addSupplier).toHaveBeenCalledWith('new supplier id')
it 'Adds order cycle distributors', ->
scope.new_distributor_id = 'new distributor id'
scope.addDistributor(event)
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.addDistributor).toHaveBeenCalledWith('new distributor id')
it 'Submits the order cycle via OrderCycle create', ->
scope.submit()
expect(OrderCycle.create).toHaveBeenCalled()
describe 'AdminEditOrderCycleCtrl', ->
ctrl = null
scope = null
event = null
location = null
OrderCycle = null
Enterprise = null
beforeEach ->
scope = {}
event =
preventDefault: jasmine.createSpy('preventDefault')
location =
absUrl: ->
'example.com/admin/order_cycles/27/edit'
OrderCycle =
load: jasmine.createSpy('load')
exchangeSelectedVariants: jasmine.createSpy('exchangeSelectedVariants').andReturn('variants selected')
productSuppliedToOrderCycle: jasmine.createSpy('productSuppliedToOrderCycle').andReturn('product supplied')
variantSuppliedToOrderCycle: jasmine.createSpy('variantSuppliedToOrderCycle').andReturn('variant supplied')
toggleProducts: jasmine.createSpy('toggleProducts')
addSupplier: jasmine.createSpy('addSupplier')
addDistributor: jasmine.createSpy('addDistributor')
update: jasmine.createSpy('update')
Enterprise =
index: jasmine.createSpy('index').andReturn('enterprises list')
supplied_products: 'supplied products'
totalVariants: jasmine.createSpy('totalVariants').andReturn('variants total')
module('order_cycle')
inject ($controller) ->
ctrl = $controller 'AdminEditOrderCycleCtrl', {$scope: scope, $location: location, OrderCycle: OrderCycle, Enterprise: Enterprise}
it 'Loads enterprises and supplied products', ->
expect(Enterprise.index).toHaveBeenCalled()
expect(scope.enterprises).toEqual('enterprises list')
expect(scope.supplied_products).toEqual('supplied products')
it 'Loads order cycles', ->
expect(OrderCycle.load).toHaveBeenCalledWith('27')
it 'Delegates exchangeSelectedVariants to OrderCycle', ->
expect(scope.exchangeSelectedVariants('exchange')).toEqual('variants selected')
expect(OrderCycle.exchangeSelectedVariants).toHaveBeenCalledWith('exchange')
it 'Delegates totalVariants to Enterprise', ->
expect(scope.enterpriseTotalVariants('enterprise')).toEqual('variants total')
expect(Enterprise.totalVariants).toHaveBeenCalledWith('enterprise')
it 'Delegates productSuppliedToOrderCycle to OrderCycle', ->
expect(scope.productSuppliedToOrderCycle('product')).toEqual('product supplied')
expect(OrderCycle.productSuppliedToOrderCycle).toHaveBeenCalledWith('product')
it 'Delegates variantSuppliedToOrderCycle to OrderCycle', ->
expect(scope.variantSuppliedToOrderCycle('variant')).toEqual('variant supplied')
expect(OrderCycle.variantSuppliedToOrderCycle).toHaveBeenCalledWith('variant')
it 'Delegates toggleProducts to OrderCycle', ->
scope.toggleProducts(event, 'exchange')
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.toggleProducts).toHaveBeenCalledWith('exchange')
it 'Adds order cycle suppliers', ->
scope.new_supplier_id = 'new supplier id'
scope.addSupplier(event)
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.addSupplier).toHaveBeenCalledWith('new supplier id')
it 'Adds order cycle distributors', ->
scope.new_distributor_id = 'new distributor id'
scope.addDistributor(event)
expect(event.preventDefault).toHaveBeenCalled()
expect(OrderCycle.addDistributor).toHaveBeenCalledWith('new distributor id')
it 'Submits the order cycle via OrderCycle update', ->
scope.submit()
expect(OrderCycle.update).toHaveBeenCalled()
describe 'OrderCycle services', ->
describe 'Enterprise service', ->
$httpBackend = null
Enterprise = null
beforeEach ->
module 'order_cycle'
inject ($injector, _$httpBackend_)->
Enterprise = $injector.get('Enterprise')
$httpBackend = _$httpBackend_
$httpBackend.whenGET('/admin/enterprises.json').respond [
{id: 1, name: 'One', supplied_products: [1, 2]}
{id: 2, name: 'Two', supplied_products: [3, 4]}
{id: 3, name: 'Three', supplied_products: [5, 6]}
]
it 'loads enterprises as a hash', ->
enterprises = Enterprise.index()
$httpBackend.flush()
expect(enterprises).toEqual
1: new Enterprise.Enterprise({id: 1, name: 'One', supplied_products: [1, 2]})
2: new Enterprise.Enterprise({id: 2, name: 'Two', supplied_products: [3, 4]})
3: new Enterprise.Enterprise({id: 3, name: 'Three', supplied_products: [5, 6]})
it 'collates all supplied products', ->
enterprises = Enterprise.index()
$httpBackend.flush()
expect(Enterprise.supplied_products).toEqual [1, 2, 3, 4, 5, 6]
it 'counts total variants supplied by an enterprise', ->
enterprise =
supplied_products: [
{variants: []},
{variants: []},
{variants: [{}, {}, {}]}
]
expect(Enterprise.totalVariants(enterprise)).toEqual(5)
describe 'OrderCycle service', ->
OrderCycle = null
$httpBackend = null
$window = null
beforeEach ->
$window = {navigator: {userAgent: 'foo'}}
module 'order_cycle', ($provide)->
$provide.value('$window', $window)
null
inject ($injector, _$httpBackend_)->
OrderCycle = $injector.get('OrderCycle')
$httpBackend = _$httpBackend_
$httpBackend.whenGET('/admin/order_cycles/123.json').respond
id: 123
name: 'Test Order Cycle'
coordinator_id: 456
exchanges: [
{sender_id: 1, receiver_id: 456}
{sender_id: 456, receiver_id: 2}
]
it 'initialises order cycle', ->
expect(OrderCycle.order_cycle).toEqual
incoming_exchanges: []
outgoing_exchanges: []
it 'counts selected variants in an exchange', ->
result = OrderCycle.exchangeSelectedVariants({variants: {1: true, 2: false, 3: true}})
expect(result).toEqual(2)
describe 'toggling products', ->
exchange = null
beforeEach ->
exchange = {}
it 'sets a blank value to true', ->
OrderCycle.toggleProducts(exchange)
expect(exchange.showProducts).toEqual(true)
it 'sets a true value to false', ->
exchange.showProducts = true
OrderCycle.toggleProducts(exchange)
expect(exchange.showProducts).toEqual(false)
it 'sets a false value to true', ->
exchange.showProducts = false
OrderCycle.toggleProducts(exchange)
expect(exchange.showProducts).toEqual(true)
describe 'adding suppliers', ->
exchange = null
it 'adds the supplier to incoming exchanges', ->
OrderCycle.addSupplier('123')
expect(OrderCycle.order_cycle.incoming_exchanges).toEqual [
{enterprise_id: '123', active: true, variants: {}}
]
describe 'adding distributors', ->
exchange = null
it 'adds the distributor to outgoing exchanges', ->
OrderCycle.addDistributor('123')
expect(OrderCycle.order_cycle.outgoing_exchanges).toEqual [
{enterprise_id: '123', active: true, variants: {}}
]
describe 'fetching all variants supplied on incoming exchanges', ->
it 'collects variants from incoming exchanges', ->
OrderCycle.order_cycle.incoming_exchanges = [
{variants: {1: true, 2: false}}
{variants: {3: false, 4: true}}
{variants: {5: true, 6: false}}
]
expect(OrderCycle.incomingExchangesVariants()).toEqual [1, 4, 5]
describe 'checking whether a product is supplied to the order cycle', ->
product_master_present = product_variant_present = product_master_absent = product_variant_absent = null
beforeEach ->
product_master_present =
name: "Linseed (500g)"
master_id: 1
variants: []
product_variant_present =
name: "Linseed (500g)"
master_id: 2
variants: [{id: 3}, {id: 4}]
product_master_absent =
name: "Linseed (500g)"
master_id: 5
variants: []
product_variant_absent =
name: "Linseed (500g)"
master_id: 6
variants: [{id: 7}, {id: 8}]
spyOn(OrderCycle, 'incomingExchangesVariants').andReturn([1, 3])
it 'returns true for products whose master is supplied', ->
expect(OrderCycle.productSuppliedToOrderCycle(product_master_present)).toBeTruthy()
it 'returns true for products for whom a variant is supplied', ->
expect(OrderCycle.productSuppliedToOrderCycle(product_variant_present)).toBeTruthy()
it 'returns false for products whose master is not supplied', ->
expect(OrderCycle.productSuppliedToOrderCycle(product_master_absent)).toBeFalsy()
it 'returns false for products whose variants are not supplied', ->
expect(OrderCycle.productSuppliedToOrderCycle(product_variant_absent)).toBeFalsy()
describe 'checking whether a variant is supplied to the order cycle', ->
beforeEach ->
spyOn(OrderCycle, 'incomingExchangesVariants').andReturn([1, 3])
it 'returns true for variants that are supplied', ->
expect(OrderCycle.variantSuppliedToOrderCycle({id: 1})).toBeTruthy()
it 'returns false for variants that are not supplied', ->
expect(OrderCycle.variantSuppliedToOrderCycle({id: 999})).toBeFalsy()
describe 'loading an order cycle', ->
beforeEach ->
OrderCycle.load('123')
$httpBackend.flush()
it 'loads basic fields', ->
expect(OrderCycle.order_cycle.id).toEqual(123)
expect(OrderCycle.order_cycle.name).toEqual('Test Order Cycle')
expect(OrderCycle.order_cycle.coordinator_id).toEqual(456)
it 'splits exchanges into incoming and outgoing', ->
expect(OrderCycle.order_cycle.incoming_exchanges).toEqual [
sender_id: 1
enterprise_id: 1
active: true
]
expect(OrderCycle.order_cycle.outgoing_exchanges).toEqual [
receiver_id: 2
enterprise_id: 2
active: true
]
it 'removes original exchanges array', ->
expect(OrderCycle.order_cycle.exchanges).toEqual(undefined)
describe 'creating an order cycle', ->
it 'redirects to the order cycles page on success', ->
OrderCycle.order_cycle = 'this is the order cycle'
spyOn(OrderCycle, 'removeInactiveExchanges')
$httpBackend.expectPOST('/admin/order_cycles.json', {
order_cycle: 'this is the order cycle'
}).respond {success: true}
OrderCycle.create()
$httpBackend.flush()
expect(OrderCycle.removeInactiveExchanges).toHaveBeenCalled()
expect($window.location).toEqual('/admin/order_cycles')
it 'does not redirect on error', ->
OrderCycle.order_cycle = 'this is the order cycle'
spyOn(OrderCycle, 'removeInactiveExchanges')
$httpBackend.expectPOST('/admin/order_cycles.json', {
order_cycle: 'this is the order cycle'
}).respond {success: false}
OrderCycle.create()
$httpBackend.flush()
expect(OrderCycle.removeInactiveExchanges).toHaveBeenCalled()
expect($window.location).toEqual(undefined)
it 'removes inactive exchanges', ->
OrderCycle.order_cycle =
incoming_exchanges: [
{enterprise_id: "1", active: false}
{enterprise_id: "2", active: true}
{enterprise_id: "3", active: false}
]
outgoing_exchanges: [
{enterprise_id: "4", active: true}
{enterprise_id: "5", active: false}
{enterprise_id: "6", active: true}
]
OrderCycle.removeInactiveExchanges()
expect(OrderCycle.order_cycle.incoming_exchanges).toEqual [
{enterprise_id: "2", active: true}
]
expect(OrderCycle.order_cycle.outgoing_exchanges).toEqual [
{enterprise_id: "4", active: true}
{enterprise_id: "6", active: true}
]

View File

@@ -0,0 +1,80 @@
require 'open_food_web/distributor_change_validator'
describe DistributorChangeValidator do
let(:order) { double(:order) }
let(:subject) { DistributorChangeValidator.new(order) }
context "permissions for changing distributor" do
it "allows distributor to be changed if line_items is empty" do
order.stub(:line_items) { [] }
subject.can_change_distributor?.should be_true
end
it "does not allow distributor to be changed if line_items is not empty" do
order.stub(:line_items) { [1, 2, 3] }
subject.can_change_distributor?.should be_false
end
end
context "finding distributors which have the same variants" do
it "matches enterprises which offer all products within the order" do
variant1 = double(:variant)
variant2 = double(:variant)
variant3 = double(:variant)
variant5 = double(:variant)
line_item_variants = [variant1, variant3, variant5]
order.stub(:line_item_variants){ line_item_variants }
enterprise = double(:enterprise)
enterprise.stub(:available_variants){ line_item_variants } # Exactly the same variants as the order
subject.available_distributors([enterprise]).should == [enterprise]
end
it "does not match enterprises with no products available" do
variant1 = double(:variant)
variant3 = double(:variant)
variant5 = double(:variant)
line_item_variants = [variant1, variant3, variant5]
order.stub(:line_item_variants){ line_item_variants }
enterprise = double(:enterprise)
enterprise.stub(:available_variants){ [] } # No variants
subject.available_distributors([enterprise]).should_not include enterprise
end
it "does not match enterprises with only some of the same variants in the order available" do
variant1 = double(:variant)
variant2 = double(:variant)
variant3 = double(:variant)
variant4 = double(:variant)
variant5 = double(:variant)
line_item_variants = [variant1, variant3, variant5]
order.stub(:line_item_variants){ line_item_variants }
enterprise_with_some_variants = double(:enterprise)
enterprise_with_some_variants.stub(:available_variants){ [variant1, variant3] } # Only some variants
enterprise_with_some_plus_extras = double(:enterprise)
enterprise_with_some_plus_extras.stub(:available_variants){ [variant1, variant2, variant3, variant4] } # Only some variants, plus extras
subject.available_distributors([enterprise_with_some_variants]).should_not include enterprise_with_some_variants
subject.available_distributors([enterprise_with_some_plus_extras]).should_not include enterprise_with_some_plus_extras
end
it "matches enteprises which offer all products in the order, plus additional products" do
variant1 = double(:variant)
variant2 = double(:variant)
variant3 = double(:variant)
variant4 = double(:variant)
variant5 = double(:variant)
line_item_variants = [variant1, variant3, variant5]
order.stub(:line_item_variants){ line_item_variants }
enterprise = double(:enterprise)
enterprise.stub(:available_variants){ [variant1, variant2, variant3, variant4, variant5] } # Excess variants
subject.available_distributors([enterprise]).should == [enterprise]
end
it "matches no enterprises when none are provided" do
subject.available_distributors([]).should == []
end
end
end

View File

@@ -1,56 +0,0 @@
require 'open_food_web/order_cycle_form_applicator'
module OpenFoodWeb
describe OrderCycleFormApplicator do
it "creates new exchanges for incoming_exchanges" do
coordinator_id = 123
supplier_id = 456
oc = double(:order_cycle, :coordinator_id => coordinator_id, :exchanges => [], :incoming_exchanges => [{:enterprise_id => supplier_id}])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_exists?).and_return(false)
applicator.should_receive(:add_exchange).with(supplier_id, coordinator_id)
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "updates existing exchanges for incoming_exchanges" do
coordinator_id = 123
supplier_id = 456
oc = double(:order_cycle,
:coordinator_id => coordinator_id,
:exchanges => [double(:exchange, :sender_id => supplier_id, :receiver_id => coordinator_id)],
:incoming_exchanges => [{:enterprise_id => supplier_id}])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_exists?).and_return(true)
applicator.should_receive(:update_exchange).with(supplier_id, coordinator_id)
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "removes exchanges that are no longer present in incoming_exchanges" do
coordinator_id = 123
supplier_id = 456
exchange = double(:exchange, :sender_id => supplier_id, :receiver_id => coordinator_id)
oc = double(:order_cycle,
:coordinator_id => coordinator_id,
:exchanges => [exchange],
:incoming_exchanges => [])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
applicator.untouched_exchanges.should == [exchange]
end
end
end

View File

@@ -0,0 +1,168 @@
require 'open_food_web/order_cycle_form_applicator'
module OpenFoodWeb
describe OrderCycleFormApplicator do
context "unit specs" do
it "creates new exchanges for incoming_exchanges" do
coordinator_id = 123
supplier_id = 456
incoming_exchange = {:enterprise_id => supplier_id, :variants => {'1' => true, '2' => false, '3' => true}}
oc = double(:order_cycle, :coordinator_id => coordinator_id, :exchanges => [], :incoming_exchanges => [incoming_exchange], :outgoing_exchanges => [])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_variant_ids).with(incoming_exchange).and_return([1, 3])
applicator.should_receive(:exchange_exists?).with(supplier_id, coordinator_id).and_return(false)
applicator.should_receive(:add_exchange).with(supplier_id, coordinator_id, {:variant_ids => [1, 3]})
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "creates new exchanges for outgoing_exchanges" do
coordinator_id = 123
distributor_id = 456
outgoing_exchange = {:enterprise_id => distributor_id, :variants => {'1' => true, '2' => false, '3' => true}, :pickup_time => 'pickup time', :pickup_instructions => 'pickup instructions'}
oc = double(:order_cycle, :coordinator_id => coordinator_id, :exchanges => [], :incoming_exchanges => [], :outgoing_exchanges => [outgoing_exchange])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_variant_ids).with(outgoing_exchange).and_return([1, 3])
applicator.should_receive(:exchange_exists?).with(coordinator_id, distributor_id).and_return(false)
applicator.should_receive(:add_exchange).with(coordinator_id, distributor_id, {:variant_ids => [1, 3], :pickup_time => 'pickup time', :pickup_instructions => 'pickup instructions'})
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "updates existing exchanges for incoming_exchanges" do
coordinator_id = 123
supplier_id = 456
incoming_exchange = {:enterprise_id => supplier_id, :variants => {'1' => true, '2' => false, '3' => true}}
oc = double(:order_cycle,
:coordinator_id => coordinator_id,
:exchanges => [double(:exchange, :sender_id => supplier_id, :receiver_id => coordinator_id)],
:incoming_exchanges => [incoming_exchange],
:outgoing_exchanges => [])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_variant_ids).with(incoming_exchange).and_return([1, 3])
applicator.should_receive(:exchange_exists?).with(supplier_id, coordinator_id).and_return(true)
applicator.should_receive(:update_exchange).with(supplier_id, coordinator_id, {:variant_ids => [1, 3]})
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "updates existing exchanges for outgoing_exchanges" do
coordinator_id = 123
distributor_id = 456
outgoing_exchange = {:enterprise_id => distributor_id, :variants => {'1' => true, '2' => false, '3' => true}, :pickup_time => 'pickup time', :pickup_instructions => 'pickup instructions'}
oc = double(:order_cycle,
:coordinator_id => coordinator_id,
:exchanges => [double(:exchange, :sender_id => coordinator_id, :receiver_id => distributor_id)],
:incoming_exchanges => [],
:outgoing_exchanges => [outgoing_exchange])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:exchange_variant_ids).with(outgoing_exchange).and_return([1, 3])
applicator.should_receive(:exchange_exists?).with(coordinator_id, distributor_id).and_return(true)
applicator.should_receive(:update_exchange).with(coordinator_id, distributor_id, {:variant_ids => [1, 3], :pickup_time => 'pickup time', :pickup_instructions => 'pickup instructions'})
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
end
it "removes exchanges that are no longer present" do
coordinator_id = 123
supplier_id = 456
exchange = double(:exchange, :sender_id => supplier_id, :receiver_id => coordinator_id)
oc = double(:order_cycle,
:coordinator_id => coordinator_id,
:exchanges => [exchange],
:incoming_exchanges => [],
:outgoing_exchanges => [])
applicator = OrderCycleFormApplicator.new(oc)
applicator.should_receive(:destroy_untouched_exchanges)
applicator.go!
applicator.send(:untouched_exchanges).should == [exchange]
end
it "converts exchange variant ids hash to an array of ids" do
applicator = OrderCycleFormApplicator.new(nil)
applicator.send(:exchange_variant_ids, {:enterprise_id => 123, :variants => {'1' => true, '2' => false, '3' => true}}).should == [1, 3]
end
end
context "integration specs" do
before(:all) do
require 'spec_helper'
end
it "checks whether exchanges exist" do
oc = FactoryGirl.create(:simple_order_cycle)
exchange = FactoryGirl.create(:exchange, order_cycle: oc)
applicator = OrderCycleFormApplicator.new(oc)
applicator.send(:exchange_exists?, exchange.sender_id, exchange.receiver_id).should be_true
applicator.send(:exchange_exists?, exchange.receiver_id, exchange.sender_id).should be_false
applicator.send(:exchange_exists?, exchange.sender_id, 999).should be_false
applicator.send(:exchange_exists?, 999, exchange.receiver_id).should be_false
applicator.send(:exchange_exists?, 999, 888).should be_false
end
it "adds exchanges" do
oc = FactoryGirl.create(:simple_order_cycle)
applicator = OrderCycleFormApplicator.new(oc)
sender = FactoryGirl.create(:enterprise)
receiver = FactoryGirl.create(:enterprise)
variant1 = FactoryGirl.create(:variant)
variant2 = FactoryGirl.create(:variant)
applicator.send(:touched_exchanges=, [])
applicator.send(:add_exchange, sender.id, receiver.id, {:variant_ids => [variant1.id, variant2.id]})
exchange = Exchange.last
exchange.sender.should == sender
exchange.receiver.should == receiver
exchange.variants.sort.should == [variant1, variant2].sort
applicator.send(:touched_exchanges).should == [exchange]
end
it "updates exchanges" do
oc = FactoryGirl.create(:simple_order_cycle)
applicator = OrderCycleFormApplicator.new(oc)
sender = FactoryGirl.create(:enterprise)
receiver = FactoryGirl.create(:enterprise)
variant1 = FactoryGirl.create(:variant)
variant2 = FactoryGirl.create(:variant)
variant3 = FactoryGirl.create(:variant)
exchange = FactoryGirl.create(:exchange, order_cycle: oc, sender: sender, receiver: receiver, variant_ids: [variant1.id, variant2.id])
applicator.send(:touched_exchanges=, [])
applicator.send(:update_exchange, sender.id, receiver.id, {:variant_ids => [variant1.id, variant3.id]})
exchange.reload
exchange.variant_ids.should == [variant1.id, variant3.id]
applicator.send(:touched_exchanges).should == [exchange]
end
end
end
end

View File

@@ -14,58 +14,6 @@ describe Spree::Order do
subject.adjustments.where(:label => "Shipping").should be_present
end
it "reveals permission for changing distributor" do
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
subject.distributor = d
subject.save!
subject.can_change_distributor?.should be_true
subject.add_variant(p.master, 1)
subject.can_change_distributor?.should be_false
end
it "raises an exception if distributor is changed without permission" do
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
subject.distributor = d
subject.save!
subject.add_variant(p.master, 1)
subject.can_change_distributor?.should be_false
expect do
subject.distributor = nil
end.to raise_error "You cannot change the distributor of an order with products"
end
it "reveals permission for adding products to the cart" do
d1 = create(:distributor_enterprise)
d2 = create(:distributor_enterprise)
p_first = create(:product, :distributors => [d1])
p_subsequent_same_dist = create(:product, :distributors => [d1])
p_subsequent_other_dist = create(:product, :distributors => [d2])
# We need to set distributor, since order.add_variant does not, and
# we also need to save the order so that line items can be added to
# the association.
subject.distributor = d1
subject.save!
# The first product in the cart can be added
subject.can_add_product_to_cart?(p_first).should be_true
subject.add_variant(p_first.master, 1)
# A subsequent product can be added if the distributor matches
subject.can_add_product_to_cart?(p_subsequent_same_dist).should be_true
subject.add_variant(p_subsequent_same_dist.master, 1)
# And cannot be added if it does not match
subject.can_add_product_to_cart?(p_subsequent_other_dist).should be_false
end
it "sets attributes on line items for variants" do
d = create(:distributor_enterprise)
p = create(:product, :distributors => [d])
@@ -79,4 +27,38 @@ describe Spree::Order do
li = Spree::LineItem.last
li.max_quantity.should == 3
end
context "validating distributor changes" do
it "checks that a distributor is available when changing" do
order_enterprise = FactoryGirl.create(:enterprise, id: 1, :name => "Order Enterprise")
subject.distributor = order_enterprise
product1 = FactoryGirl.create(:product)
product2 = FactoryGirl.create(:product)
product3 = FactoryGirl.create(:product)
variant11 = FactoryGirl.create(:variant, product: product1)
variant12 = FactoryGirl.create(:variant, product: product1)
variant21 = FactoryGirl.create(:variant, product: product2)
variant31 = FactoryGirl.create(:variant, product: product3)
variant32 = FactoryGirl.create(:variant, product: product3)
# Product Distributions
# Order Enterprise sells product 1 and product 3
FactoryGirl.create(:product_distribution, product: product1, distributor: order_enterprise)
FactoryGirl.create(:product_distribution, product: product3, distributor: order_enterprise)
# Build the current order
line_item1 = FactoryGirl.create(:line_item, order: subject, variant: variant11)
line_item2 = FactoryGirl.create(:line_item, order: subject, variant: variant12)
line_item3 = FactoryGirl.create(:line_item, order: subject, variant: variant31)
subject.line_items = [line_item1,line_item2,line_item3]
test_enterprise = FactoryGirl.create(:enterprise, id: 2, :name => "Test Enterprise")
# Test Enterprise sells only product 1
FactoryGirl.create(:product_distribution, product: product1, distributor: test_enterprise)
subject.distributor = test_enterprise
subject.should_not be_valid
subject.errors.should include :distributor_id
end
end
end

View File

@@ -1,82 +0,0 @@
require 'spec_helper'
feature %q{
As an administrator
I want to manage order cycles
}, js: true do
include AuthenticationWorkflow
include WebHelper
scenario "listing order cycles" do
# Given an order cycle
oc = create(:order_cycle)
# When I go to the admin order cycles page
login_to_admin_section
click_link 'Order Cycles'
# Then I should see the basic fields
page.should have_selector 'a', text: oc.name
page.should have_selector "input[value='#{oc.orders_open_at}']"
page.should have_selector "input[value='#{oc.orders_close_at}']"
page.should have_content oc.coordinator.name
# And I should see the suppliers and distributors
oc.suppliers.each { |s| page.should have_content s.name }
oc.distributors.each { |d| page.should have_content d.name }
# And I should see a thumbnail image for each product
all('td.products img').count.should == 2
end
scenario "creating an order cycle" do
# Given a coordinating enterprise
create(:enterprise, name: 'My coordinator')
# When I go to the new order cycle page
login_to_admin_section
click_link 'Order Cycles'
click_link 'New Order Cycle'
# And I fill in the basic fields and click Create
fill_in 'order_cycle_name', with: 'Plums & Avos'
fill_in 'order_cycle_orders_open_at', with: '2012-11-06 06:00:00'
fill_in 'order_cycle_orders_close_at', with: '2012-11-13 17:00:00'
select 'My coordinator', from: 'order_cycle_coordinator_id'
click_button 'Create'
# Then my order cycle should have been created
page.should have_content 'Your order cycle has been created.'
page.should have_selector 'a', text: 'Plums & Avos'
page.should have_selector "input[value='2012-11-06 06:00:00 UTC']"
page.should have_selector "input[value='2012-11-13 17:00:00 UTC']"
page.should have_content 'My coordinator'
end
scenario "updating many order cycle opening/closing times at once" do
# Given three order cycles
3.times { create(:order_cycle) }
# When I go to the order cycles page
login_to_admin_section
click_link 'Order Cycles'
# And I fill in some new opening/closing times and save them
fill_in 'order_cycle_set_collection_attributes_0_orders_open_at', :with => '2012-12-01 12:00:00'
fill_in 'order_cycle_set_collection_attributes_0_orders_close_at', :with => '2012-12-01 12:00:01'
fill_in 'order_cycle_set_collection_attributes_1_orders_open_at', :with => '2012-12-01 12:00:02'
fill_in 'order_cycle_set_collection_attributes_1_orders_close_at', :with => '2012-12-01 12:00:03'
fill_in 'order_cycle_set_collection_attributes_2_orders_open_at', :with => '2012-12-01 12:00:04'
fill_in 'order_cycle_set_collection_attributes_2_orders_close_at', :with => '2012-12-01 12:00:05'
click_button 'Update'
# Then my times should have been saved
flash_message.should == 'Order cycles have been updated.'
OrderCycle.all.map { |oc| oc.orders_open_at.sec }.should == [0, 2, 4]
OrderCycle.all.map { |oc| oc.orders_close_at.sec }.should == [1, 3, 5]
end
end

View File

@@ -61,6 +61,7 @@ Spork.prefork do
DatabaseCleaner.clean
end
config.include Rails.application.routes.url_helpers
config.include Spree::UrlHelpers
config.include Spree::Core::TestingSupport::ControllerRequests, :type => :controller
config.include Devise::TestHelpers, :type => :controller

View File

@@ -89,6 +89,16 @@ module WebHelper
DirtyFormDialog.new(page)
end
# http://www.elabs.se/blog/53-why-wait_until-was-removed-from-capybara
# Do not use this without good reason. Capybara's built-in waiting is very effective.
def wait_until
require "timeout"
Timeout.timeout(Capybara.default_wait_time) do
sleep(0.1) until value = yield
value
end
end
private
def wait_for_ajax
wait_until { page.evaluate_script("$.active") == 0 }