Browse files

Changed license to GPL License.

Updated README to reflect change in design (no longer quick port of Substruct).
Renamed OrderUser to Customer.
Removed various content management (CMS) models.
Removed lines of Artistic License 1.0 encumbered, Substruct copy-and-pasted code from models and views.
Added ignore rule for NB projects in .gitignore.
Commented out various routing rules.
  • Loading branch information...
1 parent e09b81d commit 09233d02a8c662968d61f6defc28fef0ae266615 @myabc committed Apr 27, 2008
Showing with 319 additions and 2,870 deletions.
  1. +1 −0 .gitignore
  2. +0 −2 CHANGELOG
  3. +278 −0 GPL-LICENSE
  4. +0 −88 LICENSE
  5. +26 −24 README.markdown
  6. +0 −34 app/controllers/questions.rb
  7. +0 −7 app/models/asset.rb
  8. +0 −12 app/models/blog.rb
  9. +0 −74 app/models/content_node.rb
  10. +1 −7 app/models/{order_user.rb → customer.rb}
  11. +0 −11 app/models/image.rb
  12. +0 −604 app/models/order.rb
  13. +0 −129 app/models/order_account.rb
  14. +1 −30 app/models/order_address.rb
  15. +0 −44 app/models/order_line_item.rb
  16. +0 −27 app/models/order_shipping_type.rb
  17. +1 −5 app/models/order_shipping_weight.rb
  18. +0 −10 app/models/order_status_code.rb
  19. +0 −5 app/models/page.rb
  20. +0 −70 app/models/preference.rb
  21. +1 −161 app/models/product.rb
  22. +0 −3 app/models/product_image.rb
  23. +0 −71 app/models/promotion.rb
  24. +0 −21 app/models/question.rb
  25. +1 −9 app/models/right.rb
  26. +0 −12 app/models/role.rb
  27. +0 −49 app/models/section.rb
  28. +0 −6 app/models/snippet.rb
  29. +0 −31 app/models/store_item.rb
  30. +0 −46 app/models/tag.rb
  31. +0 −54 app/models/user_upload.rb
  32. +0 −49 app/models/variation.rb
  33. +1 −3 app/models/wishlist_item.rb
  34. +0 −91 app/views/admin/content_nodes/index.html.erb
  35. +0 −154 app/views/admin/files/index.html.erb
  36. +0 −101 app/views/admin/orders/index.html.erb
  37. +0 −155 app/views/admin/preferences/index.html.erb
  38. +0 −57 app/views/admin/products/index.html.erb
  39. +0 −71 app/views/admin/promotions/index.html.erb
  40. +0 −43 app/views/admin/questions/index.html.erb
  41. +0 −175 app/views/admin/sections/index.html.erb
  42. +0 −179 app/views/admin/tags/index.html.erb
  43. +0 −32 app/views/content_nodes/index.html.erb
  44. +0 −2 app/views/content_nodes/show_by_name.html.erb
  45. +2 −14 app/views/layout/application.html.erb
  46. +0 −23 app/views/questions/new.html.erb
  47. +0 −2 config/init.rb
  48. +5 −7 config/router.rb
  49. +1 −66 lib/mart.rb
