From 27728c5eabea952194326ca02e90e2c1110bbe28 Mon Sep 17 00:00:00 2001 From: james ramm Date: Fri, 3 Feb 2017 10:04:57 +0000 Subject: [PATCH] First commit --- .coveragerc | 11 + .editorconfig | 23 ++ .github/ISSUE_TEMPLATE.md | 16 ++ .gitignore | 49 ++++ .travis.yml | 30 +++ AUTHORS.rst | 13 + CHANGELOG.rst | 9 + CONTRIBUTING.rst | 112 ++++++++ LICENSE | 14 + MANIFEST.in | 6 + Makefile | 59 ++++ README.rst | 75 ++++++ docs/Makefile | 177 ++++++++++++ docs/authors.rst | 1 + docs/conf.py | 254 ++++++++++++++++++ docs/contributing.rst | 1 + docs/history.rst | 1 + docs/index.rst | 19 ++ docs/installation.rst | 12 + docs/make.bat | 242 +++++++++++++++++ docs/readme.rst | 1 + docs/usage.rst | 26 ++ longclaw/__init__.py | 2 + longclaw/basket/__init__.py | 0 longclaw/basket/admin.py | 3 + longclaw/basket/api.py | 98 +++++++ longclaw/basket/app_settings.py | 3 + longclaw/basket/apps.py | 5 + longclaw/basket/context_processors.py | 5 + longclaw/basket/forms.py | 19 ++ longclaw/basket/migrations/0001_initial.py | 28 ++ .../migrations/0002_basketitem_product.py | 24 ++ longclaw/basket/migrations/__init__.py | 0 longclaw/basket/models.py | 36 +++ longclaw/basket/serializers.py | 21 ++ longclaw/basket/tests.py | 3 + longclaw/basket/urls.py | 20 ++ longclaw/basket/utils.py | 32 +++ longclaw/basket/views.py | 3 + longclaw/checkout/__init__.py | 0 longclaw/checkout/admin.py | 3 + longclaw/checkout/api.py | 173 ++++++++++++ longclaw/checkout/app_settings.py | 8 + longclaw/checkout/apps.py | 5 + longclaw/checkout/gateways/__init__.py | 5 + .../checkout/gateways/braintree_payment.py | 57 ++++ longclaw/checkout/gateways/stripe_payment.py | 37 +++ longclaw/checkout/migrations/0001_initial.py | 28 ++ .../0002_shippingcountry_country_name.py | 21 ++ longclaw/checkout/migrations/__init__.py | 0 longclaw/checkout/models.py | 17 ++ longclaw/checkout/serializers.py | 12 + longclaw/checkout/tests.py | 3 + longclaw/checkout/urls.py | 14 + longclaw/checkout/utils.py | 4 + longclaw/checkout/views.py | 3 + longclaw/orders/__init__.py | 0 longclaw/orders/admin.py | 3 + longclaw/orders/app_settings.py | 3 + longclaw/orders/apps.py | 5 + longclaw/orders/migrations/0001_initial.py | 52 ++++ .../migrations/0002_auto_20170107_1616.py | 26 ++ .../migrations/0003_auto_20170107_1631.py | 30 +++ .../migrations/0004_auto_20170107_1632.py | 20 ++ longclaw/orders/migrations/__init__.py | 0 longclaw/orders/models.py | 63 +++++ longclaw/orders/tests.py | 3 + longclaw/orders/views.py | 3 + longclaw/orders/wagtail_hooks.py | 17 ++ longclaw/products/__init__.py | 0 longclaw/products/admin.py | 3 + longclaw/products/apps.py | 5 + longclaw/products/migrations/0001_initial.py | 87 ++++++ longclaw/products/migrations/__init__.py | 0 longclaw/products/models.py | 89 ++++++ longclaw/products/serializers.py | 22 ++ longclaw/products/tests.py | 3 + longclaw/products/views.py | 3 + longclaw/tests/__init__.py | 0 longclaw/tests/settings.py | 36 +++ longclaw/tests/test_models.py | 25 ++ longclaw/tests/urls.py | 12 + manage.py | 12 + requirements.txt | 3 + requirements_dev.txt | 3 + requirements_test.txt | 8 + runtests.py | 26 ++ setup.cfg | 21 ++ setup.py | 79 ++++++ tox.ini | 20 ++ 90 files changed, 2525 insertions(+) create mode 100644 .coveragerc create mode 100644 .editorconfig create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 AUTHORS.rst create mode 100644 CHANGELOG.rst create mode 100644 CONTRIBUTING.rst create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 Makefile create mode 100644 README.rst create mode 100644 docs/Makefile create mode 100644 docs/authors.rst create mode 100644 docs/conf.py create mode 100644 docs/contributing.rst create mode 100644 docs/history.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/make.bat create mode 100644 docs/readme.rst create mode 100644 docs/usage.rst create mode 100644 longclaw/__init__.py create mode 100644 longclaw/basket/__init__.py create mode 100644 longclaw/basket/admin.py create mode 100644 longclaw/basket/api.py create mode 100644 longclaw/basket/app_settings.py create mode 100644 longclaw/basket/apps.py create mode 100644 longclaw/basket/context_processors.py create mode 100644 longclaw/basket/forms.py create mode 100644 longclaw/basket/migrations/0001_initial.py create mode 100644 longclaw/basket/migrations/0002_basketitem_product.py create mode 100644 longclaw/basket/migrations/__init__.py create mode 100644 longclaw/basket/models.py create mode 100644 longclaw/basket/serializers.py create mode 100644 longclaw/basket/tests.py create mode 100644 longclaw/basket/urls.py create mode 100644 longclaw/basket/utils.py create mode 100644 longclaw/basket/views.py create mode 100644 longclaw/checkout/__init__.py create mode 100644 longclaw/checkout/admin.py create mode 100644 longclaw/checkout/api.py create mode 100644 longclaw/checkout/app_settings.py create mode 100644 longclaw/checkout/apps.py create mode 100644 longclaw/checkout/gateways/__init__.py create mode 100644 longclaw/checkout/gateways/braintree_payment.py create mode 100644 longclaw/checkout/gateways/stripe_payment.py create mode 100644 longclaw/checkout/migrations/0001_initial.py create mode 100644 longclaw/checkout/migrations/0002_shippingcountry_country_name.py create mode 100644 longclaw/checkout/migrations/__init__.py create mode 100644 longclaw/checkout/models.py create mode 100644 longclaw/checkout/serializers.py create mode 100644 longclaw/checkout/tests.py create mode 100644 longclaw/checkout/urls.py create mode 100644 longclaw/checkout/utils.py create mode 100644 longclaw/checkout/views.py create mode 100644 longclaw/orders/__init__.py create mode 100644 longclaw/orders/admin.py create mode 100644 longclaw/orders/app_settings.py create mode 100644 longclaw/orders/apps.py create mode 100644 longclaw/orders/migrations/0001_initial.py create mode 100644 longclaw/orders/migrations/0002_auto_20170107_1616.py create mode 100644 longclaw/orders/migrations/0003_auto_20170107_1631.py create mode 100644 longclaw/orders/migrations/0004_auto_20170107_1632.py create mode 100644 longclaw/orders/migrations/__init__.py create mode 100644 longclaw/orders/models.py create mode 100644 longclaw/orders/tests.py create mode 100644 longclaw/orders/views.py create mode 100644 longclaw/orders/wagtail_hooks.py create mode 100644 longclaw/products/__init__.py create mode 100644 longclaw/products/admin.py create mode 100644 longclaw/products/apps.py create mode 100644 longclaw/products/migrations/0001_initial.py create mode 100644 longclaw/products/migrations/__init__.py create mode 100644 longclaw/products/models.py create mode 100644 longclaw/products/serializers.py create mode 100644 longclaw/products/tests.py create mode 100644 longclaw/products/views.py create mode 100644 longclaw/tests/__init__.py create mode 100644 longclaw/tests/settings.py create mode 100644 longclaw/tests/test_models.py create mode 100644 longclaw/tests/urls.py create mode 100644 manage.py create mode 100644 requirements.txt create mode 100644 requirements_dev.txt create mode 100644 requirements_test.txt create mode 100644 runtests.py create mode 100644 setup.cfg create mode 100755 setup.py create mode 100644 tox.ini diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..0f49c0e --- /dev/null +++ b/.coveragerc @@ -0,0 +1,11 @@ +[run] +branch = true + +[report] +omit = + *site-packages* + *tests* + *.tox* +show_missing = True +exclude_lines = + raise NotImplementedError diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..585e2ab --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.{html,css,scss,json,yml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..2cb7b56 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,16 @@ +* longclaw version: +* Django version: +* Python version: +* Operating System: + +### Description + +Describe what you were trying to get done. +Tell us what happened, what went wrong, and what you expected to happen. + +### What I Did + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c49995 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +*.py[cod] +__pycache__ +.directory +.vscode/ + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +nosetests.xml +htmlcov + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject + +# Pycharm/Intellij +.idea + +# Complexity +output/*.html +output/*/index.html + +# Sphinx +docs/_build diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..29b8899 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,30 @@ +# Config file for automatic testing at travis-ci.org + +language: python + +python: + - "3.5" + +env: + - TOX_ENV=py35-django-18 + - TOX_ENV=py34-django-18 + - TOX_ENV=py33-django-18 + - TOX_ENV=py27-django-18 + - TOX_ENV=py35-django-19 + - TOX_ENV=py34-django-19 + - TOX_ENV=py27-django-19 + - TOX_ENV=py35-django-110 + - TOX_ENV=py34-django-110 + - TOX_ENV=py27-django-110 + +matrix: + fast_finish: true + +# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors +install: pip install -r requirements_test.txt + +# command to run tests using coverage, e.g. python setup.py test +script: tox -e $TOX_ENV + +after_success: + - codecov -e TOX_ENV diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..f00d039 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* James Ramm + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CHANGELOG.rst b/CHANGELOG.rst new file mode 100644 index 0000000..97912a8 --- /dev/null +++ b/CHANGELOG.rst @@ -0,0 +1,9 @@ +.. :changelog: + +History +------- + +0.1.0 (yyyy-mm-dd) - IN DEVELOPMENT +++++++++++++++++++ + +* Initial release. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..3714452 --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,112 @@ +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every +little bit helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/JamesRamm/longclaw/issues. + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" +is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "feature" +is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +longclaw could always use more documentation, whether as part of the +official longclaw docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/JamesRamm/longclaw/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `longclaw` for local development. + +1. Fork the `longclaw` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/longclaw.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: + + $ mkvirtualenv longclaw + $ cd longclaw/ + $ python setup.py develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass flake8 and the + tests, including testing other Python versions with tox:: + + $ flake8 longclaw tests + $ python setup.py test + $ tox + + To get flake8 and tox, just pip install them into your virtualenv. + +6. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +7. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.rst. +3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check + https://travis-ci.org/JamesRamm/longclaw/pull_requests + and make sure that the tests pass for all supported Python versions. + +Tips +---- + +To run a subset of tests:: + + $ python -m unittest tests.test_longclaw diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0cbd5a8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,14 @@ + +MIT License + +Copyright (c) 2017, James Ramm + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..e4b7b25 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include HISTORY.rst +include LICENSE +include README.rst +recursive-include longclaw *.html *.png *.gif *js *.css *jpg *jpeg *svg *py diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..18933ea --- /dev/null +++ b/Makefile @@ -0,0 +1,59 @@ +.PHONY: clean-pyc clean-build docs help +.DEFAULT_GOAL := help +define BROWSER_PYSCRIPT +import os, webbrowser, sys +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}' + +clean: clean-build clean-pyc + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr *.egg-info + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + +lint: ## check style with flake8 + flake8 longclaw tests + +test: ## run tests quickly with the default Python + python runtests.py tests + +test-all: ## run tests on every Python version with tox + tox + +coverage: ## check code coverage quickly with the default Python + coverage run --source longclaw runtests.py tests + coverage report -m + coverage html + open htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + rm -f docs/longclaw.rst + rm -f docs/modules.rst + sphinx-apidoc -o docs/ longclaw + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/_build/html/index.html + +release: clean ## package and upload a release + python setup.py sdist upload + python setup.py bdist_wheel upload + +sdist: clean ## package + python setup.py sdist + ls -l dist diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..5b05011 --- /dev/null +++ b/README.rst @@ -0,0 +1,75 @@ +============================= +Longclaw +============================= + +.. image:: https://badge.fury.io/py/longclaw.svg + :target: https://badge.fury.io/py/longclaw + +.. image:: https://travis-ci.org/JamesRamm/longclaw.svg?branch=master + :target: https://travis-ci.org/JamesRamm/longclaw + +.. image:: https://codecov.io/gh/JamesRamm/longclaw/branch/master/graph/badge.svg + :target: https://codecov.io/gh/JamesRamm/longclaw + +A shop for `Wagtail CMS`_ + +Quickstart +---------- + +Install longclaw:: + + pip install longclaw + +Add it to your `INSTALLED_APPS`: + +.. code-block:: python + + INSTALLED_APPS = ( + ... + 'longclaw.products', + 'longclaw.orders', + 'longclaw.checkout', + 'longclaw.basket', + ... + ) + +Add longclaw's URL patterns: + +.. code-block:: python + +from longclaw.basket.urls import urlpatterns as basket_urls +from longclaw.checkout.urls import urlpatterns as checkout_urls + + urlpatterns = [ + ... + url(r'^/api/', include(basket_urls, namespace='longclaw')), + url(r'^/api/', include(checkout_urls, namespace='longclaw')), + ... + ] + +Features +-------- + +* TODO + +Running Tests +------------- + +Does the code actually work? + +:: + + source /bin/activate + (myenv) $ pip install tox + (myenv) $ tox + +Credits +------- + +Tools used in rendering this package: + +* Cookiecutter_ +* `cookiecutter-djangopackage`_ + +.. _Cookiecutter: https://github.com/audreyr/cookiecutter +.. _`cookiecutter-djangopackage`: https://github.com/pydanny/cookiecutter-djangopackage diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..0e35bee --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..f58506f --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,254 @@ +# -*- coding: utf-8 -*- +# +# complexity documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 9 22:26:36 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +cwd = os.getcwd() +parent = os.path.dirname(cwd) +sys.path.append(parent) + +import longclaw + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'longclaw' +copyright = u'2017, James Ramm' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = longclaw.__version__ +# The full version, including alpha/beta/rc tags. +release = longclaw.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'longclawdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'longclaw.tex', u'longclaw Documentation', + u'James Ramm', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'longclaw', u'longclaw Documentation', + [u'James Ramm'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'longclaw', u'longclaw Documentation', + u'James Ramm', 'longclaw', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..2506499 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1 @@ +.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..aeef573 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,19 @@ +.. complexity documentation master file, created by + sphinx-quickstart on Tue Jul 9 22:26:36 2013. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to longclaw's documentation! +================================================================= + +Contents: + +.. toctree:: + :maxdepth: 2 + + readme + installation + usage + contributing + authors + history diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..4406eb7 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,12 @@ +============ +Installation +============ + +At the command line:: + + $ easy_install longclaw + +Or, if you have virtualenvwrapper installed:: + + $ mkvirtualenv longclaw + $ pip install longclaw diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..2df9a8c --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/docs/readme.rst b/docs/readme.rst new file mode 100644 index 0000000..72a3355 --- /dev/null +++ b/docs/readme.rst @@ -0,0 +1 @@ +.. include:: ../README.rst diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..730a656 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,26 @@ +===== +Usage +===== + +To use longclaw in a project, add it to your `INSTALLED_APPS`: + +.. code-block:: python + + INSTALLED_APPS = ( + ... + 'longclaw.apps.LongclawConfig', + ... + ) + +Add longclaw's URL patterns: + +.. code-block:: python + + from longclaw import urls as longclaw_urls + + + urlpatterns = [ + ... + url(r'^', include(longclaw_urls)), + ... + ] diff --git a/longclaw/__init__.py b/longclaw/__init__.py new file mode 100644 index 0000000..b31ecc4 --- /dev/null +++ b/longclaw/__init__.py @@ -0,0 +1,2 @@ + +__version__ = "0.1.0" \ No newline at end of file diff --git a/longclaw/basket/__init__.py b/longclaw/basket/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/basket/admin.py b/longclaw/basket/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/longclaw/basket/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/longclaw/basket/api.py b/longclaw/basket/api.py new file mode 100644 index 0000000..acbed1e --- /dev/null +++ b/longclaw/basket/api.py @@ -0,0 +1,98 @@ +from django.apps import apps +from django.conf import settings +from rest_framework.decorators import api_view, permission_classes +from rest_framework import permissions, status +from rest_framework.response import Response +from longclaw.basket.models import BasketItem +from longclaw.basket.serializers import BasketItemSerializer +from longclaw.basket import utils +from longclaw.basket.app_settings import PRODUCT_VARIANT_MODEL + +ProductVariant = apps.get_model(*PRODUCT_VARIANT_MODEL.split('.')) + +@api_view(["GET"]) +@permission_classes([permissions.AllowAny]) +def get_basket(request): + ''' Get all basket items + ''' + items, _ = utils.get_basket_items(request) + serializer = BasketItemSerializer(items, many=True) + return Response(data=serializer.data, status=status.HTTP_200_OK) + +@api_view(["GET"]) +@permission_classes([permissions.AllowAny]) +def get_item_count(request): + ''' + Get quantity of a single item in the basket + ''' + bid = utils.basket_id(request) + item = ProductVariant.objects.get(id=request.GET["variant_id"]) + try: + count = BasketItem.objects.get(basket_id=bid, product=item).quantity + except BasketItem.DoesNotExist: + count = 0 + return Response(data={"quantity": count}, status=status.HTTP_200_OK) + +@api_view(["POST"]) +@permission_classes([permissions.AllowAny]) +def add_to_basket(request): + ''' + Add an item to the basket + ''' + variant = ProductVariant.objects.get(id=request.data["variant_id"]) + quantity = request.data.get("quantity", 1) + + items, bid = utils.get_basket_items(request) + # Check if the variant is already in the basket + in_basket = False + for item in items: + if item.product.id == variant.id: + item.increase_quantity(quantity) + in_basket = True + break + if not in_basket: + item = BasketItem(product=variant, quantity=quantity, basket_id=bid) + item.save() + + items, _ = utils.get_basket_items(request) + serializer = BasketItemSerializer(items, many=True) + return Response(data=serializer.data, + status=status.HTTP_201_CREATED) + +@api_view(["POST"]) +@permission_classes([permissions.AllowAny]) +def remove_from_basket(request): + ''' + Remove an item from the basket + ''' + print(request.data["variant_id"]) + variant = ProductVariant.objects.get(id=request.data["variant_id"]) + quantity = request.data.get("quantity", 1) + try: + item = BasketItem.objects.get(basket_id=utils.basket_id(request), product=variant) + except BasketItem.DoesNotExist: + return Response(data={"message": "Item does not exist in cart"}, + status=status.HTTP_400_BAD_REQUEST) + + if quantity >= item.quantity: + item.delete() + else: + item.decrease_quantity(quantity) + + items, _ = utils.get_basket_items(request) + serializer = BasketItemSerializer(items, many=True) + return Response(data=serializer.data, + status=status.HTTP_201_CREATED) + +@api_view(["GET"]) +@permission_classes([permissions.AllowAny]) +def basket_total_items(request): + ''' + Get total number of items in the basket + ''' + items, _ = utils.get_basket_items(request) + n_total = 0 + for item in items: + n_total += item.quantity + + return Response(data={"quantity": n_total}, status=status.HTTP_200_OK) diff --git a/longclaw/basket/app_settings.py b/longclaw/basket/app_settings.py new file mode 100644 index 0000000..0cf8707 --- /dev/null +++ b/longclaw/basket/app_settings.py @@ -0,0 +1,3 @@ +from django.conf import settings + +PRODUCT_VARIANT_MODEL = getattr(settings, 'PRODUCT_VARIANT_MODEL', 'products.ProductVariant') \ No newline at end of file diff --git a/longclaw/basket/apps.py b/longclaw/basket/apps.py new file mode 100644 index 0000000..a24107c --- /dev/null +++ b/longclaw/basket/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class BasketConfig(AppConfig): + name = 'basket' diff --git a/longclaw/basket/context_processors.py b/longclaw/basket/context_processors.py new file mode 100644 index 0000000..16ffb83 --- /dev/null +++ b/longclaw/basket/context_processors.py @@ -0,0 +1,5 @@ +from django.conf import settings # import the settings file + +def stripe_key(request): + # return the value you want as a dictionnary. you may add multiple values in there. + return {'STRIPE_KEY': settings.STRIPE_PUBLISHABLE} \ No newline at end of file diff --git a/longclaw/basket/forms.py b/longclaw/basket/forms.py new file mode 100644 index 0000000..f7c85b3 --- /dev/null +++ b/longclaw/basket/forms.py @@ -0,0 +1,19 @@ +from django import forms + + +class AddToBasketForm(forms.Form): + quantity = forms.IntegerField() + product_slug = forms.CharField(widget=forms.HiddenInput()) + variant_ref = forms.CharField(widget=forms.HiddenInput()) + + def __init__(self, request=None, *args, **kwargs): + self.request=request + super(AddToBasketForm, self).__init__(*args, **kwargs) + + def clean(self): + ''' Check user has cookies enabled + ''' + if self.request: + if not self.request.session.test_cookie_worked(): + raise forms.ValidationError("Cookies must be enabled.") + return self.cleaned_data diff --git a/longclaw/basket/migrations/0001_initial.py b/longclaw/basket/migrations/0001_initial.py new file mode 100644 index 0000000..ef2f98e --- /dev/null +++ b/longclaw/basket/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2016-12-14 14:11 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='BasketItem', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('basket_id', models.CharField(max_length=32)), + ('date_added', models.DateTimeField(auto_now_add=True)), + ('quantity', models.IntegerField(default=1)), + ], + options={ + 'ordering': ['date_added'], + }, + ), + ] diff --git a/longclaw/basket/migrations/0002_basketitem_product.py b/longclaw/basket/migrations/0002_basketitem_product.py new file mode 100644 index 0000000..ec44bcf --- /dev/null +++ b/longclaw/basket/migrations/0002_basketitem_product.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2016-12-14 14:11 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('products', '0001_initial'), + ('basket', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='basketitem', + name='product', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.ProductVariant'), + ), + ] diff --git a/longclaw/basket/migrations/__init__.py b/longclaw/basket/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/basket/models.py b/longclaw/basket/models.py new file mode 100644 index 0000000..a62e8af --- /dev/null +++ b/longclaw/basket/models.py @@ -0,0 +1,36 @@ +from django.db import models +from longclaw.basket.app_settings import PRODUCT_VARIANT_MODEL + +class BasketItem(models.Model): + basket_id = models.CharField(max_length=32) + date_added = models.DateTimeField(auto_now_add=True) + quantity = models.IntegerField(default=1) + product = models.ForeignKey(PRODUCT_VARIANT_MODEL, unique=False) + + class Meta: + ordering = ['date_added'] + + def total(self): + return self.quantity * self.product.price + + def name(self): + return "{} ({})".format(self.product.page.title, self.product.ref) + + def price(self): + return self.product.price + + def increase_quantity(self, quantity=1): + ''' Increase the quantity of this product in the basket + ''' + self.quantity += quantity + self.save() + + def decrease_quantity(self, quantity=1): + ''' + ''' + self.quantity -= quantity + if self.quantity <= 0: + self.delete() + else: + self.save() + diff --git a/longclaw/basket/serializers.py b/longclaw/basket/serializers.py new file mode 100644 index 0000000..ac32f54 --- /dev/null +++ b/longclaw/basket/serializers.py @@ -0,0 +1,21 @@ +from rest_framework import serializers + +from longclaw.products.serializers import ProductVariantSerializer +from longclaw.basket.models import BasketItem + +class BasketItemSerializer(serializers.ModelSerializer): + + product = ProductVariantSerializer() + price = serializers.SerializerMethodField() + total = serializers.SerializerMethodField() + + class Meta: + model = BasketItem + fields = "__all__" + + def get_price(self, obj): + return obj.price() + + def get_total(self, obj): + return obj.total() + \ No newline at end of file diff --git a/longclaw/basket/tests.py b/longclaw/basket/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/longclaw/basket/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/longclaw/basket/urls.py b/longclaw/basket/urls.py new file mode 100644 index 0000000..9b94ca4 --- /dev/null +++ b/longclaw/basket/urls.py @@ -0,0 +1,20 @@ +from django.conf.urls import url +from longclaw.basket import api + +urlpatterns = [ + url(r'add_to_basket/$', + api.add_to_basket, + name="add_to_basket"), + url(r'remove_from_basket/$', + api.remove_from_basket, + name="remove_from_basket"), + url(r'get_item_count/$', + api.get_item_count, + name="get_item_count"), + url(r'basket_total_items/$', + api.basket_total_items, + name="basket_total_items"), + url(r'get_basket/$', + api.get_basket, + name="get_basket"), +] \ No newline at end of file diff --git a/longclaw/basket/utils.py b/longclaw/basket/utils.py new file mode 100644 index 0000000..0b30309 --- /dev/null +++ b/longclaw/basket/utils.py @@ -0,0 +1,32 @@ +import random +from longclaw.basket.models import BasketItem + +BASKET_ID_SESSION_KEY = 'basket_id' + +_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()' + +def basket_id(request): + if request.session.get(BASKET_ID_SESSION_KEY, '') == '': + request.session[BASKET_ID_SESSION_KEY] = _generate_basket_id() + return request.session[BASKET_ID_SESSION_KEY] + +def _generate_basket_id(): + basket_id = '' + for i in range(32): + basket_id += _CHARS[random.randint(0, len(_CHARS)-1)] + return basket_id + + +def get_basket_items(request): + ''' + Get all items in the basket + ''' + bid = basket_id(request) + return BasketItem.objects.filter(basket_id=bid), bid + +def destroy_basket(request): + '''Delete all items in the basket + ''' + items, bid = get_basket_items(request) + for item in items: + item.delete() diff --git a/longclaw/basket/views.py b/longclaw/basket/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/longclaw/basket/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/longclaw/checkout/__init__.py b/longclaw/checkout/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/checkout/admin.py b/longclaw/checkout/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/longclaw/checkout/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/longclaw/checkout/api.py b/longclaw/checkout/api.py new file mode 100644 index 0000000..92df076 --- /dev/null +++ b/longclaw/checkout/api.py @@ -0,0 +1,173 @@ +''' +Shipping logic and payment capture API +''' +from django.utils.module_loading import import_string +from rest_framework.decorators import api_view, permission_classes +from rest_framework import permissions, status +from rest_framework.response import Response +from basket.utils import get_basket_items, destroy_basket +from orders.models import Order, OrderItem, Address +from checkout.models import ShippingCountry +from checkout import app_settings, serializers +from checkout.utils import PaymentError + +gateway = import_string(app_settings.PAYMENT_GATEWAY)() + +@api_view(['GET']) +@permission_classes([permissions.AllowAny]) +def create_token(request): + ''' Generic function for creating a payment token from the + payment backend. Some payment backends (e.g. braintree) support creating a payment + token, which should be imported from the backend as 'get_token' + ''' + token = gateway.get_token(request) + return Response({'token': token}, status=status.HTTP_200_OK) + + +@api_view(['POST']) +@permission_classes([permissions.AllowAny]) +def capture_payment(request): + ''' + Capture the payment for a basket and create an order + + request.data should contain: + + 'address': Dict with the following fields: + shipping_name + shipping_address_line1 + shipping_address_city + shipping_address_zip + shipping_address_country + billing_name + billing_address_line1 + billing_address_city + billing_address_zip + billing_address_country + + 'email': Email address of the customer + 'ip': IP address of the customer + 'shipping': The shipping rate (standard or premium) + ''' + + # Get the contents of the basket + items, _ = get_basket_items(request) + + # Compute basket total + total = 0 + for item in items: + total += item.total() + + # Create the address for the order + address = request.data['address'] + shipping_address, _ = Address.objects.get_or_create(name=address['shipping_name'], + line_1=address['shipping_address_line1'], + city=address['shipping_address_city'], + postcode=address['shipping_address_zip'], + country=address['shipping_address_country']) + shipping_address.save() + + address = request.data['address'] + billing_address, _ = Address.objects.get_or_create(name=address['billing_name'], + line_1=address['billing_address_line1'], + city=address['billing_address_city'], + postcode=address['billing_address_zip'], + country=address['billing_address_country']) + billing_address.save() + # Create the order + order = Order( + email=request.data['email'], + ip_address=request.data.get('ip', '0.0.0.0'), + shipping_address=shipping_address, + billing_address=billing_address + ) + order.save() + + # Create the order items + for item in items: + order_item = OrderItem( + product=item.product, + quantity=item.quantity, + order=order + ) + order_item.save() + + postage = float(request.data['shipping_rate']) + try: + gateway.create_payment(request, float(total)+postage) + # Once the order has been successfully taken, we can empty the basket + destroy_basket(request) + response = Response(data={"order_id": order.id}, status=status.HTTP_201_CREATED) + except PaymentError as err: + order.status = Order.CANCELLED + order.note = "Payment failed" + order.save() + response = Response(data={"message": err.message, "order_id": order.id}, + status=status.HTTP_400_BAD_REQUEST) + return response + +class InvalidShippingRate(Exception): + pass + +class InvalidShippingCountry(Exception): + pass + +def get_shipping_cost(country_code, option): + try: + obj = ShippingCountry.objects.get(country_code=country_code) + if option == 'standard': + return {"rate": obj.standard_rate, + "description": obj.standard_rate_description, + "carrier": obj.standard_rate_carrier} + elif option == 'premium': + return {"rate": obj.premium_rate, + "description": obj.premium_rate_description, + "carrier": obj.premium_rate_carrier} + else: + raise InvalidShippingRate + + except ShippingCountry.DoesNotExist: + if app_settings.DEFAULT_SHIPPING_ENABLED: + return {"rate": app_settings.DEFAULT_SHIPPING_RATE, + "description": "Standard shipping to rest of world", + "carrier": app_settings.DEFAULT_SHIPPING_CARRIER} + else: + raise InvalidShippingCountry + + + +@api_view(['GET']) +@permission_classes({permissions.AllowAny}) +def shipping_cost(request): + ''' Returns the shipping cost for a given country + If the shipping cost for the given country has not been set, it will + fallback to the default shipping cost if it has been enabled in the app + settings + ''' + try: + code = request.query_params.get('country_code') + except AttributeError: + return Response(data={"message": "No country code supplied"}, + status=status.HTTP_400_BAD_REQUEST) + + option = request.query_params.get('shipping_option', 'standard') + try: + data = get_shipping_cost(code, option) + response = Response(data=data, status=status.HTTP_200_OK) + except InvalidShippingRate: + response = Response(data={"message": "Shipping option {} is invalid".format(option)}, + status=status.HTTP_400_BAD_REQUEST) + except InvalidShippingCountry: + response = Response(data={"message": "Shipping to {} is not available".format(code)}, + status=status.HTTP_400_BAD_REQUEST) + + return response + + +@api_view(["GET"]) +@permission_classes([permissions.AllowAny]) +def get_shipping_countries(request): + ''' Get all shipping countries + ''' + queryset = ShippingCountry.objects.all() + serializer = serializers.ShippingCountrySerializer(queryset, many=True) + return Response(data=serializer.data, status=status.HTTP_200_OK) diff --git a/longclaw/checkout/app_settings.py b/longclaw/checkout/app_settings.py new file mode 100644 index 0000000..3d2e49f --- /dev/null +++ b/longclaw/checkout/app_settings.py @@ -0,0 +1,8 @@ +from django.conf import settings + +DEFAULT_SHIPPING_RATE = getattr(settings, 'DEFAULT_SHIPPING_RATE', 3.95) +DEFAULT_SHIPPING_CARRIER = getattr(settings, 'DEFAULT_SHIPPING_CARRIER', 'Royal Mail') +DEFAULT_SHIPPING_ENABLED = getattr(settings, 'DEFAULT_SHIPPING_ENABLED', True) + +PAYMENT_GATEWAY = getattr(settings, 'PAYMENT_GATEWAY', 'checkout.gateways.BraintreePayment') +CURRENCY = getattr(settings, "CURRENCY", "GBP") diff --git a/longclaw/checkout/apps.py b/longclaw/checkout/apps.py new file mode 100644 index 0000000..dd511d6 --- /dev/null +++ b/longclaw/checkout/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CheckoutConfig(AppConfig): + name = 'checkout' diff --git a/longclaw/checkout/gateways/__init__.py b/longclaw/checkout/gateways/__init__.py new file mode 100644 index 0000000..f12dbf2 --- /dev/null +++ b/longclaw/checkout/gateways/__init__.py @@ -0,0 +1,5 @@ +''' +Gateways module to hold payment processor backend logic +''' +from checkout.gateways.braintree_payment import BraintreePayment, PaypalVZeroPayment +from checkout.gateways.stripe_payment import StripePayment diff --git a/longclaw/checkout/gateways/braintree_payment.py b/longclaw/checkout/gateways/braintree_payment.py new file mode 100644 index 0000000..b5ec1de --- /dev/null +++ b/longclaw/checkout/gateways/braintree_payment.py @@ -0,0 +1,57 @@ +from django.conf import settings +import braintree +from longclaw.checkout import app_settings +from longclaw.checkout.utils import PaymentError + +class BraintreePayment(): + ''' + Create a payment using Braintree + ''' + def __init__(self): + braintree.Configuration.configure(braintree.Environment.Sandbox, + merchant_id=settings.BRAINTREE_MERCHANT_ID, + public_key=settings.BRAINTREE_PUBLIC_KEY, + private_key=settings.BRAINTREE_PRIVATE_KEY) + + def create_payment(self, request, amount): + nonce = request.data['payment_method_nonce'] + result = braintree.Transaction.sale({ + "amount": str(amount), + "payment_method_nonce": nonce, + "options": { + "submit_for_settlement": True + } + }) + if not result.is_success: + raise PaymentError(result) + return result + + def get_token(self, request): + # Generate client token for the dropin ui + return braintree.ClientToken.generate({}) + +class PaypalVZeroPayment(): + ''' + Create a payment using the Paypal/Braintree v.zero SDK + ''' + def __init__(self): + self.gateway = braintree.BraintreeGateway(access_token=settings.VZERO_ACCESS_TOKEN) + + def create_payment(self, request, amount, description=''): + nonce = request.data['payment_method_nonce'] + result = self.gateway.transaction.sale({ + "amount": str(amount), + "payment_method_nonce": nonce, + "merchant_account_id": app_settings.CURRENCY, + "options": { + "paypal": { + "description": description + } + } + }) + if not result.is_success: + raise PaymentError(result.message) + return result + + def get_token(self, request): + return self.gateway.client_token.generate() diff --git a/longclaw/checkout/gateways/stripe_payment.py b/longclaw/checkout/gateways/stripe_payment.py new file mode 100644 index 0000000..16ee9a1 --- /dev/null +++ b/longclaw/checkout/gateways/stripe_payment.py @@ -0,0 +1,37 @@ +import math +from django.conf import settings +import stripe +from longclaw.checkout.app_settings import CURRENCY +from longclaw.checkout.utils import PaymentError + + +class StripePayment(): + ''' + Create a payment using stripe + ''' + def __init__(self): + stripe.api_key = settings.STRIPE_SECRET + + def create_payment(self, request, amount): + try: + charge = stripe.Charge.create( + amount=int(math.ceil(amount * 100)), # Amount in pence + currency=CURRENCY.lower(), + source=request.data['token'], + description="Payment from" + ) + except stripe.error.CardError as error: + raise PaymentError(error) + + def get_token(self, request): + ''' Create a stripe token for a card + ''' + return stripe.Token.create( + card={ + "number": request.data["number"], + "exp_month": request.data["exp_month"], + "exp_year": request.data["exp_year"], + "cvc": request.data["cvc"] + + } + ) diff --git a/longclaw/checkout/migrations/0001_initial.py b/longclaw/checkout/migrations/0001_initial.py new file mode 100644 index 0000000..c160e8c --- /dev/null +++ b/longclaw/checkout/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-06 09:38 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='ShippingCountry', + fields=[ + ('country_code', models.CharField(max_length=3, primary_key=True, serialize=False)), + ('standard_rate', models.DecimalField(decimal_places=2, max_digits=12)), + ('standard_rate_carrier', models.CharField(default='Royal Mail', max_length=64)), + ('standard_rate_description', models.CharField(default='Royal Mail standard shipping', max_length=128)), + ('premium_rate', models.DecimalField(decimal_places=2, max_digits=12)), + ('premium_rate_carrier', models.CharField(default='Royal Mail', max_length=64)), + ('premium_rate_description', models.CharField(default='Royal Mail tracked and signed for', max_length=128)), + ], + ), + ] diff --git a/longclaw/checkout/migrations/0002_shippingcountry_country_name.py b/longclaw/checkout/migrations/0002_shippingcountry_country_name.py new file mode 100644 index 0000000..38b7e58 --- /dev/null +++ b/longclaw/checkout/migrations/0002_shippingcountry_country_name.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-16 08:24 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('checkout', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='shippingcountry', + name='country_name', + field=models.CharField(default='United Kingdom', max_length=32), + preserve_default=False, + ), + ] diff --git a/longclaw/checkout/migrations/__init__.py b/longclaw/checkout/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/checkout/models.py b/longclaw/checkout/models.py new file mode 100644 index 0000000..f413566 --- /dev/null +++ b/longclaw/checkout/models.py @@ -0,0 +1,17 @@ +from django.db import models + +class ShippingCountry(models.Model): + ''' Standard and premimum rate shipping for + individual countries. + ''' + country_code = models.CharField(max_length=3, primary_key=True) + country_name = models.CharField(max_length=32) + standard_rate = models.DecimalField(max_digits=12, decimal_places=2) + standard_rate_carrier = models.CharField(max_length=64, default="Royal Mail") + standard_rate_description = models.CharField(max_length=128, + default="Royal Mail standard shipping") + premium_rate = models.DecimalField(max_digits=12, decimal_places=2) + premium_rate_carrier = models.CharField(max_length=64, default="Royal Mail") + premium_rate_description = models.CharField(max_length=128, + default="Royal Mail tracked and signed for") + diff --git a/longclaw/checkout/serializers.py b/longclaw/checkout/serializers.py new file mode 100644 index 0000000..1124de2 --- /dev/null +++ b/longclaw/checkout/serializers.py @@ -0,0 +1,12 @@ +from rest_framework import serializers + +from longclaw.products.serializers import ProductVariantSerializer +from longclaw.checkout.models import ShippingCountry + +class ShippingCountrySerializer(serializers.ModelSerializer): + + class Meta: + model = ShippingCountry + fields = "__all__" + + \ No newline at end of file diff --git a/longclaw/checkout/tests.py b/longclaw/checkout/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/longclaw/checkout/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/longclaw/checkout/urls.py b/longclaw/checkout/urls.py new file mode 100644 index 0000000..7d7aa59 --- /dev/null +++ b/longclaw/checkout/urls.py @@ -0,0 +1,14 @@ +from django.conf.urls import url +from checkout import api + +urlpatterns = [ + url(r'shipping/$', + api.shipping_cost, + name='shipping'), + url(r'payment/$', + api.capture_payment, + name='payment'), + url(r'create_token/$', + api.create_token, + name='create_token') +] \ No newline at end of file diff --git a/longclaw/checkout/utils.py b/longclaw/checkout/utils.py new file mode 100644 index 0000000..63186e4 --- /dev/null +++ b/longclaw/checkout/utils.py @@ -0,0 +1,4 @@ + +class PaymentError(Exception): + def __init__(self, message): + self.message = str(message) diff --git a/longclaw/checkout/views.py b/longclaw/checkout/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/longclaw/checkout/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/longclaw/orders/__init__.py b/longclaw/orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/orders/admin.py b/longclaw/orders/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/longclaw/orders/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/longclaw/orders/app_settings.py b/longclaw/orders/app_settings.py new file mode 100644 index 0000000..0cf8707 --- /dev/null +++ b/longclaw/orders/app_settings.py @@ -0,0 +1,3 @@ +from django.conf import settings + +PRODUCT_VARIANT_MODEL = getattr(settings, 'PRODUCT_VARIANT_MODEL', 'products.ProductVariant') \ No newline at end of file diff --git a/longclaw/orders/apps.py b/longclaw/orders/apps.py new file mode 100644 index 0000000..384ab43 --- /dev/null +++ b/longclaw/orders/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class OrdersConfig(AppConfig): + name = 'orders' diff --git a/longclaw/orders/migrations/0001_initial.py b/longclaw/orders/migrations/0001_initial.py new file mode 100644 index 0000000..f8b2d5e --- /dev/null +++ b/longclaw/orders/migrations/0001_initial.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-07 15:33 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('products', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Address', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=64)), + ('line_1', models.CharField(max_length=128)), + ('line_2', models.CharField(blank=True, max_length=128)), + ('city', models.CharField(max_length=64)), + ('postcode', models.CharField(max_length=10)), + ('country', models.CharField(max_length=32)), + ], + ), + migrations.CreateModel( + name='Order', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('payment_date', models.DateTimeField()), + ('status', models.IntegerField(choices=[(1, 'Submitted'), (2, 'Fulfilled'), (3, 'Cancelled')], default=1)), + ('status_note', models.CharField(max_length=128)), + ('email', models.EmailField(max_length=128)), + ('ip_address', models.GenericIPAddressField()), + ('billing_address', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='orders_billing_address', to='orders.Address')), + ('shipping_address', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='orders_shipping_address', to='orders.Address')), + ], + ), + migrations.CreateModel( + name='OrderItem', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('quantity', models.IntegerField(default=1)), + ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orders.Order')), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.ProductVariant')), + ], + ), + ] diff --git a/longclaw/orders/migrations/0002_auto_20170107_1616.py b/longclaw/orders/migrations/0002_auto_20170107_1616.py new file mode 100644 index 0000000..38c30e2 --- /dev/null +++ b/longclaw/orders/migrations/0002_auto_20170107_1616.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-07 16:16 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('orders', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='orderitem', + name='order', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='orders.Order'), + ), + migrations.AlterField( + model_name='orderitem', + name='product', + field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='products.ProductVariant'), + ), + ] diff --git a/longclaw/orders/migrations/0003_auto_20170107_1631.py b/longclaw/orders/migrations/0003_auto_20170107_1631.py new file mode 100644 index 0000000..ba404b5 --- /dev/null +++ b/longclaw/orders/migrations/0003_auto_20170107_1631.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-07 16:31 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('orders', '0002_auto_20170107_1616'), + ] + + operations = [ + migrations.AlterField( + model_name='order', + name='ip_address', + field=models.GenericIPAddressField(blank=True, null=True), + ), + migrations.AlterField( + model_name='order', + name='payment_date', + field=models.DateTimeField(auto_now_add=True), + ), + migrations.AlterField( + model_name='order', + name='status_note', + field=models.CharField(blank=True, max_length=128, null=True), + ), + ] diff --git a/longclaw/orders/migrations/0004_auto_20170107_1632.py b/longclaw/orders/migrations/0004_auto_20170107_1632.py new file mode 100644 index 0000000..157851f --- /dev/null +++ b/longclaw/orders/migrations/0004_auto_20170107_1632.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2017-01-07 16:32 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('orders', '0003_auto_20170107_1631'), + ] + + operations = [ + migrations.AlterField( + model_name='order', + name='email', + field=models.EmailField(blank=True, max_length=128, null=True), + ), + ] diff --git a/longclaw/orders/migrations/__init__.py b/longclaw/orders/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/orders/models.py b/longclaw/orders/models.py new file mode 100644 index 0000000..e8c9118 --- /dev/null +++ b/longclaw/orders/models.py @@ -0,0 +1,63 @@ +from django.db import models +from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel +from longclaw.orders.app_settings import PRODUCT_VARIANT_MODEL + +class Address(models.Model): + name = models.CharField(max_length=64) + line_1 = models.CharField(max_length=128) + line_2 = models.CharField(max_length=128, blank=True) + city = models.CharField(max_length=64) + postcode = models.CharField(max_length=10) + country = models.CharField(max_length=32) + + panels = [ + FieldPanel('name'), + FieldPanel('line_1'), + FieldPanel('line_2'), + FieldPanel('city'), + FieldPanel('postcode'), + FieldPanel('country') + ] + + def __str__(self): + return "{}, {}, {}".format(self.name, self.city, self.country) + +class Order(models.Model): + SUBMITTED = 1 + FULFILLED = 2 + CANCELLED = 3 + ORDER_STATUSES = ((SUBMITTED, 'Submitted'), + (FULFILLED, 'Fulfilled'), + (CANCELLED, 'Cancelled')) + payment_date = models.DateTimeField(auto_now_add=True) + status = models.IntegerField(choices=ORDER_STATUSES, default=SUBMITTED) + status_note = models.CharField(max_length=128, blank=True, null=True) + + # contact info + email = models.EmailField(max_length=128, blank=True, null=True) + ip_address = models.GenericIPAddressField(blank=True, null=True) + + # shipping info + shipping_address = models.ForeignKey(Address, related_name="orders_shipping_address") + + # billing info + billing_address = models.ForeignKey(Address, blank=True, related_name="orders_billing_address") + + @property + def total(self): + total = 0 + for item in self.items_set.all(): + total += item.total + return total + +class OrderItem(models.Model): + product = models.ForeignKey(PRODUCT_VARIANT_MODEL, on_delete=models.DO_NOTHING) + quantity = models.IntegerField(default=1) + order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) + + @property + def total(self): + return self.quantity * self.product.price + + def __str__(self): + return "{} x {}".format(self.quantity, self.product.get_product_title()) diff --git a/longclaw/orders/tests.py b/longclaw/orders/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/longclaw/orders/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/longclaw/orders/views.py b/longclaw/orders/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/longclaw/orders/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/longclaw/orders/wagtail_hooks.py b/longclaw/orders/wagtail_hooks.py new file mode 100644 index 0000000..8601003 --- /dev/null +++ b/longclaw/orders/wagtail_hooks.py @@ -0,0 +1,17 @@ +from wagtail.contrib.modeladmin.options import ( + ModelAdmin, modeladmin_register +) + +from longclaw.orders.models import Order + +class OrderModelAdmin(ModelAdmin): + model = Order + menu_order = 100 + menu_icon = 'list-ul' + add_to_settings_menu = False + exclude_from_explorer = False + list_display = ('status', 'status_note', 'email', 'payment_date') + list_filter = ('status', 'payment_date', 'email') + inspect_view_enabled = True + +modeladmin_register(OrderModelAdmin) diff --git a/longclaw/products/__init__.py b/longclaw/products/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/products/admin.py b/longclaw/products/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/longclaw/products/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/longclaw/products/apps.py b/longclaw/products/apps.py new file mode 100644 index 0000000..864c43e --- /dev/null +++ b/longclaw/products/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ProductsConfig(AppConfig): + name = 'products' diff --git a/longclaw/products/migrations/0001_initial.py b/longclaw/products/migrations/0001_initial.py new file mode 100644 index 0000000..f67dc92 --- /dev/null +++ b/longclaw/products/migrations/0001_initial.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2016-12-14 14:11 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion +import django_extensions.db.fields +import modelcluster.contrib.taggit +import modelcluster.fields +import wagtail.wagtailcore.fields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('wagtailcore', '0030_index_on_pagerevision_created_at'), + ('wagtailimages', '0015_fill_filter_spec_field'), + ('taggit', '0002_auto_20150616_2121'), + ] + + operations = [ + migrations.CreateModel( + name='Product', + fields=[ + ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), + ('description', wagtail.wagtailcore.fields.RichTextField()), + ], + options={ + 'abstract': False, + }, + bases=('wagtailcore.page',), + ), + migrations.CreateModel( + name='ProductImage', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('sort_order', models.IntegerField(blank=True, editable=False, null=True)), + ('caption', models.CharField(blank=True, max_length=255)), + ('image', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='wagtailimages.Image')), + ('page', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='products.Product')), + ], + options={ + 'ordering': ['sort_order'], + 'abstract': False, + }, + ), + migrations.CreateModel( + name='ProductIndex', + fields=[ + ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), + ], + options={ + 'abstract': False, + }, + bases=('wagtailcore.page',), + ), + migrations.CreateModel( + name='ProductTag', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('content_object', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='tagged_items', to='products.Product')), + ('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products_producttag_items', to='taggit.Tag')), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='ProductVariant', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('ref', models.CharField(max_length=32)), + ('description', wagtail.wagtailcore.fields.RichTextField()), + ('price', models.DecimalField(decimal_places=2, max_digits=12)), + ('stock', models.IntegerField(default=0)), + ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('page', 'ref'), separator='')), + ('page', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')), + ], + ), + migrations.AddField( + model_name='product', + name='tags', + field=modelcluster.contrib.taggit.ClusterTaggableManager(blank=True, help_text='A comma-separated list of tags.', through='products.ProductTag', to='taggit.Tag', verbose_name='Tags'), + ), + ] diff --git a/longclaw/products/migrations/__init__.py b/longclaw/products/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/products/models.py b/longclaw/products/models.py new file mode 100644 index 0000000..5eddd67 --- /dev/null +++ b/longclaw/products/models.py @@ -0,0 +1,89 @@ +from django.db import models +from django_extensions.db.fields import AutoSlugField + +from modelcluster.fields import ParentalKey +from modelcluster.tags import ClusterTaggableManager +from taggit.models import TaggedItemBase + +from wagtail.wagtailcore.models import Page, Orderable +from wagtail.wagtailcore.fields import RichTextField +from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel +from wagtail.wagtailimages.edit_handlers import ImageChooserPanel +from wagtail.wagtailsearch import index + +class ProductIndex(Page): + pass + +class ProductTag(TaggedItemBase): + content_object = ParentalKey('Product', related_name='tagged_items') + +class Product(Page): + description = RichTextField() + tags = ClusterTaggableManager(through=ProductTag, blank=True) + + search_fields = Page.search_fields + [ + index.RelatedFields('tags', [ + index.SearchField('name', partial_match=True, boost=10), + ]), + ] + + content_panels = Page.content_panels + [ + FieldPanel('description'), + InlinePanel('variants', label='Product variants'), + InlinePanel('images', label='Product images'), + FieldPanel('tags'), + ] + + @property + def first_image(self): + return self.images.first() + + @property + def price_range(self): + ''' Calculate the price range of the products variants + ''' + ordered = self.variants.order_by('price') + if ordered: + return ordered.first().price, ordered.last().price + else: + return None, None + + @property + def in_stock(self): + ''' Returns True if any of the product variants are in stock + ''' + return any(self.variants.filter(stock__gt=0)) + +class ProductVariantBase(models.Model): + """ + Base model for creating product variants + """ + product = ParentalKey(Product, related_name='variants') + price = models.DecimalField(max_digits=12, decimal_places=2) + + class Meta: + abstract = True + + def get_product_title(self): + return self.product.title + + +class ProductVariant(ProductVariantBase): + ref = models.CharField(max_length=32) + description = RichTextField() + stock = models.IntegerField(default=0) + slug = AutoSlugField( + separator='', + populate_from=('product', 'ref'), + ) + +class ProductImage(Orderable): + + product = ParentalKey(Product, related_name='images') + image = models.ForeignKey('wagtailimages.Image', on_delete=models.CASCADE, related_name='+') + caption = models.CharField(blank=True, max_length=255) + + panels = [ + ImageChooserPanel('image'), + FieldPanel('caption') + ] diff --git a/longclaw/products/serializers.py b/longclaw/products/serializers.py new file mode 100644 index 0000000..aa005d4 --- /dev/null +++ b/longclaw/products/serializers.py @@ -0,0 +1,22 @@ +from django.conf import settings +from django.apps import apps +from rest_framework import serializers +from longclaw.products.models import Product + +PRODUCT_VARIANT_MODEL = getattr(settings, 'PRODUCT_VARIANT_MODEL', 'products.ProductVariant') +ProductVariant = apps.get_model(*PRODUCT_VARIANT_MODEL.split('.')) + +class ProductSerializer(serializers.ModelSerializer): + + class Meta: + model = Product + fields = "__all__" + + +class ProductVariantSerializer(serializers.ModelSerializer): + + page = ProductSerializer() + + class Meta: + model = ProductVariant + fields = "__all__" diff --git a/longclaw/products/tests.py b/longclaw/products/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/longclaw/products/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/longclaw/products/views.py b/longclaw/products/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/longclaw/products/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/longclaw/tests/__init__.py b/longclaw/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/longclaw/tests/settings.py b/longclaw/tests/settings.py new file mode 100644 index 0000000..1b55c28 --- /dev/null +++ b/longclaw/tests/settings.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 +from __future__ import unicode_literals, absolute_import + +import django + +DEBUG = True +USE_TZ = True + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": ":memory:", + } +} + +ROOT_URLCONF = "tests.urls" + +INSTALLED_APPS = [ + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sites", + "longclaw.products", + "longclaw.orders", + "longclaw.checkout", + "longclaw.basket", +] + +SITE_ID = 1 + +if django.VERSION >= (1, 10): + MIDDLEWARE = () +else: + MIDDLEWARE_CLASSES = () diff --git a/longclaw/tests/test_models.py b/longclaw/tests/test_models.py new file mode 100644 index 0000000..1581121 --- /dev/null +++ b/longclaw/tests/test_models.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +test_longclaw +------------ + +Tests for `longclaw` models module. +""" + +from django.test import TestCase + +from longclaw import models + + +class TestLongclaw(TestCase): + + def setUp(self): + pass + + def test_something(self): + pass + + def tearDown(self): + pass diff --git a/longclaw/tests/urls.py b/longclaw/tests/urls.py new file mode 100644 index 0000000..af4cec7 --- /dev/null +++ b/longclaw/tests/urls.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 +from __future__ import unicode_literals, absolute_import + +from django.conf.urls import url, include + +from longclaw.basket.urls import urlpatterns as basket_urls +from longclaw.checkout.urls import urlpatterns as checkout_urls + +urlpatterns = [ + url(r'^', include(basket_urls, namespace='longclaw')), + url(r'^', include(checkout_urls, namespace='longclaw')), +] diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..8c5be8a --- /dev/null +++ b/manage.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, absolute_import + +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") + from django.core.management import execute_from_command_line + + execute_from_command_line(sys.argv) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3103d40 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ + +# Additional requirements go here +django-rest-framework \ No newline at end of file diff --git a/requirements_dev.txt b/requirements_dev.txt new file mode 100644 index 0000000..aa8fd53 --- /dev/null +++ b/requirements_dev.txt @@ -0,0 +1,3 @@ +bumpversion==0.5.3 +wheel==0.29.0 + diff --git a/requirements_test.txt b/requirements_test.txt new file mode 100644 index 0000000..539f505 --- /dev/null +++ b/requirements_test.txt @@ -0,0 +1,8 @@ +coverage==4.3.3 +mock>=1.0.1 +flake8>=2.1.0 +tox>=1.7.0 +codecov>=2.0.0 + + +# Additional test requirements go here diff --git a/runtests.py b/runtests.py new file mode 100644 index 0000000..14ad034 --- /dev/null +++ b/runtests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 +from __future__ import unicode_literals, absolute_import + +import os +import sys + +import django +from django.conf import settings +from django.test.utils import get_runner + + +def run_tests(*test_args): + if not test_args: + test_args = ['tests'] + + os.environ['DJANGO_SETTINGS_MODULE'] = 'longclaw.tests.settings' + django.setup() + TestRunner = get_runner(settings) + test_runner = TestRunner() + failures = test_runner.run_tests(test_args) + sys.exit(bool(failures)) + + +if __name__ == '__main__': + run_tests(*sys.argv[1:]) diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..c8728aa --- /dev/null +++ b/setup.cfg @@ -0,0 +1,21 @@ +[bumpversion] +current_version = 0.1.0 +commit = True +tag = True + +[bumpversion:file:setup.py] + +[bumpversion:file:longclaw/__init__.py] + +[wheel] +universal = 1 + +[flake8] +ignore = D203 +exclude = + .git, + .tox + docs/source/conf.py, + build, + dist +max-line-length = 119 diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..f2bad34 --- /dev/null +++ b/setup.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import os +import re +import sys + +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + + +def get_version(*file_paths): + """Retrieves the version from longclaw/__init__.py""" + filename = os.path.join(os.path.dirname(__file__), *file_paths) + version_file = open(filename).read() + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", + version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError('Unable to find version string.') + + +version = get_version("longclaw", "__init__.py") + + +if sys.argv[-1] == 'publish': + try: + import wheel + print("Wheel version: ", wheel.__version__) + except ImportError: + print('Wheel library missing. Please run "pip install wheel"') + sys.exit() + os.system('python setup.py sdist upload') + os.system('python setup.py bdist_wheel upload') + sys.exit() + +if sys.argv[-1] == 'tag': + print("Tagging the version on git:") + os.system("git tag -a %s -m 'version %s'" % (version, version)) + os.system("git push --tags") + sys.exit() + +readme = open('README.rst').read() +history = open('CHANGELOG.rst').read().replace('.. :changelog:', '') + +setup( + name='longclaw', + version=version, + description="""A shop for wagtail cms""", + long_description=readme + '\n\n' + history, + author='James Ramm', + author_email='jamessramm@gmail.com', + url='https://github.com/JamesRamm/longclaw', + packages=[ + 'longclaw', + ], + include_package_data=True, + install_requires=[], + license="MIT", + zip_safe=False, + keywords='longclaw', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Framework :: Django', + 'Framework :: Django :: 1.8', + 'Framework :: Django :: 1.9', + 'Framework :: Django :: 1.10', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + ], +) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..a0720d6 --- /dev/null +++ b/tox.ini @@ -0,0 +1,20 @@ +[tox] +envlist = + {py27,py33,py34,py35}-django-18 + {py27,py34,py35}-django-19 + {py27,py34,py35}-django-110 + +[testenv] +setenv = + PYTHONPATH = {toxinidir}:{toxinidir}/longclaw +commands = coverage run --source longclaw runtests.py +deps = + django-18: Django>=1.8,<1.9 + django-19: Django>=1.9,<1.10 + django-110: Django>=1.10 + -r{toxinidir}/requirements_test.txt +basepython = + py35: python3.5 + py34: python3.4 + py33: python3.3 + py27: python2.7