commit 351d98c5236237531d0b400035e204d3099e01f9 Author: Marcus Lindvall Date: Wed Oct 18 16:35:10 2017 +0200 Initial commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e6c5909 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,76 @@ +# Git +.git +.gitignore + +# CI +.gitlab-ci.yml + +# Docker +docker-compose.yml +.docker + +# Byte-compiled / optimized / DLL files +__pycache__/ +*/__pycache__/ +*/*/__pycache__/ +*/*/*/__pycache__/ +*.py[cod] +*/*.py[cod] +*/*/*.py[cod] +*/*/*/*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Virtual environment +.env/ +.venv/ +venv/ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..abb07a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +*.py[cod] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +wheelhouse +develop-eggs +.installed.cfg +lib +lib64 +venv*/ +pyvenv*/ +env*/ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox +.coverage.* +nosetests.xml +coverage.xml +htmlcov + +# Translations +*.mo + +# Mr Developer +.mr.developer.cfg +.project +.pydevproject +.idea +*.iml +*.komodoproject + +# Complexity +output/*.html +output/*/index.html + +# Sphinx +docs/_build + +.DS_Store +*~ +.*.sw[po] +.build +.ve +.env +.cache +.pytest +.bootstrap +.appveyor.token +*.bak + +*.log +*.xls \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d70c98a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM python:3-alpine + +LABEL description="PyJeeves syncronization application" \ + maintainer="Marcus Lindvall " + +RUN apk add --no-cache build-base freetds-dev git \ + && pip install --no-cache-dir git+https://github.com/pymssql/pymssql.git \ + && apk del --purge build-base freetds-dev git + +RUN apk add --no-cache freetds + +WORKDIR /app +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir -r requirements.txt + +COPY . /app + +RUN pip install -e . + +CMD [ "python", "./pyjeeves/main.py" ] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..12ad470 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +Copyright (c) 2017, Lindvalls Kaffe AB + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..997cfaa --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +init: + pip install -r requirements.txt + +test: + nosetests tests diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..830553d --- /dev/null +++ b/README.rst @@ -0,0 +1,22 @@ +PyJeeves Module +=============== + +This project is a Jeeves data extraction and integration project. + + +## Initial creation of database schema. + +´docker run --link db --network marcus_default -v /srv/pyjeeves/config.yml:/app/config.yml gitlab.lndvll.se:5500/lindvallskaffe/pyjeeves python ./pyjeeves/db.py´ + + +## Connecting to DB with client + +´docker run -it --network marcus_default --link db:mysql --rm mysql sh -c 'exec mysql -h"db" -P"3306" -uroot -p"ROOT_PW"'´ + + +## Forcing updates + +You may force updates of objects by setting RowUpdatedDt to null. +For example: +´update jvs_customers set RowUpdatedDt = null;´ + diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..3ffd367 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,5 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..8ed958c --- /dev/null +++ b/config.yml @@ -0,0 +1,50 @@ +sync_interval: 60 + +mysql: + host: localhost + port: 3306 + user: pyjeeves + passwd: jeeves + db: pyjeeves + +jeeves_db: + server: 'BlackSheep01' + database: 'LKTest' + user: 'jvsdbo' + password: 'password' + +logging: + version: 1 + handlers: + fileHandler: + class: logging.FileHandler + formatter: simpleFormatter + filename: pyjeeves.log + level: INFO + consoleHandler: + class: logging.StreamHandler + level: DEBUG + formatter: simpleFormatter + stream: ext://sys.stdout + loggers: + PyJeeves: + handlers: + - fileHandler + - consoleHandler + level: DEBUG + alembic: + handlers: + - consoleHandler + level: INFO + sqlalchemy: + handlers: + - consoleHandler + level: WARN + qualname: sqlalchemy.engine + formatters: + simpleFormatter: + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + +alembic: + script_location: migrations + sqlalchemy.url: 'mysql+pymysql://pyjeeves:jeeves@localhost/pyjeeves' diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f02bda0 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,52 @@ +version: '2' + +services: + db: + image: mysql + restart: always + environment: + MYSQL_ROOT_PASSWORD: rootpassword + MYSQL_USER: pyjeeves + MYSQL_PASSWORD: jeeves + MYSQL_DATABASE: pyjeeves + + pyjeeves: + container_name: pyjeeves + build: ./ + image: gitlab.lndvll.se:5500/lindvallskaffe/pyjeeves + links: + - db + volumes: + - ./config.yml:/app/config.yml + - ./:/app/ + + metabase: + image: metabase/metabase + container_name: metabase + restart: unless-stopped + ports: + - 80:3000 + links: + - postgres + - db + volumes: + - ./metabase/tmp:/tmp + environment: + - MB_DB_TYPE=postgres + - MB_DB_DBNAME=metabase + - MB_DB_PORT=5432 + - MB_DB_USER=metabase + - MB_DB_PASS="m3t@b@s3" + - MB_DB_HOST=postgres + - JAVA_TIMEZONE=Europe/Stockholm + + postgres: + image: postgres:9-alpine + container_name: postgres + restart: unless-stopped + volumes: + - ./postgresql/data:/var/lib/postgresql/data + environment: + - POSTGRES_DB=metabase + - POSTGRES_USER=metabase + - POSTGRES_PASSWORD="m3t@b@s3" \ No newline at end of file diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..f828634 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# 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 " 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 " 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/sample.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/sample.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/sample" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/sample" + @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." + +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." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..ac03bd0 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# +# sample documentation build configuration file, created by +# sphinx-quickstart on Mon Apr 16 21:22:43 2012. +# +# 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('.')) + +# -- 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 = [] + +# 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'sample' +copyright = u'2012, Kenneth Reitz' + +# 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 = 'v0.0.1' +# The full version, including alpha/beta/rc tags. +release = 'v0.0.1' + +# 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 = [] + + +# -- 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 = 'sampledoc' + + +# -- 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', 'sample.tex', u'sample Documentation', + u'Kenneth Reitz', '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', 'sample', u'sample Documentation', + [u'Kenneth Reitz'], 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', 'sample', u'sample Documentation', + u'Kenneth Reitz', 'sample', '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' diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..46f3fe8 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,22 @@ +.. sample documentation master file, created by + sphinx-quickstart on Mon Apr 16 21:22:43 2012. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to sample's documentation! +================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..deed45a --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,190 @@ +@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. 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 +) + +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\sample.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\sample.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" == "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 +) + +:end diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..6c8ea19 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,70 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import dictConfig + +import yaml +from pyjeeves.models.jvsmodels import Base + + +# Read the config file +with open("config.yml", 'r') as ymlfile: + cfg = yaml.load(ymlfile) + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +dictConfig(cfg.get('logging')) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = Base.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = cfg.get('alembic', {}).get("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + cfg.get('alembic', {}), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/18b08d122636_initial_creation_of_db.py b/migrations/versions/18b08d122636_initial_creation_of_db.py new file mode 100644 index 0000000..78e90d0 --- /dev/null +++ b/migrations/versions/18b08d122636_initial_creation_of_db.py @@ -0,0 +1,145 @@ +"""Initial creation of DB + +Revision ID: 18b08d122636 +Revises: +Create Date: 2017-10-17 11:06:14.745786 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '18b08d122636' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'jvs_articles', + sa.Column('ArtNr', sa.String(length=16), nullable=False), + sa.Column('ForetagKod', sa.SmallInteger(), nullable=False), + sa.Column('ArtBeskr', sa.String(length=128), nullable=True), + sa.Column('ArtBeskr2', sa.String(length=256), nullable=True), + sa.Column('ArtBeskrSpec', sa.String(length=128), nullable=True), + sa.Column('ArtProdKonto', sa.String(length=8), nullable=True), + sa.Column('ArtProdKontoBeskr', sa.String(length=64), nullable=True), + sa.Column('VaruGruppKod', sa.String(length=8), nullable=True), + sa.Column('VaruGruppBeskr', sa.String(length=64), nullable=True), + sa.Column('ArtProdKlass', sa.String(length=8), nullable=True), + sa.Column('ArtProdklBeskr', sa.String(length=64), nullable=True), + sa.Column('ArtKod', sa.SmallInteger(), nullable=True), + sa.Column('ArtTypBeskr', sa.String(length=64), nullable=True), + sa.Column('LagTyp', sa.SmallInteger(), nullable=True), + sa.Column('EnhetsKod', sa.String(length=8), nullable=True), + sa.Column('LevNr', sa.String(length=16), nullable=True), + sa.Column('ItemStatusCode', sa.Integer(), nullable=True), + sa.Column('LagSaldoArtikel', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('RowCreatedDt', sa.DateTime(), nullable=True), + sa.Column('RowCreatedBy', sa.String(length=16), nullable=True), + sa.Column('RowUpdatedDt', sa.DateTime(), nullable=True), + sa.Column('RowUpdatedBy', sa.String(length=16), nullable=True), + sa.PrimaryKeyConstraint('ArtNr', 'ForetagKod', name='articles_primary_key') + ) + op.create_table( + 'jvs_customers', + sa.Column('FtgNr', sa.String(length=16), nullable=False), + sa.Column('ForetagKod', sa.SmallInteger(), nullable=False), + sa.Column('BetKod', sa.String(length=8), nullable=True), + sa.Column('kundbetalarenr', sa.String(length=16), nullable=True), + sa.Column('RowCreatedDt', sa.DateTime(), nullable=True), + sa.Column('RowCreatedBy', sa.String(length=16), nullable=True), + sa.Column('RowUpdatedDt', sa.DateTime(), nullable=True), + sa.Column('RowUpdatedBy', sa.String(length=16), nullable=True), + sa.Column('Saljare', sa.String(length=32), nullable=True), + sa.Column('SaljareNamn', sa.String(length=64), nullable=True), + sa.Column('KundKategoriKod', sa.SmallInteger(), nullable=True), + sa.Column('KundKatBeskr', sa.String(length=64), nullable=True), + sa.Column('OrgNr', sa.String(length=32), nullable=True), + sa.Column('FtgNamn', sa.String(length=64), nullable=True), + sa.Column('FtgPostAdr1', sa.String(length=64), nullable=True), + sa.Column('FtgPostAdr2', sa.String(length=64), nullable=True), + sa.Column('FtgPostAdr3', sa.String(length=64), nullable=True), + sa.Column('FtgPostadr4', sa.String(length=64), nullable=True), + sa.Column('FtgPostadr5', sa.String(length=128), nullable=True), + sa.Column('FtgPostnr', sa.String(length=16), nullable=True), + sa.Column('LandsKod', sa.String(length=16), nullable=True), + sa.Column('FtgPostLevAdr3', sa.String(length=64), nullable=True), + sa.Column('FtgLevPostNr', sa.String(length=16), nullable=True), + sa.PrimaryKeyConstraint('FtgNr', 'ForetagKod', name='customers_primary_key') + ) + op.create_table( + 'jvs_invoice_rows', + sa.Column('FaktNr', sa.BigInteger(), nullable=False), + sa.Column('FaktRadnr', sa.Integer(), nullable=False), + sa.Column('ForetagKod', sa.SmallInteger(), nullable=False), + sa.Column('FtgNr', sa.String(length=16), nullable=True), + sa.Column('OrderNr', sa.BigInteger(), nullable=True), + sa.Column('OrdTyp', sa.SmallInteger(), nullable=True), + sa.Column('Saljare', sa.String(length=16), nullable=True), + sa.Column('KundKategoriKod', sa.SmallInteger(), nullable=True), + sa.Column('ArtNr', sa.String(length=16), nullable=True), + sa.Column('EnhetsKod', sa.String(length=8), nullable=True), + sa.Column('VaruGruppKod', sa.String(length=8), nullable=True), + sa.Column('Redovisnar', sa.SmallInteger(), nullable=True), + sa.Column('Period', sa.SmallInteger(), nullable=True), + sa.Column('FaktDat', sa.DateTime(), nullable=True), + sa.Column('FaktTB', sa.Numeric(precision=19, scale=4), nullable=True), + sa.Column('FaktTG', sa.Numeric(precision=8, scale=3), nullable=True), + sa.Column('FaktLevAnt', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('FaktLevAntAltEnh', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('FPris', sa.Numeric(precision=19, scale=4), nullable=True), + sa.Column('FaktRadSumma', sa.Numeric(precision=19, scale=4), nullable=True), + sa.Column('ValKod', sa.String(length=3), nullable=True), + sa.Column('ValKurs', sa.Numeric(precision=22, scale=14), nullable=True), + sa.Column('RowCreatedDt', sa.DateTime(), nullable=True), + sa.Column('RowUpdatedDt', sa.DateTime(), nullable=True), + sa.Column('RowUpdatedBy', sa.String(length=16), nullable=True), + sa.ForeignKeyConstraint(['FtgNr'], ['jvs_customers.FtgNr'], ), + sa.PrimaryKeyConstraint( + 'FaktNr', 'FaktRadnr', 'ForetagKod', name='invoice_rows_primary_key') + ) + op.create_table( + 'jvs_order_rows', + sa.Column('OrderNr', sa.BigInteger(), nullable=False), + sa.Column('OrdRadnr', sa.Integer(), nullable=False), + sa.Column('OrdRadNrStrPos', sa.Integer(), nullable=False), + sa.Column('OrdRestNr', sa.SmallInteger(), nullable=False), + sa.Column('ForetagKod', sa.SmallInteger(), nullable=False), + sa.Column('ArtNr', sa.String(length=16), nullable=True), + sa.Column('FtgNr', sa.String(length=16), nullable=True), + sa.Column('vb_pris', sa.Numeric(precision=19, scale=4), nullable=True), + sa.Column('OrdAntal', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('OrdAntalAltEnh', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('AltEnhetKod', sa.String(length=16), nullable=True), + sa.Column('OrdLevAntal', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('OrdLevAntalAltEnh', sa.Numeric(precision=15, scale=6), nullable=True), + sa.Column('FaktNr', sa.BigInteger(), nullable=True), + sa.Column('OrdDatum', sa.DateTime(), nullable=True), + sa.Column('OrdBerLevDat', sa.DateTime(), nullable=True), + sa.Column('OrdBerednDat', sa.DateTime(), nullable=True), + sa.Column('OrdLevDat', sa.DateTime(), nullable=True), + sa.Column('Saljare', sa.String(length=32), nullable=True), + sa.Column('SaljareNamn', sa.String(length=64), nullable=True), + sa.Column('OrdRadSt', sa.SmallInteger(), nullable=True), + sa.Column('OrdRStatBeskr', sa.String(length=64), nullable=True), + sa.Column('OrdTyp', sa.SmallInteger(), nullable=True), + sa.Column('OrdTypBeskr', sa.String(length=64), nullable=True), + sa.Column('RowCreatedDt', sa.DateTime(), nullable=True), + sa.Column('RowCreatedBy', sa.String(length=16), nullable=True), + sa.Column('RowUpdatedDt', sa.DateTime(), nullable=True), + sa.Column('RowUpdatedBy', sa.String(length=16), nullable=True), + sa.ForeignKeyConstraint(['FtgNr'], ['jvs_customers.FtgNr'], ), + sa.PrimaryKeyConstraint( + 'OrderNr', 'OrdRadnr', 'OrdRadNrStrPos', + 'OrdRestNr', 'ForetagKod', name='order_rows_primary_key') + ) + + +def downgrade(): + op.drop_table('jvs_order_rows') + op.drop_table('jvs_invoice_rows') + op.drop_table('jvs_customers') + op.drop_table('jvs_articles') diff --git a/migrations/versions/65b6accf25bd_add_customerclasses_to_customers.py b/migrations/versions/65b6accf25bd_add_customerclasses_to_customers.py new file mode 100644 index 0000000..c2e2178 --- /dev/null +++ b/migrations/versions/65b6accf25bd_add_customerclasses_to_customers.py @@ -0,0 +1,28 @@ +"""Add CustomerClasses to Customers + +Revision ID: 65b6accf25bd +Revises: 18b08d122636 +Create Date: 2017-10-17 13:48:46.424978 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '65b6accf25bd' +down_revision = '18b08d122636' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + 'jvs_customers', sa.Column('KundKlassBeskr', sa.String(length=64), nullable=True)) + op.add_column( + 'jvs_customers', sa.Column('Kundklass', sa.String(length=16), nullable=True)) + + +def downgrade(): + op.drop_column('jvs_customers', 'Kundklass') + op.drop_column('jvs_customers', 'KundKlassBeskr') diff --git a/migrations/versions/6b35aaafded7_support_disabled_flag_for_customers.py b/migrations/versions/6b35aaafded7_support_disabled_flag_for_customers.py new file mode 100644 index 0000000..8541d3f --- /dev/null +++ b/migrations/versions/6b35aaafded7_support_disabled_flag_for_customers.py @@ -0,0 +1,30 @@ +"""Support 'disabled' flag for Customers + +Revision ID: 6b35aaafded7 +Revises: 65b6accf25bd +Create Date: 2017-10-17 15:23:48.164464 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6b35aaafded7' +down_revision = '65b6accf25bd' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('jvs_customers', sa.Column('MakDateTime', sa.DateTime(), nullable=True)) + op.add_column('jvs_customers', sa.Column('Makulerad', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('jvs_customers', 'Makulerad') + op.drop_column('jvs_customers', 'MakDateTime') + # ### end Alembic commands ### diff --git a/pyjeeves/__init__.py b/pyjeeves/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pyjeeves/db.py b/pyjeeves/db.py new file mode 100644 index 0000000..840d3c5 --- /dev/null +++ b/pyjeeves/db.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +from sqlalchemy import create_engine +from sqlalchemy.orm.session import Session + +from models.jvsmodels import Base + + +class MySQLSession(Session): + """docstring for MySQLSession""" + def __init__(self, settings): + self.engine = create_engine( + 'mysql+pymysql://{user}:{passwd}@{host}:{port}/{db}'.format(**settings)) + super(MySQLSession, self).__init__(bind=self.engine) + + def create_db(self): + Base.metadata.create_all(self.engine) + + +if __name__ == '__main__': + import yaml + with open("config.yml", 'r') as ymlfile: + cfg = yaml.load(ymlfile) + + session = MySQLSession(cfg['mysql']) + session.create_db() diff --git a/pyjeeves/jvsquery.py b/pyjeeves/jvsquery.py new file mode 100644 index 0000000..f866a31 --- /dev/null +++ b/pyjeeves/jvsquery.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +""" + pyjeeves.jvsquery + ~~~~~~~~~~~~~~~~~~~~~~ + + Jeeves data queries +""" +import pymssql +import datetime +import logging + + +class JvsQuery(): + """docstring for JvsQuery""" + def __init__(self, settings): + super(JvsQuery, self).__init__() + self.settings = settings + self.logger = logging.getLogger("PyJeeves.jvsquery") + + def _execute(self, query="", params=(), iterator=True): + with pymssql.connect(**self.settings) as conn: + with conn.cursor(as_dict=True) as cursor: + cursor.execute(query, params) + if iterator: + for row in cursor: + if cursor.rownumber % 1000 == 0 and cursor.rownumber != 0: + self.logger.debug("Cursor is at pos %d" % cursor.rownumber) + yield row + else: + return cursor.fetchall() + + def _ft(self, updated_dt='2000-01-01 00:00:00.000', + created_dt='2000-01-01 00:00:00.000', limit=None): + query = ( + """SELECT FaktNr, FaktRadnr, ForetagKod, FtgNr, OrderNr, OrdTyp, Saljare, + KundKategoriKod, ArtNr, EnhetsKod, VaruGruppKod, Redovisnar, Period, FaktTB, + FaktTG, FaktLevAnt, FaktLevAntAltEnh, FPris, FaktRadSumma, ValKod, ValKurs, + RowCreatedDt, RowUpdatedDt, RowUpdatedBy, FaktDat + FROM ft + WHERE ft.ForetagKod = 1 + AND (ft.RowCreatedDt > %(created_dt)s + OR ft.RowUpdatedDt > %(updated_dt)s)""") + params = {'created_dt': created_dt, 'updated_dt': updated_dt} + + return self._execute(query, params) + + def _orp(self, updated_dt='2000-01-01 00:00:00.000', + created_dt='2000-01-01 00:00:00.000', limit=None): + query = ( + """SELECT orp.OrderNr, OrdRadnr, OrdRadNrStrPos, orp.OrdRestNr, orp.ForetagKod, + ArtNr, orp.FtgNr, vb_pris, + OrdAntal, OrdAntalAltEnh, AltEnhetKod, OrdLevAntal, OrdLevAntalAltEnh, + orp.FaktNr, orp.OrdDatum, orp.OrdBerLevDat, orp.OrdBerednDat, orp.OrdLevDat, + orp.RowUpdatedBy, orp.RowUpdatedDt, orp.RowCreatedBy, orp.RowCreatedDt, + salj.Saljare, salj.SaljareNamn, + xs.OrdRadSt, xs.OrdRStatBeskr, x6.OrdTyp, x6.OrdTypBeskr + FROM orp + LEFT OUTER JOIN oh ON oh.OrderNr = orp.OrderNr + AND oh.ForetagKod = orp.ForetagKod + LEFT OUTER JOIN salj ON salj.Saljare = orp.Saljare + AND salj.ForetagKod = orp.ForetagKod + LEFT OUTER JOIN xs ON xs.OrdRadSt = orp.OrdRadSt + AND xs.ForetagKod = orp.ForetagKod + LEFT OUTER JOIN x6 ON x6.OrdTyp = orp.OrdTyp + AND x6.ForetagKod = orp.ForetagKod + WHERE orp.ForetagKod = 1 + AND (oh.RowCreatedDt > %(created_dt)s + OR oh.RowUpdatedDt > %(updated_dt)s + OR salj.RowCreatedDt > %(created_dt)s + OR salj.RowUpdatedDt > %(updated_dt)s + OR xs.RowCreatedDt > %(created_dt)s + OR xs.RowUpdatedDt > %(updated_dt)s + OR x6.RowCreatedDt > %(created_dt)s + OR x6.RowUpdatedDt > %(updated_dt)s)""") + params = {'created_dt': created_dt, 'updated_dt': updated_dt} + + return self._execute(query, params) + + def _ar(self, limit=None): + query = ( + """SELECT ArtNr, ar.VaruGruppKod, VaruGruppBeskr, ArtBeskr, ArtBeskr2, ArtBeskrSpec, + ar.ArtProdKlass, ArtProdklBeskr, ar.ArtProdKonto, ArtProdKontoBeskr, ar.ArtKod, + ArtTypBeskr, LagTyp, EnhetsKod, LevNr, ItemStatusCode, LagSaldoArtikel, + ar.RowUpdatedBy, ar.RowUpdatedDt, ar.RowCreatedBy, ar.RowCreatedDt, ar.ForetagKod + FROM ar + LEFT OUTER JOIN arpk ON ar.ArtProdKonto = arpk.ArtprodKonto + AND ar.ForetagKod = arpk.ForetagKod + LEFT OUTER JOIN vg ON ar.VaruGruppKod = vg.VaruGruppKod + AND ar.ForetagKod = vg.ForetagKod + AND vg.SprakKod = 0 + LEFT OUTER JOIN xp ON ar.ArtProdKlass = xp.ArtProdKlass + AND ar.ForetagKod = xp.ForetagKod + LEFT OUTER JOIN xm ON ar.ArtKod = xm.ArtKod + AND ar.ForetagKod = xm.ForetagKod + WHERE ar.ForetagKod = 1""") + + return self._execute(query) + + def _kus(self, updated_dt='2000-01-01 00:00:00.000', + created_dt='2000-01-01 00:00:00.000', limit=None): + query = ( + """SELECT kus.FtgNr, BetKod, kus.kundbetalarenr, kus.RowUpdatedBy, kus.RowUpdatedDt, + kus.RowCreatedBy, kus.RowCreatedDt, kus.ForetagKod, kus.MakDateTime, kus.Makulerad, + x1k.KundKategoriKod, x1k.KundKatBeskr, + x1kk.Kundklass, x1kk.KundKlassBeskr, + salj.Saljare, salj.SaljareNamn, + OrgNr, FtgNamn, FtgPostAdr1, FtgPostAdr2, FtgPostAdr3, + FtgPostadr4, FtgPostadr5, FtgPostnr, fr.LandsKod, FtgPostLevAdr3, FtgLevPostNr + FROM kus + LEFT OUTER JOIN fr ON fr.FtgNr = kus.FtgNr + AND fr.ForetagKod = kus.ForetagKod + LEFT OUTER JOIN x1k ON x1k.KundKategoriKod = kus.kundkategorikod + AND x1k.ForetagKod = kus.ForetagKod + LEFT OUTER JOIN x1kk ON x1kk.Kundklass = kus.kundklass + AND x1kk.ForetagKod = kus.ForetagKod + LEFT OUTER JOIN salj ON salj.Saljare = kus.Saljare + AND salj.ForetagKod = kus.ForetagKod + WHERE kus.ForetagKod = 1 + AND (kus.RowCreatedDt > %(created_dt)s + OR kus.RowUpdatedDt > %(updated_dt)s + OR fr.RowCreatedDt > %(created_dt)s + OR fr.RowUpdatedDt > %(updated_dt)s + OR x1k.RowCreatedDt > %(created_dt)s + OR x1k.RowUpdatedDt > %(updated_dt)s + OR x1kk.RowCreatedDt > %(created_dt)s + OR x1kk.RowUpdatedDt > %(updated_dt)s + OR salj.RowCreatedDt > %(created_dt)s + OR salj.RowUpdatedDt > %(updated_dt)s)""") + params = {'created_dt': created_dt, 'updated_dt': updated_dt} + + return self._execute(query, params) + + def get(self, jvs_tbl, updated_dt, created_dt): + if not updated_dt: + updated_dt = datetime.date(2000, 1, 1) + if not created_dt: + created_dt = datetime.date(2000, 1, 1) + + updated_dt = updated_dt.strftime("%Y-%m-%d %H:%M:%S") + created_dt = created_dt.strftime("%Y-%m-%d %H:%M:%S") + + if jvs_tbl == 'Articles': + return self._ar() + elif jvs_tbl == 'Customers': + return self._kus(updated_dt, created_dt) + elif jvs_tbl == 'InvoiceRows': + return self._ft(updated_dt, created_dt) + elif jvs_tbl == 'OrderRows': + return self._orp(updated_dt, created_dt) + else: + self.logger.warning("%s table has no get query" % jvs_tbl) diff --git a/pyjeeves/main.py b/pyjeeves/main.py new file mode 100644 index 0000000..27cd260 --- /dev/null +++ b/pyjeeves/main.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +import pprint +import yaml +import signal +import sys + +import logging +import logging.config + +from alembic.config import Config +from alembic import command + +from process import Process +from jvsquery import JvsQuery +from db import MySQLSession +from utils import TaskThread + + +pp = pprint.PrettyPrinter(indent=4) + + +class SyncTread(TaskThread): + """docstring for ClassName""" + def __init__(self, config): + super(SyncTread, self).__init__() + + jvs_query = JvsQuery(config['jeeves_db']) + db_session = MySQLSession(config['mysql']) + self.process = Process(jvs_query, db_session) + + self.logger = logging.getLogger("PyJeeves.SyncTread") + + def task(self): + self.logger.info("Started sync") + self.process.sync_data() + self.logger.info("Finished sync") + + +if __name__ == '__main__': + with open("config.yml", 'r') as ymlfile: + cfg = yaml.load(ymlfile) + + logging.config.dictConfig(cfg['logging']) + logger = logging.getLogger("PyJeeves") + + logger.info("Running migrations") + alembic_cfg = Config() + for k in cfg['alembic']: + alembic_cfg.set_main_option(k, cfg['alembic'][k]) + command.upgrade(alembic_cfg, "head") + + logger.info("Application started") + + def sigterm_handler(signal, frame): + # save the state here or do whatever you want + logger.info('Application interrupted') + sys.exit(0) + signal.signal(signal.SIGINT, sigterm_handler) + signal.signal(signal.SIGTERM, sigterm_handler) + + sync_thread = SyncTread(cfg) + try: + sync_thread.setInterval(cfg['sync_interval']) + sync_thread.start() + sync_thread.join() + finally: + sync_thread.shutdown() + logger.info("Thread stopped") + + logger.info("Application stopped") diff --git a/pyjeeves/models/__init__.py b/pyjeeves/models/__init__.py new file mode 100644 index 0000000..99b282c --- /dev/null +++ b/pyjeeves/models/__init__.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- +""" + pyjeeves.models + ~~~~~~~~~~~~~~~ + + consolodated models module +""" + +from .jvsmodels import * # noqa diff --git a/pyjeeves/models/jvsmodels.py b/pyjeeves/models/jvsmodels.py new file mode 100644 index 0000000..dbf61b6 --- /dev/null +++ b/pyjeeves/models/jvsmodels.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +""" + pyjeeves.models + ~~~~~~~~~~~~~~~~~~~~~~ + + Jeeves data models +""" + +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import (Column, Integer, BigInteger, SmallInteger, + String, ForeignKey, Numeric, DateTime, Boolean) +from sqlalchemy.orm import relationship +from sqlalchemy.schema import PrimaryKeyConstraint + +Base = declarative_base() + + +class InvoiceRows(Base): + __tablename__ = 'jvs_invoice_rows' + __table_args__ = ( + PrimaryKeyConstraint(name='invoice_rows_primary_key', mssql_clustered=True),) + + FaktNr = Column(BigInteger, primary_key=True) + FaktRadnr = Column(Integer, primary_key=True) + ForetagKod = Column(SmallInteger, primary_key=True) + + FtgNr = Column(String(length=16), ForeignKey(u'jvs_customers.FtgNr')) + OrderNr = Column(BigInteger) + OrdTyp = Column(SmallInteger) + Saljare = Column(String(length=16)) + KundKategoriKod = Column(SmallInteger) # Can't have foreign key, as foreing data is mutalble + ArtNr = Column(String(length=16)) # Can't have foreign key, as foreing data is mutalble + EnhetsKod = Column(String(length=8)) + VaruGruppKod = Column(String(length=8)) + + Redovisnar = Column(SmallInteger) + Period = Column(SmallInteger) + FaktDat = Column(DateTime) + FaktTB = Column(Numeric(precision=19, scale=4)) + FaktTG = Column(Numeric(precision=8, scale=3)) + FaktLevAnt = Column(Numeric(precision=15, scale=6)) + FaktLevAntAltEnh = Column(Numeric(precision=15, scale=6)) + FPris = Column(Numeric(precision=19, scale=4)) + FaktRadSumma = Column(Numeric(precision=19, scale=4)) + ValKod = Column(String(length=3)) + ValKurs = Column(Numeric(precision=22, scale=14)) + RowCreatedDt = Column(DateTime) + RowUpdatedDt = Column(DateTime) + RowUpdatedBy = Column(String(length=16)) + + customer = relationship(u'Customers') + articles = relationship(u'Articles', foreign_keys=[ArtNr], + primaryjoin='Articles.ArtNr == InvoiceRows.ArtNr') + + +class OrderRows(Base): + __tablename__ = 'jvs_order_rows' + __table_args__ = ( + PrimaryKeyConstraint(name='order_rows_primary_key', mssql_clustered=True),) + + OrderNr = Column(BigInteger, primary_key=True) + OrdRadnr = Column(Integer, primary_key=True) + OrdRadNrStrPos = Column(Integer, primary_key=True) + OrdRestNr = Column(SmallInteger, primary_key=True) + ForetagKod = Column(SmallInteger, primary_key=True) + + ArtNr = Column(String(length=16)) + FtgNr = Column(String(length=16), ForeignKey(u'jvs_customers.FtgNr')) + vb_pris = Column(Numeric(precision=19, scale=4)) + OrdAntal = Column(Numeric(precision=15, scale=6)) + OrdAntalAltEnh = Column(Numeric(precision=15, scale=6)) + AltEnhetKod = Column(String(length=16)) + OrdLevAntal = Column(Numeric(precision=15, scale=6)) + OrdLevAntalAltEnh = Column(Numeric(precision=15, scale=6)) + FaktNr = Column(BigInteger) + OrdDatum = Column(DateTime) + OrdBerLevDat = Column(DateTime) + OrdBerednDat = Column(DateTime) + OrdLevDat = Column(DateTime) + + # Data from SalesPersonel (salj) in Jeeves + Saljare = Column(String(length=32)) + SaljareNamn = Column(String(length=64)) + + # Data from OrderRowStatuses (xs) in Jeeves + OrdRadSt = Column(SmallInteger) + OrdRStatBeskr = Column(String(length=64)) + + # Data from OrderTypes (x6) in Jeeves + OrdTyp = Column(SmallInteger) + OrdTypBeskr = Column(String(length=64)) + + RowCreatedDt = Column(DateTime) + RowCreatedBy = Column(String(length=16)) + RowUpdatedDt = Column(DateTime) + RowUpdatedBy = Column(String(length=16)) + + customer = relationship(u'Customers') + invoice_rows = relationship(u'InvoiceRows', foreign_keys=[FaktNr], + primaryjoin='InvoiceRows.FaktNr == OrderRows.FaktNr') + articles = relationship(u'Articles', foreign_keys=[ArtNr], + primaryjoin='Articles.ArtNr == OrderRows.ArtNr') + + +class Articles(Base): + __tablename__ = 'jvs_articles' + __table_args__ = ( + PrimaryKeyConstraint(name='articles_primary_key', mssql_clustered=True),) + + ArtNr = Column(String(length=16), primary_key=True) + ForetagKod = Column(SmallInteger, primary_key=True) + + ArtBeskr = Column(String(length=128)) + ArtBeskr2 = Column(String(length=256)) + ArtBeskrSpec = Column(String(length=128)) + + ArtProdKonto = Column(String(length=8)) + ArtProdKontoBeskr = Column(String(length=64)) + VaruGruppKod = Column(String(length=8)) + VaruGruppBeskr = Column(String(length=64)) + ArtProdKlass = Column(String(length=8)) + ArtProdklBeskr = Column(String(length=64)) + ArtKod = Column(SmallInteger) + ArtTypBeskr = Column(String(length=64)) + + LagTyp = Column(SmallInteger) + EnhetsKod = Column(String(length=8)) + LevNr = Column(String(length=16)) + ItemStatusCode = Column(Integer) + LagSaldoArtikel = Column(Numeric(precision=15, scale=6)) + + RowCreatedDt = Column(DateTime) + RowCreatedBy = Column(String(length=16)) + RowUpdatedDt = Column(DateTime) + RowUpdatedBy = Column(String(length=16)) + + +class Customers(Base): + __tablename__ = 'jvs_customers' + __table_args__ = ( + PrimaryKeyConstraint(name='customers_primary_key', mssql_clustered=True),) + + FtgNr = Column(String(length=16), primary_key=True) + ForetagKod = Column(SmallInteger, primary_key=True) + + BetKod = Column(String(length=8)) + Saljare = Column(String(length=16)) + kundbetalarenr = Column(String(length=16)) + + Makulerad = Column(Boolean) + MakDateTime = Column(DateTime) + + RowCreatedDt = Column(DateTime) + RowCreatedBy = Column(String(length=16)) + RowUpdatedDt = Column(DateTime) + RowUpdatedBy = Column(String(length=16)) + + # Data from SalesPersonel (salj) in Jeeves + Saljare = Column(String(length=32)) + SaljareNamn = Column(String(length=64)) + + # Data from CustomerCategories (x1k) in Jeeves + KundKategoriKod = Column(SmallInteger) + KundKatBeskr = Column(String(length=64)) + + # Data from CustomerClasses (x1kk) in Jeeves + Kundklass = Column(String(length=16)) + KundKlassBeskr = Column(String(length=64)) + + # Data from Companies (fr) in Jeeves + OrgNr = Column(String(length=32)) + FtgNamn = Column(String(length=64)) + FtgPostAdr1 = Column(String(length=64)) + FtgPostAdr2 = Column(String(length=64)) + FtgPostAdr3 = Column(String(length=64)) + FtgPostadr4 = Column(String(length=64)) + FtgPostadr5 = Column(String(length=128)) + FtgPostnr = Column(String(length=16)) + LandsKod = Column(String(length=16)) + FtgPostLevAdr3 = Column(String(length=64)) + FtgLevPostNr = Column(String(length=16)) diff --git a/pyjeeves/process.py b/pyjeeves/process.py new file mode 100644 index 0000000..c0822b3 --- /dev/null +++ b/pyjeeves/process.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" + pyjeeves.process + ~~~~~~~~~~~~~~~~~~~~~~ + + Jeeves data process +""" + + +from models import Articles, Customers, InvoiceRows, OrderRows + +from sqlalchemy import desc +from sqlalchemy.inspection import inspect + +import logging + + +class Process(): + """docstring for Process""" + def __init__(self, jvs_query, db_session): + super(Process, self).__init__() + self.query = jvs_query + self.session = db_session + self.logger = logging.getLogger("PyJeeves.process") + + def _update_model(self, model, kwargs): + for k, v in kwargs.items(): + if getattr(model, k) != v: + if type(getattr(model, k)) is bool: + setattr(model, k, bool(int(v))) + else: + setattr(model, k, v) + + def _get_last_dates(self, model): + _last_update = self.session.query(model).\ + order_by(desc(model.RowUpdatedDt)).first() + _last_create = self.session.query(model).\ + order_by(desc(model.RowCreatedDt)).first() + + return (_last_update.RowUpdatedDt if _last_update else None, + _last_create.RowCreatedDt if _last_create else None) + + def _sync_model(self, model, jvs_tbl='companies'): + _p_keys = [key.name for key in inspect(model).primary_key] + _last_update, _last_create = self._get_last_dates(model) + _data = self.query.get(jvs_tbl, _last_update, _last_create) + + if _data: + self.logger.info("Syncing %s" % jvs_tbl) + for item in _data: + _filter_kwargs = {k: item.get(k) for k in _p_keys} + _existing = self.session.query(model).\ + filter_by(**_filter_kwargs).first() + + if _existing: + self._update_model(_existing, item) + else: + _new = model(**item) + self.session.add(_new) + else: + self.logger.info("No sync made for %s" % jvs_tbl) + + def sync_data(self): + self._sync_model(Customers, 'Customers') + self._sync_model(Articles, 'Articles') + self._sync_model(InvoiceRows, 'InvoiceRows') + self._sync_model(OrderRows, 'OrderRows') + self.session.commit() diff --git a/pyjeeves/utils.py b/pyjeeves/utils.py new file mode 100644 index 0000000..c4e3455 --- /dev/null +++ b/pyjeeves/utils.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +""" + pyjeeves.utils + ~~~~~~~~~~~~~~~~~~~~~~ + + Utils to improve usablity +""" +import threading + + +class TaskThread(threading.Thread): + """Thread that executes a task every N seconds""" + + def __init__(self): + threading.Thread.__init__(self) + self._finished = threading.Event() + self._interval = 15.0 + + def setInterval(self, interval): + """Set the number of seconds we sleep between executing our task""" + self._interval = interval + + def shutdown(self): + """Stop this thread""" + self._finished.set() + + def run(self): + while 1: + if self._finished.isSet(): + return + self.task() + + # sleep for interval or until shutdown + self._finished.wait(self._interval) + + def task(self): + """The task done by this thread - override in subclasses""" + pass diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8b46b61 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +nose +sphinx +pymssql +sqlalchemy +PyMySQL +alembic +pyyaml \ No newline at end of file diff --git a/sample/__init__.py b/sample/__init__.py new file mode 100644 index 0000000..f4633fa --- /dev/null +++ b/sample/__init__.py @@ -0,0 +1 @@ +from .core import hmm \ No newline at end of file diff --git a/sample/core.py b/sample/core.py new file mode 100644 index 0000000..b5ded8c --- /dev/null +++ b/sample/core.py @@ -0,0 +1,9 @@ +# -*- coding: utf-8 -*- + +def get_hmm(): + """Get a thought.""" + return 'hmmm...' + +def hmm(): + """Contemplation...""" + print(get_hmm()) diff --git a/sample/helpers.py b/sample/helpers.py new file mode 100644 index 0000000..e69de29 diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..f9a041b --- /dev/null +++ b/setup.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +from setuptools import setup, find_packages + + +with open('README.rst') as f: + readme = f.read() + +with open('LICENSE') as f: + license = f.read() + +setup( + name='pyjeeves', + version='0.0.1', + description='PyJeeves syncronization module', + long_description=readme, + author='Marcus Lindvall', + author_email='marcus.lindvall@lindvallskaffe.se', + url='https://gitlab.lndvll.se/lindvallskaffe/pyjeeves', + license=license, + packages=find_packages(exclude=('tests', 'docs', 'sample', 'env', 'migrations')) +) + diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/context.py b/tests/context.py new file mode 100644 index 0000000..349ae8a --- /dev/null +++ b/tests/context.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +import sys +import os +sys.path.insert(0, os.path.abspath('..')) + +import sample \ No newline at end of file diff --git a/tests/test_advanced.py b/tests/test_advanced.py new file mode 100644 index 0000000..5438ac3 --- /dev/null +++ b/tests/test_advanced.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +from .context import sample + +import unittest + + +class AdvancedTestSuite(unittest.TestCase): + """Advanced test cases.""" + + def test_thoughts(self): + sample.hmm() + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/tests/test_basic.py b/tests/test_basic.py new file mode 100644 index 0000000..d3e4d5a --- /dev/null +++ b/tests/test_basic.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +from .context import sample + +import unittest + + +class BasicTestSuite(unittest.TestCase): + """Basic test cases.""" + + def test_absolute_truth_and_meaning(self): + assert True + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file