View
1 .gitignore
@@ -8,6 +8,7 @@ cache/*
config/database.yml
coverage
gems
+nbproject
pkg
pkg/*
tmp
View
2 CHANGELOG
@@ -1,4 +1,2 @@
= Change Log
-
-pre-0.1: Changes from Substruct:
View
278 GPL-LICENSE
@@ -0,0 +1,278 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
View
88 LICENSE
@@ -1,88 +0,0 @@
-= LICENSE
-
-== Copyright
-
-Substruct Design and code Copyright(c) Subimage Interactive - http://www.subimage.com
-Merb Port Design and Code Copyright(c) Alex Coles / Ikonoklastik Productions
-
-== Artistic License
-
-http://www.opensource.org/licenses/artistic-license-1.0.php
-
-Preamble
-
-The intent of this document is to state the conditions under which a Package
-may be copied, such that the Copyright Holder maintains some semblance of
-artistic control over the development of the package, while giving the users
-of the package the right to use and distribute the Package in a more-or-less
-customary fashion, plus the right to make reasonable modifications.
-
-Definitions:
-
- * "Package" refers to the collection of files distributed by the Copyright
- Holder, and derivatives of that collection of files created through textual
- modification.
- * "Standard Version" refers to such a Package if it has not been modified, or
- has been modified in accordance with the wishes of the Copyright Holder.
- * "Copyright Holder" is whoever is named in the copyright or copyrights for
- the package.
- * "You" is you, if you're thinking about copying or distributing this Package.
- * "Reasonable copying fee" is whatever you can justify on the basis of media
- cost, duplication charges, time of people involved, and so on. (You will not
- be required to justify it to the Copyright Holder, but only to the computing
- community at large as a market that must bear the fee.)
- * "Freely Available" means that no fee is charged for the item itself, though
- there may be fees involved in handling the item. It also means that
- recipients of the item may redistribute it under the same conditions they
- received it.
-
- 1. You may make and give away verbatim copies of the source form of the
- Standard Version of this Package without restriction, provided that you
- duplicate all of the original copyright notices and associated disclaimers.
- 2. You may apply bug fixes, portability fixes and other modifications derived
- from the Public Domain or from the Copyright Holder. A Package modified in
- such a way shall still be considered the Standard Version.
- 3. You may otherwise modify your copy of this Package in any way, provided
- that you insert a prominent notice in each changed file stating how and when
- you changed that file, and provided that you do at least ONE of the following:
- 1. Place your modifications in the Public Domain or otherwise make them
- Freely Available, such as by posting said modifications to this web site,
- or by allowing the Copyright Holder to include your modifications in the
- Standard Version of the Package.
- 2. Use the modified Package only within your corporation or organization.
- 3. Rename any non-standard executables so the names do not conflict with
- standard executables, which must also be provided, and provide a separate
- manual page for each non-standard executable that clearly documents how it
- differs from the Standard Version.
- 4. Make other distribution arrangements with the Copyright Holder.
- 4. You may distribute the programs of this Package in object code or
- executable form, provided that you do at least ONE of the following:
- 1. Distribute a Standard Version of the executables and library files,
- together with instructions (in the manual page or equivalent) on where to
- get the Standard Version.
- 2. Accompany the distribution with the machine-readable source of the
- Package with your modifications.
- 3. Accompany any non-standard executables with their corresponding
- Standard Version executables, giving the non-standard executables
- non-standard names, and clearly documenting the differences in manual
- pages (or equivalent), together with instructions on where to get the
- Standard Version.
- 4. Make other distribution arrangements with the Copyright Holder.
- 5. You may charge a reasonable copying fee for any distribution of this
- Package. You may charge any fee you choose for support of this Package. You
- may not charge a fee for this Package itself. However, you may distribute
- this Package in aggregate with other (possibly commercial) programs as part
- of a larger (possibly commercial) software distribution provided that you do
- not advertise this Package as a product of your own.
- 6. The scripts and library files supplied as input to or produced as output
- from the programs of this Package do not automatically fall under the
- copyright of this Package, but belong to whomever generated them, and may be
- sold commercially, and may be aggregated with this Package.
- 7. Any subroutines supplied by you and linked into this Package shall not be
- considered part of this Package.
- 8. The name of the Copyright Holder may not be used to endorse or promote
- products derived from this software without specific prior written permission.
- 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
- WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
- MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-
View
50 README.markdown
@@ -1,37 +1,37 @@
MerbMart README
===============
-MerbMart is an *open-source e-commerce engine*, developed on top of the recent
-Ruby-language Merb MVC framework. Although MerbMart is designed for e-commerce
-sites of all sizes, the speed and scalability of the Merb framework make it
-scalable for even large online vendors.
-
-In addition to Merb framework, MerbMart is also built on the following open-
-source foundations:
-
- * DataMapper (0.9 branch), for object relation mapping (ORM) and persistence.
- * RSpec, for behavio(u)r driven development (BDD).
- * ActiveMerchant, for Credit Card, payment and shipping processing.
+MerbMart is an *open-source e-commerce application*, developed on top of the
+recent Ruby-language Merb MVC framework. Although MerbMart is designed for
+e-commerce sites of all sizes, the speed and scalability of the Merb framework
+make it scalable even for large online vendors.
+
+In addition to Merb framework, the following technologies and frameworks
+provide a foundation for MerbMart:
+
+ * **DataMapper** (bleeding-edge 0.9), for object relation mapping (ORM) and
+ persistence.
+ * **RSpec**, for behavio(u)r driven development (BDD).
+ * **ActiveMerchant**, for Credit Card, payment and shipping processing.
as well as attachmerb\_fu, merb\_paginate.
See INSTALL or the project wiki for a full list of dependencies.
-MerbMart is a loose port of the Substruct e-commerce application for Ruby-on-
-Rails. The initial 0.1 release of MerbMart will be a feature-equivalent port
-of Substruct 0.97. MerbMart borrows many ideas, its database entity-
-relationship design and some lines of code from Substruct, and is grateful to i
-ts developers for developing such a great application:
- http://code.google.com/p/substruct/
- http://substruct.subimage.com/
+MerbMart is inspired by other, Rails based e-commerce applications, including
+[Substruct][substruct] and [Spree][spree]. Although MerbMart started out as a
+project to port Substruct to Merb, the initial 0.1 release of MerbMart will
+instead be a its own implementation of an e-commerce engine, trying to match
+the feature sets other e-commerce applications, but taking advantages of the
+unique features of Merb and DataMapper.
-Developer ReadMe
-----------------
+Developer Notes
+---------------
**WARNING** : MerbMart is at a very early development stages. At this stage,
the application should be considered only for consumption by advanced Ruby and
Merb developers. If you're looking for something for production consumption,
or not yet ready to jump from Ruby on Rails, then we would strongly advise
-trying Substruct.
+trying [Substruct][substruct] or [Spree][spree].
**REQUEST** : Your development support is very much appreciated. Please
contact us below if you're interested in lending a hand with the development
@@ -61,8 +61,8 @@ MerbMart.
Licensing and Copyright
-----------------------
-MerbMart is released under the **Artistic License**. Copyright information,
-as well as a copy of the Artistic License may be found in the LICENSE file.
+This code is licensed under the **GNU Public License (GPL) v2**. Please see
+LICENSE for licensing and copyright information.
Support
-------
@@ -83,4 +83,6 @@ list:
* **MerbMart homepage**: _coming soon_
* Contact the developers directly:
- <alex@alexcolesportfolio.com> | myabc on #datamapper, #merb IRC
-
+
+[substruct]:http://code.google.com/p/substruct/ "Substruct e-commerce project"
+[spree]:http://spreehq.org/ "Spree Online Commerce for Ruby on Rails"
View
34 app/controllers/questions.rb
@@ -1,34 +0,0 @@
-class Questions < Application
-
- def index
- @title = "Questions"
- #@questions = Question.all
-
- #display @questions
- end
-
- def faq
- @title = "FAQ (Frequently Asked Questions)"
-
- @questions = Question.all
- #@questions = Question.find(:all,
- # :conditions => "featured = 1",
- # :order => "-rank DESC, times_viewed DESC")
- end
-
- # Ask a question, also known as /contact
- def new
- @question = Question.new
- render
- end
-
- # Actually creates the question
- def create
- @question = Question.new(params[:question])
- @question.short_question = "Message from the contact form"
- if !@question.save then
- render :action => 'new'
- end
- end
-
-end
View
7 app/models/asset.rb
@@ -1,11 +1,4 @@
-# Represents any type of user upload that's not an image.
-#
class Asset < UserUpload
-# has_attachment :storage => :file_system,
-# :max_size => MAX_SIZE,
-# :path_prefix => 'public/system/'
-
-# validates_as_attachment
end
View
12 app/models/blog.rb
@@ -1,12 +0,0 @@
-# A post in the blog
-#
-class Blog < ContentNode
-
- #############################################################################
- # CLASS METHODS
- #############################################################################
- def self.find_latest
- first #:order => "display_on DESC"
- end
-
-end
View
74 app/models/content_node.rb
@@ -1,74 +0,0 @@
-require 'validate'
-
-# ContentNode is the base class for all of our content.
-#
-class ContentNode
-
- include DataMapper::Resource
- include DataMapper::Validate
-
- many_to_many :sections
-
- TYPES = ['Blog', 'Page', 'Snippet']
-
- property :id, Fixnum, :serial => true
- property :name, String, :length => 200, :default => "", :nullable => false, :index => true
- property :title, String, :length => 100, :default => "", :nullable => false
- property :content, DataMapper::Types::Text
- property :display_on, DateTime
- property :created_on, DateTime
-
- property :type, Class # support single-table inheritence
-
- # TODO: get composite index working
- #index [:id, :type]
-
- #############################################################################
- # VALIDATION
- #############################################################################
-
- validates_presence_of :name, :title, :content
- # FIXME: fix validates_uniqueness_of
-# validates_uniqueness_of :name, :message => 'This URL has already been taken. Create a unique URL please.'
-
-# before_validation :normalize
-
- def normalize
- self.name.downcase!
- # replace quotes by nothing
- self.name.gsub!(/['"]/, '')
- # strip all non word chars
- self.name.gsub!(/\W/, ' ')
-
- # replace all white space sections with an underscore
- self.name.gsub!(/\ +/, '_')
- # trim underscores
- self.name.gsub!(/(_)$/, '')
- self.name.gsub!(/^(_)/, '')
- self.name.strip!
- self.name
- end
-
- #############################################################################
- # INSTANCE METHODS
- #############################################################################
-
- # Defined to save sections from edit view
- def sections=(list)
- sections.clear
- for id in list
- sections << Section[id] if !id.empty?
- end
- end
-
- # URL is just a synonym for name
- def url
- self.name
- end
-
- # Lets us know if this is a blog post or not
- def is_blog_post?
- self.content_node_type_id == 1
- end
-
-end
View
8 app/models/order_user.rb → app/models/customer.rb
@@ -1,12 +1,6 @@
require 'validate'
-# OrderUser aka Customer
-#
-# This is what ties all orders / addresses / wishlist items
-# together for a customer. Lets them login, etc.
-#
-#
-class OrderUser
+class Customer
include DataMapper::Resource
include DataMapper::Validate
View
11 app/models/image.rb
@@ -1,17 +1,6 @@
-# Represents an image
-#
class Image < UserUpload
one_to_many :product_images
one_to_many :products, :through => :product_images
-# has_attachment :content_type => :image,
-# :storage => :file_system,
-# :max_size => MAX_SIZE,
-# :thumbnails => { :thumb => '50x50>', :small => '200x200' },
-# :processor => 'MiniMagick',
-# :path_prefix => 'public/system/'
-#
-# validates_as_attachment
-
end
View
604 app/models/order.rb
@@ -29,612 +29,8 @@ class Order
property :shipping_cost, Float, :default => 0.0
property :tax, Float, :default => 0.0, :nullable => false
- #property t.string :auth_transaction_id"
- #property t.integer :shipping_address_id", :default => 0, :null => false
- #property t.integer :billing_address_id", :default => 0, :null => false
validates_presence_of :order_number
- # FIXME: fix validates_uniqueness_of
- #validates_uniqueness_of :order_number
-
- # CALLBACKS =================================================================
-
- # FIXME: callbacks
- #before_save :set_product_cost
- #before_save :set_promo_code
-
- # Sets product cost based on line items total before a save.
- def set_product_cost
- self.product_cost = self.line_items_total
- end
-
- # Modifies the order based on any promotion codes passed in.
- #
- # This can add discounts to the order or add items.
- #
- # Returns silently and just doesn't add the promo if something
- # is wrong.
- #
- def set_promo_code
- # Find promotion based on code entered
- promo = Promotion.first(:code => self.promotion_code)
-
- # No promo code? Not active? No deal...
- return if !promo || !promo.is_active?
-
- # Make sure it's valid to add
- if promo.minimum_cart_value
- return if promo.minimum_cart_value > self.total
- end
- logger.info "PROMO MIN CART VALUE PASSED"
-
- # Don't allow more than one promotion?
- # This destroys any line items created previously.
- self.promotion_line_item.destroy if self.promotion_line_item
-
- # Assign proper promotion ID
- self.promotion_id = promo.id
-
- # Add any line items necessary from promotion.
- oli = OrderLineItem.new
- logger.info "CREATED OLI"
- # Set name & item...
- oli.name = promo.description
- oli.item_id = promo.item_id
-
- # Figure out how to apply the promotion
- case promo.discount_type
- # Dollars
- when 0 then
- oli.quantity = 1
- oli.unit_price = -promo.discount_amount
- #
- # Percent
- when 1 then
- oli.quantity = 1
- oli.unit_price = -(self.total * (promo.discount_amount/100))
- #
- # Buy N get 1 free
- when 2 then
- item = self.order_line_items.detect { |i| i.item_id == promo.item_id }
- if item && item.quantity >= promo.discount_amount.to_i
- oli.quantity = item.quantity / promo.discount_amount.to_i
- logger.info "ITEM QUANTITY #{oli.quantity}"
- else
- return
- end
- end
-
- self.order_line_items << oli
- end
-
- # CLASS METHODS =============================================================
-
- # Searches an order
- # Uses order number, first name, last name
- def self.search(search_term, count=false, limit_sql=nil)
- if (count == true) then
- sql = "SELECT COUNT(*) "
- else
- sql = "SELECT DISTINCT orders.* "
- end
- sql << "FROM orders "
- sql << "JOIN order_addresses ON orders.order_user_id = order_addresses.order_user_id "
- sql << "WHERE orders.order_number = ? "
- sql << "OR order_addresses.first_name LIKE ? "
- sql << "OR order_addresses.last_name LIKE ? "
- sql << "OR CONCAT(order_addresses.first_name, ' ', order_addresses.last_name) LIKE ? "
- sql << "ORDER BY orders.created_on DESC "
- sql << "LIMIT #{limit_sql}" if limit_sql
- arg_arr = [sql, search_term, "%#{search_term}%", "%#{search_term}%", "%#{search_term}%"]
- if (count == true) then
- count_by_sql(arg_arr)
- else
- find_by_sql(arg_arr)
- end
- end
-
- # Finds orders by country
- #
- def self.find_by_country(country_id, count=false, limit_sql=nil)
- if (count == true) then
- sql = "SELECT COUNT(*) "
- else
- sql = "SELECT DISTINCT orders.* "
- end
- sql << "FROM orders "
- sql << "INNER JOIN order_users ON order_users.id = orders.order_user_id "
- sql << "INNER JOIN order_addresses ON ( "
- sql << " order_addresses.country_id = ? AND order_addresses.order_user_id = order_users.id "
- sql << ")"
- arg_arr = [sql, country_id]
- if (count == true) then
- count_by_sql(arg_arr)
- else
- find_by_sql(arg_arr)
- end
- end
-
- # Generates a unique order number.
- # This number isn't ID because we want to mask that from the customers.
- def self.generate_order_number
- record = Object.new
- while record
- random = rand(999999999)
- record = first(:conditions => ['order_number = ?', random])
- end
- return random
- end
-
- # Returns array of sales totals (hash) for a given year.
- # Hash contains
- # * :number_of_sales
- # * :sales_total
- # * :tax
- # * :shipping
- def self.get_totals_for_year(year)
- months = Array.new
- 0.upto(12) { |i|
- sql = "SELECT COUNT(*) AS number_of_sales, SUM(product_cost) AS sales_total, "
- sql << "SUM(tax) AS tax, SUM(shipping_cost) AS shipping "
- sql << "FROM orders "
- sql << "WHERE YEAR(created_on) = ? "
- if i != 0 then
- sql << "AND MONTH(created_on) = ? "
- end
- sql << "AND (order_status_code_id = 5 OR order_status_code_id = 6 OR order_status_code_id = 7) "
- sql << "LIMIT 0,1"
- if i != 0 then
- months[i] = self.find_by_sql([sql, year, i])[0]
- else
- months[i] = self.find_by_sql([sql, year])[0]
- end
- }
- return months
- end
-
- # Gets a CSV string that represents an order list.
- def self.get_csv_for_orders(order_list)
- require 'fastercsv'
- csv_string = FasterCSV.generate do |csv|
- # Do header generation 1st
- csv << [
- "OrderNumber", "Company", "ShippingType", "Date",
- "BillLastName", "BillFirstName", "BillAddress", "BillCity",
- "BillState", "BillZip", "BillCountry", "BillTelephone",
- "ShipLastName", "ShipFirstName", "ShipAddress", "ShipCity",
- "ShipState", "ShipZip", "ShipCountry", "ShipTelephone",
- "Item1",
- "Quantity1", "Item2", "Quantity2", "Item3", "Quantity3", "Item4",
- "Quantity4", "Item5", "Quantity5", "Item6", "Quantity6", "Item7",
- "Quantity7", "Item8", "Quantity8", "Item9", "Quantity9", "Item10",
- "Quantity10", "Item11", "Quantity11", "Item12", "Quantity12", "Item13",
- "Quantity13", "Item14", "Quantity14", "Item15", "Quantity15", "Item16",
- "Quantity16"
- ]
- for order in order_list
- bill = order.billing_address
- ship = order.shipping_address
- pretty_date = order.created_on.strftime("%m/%d/%y")
- if !order.order_shipping_type.nil?
- ship_code = order.order_shipping_type.code
- else
- ship_code = ''
- end
- order_arr = [
- order.order_number, '', ship_code, pretty_date,
- bill.last_name, bill.first_name, bill.address, bill.city,
- bill.state, bill.zip, bill.country.name, bill.telephone,
- ship.last_name, ship.first_name, ship.address, ship.city,
- ship.state, ship.zip, ship.country.name, ship.telephone
- ]
- item_arr = []
- # Generate spaces for items up to 16 deep
- 0.upto(15) do |i|
- item = order.order_line_items[i]
- if !item.nil? && !item.product.nil? then
- item_arr << item.product.code
- item_arr << item.quantity
- else
- item_arr << ''
- item_arr << ''
- end
- end
- # Add csv string by joining arrays
- csv << order_arr.concat(item_arr)
- end
- end
- return csv_string
- end
-
- # Returns an XML string for each order in the order list.
- # This format is for sending orders to Tony's Fine Foods
- def self.get_xml_for_orders(order_list)
- xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- xml << "<orders>\n"
- for order in order_list
- if order.order_shipping_type
- shipping_type = order.order_shipping_type.code
- else
- shipping_type = ''
- end
- #pretty_date = order.created_on.strftime("%m/%d/%y")
- pretty_date = order.created_on
- xml << " <order>\n"
- xml << " <date>#{pretty_date}</date>\n"
- xml << " <shippingCode>#{shipping_type}</shippingCode>\n"
- xml << " <invoiceNumber>#{order.order_number}</invoiceNumber>\n"
- xml << " <emailAddress>#{order.order_user.email_address}</emailAddress>\n"
- # Shipping address
- address = order.shipping_address
- xml << " <shippingAddress>\n"
- xml << " <firstName>#{address.first_name}</firstName>\n"
- xml << " <lastName>#{address.last_name}</lastName>\n"
- xml << " <address1>#{address.address}</address1>\n"
- xml << " <address2></address2>\n"
- xml << " <city>#{address.city}</city>\n"
- xml << " <state>#{address.state}</state>\n"
- xml << " <zip>#{address.zip}</zip>\n"
- xml << " <countryCode>#{address.country.fedex_code}</countryCode>\n"
- xml << " <telephone>#{address.telephone}</telephone>\n"
- xml << " </shippingAddress>\n"
- # Items
- xml << " <items>\n"
- for item in order.order_line_items
- xml << " <item>\n"
- xml << " <name>#{item.product.name}</name>\n"
- xml << " <id>#{item.product.code}</id>\n"
- xml << " <quantity>#{item.quantity}</quantity>\n"
- xml << " </item>\n"
- end
- xml << " </items>\n"
- # End
- xml << " </order>\n"
- end
- # End orders
- xml << "</orders>\n"
- return xml
- end
-
-
- # INSTANCE METHODS ==========================================================
-
- # Shortcut to find order_line_item for a promotion that has been applied.
- def promotion_line_item
- if self.promotion
- return self.order_line_items.find_by_name(self.promotion.description)
- else
- return nil
- end
- end
-
- # Order status name
- def status
- code = OrderStatusCode.first(:id => self.order_status_code_id)
- code.name
- end
-
- # Shortcut to items
- def items
- self.order_line_items
- end
-
- # Total for the order, including shipping and tax.
- #
- def total
- logger.info "CALCULATING SHIPPING TOTAL"
- logger.info "LINE ITEMS TOTAL: #{self.line_items_total}"
- logger.info "SHIPPING COST: #{self.shipping_cost}"
- logger.info "TAX COST: #{self.tax_cost}"
- self.line_items_total + self.shipping_cost + self.tax_cost
- end
-
- # The tax of items if applied.
- #
- def tax_cost
- (self.line_items_total) * (self.tax/100)
- end
-
- def name
- return "#{billing_address.first_name} #{billing_address.last_name}"
- end
-
- def account
- self.order_account
- end
-
- # Sets line items from the product output table on the edit page.
- #
- # Deletes any line items with a quantity of 0.
- # Adds line items with a quantity > 0.
- #
- # This is called from update in our controllers.
- # What's passed looks something like this...
- # @products = {'1' => {'quantity' => 2}, '2' => {'quantity' => 0}, etc}
- def line_items=(products)
- # Clear out all line items
- self.order_line_items.clear
- # Go through all products
- products.each do |id, product|
- quantity = product['quantity']
- if quantity.blank? then
- quantity = 0
- else
- quantity = Integer(quantity)
- end
-
- if (quantity > 0) then
- new_item = self.order_line_items.build
- logger.info("\n\nBUILDING NEW LINE ITEM\n")
- logger.info(new_item.inspect+"\n")
- new_item.quantity = quantity
- new_item.item_id = id
- new_item.unit_price = Item[:id].price
- new_item.save
- end
- end
- end
-
- # Do we have a valid transaction id
- def contains_valid_transaction_id?()
- return (!self.auth_transaction_id.blank? && self.auth_transaction_id != 0)
- end
-
- # Determines if an order has a line item based on product id
- def has_line_item?(id)
- self.order_line_items.each do |item|
- return true if item.id == id
- end
- return false
- end
-
- # Gets quantity of a product if exists in current line items.
- def get_line_item_quantity(id)
- self.order_line_items.each do |item|
- return item.quantity if item.id == id
- end
- return 0
- end
-
- # Gets a subtotal for line items based on product id
- def get_line_item_total(id)
- self.order_line_items.each do |item|
- return item.total if item.id == id
- end
- return 0
- end
-
- # Grabs the total amount of all line items associated with this order
- def line_items_total
- total = 0
- for item in self.order_line_items
- total += item.total
- end
- return total
- end
-
- # Adds a new order note from the edit page.
- #
- # We display notes as read-only, so we only have to use a text field
- # instead of multiple records.
- def new_notes=(note)
- if !note.blank? then
- time = Time.now.strftime("%m-%d-%y %I:%M %p")
- new_note = "<p>#{note}<br/>"
- new_note << "<span class=\"info\">"
- new_note << "[#{time}]"
- new_note << "</span></p>"
- if self.notes.blank? then
- self.notes = new_note
- else
- self.notes << new_note
- end
- end
- end
-
- # Calculates the weight of an order
- def weight
- weight = 0
- self.order_line_items.each do |item|
- weight += item.quantity * item.product.weight rescue 0
- end
- return weight
- end
-
- # Gets a flat shipping price for an order.
- # This is if we're not using live rate calculation usually
- #
- # A lot of people will want this overridden in their app
- def get_flat_shipping_price
- return Preference.find_by_name('store_handling_fee').value.to_f
- end
-
- # Gets all LIVE shipping prices for an order.
- #
- # Returns an array of OrderShippingTypes
- def get_shipping_prices
- prices = []
- # If they're in the USA
- address = self.shipping_address
-
- # TODO - set this country_id as a preference in the admin UI
- #
- if address.country_id == 1 then
- shipping_types = OrderShippingType.get_domestic
- else
- shipping_types = OrderShippingType.get_foreign
- end
-
- for type in shipping_types
- type.calculate_price(self.weight)
- prices << type
- end
-
- return prices
-
- end
-
- # Runs an order transaction.
- # Farms out the work to an Authorize.net or PayPal method
- # (or one of your devising).
- #
- # Should return TRUE if the process is successful.
- # Should return AN ERROR MESSAGE if not...
- #
- def run_transaction
- cc_processor = Order.get_cc_processor
- if cc_processor == Preference::CC_PROCESSORS[0]
- run_transaction_authorize
- elsif cc_processor == Preference::CC_PROCESSORS[1]
- run_transaction_paypal_ipn
- else
- throw "The currently set preference for cc_processor is not recognized. You might want to add it to the code..."
- end
- end
- # Check to see which cc processor is used
- def self.get_cc_processor
- Preference.find_by_name('cc_processor').value
- end
-
- # Get the login info for the cc processor (if any)
- def self.get_cc_login
- Preference.find_by_name('cc_login').value
- end
-
- # Runs an order through Authorize.net
- #
- # Returns true
- #
- def run_transaction_authorize
- ba = self.billing_address
-
- # For debugging with a test account...
- # ActiveMerchant::Billing::Base.mode = :test
-
- credit_card = ActiveMerchant::Billing::CreditCard.new(
- :number => self.account.cc_number,
- :month => self.account.expiration_month,
- :year => self.account.expiration_year,
- :first_name => ba.first_name,
- :last_name => ba.last_name
- )
- gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new(
- :login => Preference.find_by_name('cc_login').value,
- :password => Preference.find_by_name('cc_pass').value,
- :ssl_strict => true,
- :test => Preference.find_by_name('store_test_transactions').is_true?
- )
- address = {
- :address1 => ba.address,
- :city => ba.city,
- :state => ba.state,
- :zip => ba.zip,
- :country => ba.country.name
- }
-
- # AM requires it's purchaes in CENTS, so adjust accordingly.
- response = gateway.purchase(self.total.to_f*100, credit_card, {:address => address})
- # Save transaction id for later
- self.auth_transaction_id = response.params[:transaction_id]
-
- # Handle the response
- if response.success?
- logger.info("\n\nORDER TRANSACTION ID - #{self.auth_transaction_id}\n\n")
- # Set completed
- self.cleanup_successful
- # Send success message
- begin
- self.deliver_receipt
- rescue => e
- logger.error("FAILED TO SEND THE CONFIRM EMAIL")
- end
- return true
- else
- # Log errors
- logger.error("\n\n[ERROR] FAILED ORDER \n")
- logger.error(response.inspect)
- logger.error(response.message)
- logger.error("\n\n")
- # Order failed - store transaction id
- self.cleanup_failed(response.message)
- # Send failed message
- begin
- self.deliver_failed
- rescue => e
- logger.error("FAILED TO SEND THE CONFIRM EMAIL")
- end
-
- return response.message
- end
-
- return false
- end
-
- # Do the cleanup for orders run through Paypal
- #
- def run_transaction_paypal_ipn
-
- status_code = self.order_status_code_id
-
- # Under normal conditions, the paypal ipn should be confirmed already
- # but we can't count on that. Assign a status of 4 (awaiting payment)
- # if the status is still 1 (cart)
- if status_code == 1
- self.order_status_code_id = 4
- self.new_notes = "The order was processed at PayPal but not yet confirmed."
- end
-
- self.save
-
- self.order_status_code_id
-
- end
-
- # Cleans up a successful order
- def cleanup_successful
- # Decrement inventory for items...
- # Also driven by the inventory control preference from the
- # admin UI
- if Preference.find_by_name('store_use_inventory_control').is_true?
- for oli in self.order_line_items do
- oli.item.update_attribute('quantity', oli.item.quantity-oli.quantity)if oli.quantity rescue false && oli.item.quantity rescue false
- end
- end
-
- self.order_status_code_id = 5
- self.new_notes="Order completed."
- if Preference.find_by_name('cc_clear_after_order').is_true?
- self.account.clear_personal_information
- end
- self.save
- end
-
- # Cleans up a failed order
- def cleanup_failed(msg)
- self.order_status_code_id = 3
- self.new_notes="Order failed!<br/>#{msg}"
- self.save
- end
-
- # We define deliver_receipt here because ActionMailer can't seem to render
- # components inside a template.
- #
- # I'm getting around this by passing the text into the mailer.
- def deliver_receipt
- @content_node = ContentNode.find(:first, :conditions => ["name = ?", 'OrderReceipt'])
- OrdersMailer.deliver_receipt(self, @content_node.content)
- end
-
- # If we're going to define deliver_receipt here, why not wrap deliver_failed as well?
- def deliver_failed
- OrdersMailer.deliver_failed(self)
- end
-
- # Is a discount present?
- def is_discounted?
- self.order_line_items.collect.each {|item| return true if item.unit_price < 0 }
- false
- end
end
View
129 app/models/order_account.rb
@@ -10,21 +10,6 @@ class OrderAccount
one_to_one :order
many_to_one :order_user, :accessor => :protected
- @@salt = 'salt_$alt_salt'
- #cattr_accessor :salt
- @@password = '$ub$truct_change_me'
- #cattr_accessor :password
-
- #attr_protected :order_user_id
-
- TYPES = {
- 'Credit Card' => 1,
- 'Checking' => 2,
- 'Savings' => 3,
- 'Business Checking' => 4,
- 'PayPal' => 5
- }
-
property :cc_number, String
property :account_number, String
property :expiration_month, Fixnum, :length => 2
@@ -33,119 +18,5 @@ class OrderAccount
property :routing_number, String, :length => 20
property :bank_name, String, :length => 50
- # VALIDATION ================================================================
-
- #validates_presence_of :order_user_id
-
- validates_presence_of :cc_number,
- :if => Proc.new { |oa| oa.order_account_type_id == TYPES['Credit Card'] },
- :message => ERROR_EMPTY
-
- validates_presence_of :routing_number,
- :if => Proc.new { |oa| oa.order_account_type_id == TYPES['Checking'] || oa.order_account_type_id == TYPES['Business Checking'] },
- :message => ERROR_EMPTY
-
- validates_presence_of :account_number,
- :if => Proc.new { |oa| oa.order_account_type_id == TYPES['Checking'] || oa.order_account_type_id == TYPES['Business Checking'] },
- :message => ERROR_EMPTY
-
- # TODO: add validates_absence_of here
-
- validates_format_of :credit_ccv, :with => /^[\d]*$/, :message => ERROR_NUMBER
- validates_numericalnes_of :expiration_month, :expiration_year
-
- # Make sure expiration date is ok.
- def validate
- today = DateTime.now
- begin
- if (today.month > self.expiration_month && today.year >= self.expiration_year)
- errors.add(:expiration_month, 'Please enter a valid expiration date.')
- end
- rescue
- errors.add(:expiration_month, 'Please enter a valid expiration date.')
- end
- end
-
- # CLASS METHODS =============================================================
-
- # List of months for dropdown in UI
- def self.months
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
- end
-
- # List of years for dropdown in UI
- def self.years
- start_year = Date.today.year
- years = Array.new
- 10.times do
- years << start_year
- start_year += 1
- end
- return years
- end
-
- # INSTANCE METHODS ==========================================================
-
- # Obfuscates personal information about this account
- # - CC number
- def clear_personal_information
- number = String.new(self.cc_number)
- # How many spaces to replace with X's
- spaces_to_pad = number.length-4
- # Cut string
- new_number = number[spaces_to_pad,number.length]
- # Pad with X's
- new_number = new_number.rjust(spaces_to_pad, 'X')
- self.cc_number = new_number
- self.save
- # Return number in case we need it
- return new_number
- end
-
- # Setter for cc number.
- # Crypts before it saves.
- #
- def cc_number=(number='')
- self.set_unencrypted_number(number, 'cc_number')
- end
- def cc_number
- self.get_unencrypted_number('cc_number')
- end
-
- # Setter for account number.
- # Crypts before it saves.
- #
- def account_number=(number='')
- self.set_unencrypted_number(number, 'account_number')
- end
- def account_number
- self.get_unencrypted_number('account_number')
- end
-
- # Gets an unencrypted # from the db.
- #
- def get_unencrypted_number(attribute)
- key = EzCrypto::Key.with_password(@@password, @@salt)
- # For blanks this can throw a "wrong final block length" error.
- begin
- value = self[attribute.to_sym]
- return key.decrypt64(value)
- rescue
- nil
- end
- end
-
- # Crypts & sets unencrypted number to db.
- # This would probably be best as a plugin...but maybe later.
- # acts_as_crypted_number ?
- def set_unencrypted_number(number='', attribute='')
- return if attribute.empty?
- key = EzCrypto::Key.with_password(@@password, @@salt)
- begin
- self[attribute.to_sym] = key.encrypt64(number)
- rescue
- self[attribute.to_sym] = ''
- end
- end
end
View
31 app/models/order_address.rb
@@ -8,9 +8,7 @@ class OrderAddress
one_to_one :order
many_to_one :order_user
many_to_one :country
-
- #t.integer "order_user_id", :default => 0, :null => false
-
+
property :first_name, String, :length => 50, :default => "", :nullable => false
property :last_name, String, :length => 50, :default => "", :nullable => false
property :telephone, String, :length => 20
@@ -31,31 +29,4 @@ class OrderAddress
validates_length_of :last_name, :maximum => 50
validates_length_of :address, :maximum => 255
- # TODO: validates_with_method here??
- #validates_exclusion_of :address, :in => ['PO BOX', 'P.O. BOX', 'AFO', 'A.F.O.', 'APO', 'A.P.O.'],
- # :message => 'Sorry, we don\'nt ship to P.O. boxes'
-
- # Makes sure validation address doesn't allow PO Box or variants
- def validate
- invalid_strings = ['PO BOX', 'P.O. BOX', 'P.O BOX', 'PO. BOX',
- 'POBOX', 'P.OBOX', 'P.O.BOX', 'PO.BOX', 'P.BOX',
- 'PBOX', 'AFO', 'A.F.O.', 'APO', 'A.P.O.']
- cap_address = self.address.upcase()
- invalid_strings.each do |string|
- if cap_address.include?(string) then
- errors.add(:address, "Sorry, we don't ship to P.O. boxes")
- return
- end
- end
- end
-
- # Finds the shipping address for a given OrderUser
- def self.find_shipping_address_for_user(user)
- first(:conditions => ["order_user_id = ? AND is_shipping = 1", user.id])
- end
-
- def name
- "#{self.first_name} #{self.last_name}"
- end
-
end
View
44 app/models/order_line_item.rb
@@ -10,48 +10,4 @@ class OrderLineItem
property :unit_price, Float, :default => 0.0, :nullable => false
property :name, String, :default => ""
- #alias_attribute :price, :unit_price
-
- # Creates and returns a line item when a product is passed in
- def self.for_product(item)
- ol_item = self.new
- ol_item.quantity = 1
- ol_item.item = item
- ol_item.name = item.name
- ol_item.unit_price = item.price
- return ol_item
- end
-
- def total
- self.quantity * self.unit_price
- end
-
- # We still have view code referencing product_id
- # Since we changed to variations / products we need
- # to use item_id.
- #
- def product_id
- self.item_id
- end
-
- def product
- self.item
- end
-
- def code
- self.item.code
- end
-
- def name
- if !self.item.nil?
- return self.item.name
- else
- return self.attributes['name']
- end
- end
-
- def price
- self.unit_price
- end
-
end
View
27 app/models/order_shipping_type.rb
@@ -21,31 +21,4 @@ def self.get_foreign
all(:is_domestic => false, :order => "price ASC")
end
- # Calculates shipping price for a shipping type with weight.
- # If no weight found, use the default.
- def calculate_price(weight)
-
- price = self.price
-
- if self.weights.size > 0
- proper_weight = self.weights.first(
- :conditions => ["? BETWEEN min_weight AND max_weight", weight]
- )
- price = proper_weight.price if proper_weight
- end
-
- #self.calculated_price = price + Preference.find_by_name('store_handling_fee').value.to_f
- self.calculated_price = price
- end
-
- # Sets weight variations from attribute list.
- #
- def weights=(list)
- self.weights.clear
- for variation in list do
- v = OrderShippingWeight.create(variation)
- self.weights << v
- end
- end
-
end
View
6 app/models/order_shipping_weight.rb
@@ -1,8 +1,4 @@
-# These are the "variations" of an OrderShippingType
-#
-# They allow an admin to specify weight ranges and prices
-# for an OrderShippingType.
-#
+
class OrderShippingWeight
include DataMapper::Resource
View
10 app/models/order_status_code.rb
@@ -7,14 +7,4 @@ class OrderStatusCode
property :id, Fixnum, :serial => true
property :name, String, :length => 30, :nullable => false
- # Defines if we can edit this order or not based on the status code
- def is_editable?
- case self.id
- when 1..5
- return true
- else
- return false
- end
- end
-
end
View
5 app/models/page.rb
@@ -1,5 +0,0 @@
-# A full page of content on the site
-#
-class Page < ContentNode
-
-end
View
70 app/models/preference.rb
@@ -1,70 +0,0 @@
-require 'validate'
-
-# Handles storing of preferences for the application.
-#
-# This is an internal structure mostly, which is useful to access / save
-# things from the GUI.
-#
-# Prefs are used all over to handle decisions that we'd rather
-# not use config files for.
-#
-class Preference
-
- include DataMapper::Resource
- include DataMapper::Validate
-
- # Types can hold strings, booleans, or pointers to
- # other records (like country)
- CC_PROCESSORS = ['Authorize.net', 'PayPal IPN']
- MAIL_AUTH = ['none', 'plain', 'login', 'cram_md5']
-
- property :id, Fixnum, :serial => true
- property :name, String, :default => "", :nullable => false
- property :value, String, :default => ""
-
- validates_presence_of :name, :type
- # FIXME: fix validates_uniqueness_of
- #validates_uniqueness_of :name
-
- def self.find_by_name(name)
- first(:name => name)
- end
-
- # Can throw an error if these items aren't set.
- # Make sure to wrap any block that calls this
- def self.init_mail_settings
- # SET MAIL SERVER SETTINGS FROM PREFERENCES
- mail_host = find_by_name('mail_host').value
- mail_server_settings = {
- :address => mail_host,
- :domain => mail_host,
- :port => find_by_name('mail_port').value,
- }
- mail_auth_type = find_by_name('mail_auth_type').value
- if !mail_auth_type != 'none'
- mail_server_settings[:authentication] = mail_auth_type.to_sym
- mail_server_settings[:user_name] = find_by_name('mail_username').value
- mail_server_settings[:password] = find_by_name('mail_password').value
- end
- ActionMailer::Base.smtp_settings = mail_server_settings
- end
-
- # Saves preferences passed in from our form.
- #
- def self.save_settings(settings)
- logger.info "SERVER SETTINGS..."
- logger.info settings.inspect
- settings.each do |name, value|
- update_all("value = '#{value}'", "name = '#{name}'")
- end
- end
-
- # Determines if a preference is "true" or not.
- # This is the ghetto, bootleg way to determine booleans.
- def is_true?
- if self.value == '1' || self.value == 'true'
- return true
- end
- return false
- end
-end
View
162 app/models/product.rb
@@ -1,12 +1,5 @@
class Product < StoreItem
- # Conditions that the product is in stock, or available
- # and just out of stock.
- CONDITIONS_AVAILABLE = %Q/
- CURRENT_DATE() >= DATE(items.date_available)
- AND items.is_discontinued = 0
- OR (items.is_discontinued = 1 AND (items.quantity > 0 OR items.variation_quantity > 0))
- /
-
+
one_to_many :product_images
one_to_many :variations, :dependent => :destroy, :order => 'name ASC'
one_to_many :images,
@@ -19,160 +12,7 @@ class Product < StoreItem
:join_table => 'related_products',
:association_foreign_key => 'related_id',
:foreign_key => 'product_id'
- # :after_add => :add_return_relation,
- # :after_remove => :remove_return_relation
-
- def add_return_relation(relative)
- relative.related_products << self unless relative.related_products.include?(self)
- end
- def remove_return_relation(relative)
- sql = "DELETE FROM related_products "
- sql << "WHERE product_id = #{relative.id} AND related_id = #{self.id}"
-
- database.query(sql)
- end
many_to_many :tags
- #############################################################################
- # CALLBACKS
- #############################################################################
-
- # FIXME Fix callbacks
- #after_create :add_cached_related_products
-
- # Related products (associations) freak out if this
- # object isn't saved before adding relatives.
- #
- # If there's a cached @related_list we try to add em.
- #
- def add_cached_related_products
- self.related_product_ids=@cached_related_list if @cached_related_list
- end
-
- #############################################################################
- # CLASS METHODS
- #############################################################################
-
- # Admin search for products
- # Uses product name, code, or description
- def self.search(search_term, count=false, limit_sql=nil)
- if (count == true) then
- sql = "SELECT COUNT(*) "
- else
- sql = "SELECT DISTINCT * "
- end
- sql << "FROM items "
- sql << "WHERE ("
- sql << " name LIKE ? "
- sql << " OR items.description LIKE ? "
- sql << " OR items.code LIKE ? "
- sql << ") AND items.type = 'Product' "
- sql << "ORDER BY date_available DESC "
- sql << "LIMIT #{limit_sql}" if limit_sql
- arg_arr = [sql, "%#{search_term}%", "%#{search_term}%", "%#{search_term}%"]
- if (count == true) then
- count_by_sql(arg_arr)
- else
- find_by_sql(arg_arr)
- end
- end
-
- # Finds products by list of tag ids passed in
- #
- # We could JOIN multiple times, but selecting IN grabs us the products
- # and using GROUP BY & COUNT with the number of tag id's given
- # is a faster approach according to freenode #mysql
- def self.find_by_tags(tag_ids, find_available=false, order_by="items.date_available DESC")
- sql = "SELECT * "
- sql << "FROM items "
- sql << "JOIN products_tags on items.id = products_tags.product_id "
- sql << "WHERE products_tags.tag_id IN (#{tag_ids.join(",")}) "
- sql << "AND #{CONDITIONS_AVAILABLE}" if find_available==true
- sql << "GROUP BY items.id HAVING COUNT(*)=#{tag_ids.length} "
- sql << "ORDER BY #{order_by};"
- find_by_sql(sql)
- end
-
- #############################################################################
- # INSTANCE METHODS
- #############################################################################
-
- # Defined to save tags from product edit view
- def tags=(list)
- tags.clear
- for id in list
- tags << Tag[id] if !id.empty?
- end
- end
-
- # Calculated based on variations
- #
- def display_price
- variations = self.variations.all # :order => "price ASC")
- if variations.size == 0
- return self.price
- else
- low_price = variations[0].price
- high_price = variations[variations.size-1].price
- if low_price == high_price
- return low_price
- else
- return [low_price, high_price]
- end
- end
- end
-
- def quantity
- if self.variations.count == 0
- return self.attributes['quantity']
- else
- return self.variation_quantity
- end
- end
-
- # Is the item active on the site? Is it listed in the store?
- #
- def is_published?
- !self.is_discontinued? || self.quantity > 0
- end
-
- # Is this product new?
- #
- def is_new?
- @cached_is_new ||=
- begin
- self.date_available >= 2.weeks.ago
- end
- end
-
- # Is this product on sale?
- #
- def is_on_sale?
- @cached_on_sale ||=
- begin
- !self.tags.find_by_name('On Sale').nil?
- end
- end
-
- # Adds related products from list.
- # Used in UI for auto-completion
- #
- # See callback for why we return if this is a new record.
- #
- def related_product_ids=(list)
- if self.new_record?
- @cached_related_list = list
- return
- end
-
- # If self is a new record shit fails
- self.related_products.clear
- for name in list do
- p = Product.find_by_code(name.split(':')[0])
- next if !p || p == self
- self.related_products << p
- end
- end
-
end
View
3 app/models/product_image.rb
@@ -1,6 +1,3 @@
-# Represents a connection from an image to a product.
-#
-#
class ProductImage
include DataMapper::Resource
View
71 app/models/promotion.rb
@@ -1,9 +1,5 @@
require 'validate'
-# Promotions allow discounts to be applied to orders, and
-# have the ability to add items to an order as well.
-#
-#
class Promotion
include DataMapper::Resource
@@ -31,74 +27,7 @@ class Promotion
# Validation
validates_presence_of :code, :discount_amount, :discount_type, :description
- # FIXME: fix validates_uniqueness_of
- #validates_uniqueness_of :code
validates_numericalnes_of :discount_amount
- # FIXME: call backs
- #before_save :clean_code
-
- def clean_code
- self.code.gsub!(' ', '')
- end
-
- # Makes sure if 'buy n get one free' discount type that
- # a product is selected.
- def validate
- if self.discount_type == 2 && self.item_id.nil?
- errors.add(:item_id, "Please add an item for the 'Buy [n] get 1 free' promotion")
- end
- end
-
- # Generates a 15 character alphanumeric code
- # that we use to track affiliates and promotions.
- #
- def self.generate_code(size=15)
- # characters used to generate affiliate code
- chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
- # create a new record object to satisfy while loop initially
- record = Promotion.new
- # loop through, creating random affiliate codes until
- # we create one that doesn't exist in the db
- while record
- test_code = ""
- srand
- size.times do
- pos = rand(chars.length)
- test_code += chars[pos..pos]
- end
- # find any affiliates with this same code string
- # if none are found the while loop exits
- record = first(:code => test_code)
- end
- # return our random code
- return test_code
- end
-
- # Lets us know if any promotions are active.
- #
- def self.any_active?
- !Promotion.find(
- :first,
- :conditions => "NOW() BETWEEN start AND end"
- ).nil?
- end
-
- def is_active?
- Time.now.between?(self.start, self.end)
- end
-
- # Setter for product name. Uses suggestion JS and pop-up.
- #
- # We only really use the first item, which is the ID to look
- # up the product.
- def product_name=(name)
- item = StoreItem.find_by_code(name.split(':')[0])
- if !item
- self.item_id = nil
- else
- self.item_id = item.id
- end
- end
end
View
21 app/models/question.rb
@@ -1,21 +0,0 @@
-require 'validate'
-
-class Question
-
- include DataMapper::Resource
- include DataMapper::Validate
-
- property :id, Fixnum, :serial => true
- property :short_question, String
- property :long_question, DataMapper::Types::Text
- property :answer, DataMapper::Types::Text
- property :rank, Fixnum
- property :featured, TrueClass, :default => false, :nullable => false
- property :times_viewed, Fixnum, :default => 0, :nullable => false
- property :created_on, DateTime, :nullable => false
- property :answered_on, DateTime
- property :email_address, String, :length => 50
-
- # Validation
- validates_presence_of :short_question, :message => ERROR_EMPTY
-end
View
10 app/models/right.rb
@@ -1,12 +1,4 @@
-# A right is a controller resource that determines
-# access.
-#
-# Rights are assigned to roles, roles to users.
-#
-# Rights consist of a controller name and an action list.
-# This action list can be either '*' for access to all actions
-# or a CSV list of actions.
-#
+
class Right
include DataMapper::Resource
View
12 app/models/role.rb
@@ -1,5 +1,3 @@
-# A role is a collection of rights.
-#
class Role
include DataMapper::Resource
@@ -11,14 +9,4 @@ class Role
property :name, String
property :description, DataMapper::Types::Text
- # Sets rights by list of id's passed in
- def right_ids=(id_list)
- self.rights.clear
- for id in id_list
- next if id.empty?
- right = Right[id]
- self.rights << right if right
- end
- end
-
end
View
49 app/models/section.rb
@@ -1,49 +0,0 @@
-require 'validate'
-
-# A section is an organizational unit for content nodes.
-#
-# Sections can be applied to pages or snippets, but really are
-# only meant for blogs.
-#
-class Section
-
- include DataMapper::Resource
- include DataMapper::Validate
- #include DataMapper::Is::Tree
-
- many_to_many :content_nodes
- many_to_many :blogs,
- :join_table => 'content_nodes_sections',
- :association_foreign_key => 'content_node_id',
- :conditions => "content_nodes.type = 'Blog'",
- :order => 'display_on DESC'
-
- property :id, Fixnum, :serial => true
- property :name, String, :length => 100, :default => "", :nullable => false
- property :rank, Fixnum
- property :parent_id, Fixnum
-
- validates_presence_of :name
- # FIXME: fix validates_uniqueness_of (not available yet)
- #validates_uniqueness_of :name
- # FIXME : tree
- #is_a_tree :order => 'rank' # '-rank DESC'
-
- # Most used finder function for tags.
- # Selects by alpha sort.
- def self.find_alpha
- all(:order => [ DataMapper::Query::Direction.new(:name, :asc) ])
- end
-
- # Finds ordered parent tags.
- def self.find_ordered_parents
- all(:conditions => [:parent_id => nil, :parent_id => 0],
- :order => [ DataMapper::Query::Direction.new(:rank, :asc) ])
- end
-
- # Returns the number of products tagged with this item
- def content_count
- @cached_content_count ||= self.content_nodes.count
- end
-
-end
View
6 app/models/snippet.rb
@@ -1,6 +0,0 @@
-
-# A snippet of content inserted into another dynamic page.
-#
-class Snippet < ContentNode
-
-end
View
31 app/models/store_item.rb
@@ -1,5 +1,3 @@
-# This is the base model for Product and ProductVariation.
-#
require "date"
require "validate"
@@ -25,36 +23,7 @@ class StoreItem
property :is_discontinued, TrueClass, :default => false, :nullable => false
property :type, Class # enable single-table inheritence
-
- #t.integer "product_id", :default => 0, :null => false
-
- # FIXME
- #add_index ["quantity", "is_discontinued", "variation_quantity"], :name => "published"
- #add_index ["product_id", "type"], :name => "variation"
- #add_index ["date_available", "is_discontinued", "quantity", "variation_quantity", "type"], :name => "tag_view"
- #add_index ["name", "code", "is_discontinued", "date_available", "quantity", "variation_quantity", "type"], :name => "search"
validates_presence_of :name, :code
- # FIXME: fix validates_uniqueness_of
- #validates_uniqueness_of :code
-
- #############################################################################
- # CALLBACKS
- #############################################################################
-
-
- #############################################################################
- # CLASS METHODS
- #############################################################################
-
- def find_by_code(code)
- first(:code => code)
- end
-
- # Name output for product suggestion JS
- #
- def suggestion_name
- "#{self.code}: #{self.name}"
- end
end
View
46 app/models/tag.rb
@@ -1,11 +1,5 @@
require 'validate'
-# Tags are how we organize products inside Substruct.
-#
-# Tags may be ordered, and contain other tags. In this fashion,
-# they can act like old-school "categories", or new-school tagging
-# systems.
-#
class Tag
include DataMapper::Resource
@@ -22,53 +16,13 @@ class Tag
validates_presence_of :name
#validates_uniqueness_of :name
- # FIXME : fix the tree
- #is_a_tree
- #acts_as_tree :order => '-rank DESC'
-
- # Most used finder function for tags.
- # Selects by alpha sort.
def self.find_alpha
all(:order => [ DataMapper::Query::Direction.new("name", :asc) ])
end
- # Finds ordered parent tags.
- #
def self.find_ordered_parents
all(:conditions => [:parent_id => nil, :parent_id => 0],
:order => [ DataMapper::Query::Direction.new(:rank, :desc) ])
end
- # Finds a list of related tags for the tag id's passed in
- #
- # Uses the tag ids passed in
- # - Finds products with the tags applied (inside the subselect)
- # - Find and returns tags also tagged to the products, but not passed in
- def self.find_related_tags(tag_id_list)
- tag_id_list_string = tag_id_list.join(",")
- sql = "SELECT items.id "
- sql << "FROM items "
- sql << "JOIN products_tags on items.id = products_tags.product_id "
- sql << "WHERE products_tags.tag_id IN (#{tag_id_list_string}) "
- sql << "GROUP BY items.id HAVING COUNT(*)=#{tag_id_list.length};"
- items = StoreItem.find_by_sql(sql)
-
- item_ids = items.collect { |i| i.id }
- item_id_str = item_ids.join(',')
-
- if item_ids.size > 0
- sql = "SELECT DISTINCT t.* FROM products_tags pt, tags t WHERE pt.product_id IN(#{item_id_str})"
- sql << "AND t.id = pt.tag_id "
- sql << "AND t.id NOT IN (#{tag_id_list_string});"
- return find_by_sql(sql)
- else
- return []
- end
- end
-
- # Returns the number of products tagged with this item
- def product_count
- @cached_product_count ||= self.products.count
- end
-
end
View
54 app/models/user_upload.rb
@@ -1,9 +1,3 @@
-# Represents a file uploaded by a user.
-#
-# Subclassed by Image and Asset
-#
-# Before a save, checks to set the type, based on file extension.
-#
class UserUpload
include DataMapper::Resource
@@ -20,53 +14,5 @@ class UserUpload
property :thumbnail, String
property :size, Fixnum
property :type, Class
-
- # Checks what type of file this is based on extension.
- #
- # If it's an image, we treat it differently and save
- # as an image type.
- #
- # No, we're not using anything fancy here, just the extension set.
- #
-
- # FIXME
- #before_save :downcase_extension
-
- def downcase_extension
- self.filename = "#{self.filename[0, self.filename.rindex('.')]}.#{self.extension.downcase}"
- end
-
- # Returns extension
- #
- def extension
- self.filename[self.filename.rindex('.') + 1, self.filename.size]
- end
-
- # Returns file name
- #
- def name
- self.filename
- end
-
- def relative_path
- #self.filename[self.filename.rindex('/public/system')+7, self.filename.size]
- self.filename
- end
-
- def filename_without_ext
- self.filename[0, self.filename.rindex('.')]
- end
- # use this to make a new user upload when you don't know whether it should
- # be an image or an asset. Can't use UserUpload.new since it doesn't have uploaded_data.
- def self.init(file_data)
- if file_data.content_type.index('image')
- upload = Image.new
- else
- upload = Asset.new
- end
- upload.uploaded_data = file_data
- upload
- end
-
end
View
49 app/models/variation.rb
@@ -1,54 +1,5 @@
-# Holds information about how the product varies.
-#
class Variation < StoreItem
many_to_one :product
-
- # FIXME: work out why this isn't working!
- #property :variation_quantity, Fixnum, :default => 0, :nullable => false
-
- #############################################################################
- # CALLBACKS
- #############################################################################
-
- # FIXME: fix callbacks
- #before_save :set_date_available
- #after_save :update_parent_quantity
-
- # DB complains if there's not a date available set.
- # This is a cheap fix.
- def set_date_available
- self.date_available = Date.today if !self.date_available
- end
-
- def update_parent_quantity
- self.product.update_attribute('variation_quantity&#